repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
soravux/scoop | scoop/launcher.py | ScoopApp.close | def close(self):
"""Subprocess cleanup."""
# Give time to flush data if debug was on
if self.debug:
time.sleep(10)
# Terminate workers
for host in self.workers:
host.close()
# Terminate the brokers
for broker in self.brokers:
try:
broker.close()
except AttributeError:
# Broker was not started (probably mislaunched)
pass
scoop.logger.info('Finished cleaning spawned subprocesses.') | python | def close(self):
"""Subprocess cleanup."""
# Give time to flush data if debug was on
if self.debug:
time.sleep(10)
# Terminate workers
for host in self.workers:
host.close()
# Terminate the brokers
for broker in self.brokers:
try:
broker.close()
except AttributeError:
# Broker was not started (probably mislaunched)
pass
scoop.logger.info('Finished cleaning spawned subprocesses.') | [
"def",
"close",
"(",
"self",
")",
":",
"# Give time to flush data if debug was on",
"if",
"self",
".",
"debug",
":",
"time",
".",
"sleep",
"(",
"10",
")",
"# Terminate workers",
"for",
"host",
"in",
"self",
".",
"workers",
":",
"host",
".",
"close",
"(",
")",
"# Terminate the brokers",
"for",
"broker",
"in",
"self",
".",
"brokers",
":",
"try",
":",
"broker",
".",
"close",
"(",
")",
"except",
"AttributeError",
":",
"# Broker was not started (probably mislaunched)",
"pass",
"scoop",
".",
"logger",
".",
"info",
"(",
"'Finished cleaning spawned subprocesses.'",
")"
] | Subprocess cleanup. | [
"Subprocess",
"cleanup",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/launcher.py#L320-L338 | train |
soravux/scoop | scoop/broker/brokerzmq.py | Broker.processConfig | def processConfig(self, worker_config):
"""Update the pool configuration with a worker configuration.
"""
self.config['headless'] |= worker_config.get("headless", False)
if self.config['headless']:
# Launch discovery process
if not self.discovery_thread:
self.discovery_thread = discovery.Advertise(
port=",".join(str(a) for a in self.getPorts()),
) | python | def processConfig(self, worker_config):
"""Update the pool configuration with a worker configuration.
"""
self.config['headless'] |= worker_config.get("headless", False)
if self.config['headless']:
# Launch discovery process
if not self.discovery_thread:
self.discovery_thread = discovery.Advertise(
port=",".join(str(a) for a in self.getPorts()),
) | [
"def",
"processConfig",
"(",
"self",
",",
"worker_config",
")",
":",
"self",
".",
"config",
"[",
"'headless'",
"]",
"|=",
"worker_config",
".",
"get",
"(",
"\"headless\"",
",",
"False",
")",
"if",
"self",
".",
"config",
"[",
"'headless'",
"]",
":",
"# Launch discovery process",
"if",
"not",
"self",
".",
"discovery_thread",
":",
"self",
".",
"discovery_thread",
"=",
"discovery",
".",
"Advertise",
"(",
"port",
"=",
"\",\"",
".",
"join",
"(",
"str",
"(",
"a",
")",
"for",
"a",
"in",
"self",
".",
"getPorts",
"(",
")",
")",
",",
")"
] | Update the pool configuration with a worker configuration. | [
"Update",
"the",
"pool",
"configuration",
"with",
"a",
"worker",
"configuration",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/broker/brokerzmq.py#L173-L182 | train |
soravux/scoop | scoop/bootstrap/__main__.py | Bootstrap.main | def main(self):
"""Bootstrap an arbitrary script.
If no agruments were passed, use discovery module to search and connect
to a broker."""
if self.args is None:
self.parse()
self.log = utils.initLogging(self.verbose)
# Change to the desired directory
if self.args.workingDirectory:
os.chdir(self.args.workingDirectory)
if not self.args.brokerHostname:
self.log.info("Discovering SCOOP Brokers on network...")
pools = discovery.Seek()
if not pools:
self.log.error("Could not find a SCOOP Broker broadcast.")
sys.exit(-1)
self.log.info("Found a broker named {name} on {host} port "
"{ports}".format(
name=pools[0].name,
host=pools[0].host,
ports=pools[0].ports,
))
self.args.brokerHostname = pools[0].host
self.args.taskPort = pools[0].ports[0]
self.args.metaPort = pools[0].ports[0]
self.log.debug("Using following addresses:\n{brokerAddress}\n"
"{metaAddress}".format(
brokerAddress=self.args.brokerAddress,
metaAddress=self.args.metaAddress,
))
self.args.origin = True
self.setScoop()
self.run() | python | def main(self):
"""Bootstrap an arbitrary script.
If no agruments were passed, use discovery module to search and connect
to a broker."""
if self.args is None:
self.parse()
self.log = utils.initLogging(self.verbose)
# Change to the desired directory
if self.args.workingDirectory:
os.chdir(self.args.workingDirectory)
if not self.args.brokerHostname:
self.log.info("Discovering SCOOP Brokers on network...")
pools = discovery.Seek()
if not pools:
self.log.error("Could not find a SCOOP Broker broadcast.")
sys.exit(-1)
self.log.info("Found a broker named {name} on {host} port "
"{ports}".format(
name=pools[0].name,
host=pools[0].host,
ports=pools[0].ports,
))
self.args.brokerHostname = pools[0].host
self.args.taskPort = pools[0].ports[0]
self.args.metaPort = pools[0].ports[0]
self.log.debug("Using following addresses:\n{brokerAddress}\n"
"{metaAddress}".format(
brokerAddress=self.args.brokerAddress,
metaAddress=self.args.metaAddress,
))
self.args.origin = True
self.setScoop()
self.run() | [
"def",
"main",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
"is",
"None",
":",
"self",
".",
"parse",
"(",
")",
"self",
".",
"log",
"=",
"utils",
".",
"initLogging",
"(",
"self",
".",
"verbose",
")",
"# Change to the desired directory",
"if",
"self",
".",
"args",
".",
"workingDirectory",
":",
"os",
".",
"chdir",
"(",
"self",
".",
"args",
".",
"workingDirectory",
")",
"if",
"not",
"self",
".",
"args",
".",
"brokerHostname",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Discovering SCOOP Brokers on network...\"",
")",
"pools",
"=",
"discovery",
".",
"Seek",
"(",
")",
"if",
"not",
"pools",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Could not find a SCOOP Broker broadcast.\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"Found a broker named {name} on {host} port \"",
"\"{ports}\"",
".",
"format",
"(",
"name",
"=",
"pools",
"[",
"0",
"]",
".",
"name",
",",
"host",
"=",
"pools",
"[",
"0",
"]",
".",
"host",
",",
"ports",
"=",
"pools",
"[",
"0",
"]",
".",
"ports",
",",
")",
")",
"self",
".",
"args",
".",
"brokerHostname",
"=",
"pools",
"[",
"0",
"]",
".",
"host",
"self",
".",
"args",
".",
"taskPort",
"=",
"pools",
"[",
"0",
"]",
".",
"ports",
"[",
"0",
"]",
"self",
".",
"args",
".",
"metaPort",
"=",
"pools",
"[",
"0",
"]",
".",
"ports",
"[",
"0",
"]",
"self",
".",
"log",
".",
"debug",
"(",
"\"Using following addresses:\\n{brokerAddress}\\n\"",
"\"{metaAddress}\"",
".",
"format",
"(",
"brokerAddress",
"=",
"self",
".",
"args",
".",
"brokerAddress",
",",
"metaAddress",
"=",
"self",
".",
"args",
".",
"metaAddress",
",",
")",
")",
"self",
".",
"args",
".",
"origin",
"=",
"True",
"self",
".",
"setScoop",
"(",
")",
"self",
".",
"run",
"(",
")"
] | Bootstrap an arbitrary script.
If no agruments were passed, use discovery module to search and connect
to a broker. | [
"Bootstrap",
"an",
"arbitrary",
"script",
".",
"If",
"no",
"agruments",
"were",
"passed",
"use",
"discovery",
"module",
"to",
"search",
"and",
"connect",
"to",
"a",
"broker",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/bootstrap/__main__.py#L54-L92 | train |
soravux/scoop | scoop/bootstrap/__main__.py | Bootstrap.makeParser | def makeParser(self):
"""Generate the argparse parser object containing the bootloader
accepted parameters
"""
self.parser = argparse.ArgumentParser(description='Starts the executable.',
prog=("{0} -m scoop.bootstrap"
).format(sys.executable))
self.parser.add_argument('--origin',
help="To specify that the worker is the origin",
action='store_true')
self.parser.add_argument('--brokerHostname',
help="The routable hostname of a broker",
default="")
self.parser.add_argument('--externalBrokerHostname',
help="Externally routable hostname of local "
"worker",
default="")
self.parser.add_argument('--taskPort',
help="The port of the broker task socket",
type=int)
self.parser.add_argument('--metaPort',
help="The port of the broker meta socket",
type=int)
self.parser.add_argument('--size',
help="The size of the worker pool",
type=int,
default=1)
self.parser.add_argument('--nice',
help="Adjust the niceness of the process",
type=int,
default=0)
self.parser.add_argument('--debug',
help="Activate the debug",
action='store_true')
self.parser.add_argument('--profile',
help="Activate the profiler",
action='store_true')
self.parser.add_argument('--workingDirectory',
help="Set the working directory for the "
"execution",
default=os.path.expanduser("~"))
self.parser.add_argument('--backend',
help="Choice of communication backend",
choices=['ZMQ', 'TCP'],
default='ZMQ')
self.parser.add_argument('executable',
nargs='?',
help='The executable to start with scoop')
self.parser.add_argument('args',
nargs=argparse.REMAINDER,
help='The arguments to pass to the executable',
default=[])
self.parser.add_argument('--verbose', '-v', action='count',
help=("Verbosity level of this launch script"
"(-vv for more)"),
default=0) | python | def makeParser(self):
"""Generate the argparse parser object containing the bootloader
accepted parameters
"""
self.parser = argparse.ArgumentParser(description='Starts the executable.',
prog=("{0} -m scoop.bootstrap"
).format(sys.executable))
self.parser.add_argument('--origin',
help="To specify that the worker is the origin",
action='store_true')
self.parser.add_argument('--brokerHostname',
help="The routable hostname of a broker",
default="")
self.parser.add_argument('--externalBrokerHostname',
help="Externally routable hostname of local "
"worker",
default="")
self.parser.add_argument('--taskPort',
help="The port of the broker task socket",
type=int)
self.parser.add_argument('--metaPort',
help="The port of the broker meta socket",
type=int)
self.parser.add_argument('--size',
help="The size of the worker pool",
type=int,
default=1)
self.parser.add_argument('--nice',
help="Adjust the niceness of the process",
type=int,
default=0)
self.parser.add_argument('--debug',
help="Activate the debug",
action='store_true')
self.parser.add_argument('--profile',
help="Activate the profiler",
action='store_true')
self.parser.add_argument('--workingDirectory',
help="Set the working directory for the "
"execution",
default=os.path.expanduser("~"))
self.parser.add_argument('--backend',
help="Choice of communication backend",
choices=['ZMQ', 'TCP'],
default='ZMQ')
self.parser.add_argument('executable',
nargs='?',
help='The executable to start with scoop')
self.parser.add_argument('args',
nargs=argparse.REMAINDER,
help='The arguments to pass to the executable',
default=[])
self.parser.add_argument('--verbose', '-v', action='count',
help=("Verbosity level of this launch script"
"(-vv for more)"),
default=0) | [
"def",
"makeParser",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Starts the executable.'",
",",
"prog",
"=",
"(",
"\"{0} -m scoop.bootstrap\"",
")",
".",
"format",
"(",
"sys",
".",
"executable",
")",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--origin'",
",",
"help",
"=",
"\"To specify that the worker is the origin\"",
",",
"action",
"=",
"'store_true'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--brokerHostname'",
",",
"help",
"=",
"\"The routable hostname of a broker\"",
",",
"default",
"=",
"\"\"",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--externalBrokerHostname'",
",",
"help",
"=",
"\"Externally routable hostname of local \"",
"\"worker\"",
",",
"default",
"=",
"\"\"",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--taskPort'",
",",
"help",
"=",
"\"The port of the broker task socket\"",
",",
"type",
"=",
"int",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--metaPort'",
",",
"help",
"=",
"\"The port of the broker meta socket\"",
",",
"type",
"=",
"int",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--size'",
",",
"help",
"=",
"\"The size of the worker pool\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--nice'",
",",
"help",
"=",
"\"Adjust the niceness of the process\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--debug'",
",",
"help",
"=",
"\"Activate the debug\"",
",",
"action",
"=",
"'store_true'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--profile'",
",",
"help",
"=",
"\"Activate the profiler\"",
",",
"action",
"=",
"'store_true'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--workingDirectory'",
",",
"help",
"=",
"\"Set the working directory for the \"",
"\"execution\"",
",",
"default",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--backend'",
",",
"help",
"=",
"\"Choice of communication backend\"",
",",
"choices",
"=",
"[",
"'ZMQ'",
",",
"'TCP'",
"]",
",",
"default",
"=",
"'ZMQ'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'executable'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'The executable to start with scoop'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'args'",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"'The arguments to pass to the executable'",
",",
"default",
"=",
"[",
"]",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--verbose'",
",",
"'-v'",
",",
"action",
"=",
"'count'",
",",
"help",
"=",
"(",
"\"Verbosity level of this launch script\"",
"\"(-vv for more)\"",
")",
",",
"default",
"=",
"0",
")"
] | Generate the argparse parser object containing the bootloader
accepted parameters | [
"Generate",
"the",
"argparse",
"parser",
"object",
"containing",
"the",
"bootloader",
"accepted",
"parameters"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/bootstrap/__main__.py#L94-L150 | train |
soravux/scoop | scoop/bootstrap/__main__.py | Bootstrap.parse | def parse(self):
"""Generate a argparse parser and parse the command-line arguments"""
if self.parser is None:
self.makeParser()
self.args = self.parser.parse_args()
self.verbose = self.args.verbose | python | def parse(self):
"""Generate a argparse parser and parse the command-line arguments"""
if self.parser is None:
self.makeParser()
self.args = self.parser.parse_args()
self.verbose = self.args.verbose | [
"def",
"parse",
"(",
"self",
")",
":",
"if",
"self",
".",
"parser",
"is",
"None",
":",
"self",
".",
"makeParser",
"(",
")",
"self",
".",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"self",
".",
"verbose",
"=",
"self",
".",
"args",
".",
"verbose"
] | Generate a argparse parser and parse the command-line arguments | [
"Generate",
"a",
"argparse",
"parser",
"and",
"parse",
"the",
"command",
"-",
"line",
"arguments"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/bootstrap/__main__.py#L152-L157 | train |
soravux/scoop | scoop/bootstrap/__main__.py | Bootstrap.setScoop | def setScoop(self):
"""Setup the SCOOP constants."""
scoop.IS_RUNNING = True
scoop.IS_ORIGIN = self.args.origin
scoop.BROKER = BrokerInfo(
self.args.brokerHostname,
self.args.taskPort,
self.args.metaPort,
self.args.externalBrokerHostname
if self.args.externalBrokerHostname
else self.args.brokerHostname,
)
scoop.SIZE = self.args.size
scoop.DEBUG = self.args.debug
scoop.MAIN_MODULE = self.args.executable
scoop.CONFIGURATION = {
'headless': not bool(self.args.executable),
'backend': self.args.backend,
}
scoop.WORKING_DIRECTORY = self.args.workingDirectory
scoop.logger = self.log
if self.args.nice:
if not psutil:
scoop.logger.error("psutil not installed.")
raise ImportError("psutil is needed for nice functionnality.")
p = psutil.Process(os.getpid())
p.set_nice(self.args.nice)
if scoop.DEBUG or self.args.profile:
from scoop import _debug
if scoop.DEBUG:
_debug.createDirectory() | python | def setScoop(self):
"""Setup the SCOOP constants."""
scoop.IS_RUNNING = True
scoop.IS_ORIGIN = self.args.origin
scoop.BROKER = BrokerInfo(
self.args.brokerHostname,
self.args.taskPort,
self.args.metaPort,
self.args.externalBrokerHostname
if self.args.externalBrokerHostname
else self.args.brokerHostname,
)
scoop.SIZE = self.args.size
scoop.DEBUG = self.args.debug
scoop.MAIN_MODULE = self.args.executable
scoop.CONFIGURATION = {
'headless': not bool(self.args.executable),
'backend': self.args.backend,
}
scoop.WORKING_DIRECTORY = self.args.workingDirectory
scoop.logger = self.log
if self.args.nice:
if not psutil:
scoop.logger.error("psutil not installed.")
raise ImportError("psutil is needed for nice functionnality.")
p = psutil.Process(os.getpid())
p.set_nice(self.args.nice)
if scoop.DEBUG or self.args.profile:
from scoop import _debug
if scoop.DEBUG:
_debug.createDirectory() | [
"def",
"setScoop",
"(",
"self",
")",
":",
"scoop",
".",
"IS_RUNNING",
"=",
"True",
"scoop",
".",
"IS_ORIGIN",
"=",
"self",
".",
"args",
".",
"origin",
"scoop",
".",
"BROKER",
"=",
"BrokerInfo",
"(",
"self",
".",
"args",
".",
"brokerHostname",
",",
"self",
".",
"args",
".",
"taskPort",
",",
"self",
".",
"args",
".",
"metaPort",
",",
"self",
".",
"args",
".",
"externalBrokerHostname",
"if",
"self",
".",
"args",
".",
"externalBrokerHostname",
"else",
"self",
".",
"args",
".",
"brokerHostname",
",",
")",
"scoop",
".",
"SIZE",
"=",
"self",
".",
"args",
".",
"size",
"scoop",
".",
"DEBUG",
"=",
"self",
".",
"args",
".",
"debug",
"scoop",
".",
"MAIN_MODULE",
"=",
"self",
".",
"args",
".",
"executable",
"scoop",
".",
"CONFIGURATION",
"=",
"{",
"'headless'",
":",
"not",
"bool",
"(",
"self",
".",
"args",
".",
"executable",
")",
",",
"'backend'",
":",
"self",
".",
"args",
".",
"backend",
",",
"}",
"scoop",
".",
"WORKING_DIRECTORY",
"=",
"self",
".",
"args",
".",
"workingDirectory",
"scoop",
".",
"logger",
"=",
"self",
".",
"log",
"if",
"self",
".",
"args",
".",
"nice",
":",
"if",
"not",
"psutil",
":",
"scoop",
".",
"logger",
".",
"error",
"(",
"\"psutil not installed.\"",
")",
"raise",
"ImportError",
"(",
"\"psutil is needed for nice functionnality.\"",
")",
"p",
"=",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"p",
".",
"set_nice",
"(",
"self",
".",
"args",
".",
"nice",
")",
"if",
"scoop",
".",
"DEBUG",
"or",
"self",
".",
"args",
".",
"profile",
":",
"from",
"scoop",
"import",
"_debug",
"if",
"scoop",
".",
"DEBUG",
":",
"_debug",
".",
"createDirectory",
"(",
")"
] | Setup the SCOOP constants. | [
"Setup",
"the",
"SCOOP",
"constants",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/bootstrap/__main__.py#L159-L191 | train |
soravux/scoop | examples/shared_example.py | myFunc | def myFunc(parameter):
"""This function will be executed on the remote host even if it was not
available at launch."""
print('Hello World from {0}!'.format(scoop.worker))
# It is possible to get a constant anywhere
print(shared.getConst('myVar')[2])
# Parameters are handled as usual
return parameter + 1 | python | def myFunc(parameter):
"""This function will be executed on the remote host even if it was not
available at launch."""
print('Hello World from {0}!'.format(scoop.worker))
# It is possible to get a constant anywhere
print(shared.getConst('myVar')[2])
# Parameters are handled as usual
return parameter + 1 | [
"def",
"myFunc",
"(",
"parameter",
")",
":",
"print",
"(",
"'Hello World from {0}!'",
".",
"format",
"(",
"scoop",
".",
"worker",
")",
")",
"# It is possible to get a constant anywhere",
"print",
"(",
"shared",
".",
"getConst",
"(",
"'myVar'",
")",
"[",
"2",
"]",
")",
"# Parameters are handled as usual",
"return",
"parameter",
"+",
"1"
] | This function will be executed on the remote host even if it was not
available at launch. | [
"This",
"function",
"will",
"be",
"executed",
"on",
"the",
"remote",
"host",
"even",
"if",
"it",
"was",
"not",
"available",
"at",
"launch",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/shared_example.py#L26-L35 | train |
soravux/scoop | scoop/_comm/scooptcp.py | TCPCommunicator.sendResult | def sendResult(self, future):
"""Send a terminated future back to its parent."""
future = copy.copy(future)
# Remove the (now) extraneous elements from future class
future.callable = future.args = future.kargs = future.greenlet = None
if not future.sendResultBack:
# Don't reply back the result if it isn't asked
future.resultValue = None
self._sendReply(
future.id.worker,
pickle.dumps(
future,
pickle.HIGHEST_PROTOCOL,
),
) | python | def sendResult(self, future):
"""Send a terminated future back to its parent."""
future = copy.copy(future)
# Remove the (now) extraneous elements from future class
future.callable = future.args = future.kargs = future.greenlet = None
if not future.sendResultBack:
# Don't reply back the result if it isn't asked
future.resultValue = None
self._sendReply(
future.id.worker,
pickle.dumps(
future,
pickle.HIGHEST_PROTOCOL,
),
) | [
"def",
"sendResult",
"(",
"self",
",",
"future",
")",
":",
"future",
"=",
"copy",
".",
"copy",
"(",
"future",
")",
"# Remove the (now) extraneous elements from future class\r",
"future",
".",
"callable",
"=",
"future",
".",
"args",
"=",
"future",
".",
"kargs",
"=",
"future",
".",
"greenlet",
"=",
"None",
"if",
"not",
"future",
".",
"sendResultBack",
":",
"# Don't reply back the result if it isn't asked\r",
"future",
".",
"resultValue",
"=",
"None",
"self",
".",
"_sendReply",
"(",
"future",
".",
"id",
".",
"worker",
",",
"pickle",
".",
"dumps",
"(",
"future",
",",
"pickle",
".",
"HIGHEST_PROTOCOL",
",",
")",
",",
")"
] | Send a terminated future back to its parent. | [
"Send",
"a",
"terminated",
"future",
"back",
"to",
"its",
"parent",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scooptcp.py#L315-L332 | train |
soravux/scoop | examples/url_fetch.py | getSize | def getSize(string):
""" This functions opens a web sites and then calculate the total
size of the page in bytes. This is for the sake of the example. Do
not use this technique in real code as it is not a very bright way
to do this."""
try:
# We open the web page
with urllib.request.urlopen(string, None, 1) as f:
return sum(len(line) for line in f)
except (urllib.error.URLError, socket.timeout) as e:
return 0 | python | def getSize(string):
""" This functions opens a web sites and then calculate the total
size of the page in bytes. This is for the sake of the example. Do
not use this technique in real code as it is not a very bright way
to do this."""
try:
# We open the web page
with urllib.request.urlopen(string, None, 1) as f:
return sum(len(line) for line in f)
except (urllib.error.URLError, socket.timeout) as e:
return 0 | [
"def",
"getSize",
"(",
"string",
")",
":",
"try",
":",
"# We open the web page",
"with",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"string",
",",
"None",
",",
"1",
")",
"as",
"f",
":",
"return",
"sum",
"(",
"len",
"(",
"line",
")",
"for",
"line",
"in",
"f",
")",
"except",
"(",
"urllib",
".",
"error",
".",
"URLError",
",",
"socket",
".",
"timeout",
")",
"as",
"e",
":",
"return",
"0"
] | This functions opens a web sites and then calculate the total
size of the page in bytes. This is for the sake of the example. Do
not use this technique in real code as it is not a very bright way
to do this. | [
"This",
"functions",
"opens",
"a",
"web",
"sites",
"and",
"then",
"calculate",
"the",
"total",
"size",
"of",
"the",
"page",
"in",
"bytes",
".",
"This",
"is",
"for",
"the",
"sake",
"of",
"the",
"example",
".",
"Do",
"not",
"use",
"this",
"technique",
"in",
"real",
"code",
"as",
"it",
"is",
"not",
"a",
"very",
"bright",
"way",
"to",
"do",
"this",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/url_fetch.py#L30-L40 | train |
soravux/scoop | examples/shared_example_doc.py | getValue | def getValue(words):
"""Computes the sum of the values of the words."""
value = 0
for word in words:
for letter in word:
# shared.getConst will evaluate to the dictionary broadcasted by
# the root Future
value += shared.getConst('lettersValue')[letter]
return value | python | def getValue(words):
"""Computes the sum of the values of the words."""
value = 0
for word in words:
for letter in word:
# shared.getConst will evaluate to the dictionary broadcasted by
# the root Future
value += shared.getConst('lettersValue')[letter]
return value | [
"def",
"getValue",
"(",
"words",
")",
":",
"value",
"=",
"0",
"for",
"word",
"in",
"words",
":",
"for",
"letter",
"in",
"word",
":",
"# shared.getConst will evaluate to the dictionary broadcasted by",
"# the root Future",
"value",
"+=",
"shared",
".",
"getConst",
"(",
"'lettersValue'",
")",
"[",
"letter",
"]",
"return",
"value"
] | Computes the sum of the values of the words. | [
"Computes",
"the",
"sum",
"of",
"the",
"values",
"of",
"the",
"words",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/shared_example_doc.py#L23-L31 | train |
soravux/scoop | scoop/backports/runpy.py | _run_module_code | def _run_module_code(code, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, pkg_name=None):
"""Helper to run code in new namespace with sys modified"""
with _ModifiedArgv0(mod_fname):
with _TempModule(mod_name) as temp_module:
mod_globals = temp_module.module.__dict__
_run_code(code, mod_globals, init_globals,
mod_name, mod_fname, mod_loader, pkg_name)
# Copy the globals of the temporary module, as they
# may be cleared when the temporary module goes away
return mod_globals.copy() | python | def _run_module_code(code, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, pkg_name=None):
"""Helper to run code in new namespace with sys modified"""
with _ModifiedArgv0(mod_fname):
with _TempModule(mod_name) as temp_module:
mod_globals = temp_module.module.__dict__
_run_code(code, mod_globals, init_globals,
mod_name, mod_fname, mod_loader, pkg_name)
# Copy the globals of the temporary module, as they
# may be cleared when the temporary module goes away
return mod_globals.copy() | [
"def",
"_run_module_code",
"(",
"code",
",",
"init_globals",
"=",
"None",
",",
"mod_name",
"=",
"None",
",",
"mod_fname",
"=",
"None",
",",
"mod_loader",
"=",
"None",
",",
"pkg_name",
"=",
"None",
")",
":",
"with",
"_ModifiedArgv0",
"(",
"mod_fname",
")",
":",
"with",
"_TempModule",
"(",
"mod_name",
")",
"as",
"temp_module",
":",
"mod_globals",
"=",
"temp_module",
".",
"module",
".",
"__dict__",
"_run_code",
"(",
"code",
",",
"mod_globals",
",",
"init_globals",
",",
"mod_name",
",",
"mod_fname",
",",
"mod_loader",
",",
"pkg_name",
")",
"# Copy the globals of the temporary module, as they",
"# may be cleared when the temporary module goes away",
"return",
"mod_globals",
".",
"copy",
"(",
")"
] | Helper to run code in new namespace with sys modified | [
"Helper",
"to",
"run",
"code",
"in",
"new",
"namespace",
"with",
"sys",
"modified"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L75-L86 | train |
soravux/scoop | scoop/backports/runpy.py | run_module | def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
mod_name, loader, code, fname = _get_module_details(mod_name)
if run_name is None:
run_name = mod_name
pkg_name = mod_name.rpartition('.')[0]
if alter_sys:
return _run_module_code(code, init_globals, run_name,
fname, loader, pkg_name)
else:
# Leave the sys module alone
return _run_code(code, {}, init_globals, run_name,
fname, loader, pkg_name) | python | def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
mod_name, loader, code, fname = _get_module_details(mod_name)
if run_name is None:
run_name = mod_name
pkg_name = mod_name.rpartition('.')[0]
if alter_sys:
return _run_module_code(code, init_globals, run_name,
fname, loader, pkg_name)
else:
# Leave the sys module alone
return _run_code(code, {}, init_globals, run_name,
fname, loader, pkg_name) | [
"def",
"run_module",
"(",
"mod_name",
",",
"init_globals",
"=",
"None",
",",
"run_name",
"=",
"None",
",",
"alter_sys",
"=",
"False",
")",
":",
"mod_name",
",",
"loader",
",",
"code",
",",
"fname",
"=",
"_get_module_details",
"(",
"mod_name",
")",
"if",
"run_name",
"is",
"None",
":",
"run_name",
"=",
"mod_name",
"pkg_name",
"=",
"mod_name",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"alter_sys",
":",
"return",
"_run_module_code",
"(",
"code",
",",
"init_globals",
",",
"run_name",
",",
"fname",
",",
"loader",
",",
"pkg_name",
")",
"else",
":",
"# Leave the sys module alone",
"return",
"_run_code",
"(",
"code",
",",
"{",
"}",
",",
"init_globals",
",",
"run_name",
",",
"fname",
",",
"loader",
",",
"pkg_name",
")"
] | Execute a module's code without importing it
Returns the resulting top level namespace dictionary | [
"Execute",
"a",
"module",
"s",
"code",
"without",
"importing",
"it"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L165-L181 | train |
soravux/scoop | scoop/backports/runpy.py | _get_importer | def _get_importer(path_name):
"""Python version of PyImport_GetImporter C API function"""
cache = sys.path_importer_cache
try:
importer = cache[path_name]
except KeyError:
# Not yet cached. Flag as using the
# standard machinery until we finish
# checking the hooks
cache[path_name] = None
for hook in sys.path_hooks:
try:
importer = hook(path_name)
break
except ImportError:
pass
else:
# The following check looks a bit odd. The trick is that
# NullImporter throws ImportError if the supplied path is a
# *valid* directory entry (and hence able to be handled
# by the standard import machinery)
try:
importer = imp.NullImporter(path_name)
except ImportError:
return None
cache[path_name] = importer
return importer | python | def _get_importer(path_name):
"""Python version of PyImport_GetImporter C API function"""
cache = sys.path_importer_cache
try:
importer = cache[path_name]
except KeyError:
# Not yet cached. Flag as using the
# standard machinery until we finish
# checking the hooks
cache[path_name] = None
for hook in sys.path_hooks:
try:
importer = hook(path_name)
break
except ImportError:
pass
else:
# The following check looks a bit odd. The trick is that
# NullImporter throws ImportError if the supplied path is a
# *valid* directory entry (and hence able to be handled
# by the standard import machinery)
try:
importer = imp.NullImporter(path_name)
except ImportError:
return None
cache[path_name] = importer
return importer | [
"def",
"_get_importer",
"(",
"path_name",
")",
":",
"cache",
"=",
"sys",
".",
"path_importer_cache",
"try",
":",
"importer",
"=",
"cache",
"[",
"path_name",
"]",
"except",
"KeyError",
":",
"# Not yet cached. Flag as using the",
"# standard machinery until we finish",
"# checking the hooks",
"cache",
"[",
"path_name",
"]",
"=",
"None",
"for",
"hook",
"in",
"sys",
".",
"path_hooks",
":",
"try",
":",
"importer",
"=",
"hook",
"(",
"path_name",
")",
"break",
"except",
"ImportError",
":",
"pass",
"else",
":",
"# The following check looks a bit odd. The trick is that",
"# NullImporter throws ImportError if the supplied path is a",
"# *valid* directory entry (and hence able to be handled",
"# by the standard import machinery)",
"try",
":",
"importer",
"=",
"imp",
".",
"NullImporter",
"(",
"path_name",
")",
"except",
"ImportError",
":",
"return",
"None",
"cache",
"[",
"path_name",
"]",
"=",
"importer",
"return",
"importer"
] | Python version of PyImport_GetImporter C API function | [
"Python",
"version",
"of",
"PyImport_GetImporter",
"C",
"API",
"function"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L186-L212 | train |
soravux/scoop | scoop/backports/runpy.py | run_path | def run_path(path_name, init_globals=None, run_name=None):
"""Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script.
"""
if run_name is None:
run_name = "<run_path>"
importer = _get_importer(path_name)
if isinstance(importer, imp.NullImporter):
# Not a valid sys.path entry, so run the code directly
# execfile() doesn't help as we want to allow compiled files
code = _get_code_from_file(path_name)
return _run_module_code(code, init_globals, run_name, path_name)
else:
# Importer is defined for path, so add it to
# the start of sys.path
sys.path.insert(0, path_name)
try:
# Here's where things are a little different from the run_module
# case. There, we only had to replace the module in sys while the
# code was running and doing so was somewhat optional. Here, we
# have no choice and we have to remove it even while we read the
# code. If we don't do this, a __loader__ attribute in the
# existing __main__ module may prevent location of the new module.
main_name = "__main__"
saved_main = sys.modules[main_name]
del sys.modules[main_name]
try:
mod_name, loader, code, fname = _get_main_module_details()
finally:
sys.modules[main_name] = saved_main
pkg_name = ""
with _ModifiedArgv0(path_name):
with _TempModule(run_name) as temp_module:
mod_globals = temp_module.module.__dict__
return _run_code(code, mod_globals, init_globals,
run_name, fname, loader, pkg_name).copy()
finally:
try:
sys.path.remove(path_name)
except ValueError:
pass | python | def run_path(path_name, init_globals=None, run_name=None):
"""Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script.
"""
if run_name is None:
run_name = "<run_path>"
importer = _get_importer(path_name)
if isinstance(importer, imp.NullImporter):
# Not a valid sys.path entry, so run the code directly
# execfile() doesn't help as we want to allow compiled files
code = _get_code_from_file(path_name)
return _run_module_code(code, init_globals, run_name, path_name)
else:
# Importer is defined for path, so add it to
# the start of sys.path
sys.path.insert(0, path_name)
try:
# Here's where things are a little different from the run_module
# case. There, we only had to replace the module in sys while the
# code was running and doing so was somewhat optional. Here, we
# have no choice and we have to remove it even while we read the
# code. If we don't do this, a __loader__ attribute in the
# existing __main__ module may prevent location of the new module.
main_name = "__main__"
saved_main = sys.modules[main_name]
del sys.modules[main_name]
try:
mod_name, loader, code, fname = _get_main_module_details()
finally:
sys.modules[main_name] = saved_main
pkg_name = ""
with _ModifiedArgv0(path_name):
with _TempModule(run_name) as temp_module:
mod_globals = temp_module.module.__dict__
return _run_code(code, mod_globals, init_globals,
run_name, fname, loader, pkg_name).copy()
finally:
try:
sys.path.remove(path_name)
except ValueError:
pass | [
"def",
"run_path",
"(",
"path_name",
",",
"init_globals",
"=",
"None",
",",
"run_name",
"=",
"None",
")",
":",
"if",
"run_name",
"is",
"None",
":",
"run_name",
"=",
"\"<run_path>\"",
"importer",
"=",
"_get_importer",
"(",
"path_name",
")",
"if",
"isinstance",
"(",
"importer",
",",
"imp",
".",
"NullImporter",
")",
":",
"# Not a valid sys.path entry, so run the code directly",
"# execfile() doesn't help as we want to allow compiled files",
"code",
"=",
"_get_code_from_file",
"(",
"path_name",
")",
"return",
"_run_module_code",
"(",
"code",
",",
"init_globals",
",",
"run_name",
",",
"path_name",
")",
"else",
":",
"# Importer is defined for path, so add it to",
"# the start of sys.path",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path_name",
")",
"try",
":",
"# Here's where things are a little different from the run_module",
"# case. There, we only had to replace the module in sys while the",
"# code was running and doing so was somewhat optional. Here, we",
"# have no choice and we have to remove it even while we read the",
"# code. If we don't do this, a __loader__ attribute in the",
"# existing __main__ module may prevent location of the new module.",
"main_name",
"=",
"\"__main__\"",
"saved_main",
"=",
"sys",
".",
"modules",
"[",
"main_name",
"]",
"del",
"sys",
".",
"modules",
"[",
"main_name",
"]",
"try",
":",
"mod_name",
",",
"loader",
",",
"code",
",",
"fname",
"=",
"_get_main_module_details",
"(",
")",
"finally",
":",
"sys",
".",
"modules",
"[",
"main_name",
"]",
"=",
"saved_main",
"pkg_name",
"=",
"\"\"",
"with",
"_ModifiedArgv0",
"(",
"path_name",
")",
":",
"with",
"_TempModule",
"(",
"run_name",
")",
"as",
"temp_module",
":",
"mod_globals",
"=",
"temp_module",
".",
"module",
".",
"__dict__",
"return",
"_run_code",
"(",
"code",
",",
"mod_globals",
",",
"init_globals",
",",
"run_name",
",",
"fname",
",",
"loader",
",",
"pkg_name",
")",
".",
"copy",
"(",
")",
"finally",
":",
"try",
":",
"sys",
".",
"path",
".",
"remove",
"(",
"path_name",
")",
"except",
"ValueError",
":",
"pass"
] | Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script. | [
"Execute",
"code",
"located",
"at",
"the",
"specified",
"filesystem",
"location"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L224-L270 | train |
soravux/scoop | examples/tree_traversal.py | maxTreeDepthDivide | def maxTreeDepthDivide(rootValue, currentDepth=0, parallelLevel=2):
"""Finds a tree node that represents rootValue and computes the max depth
of this tree branch.
This function will emit new futures until currentDepth=parallelLevel"""
thisRoot = shared.getConst('myTree').search(rootValue)
if currentDepth >= parallelLevel:
return thisRoot.maxDepth(currentDepth)
else:
# Base case
if not any([thisRoot.left, thisRoot.right]):
return currentDepth
if not all([thisRoot.left, thisRoot.right]):
return thisRoot.maxDepth(currentDepth)
# Parallel recursion
return max(
futures.map(
maxTreeDepthDivide,
[
thisRoot.left.payload,
thisRoot.right.payload,
],
cycle([currentDepth + 1]),
cycle([parallelLevel]),
)
) | python | def maxTreeDepthDivide(rootValue, currentDepth=0, parallelLevel=2):
"""Finds a tree node that represents rootValue and computes the max depth
of this tree branch.
This function will emit new futures until currentDepth=parallelLevel"""
thisRoot = shared.getConst('myTree').search(rootValue)
if currentDepth >= parallelLevel:
return thisRoot.maxDepth(currentDepth)
else:
# Base case
if not any([thisRoot.left, thisRoot.right]):
return currentDepth
if not all([thisRoot.left, thisRoot.right]):
return thisRoot.maxDepth(currentDepth)
# Parallel recursion
return max(
futures.map(
maxTreeDepthDivide,
[
thisRoot.left.payload,
thisRoot.right.payload,
],
cycle([currentDepth + 1]),
cycle([parallelLevel]),
)
) | [
"def",
"maxTreeDepthDivide",
"(",
"rootValue",
",",
"currentDepth",
"=",
"0",
",",
"parallelLevel",
"=",
"2",
")",
":",
"thisRoot",
"=",
"shared",
".",
"getConst",
"(",
"'myTree'",
")",
".",
"search",
"(",
"rootValue",
")",
"if",
"currentDepth",
">=",
"parallelLevel",
":",
"return",
"thisRoot",
".",
"maxDepth",
"(",
"currentDepth",
")",
"else",
":",
"# Base case",
"if",
"not",
"any",
"(",
"[",
"thisRoot",
".",
"left",
",",
"thisRoot",
".",
"right",
"]",
")",
":",
"return",
"currentDepth",
"if",
"not",
"all",
"(",
"[",
"thisRoot",
".",
"left",
",",
"thisRoot",
".",
"right",
"]",
")",
":",
"return",
"thisRoot",
".",
"maxDepth",
"(",
"currentDepth",
")",
"# Parallel recursion",
"return",
"max",
"(",
"futures",
".",
"map",
"(",
"maxTreeDepthDivide",
",",
"[",
"thisRoot",
".",
"left",
".",
"payload",
",",
"thisRoot",
".",
"right",
".",
"payload",
",",
"]",
",",
"cycle",
"(",
"[",
"currentDepth",
"+",
"1",
"]",
")",
",",
"cycle",
"(",
"[",
"parallelLevel",
"]",
")",
",",
")",
")"
] | Finds a tree node that represents rootValue and computes the max depth
of this tree branch.
This function will emit new futures until currentDepth=parallelLevel | [
"Finds",
"a",
"tree",
"node",
"that",
"represents",
"rootValue",
"and",
"computes",
"the",
"max",
"depth",
"of",
"this",
"tree",
"branch",
".",
"This",
"function",
"will",
"emit",
"new",
"futures",
"until",
"currentDepth",
"=",
"parallelLevel"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/tree_traversal.py#L27-L52 | train |
soravux/scoop | examples/tree_traversal.py | BinaryTreeNode.insert | def insert(self, value):
"""Insert a value in the tree"""
if not self.payload or value == self.payload:
self.payload = value
else:
if value <= self.payload:
if self.left:
self.left.insert(value)
else:
self.left = BinaryTreeNode(value)
else:
if self.right:
self.right.insert(value)
else:
self.right = BinaryTreeNode(value) | python | def insert(self, value):
"""Insert a value in the tree"""
if not self.payload or value == self.payload:
self.payload = value
else:
if value <= self.payload:
if self.left:
self.left.insert(value)
else:
self.left = BinaryTreeNode(value)
else:
if self.right:
self.right.insert(value)
else:
self.right = BinaryTreeNode(value) | [
"def",
"insert",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"payload",
"or",
"value",
"==",
"self",
".",
"payload",
":",
"self",
".",
"payload",
"=",
"value",
"else",
":",
"if",
"value",
"<=",
"self",
".",
"payload",
":",
"if",
"self",
".",
"left",
":",
"self",
".",
"left",
".",
"insert",
"(",
"value",
")",
"else",
":",
"self",
".",
"left",
"=",
"BinaryTreeNode",
"(",
"value",
")",
"else",
":",
"if",
"self",
".",
"right",
":",
"self",
".",
"right",
".",
"insert",
"(",
"value",
")",
"else",
":",
"self",
".",
"right",
"=",
"BinaryTreeNode",
"(",
"value",
")"
] | Insert a value in the tree | [
"Insert",
"a",
"value",
"in",
"the",
"tree"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/tree_traversal.py#L62-L76 | train |
soravux/scoop | examples/tree_traversal.py | BinaryTreeNode.maxDepth | def maxDepth(self, currentDepth=0):
"""Compute the depth of the longest branch of the tree"""
if not any((self.left, self.right)):
return currentDepth
result = 0
for child in (self.left, self.right):
if child:
result = max(result, child.maxDepth(currentDepth + 1))
return result | python | def maxDepth(self, currentDepth=0):
"""Compute the depth of the longest branch of the tree"""
if not any((self.left, self.right)):
return currentDepth
result = 0
for child in (self.left, self.right):
if child:
result = max(result, child.maxDepth(currentDepth + 1))
return result | [
"def",
"maxDepth",
"(",
"self",
",",
"currentDepth",
"=",
"0",
")",
":",
"if",
"not",
"any",
"(",
"(",
"self",
".",
"left",
",",
"self",
".",
"right",
")",
")",
":",
"return",
"currentDepth",
"result",
"=",
"0",
"for",
"child",
"in",
"(",
"self",
".",
"left",
",",
"self",
".",
"right",
")",
":",
"if",
"child",
":",
"result",
"=",
"max",
"(",
"result",
",",
"child",
".",
"maxDepth",
"(",
"currentDepth",
"+",
"1",
")",
")",
"return",
"result"
] | Compute the depth of the longest branch of the tree | [
"Compute",
"the",
"depth",
"of",
"the",
"longest",
"branch",
"of",
"the",
"tree"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/tree_traversal.py#L78-L86 | train |
soravux/scoop | examples/tree_traversal.py | BinaryTreeNode.search | def search(self, value):
"""Find an element in the tree"""
if self.payload == value:
return self
else:
if value <= self.payload:
if self.left:
return self.left.search(value)
else:
if self.right:
return self.right.search(value)
return None | python | def search(self, value):
"""Find an element in the tree"""
if self.payload == value:
return self
else:
if value <= self.payload:
if self.left:
return self.left.search(value)
else:
if self.right:
return self.right.search(value)
return None | [
"def",
"search",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"payload",
"==",
"value",
":",
"return",
"self",
"else",
":",
"if",
"value",
"<=",
"self",
".",
"payload",
":",
"if",
"self",
".",
"left",
":",
"return",
"self",
".",
"left",
".",
"search",
"(",
"value",
")",
"else",
":",
"if",
"self",
".",
"right",
":",
"return",
"self",
".",
"right",
".",
"search",
"(",
"value",
")",
"return",
"None"
] | Find an element in the tree | [
"Find",
"an",
"element",
"in",
"the",
"tree"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/tree_traversal.py#L88-L99 | train |
soravux/scoop | scoop/_comm/scoopzmq.py | ZMQCommunicator.createZMQSocket | def createZMQSocket(self, sock_type):
"""Create a socket of the given sock_type and deactivate message dropping"""
sock = self.ZMQcontext.socket(sock_type)
sock.setsockopt(zmq.LINGER, LINGER_TIME)
sock.setsockopt(zmq.IPV4ONLY, 0)
# Remove message dropping
sock.setsockopt(zmq.SNDHWM, 0)
sock.setsockopt(zmq.RCVHWM, 0)
try:
sock.setsockopt(zmq.IMMEDIATE, 1)
except:
# This parameter was recently added by new libzmq versions
pass
# Don't accept unroutable messages
if sock_type == zmq.ROUTER:
sock.setsockopt(zmq.ROUTER_MANDATORY, 1)
return sock | python | def createZMQSocket(self, sock_type):
"""Create a socket of the given sock_type and deactivate message dropping"""
sock = self.ZMQcontext.socket(sock_type)
sock.setsockopt(zmq.LINGER, LINGER_TIME)
sock.setsockopt(zmq.IPV4ONLY, 0)
# Remove message dropping
sock.setsockopt(zmq.SNDHWM, 0)
sock.setsockopt(zmq.RCVHWM, 0)
try:
sock.setsockopt(zmq.IMMEDIATE, 1)
except:
# This parameter was recently added by new libzmq versions
pass
# Don't accept unroutable messages
if sock_type == zmq.ROUTER:
sock.setsockopt(zmq.ROUTER_MANDATORY, 1)
return sock | [
"def",
"createZMQSocket",
"(",
"self",
",",
"sock_type",
")",
":",
"sock",
"=",
"self",
".",
"ZMQcontext",
".",
"socket",
"(",
"sock_type",
")",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"LINGER_TIME",
")",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"IPV4ONLY",
",",
"0",
")",
"# Remove message dropping",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"0",
")",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVHWM",
",",
"0",
")",
"try",
":",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"IMMEDIATE",
",",
"1",
")",
"except",
":",
"# This parameter was recently added by new libzmq versions",
"pass",
"# Don't accept unroutable messages",
"if",
"sock_type",
"==",
"zmq",
".",
"ROUTER",
":",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"ROUTER_MANDATORY",
",",
"1",
")",
"return",
"sock"
] | Create a socket of the given sock_type and deactivate message dropping | [
"Create",
"a",
"socket",
"of",
"the",
"given",
"sock_type",
"and",
"deactivate",
"message",
"dropping"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scoopzmq.py#L164-L182 | train |
soravux/scoop | scoop/_comm/scoopzmq.py | ZMQCommunicator._reportFutures | def _reportFutures(self):
"""Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread."""
try:
while True:
time.sleep(scoop.TIME_BETWEEN_STATUS_REPORTS)
fids = set(x.id for x in scoop._control.execQueue.movable)
fids.update(set(x.id for x in scoop._control.execQueue.ready))
fids.update(set(x.id for x in scoop._control.execQueue.inprogress))
self.socket.send_multipart([
STATUS_UPDATE,
pickle.dumps(fids),
])
except AttributeError:
# The process is being shut down.
pass | python | def _reportFutures(self):
"""Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread."""
try:
while True:
time.sleep(scoop.TIME_BETWEEN_STATUS_REPORTS)
fids = set(x.id for x in scoop._control.execQueue.movable)
fids.update(set(x.id for x in scoop._control.execQueue.ready))
fids.update(set(x.id for x in scoop._control.execQueue.inprogress))
self.socket.send_multipart([
STATUS_UPDATE,
pickle.dumps(fids),
])
except AttributeError:
# The process is being shut down.
pass | [
"def",
"_reportFutures",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"scoop",
".",
"TIME_BETWEEN_STATUS_REPORTS",
")",
"fids",
"=",
"set",
"(",
"x",
".",
"id",
"for",
"x",
"in",
"scoop",
".",
"_control",
".",
"execQueue",
".",
"movable",
")",
"fids",
".",
"update",
"(",
"set",
"(",
"x",
".",
"id",
"for",
"x",
"in",
"scoop",
".",
"_control",
".",
"execQueue",
".",
"ready",
")",
")",
"fids",
".",
"update",
"(",
"set",
"(",
"x",
".",
"id",
"for",
"x",
"in",
"scoop",
".",
"_control",
".",
"execQueue",
".",
"inprogress",
")",
")",
"self",
".",
"socket",
".",
"send_multipart",
"(",
"[",
"STATUS_UPDATE",
",",
"pickle",
".",
"dumps",
"(",
"fids",
")",
",",
"]",
")",
"except",
"AttributeError",
":",
"# The process is being shut down.",
"pass"
] | Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread. | [
"Sends",
"futures",
"status",
"updates",
"to",
"broker",
"at",
"intervals",
"of",
"scoop",
".",
"TIME_BETWEEN_STATUS_REPORTS",
"seconds",
".",
"Is",
"intended",
"to",
"be",
"run",
"by",
"a",
"separate",
"thread",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scoopzmq.py#L184-L200 | train |
soravux/scoop | scoop/_comm/scoopzmq.py | ZMQCommunicator._sendReply | def _sendReply(self, destination, fid, *args):
"""Send a REPLY directly to its destination. If it doesn't work, launch
it back to the broker."""
# Try to send the result directly to its parent
self.addPeer(destination)
try:
self.direct_socket.send_multipart([
destination,
REPLY,
] + list(args),
flags=zmq.NOBLOCK)
except zmq.error.ZMQError as e:
# Fallback on Broker routing if no direct connection possible
scoop.logger.debug(
"{0}: Could not send result directly to peer {1}, routing through "
"broker.".format(scoop.worker, destination)
)
self.socket.send_multipart([
REPLY,
] + list(args) + [
destination,
])
self.socket.send_multipart([
STATUS_DONE,
fid,
]) | python | def _sendReply(self, destination, fid, *args):
"""Send a REPLY directly to its destination. If it doesn't work, launch
it back to the broker."""
# Try to send the result directly to its parent
self.addPeer(destination)
try:
self.direct_socket.send_multipart([
destination,
REPLY,
] + list(args),
flags=zmq.NOBLOCK)
except zmq.error.ZMQError as e:
# Fallback on Broker routing if no direct connection possible
scoop.logger.debug(
"{0}: Could not send result directly to peer {1}, routing through "
"broker.".format(scoop.worker, destination)
)
self.socket.send_multipart([
REPLY,
] + list(args) + [
destination,
])
self.socket.send_multipart([
STATUS_DONE,
fid,
]) | [
"def",
"_sendReply",
"(",
"self",
",",
"destination",
",",
"fid",
",",
"*",
"args",
")",
":",
"# Try to send the result directly to its parent",
"self",
".",
"addPeer",
"(",
"destination",
")",
"try",
":",
"self",
".",
"direct_socket",
".",
"send_multipart",
"(",
"[",
"destination",
",",
"REPLY",
",",
"]",
"+",
"list",
"(",
"args",
")",
",",
"flags",
"=",
"zmq",
".",
"NOBLOCK",
")",
"except",
"zmq",
".",
"error",
".",
"ZMQError",
"as",
"e",
":",
"# Fallback on Broker routing if no direct connection possible",
"scoop",
".",
"logger",
".",
"debug",
"(",
"\"{0}: Could not send result directly to peer {1}, routing through \"",
"\"broker.\"",
".",
"format",
"(",
"scoop",
".",
"worker",
",",
"destination",
")",
")",
"self",
".",
"socket",
".",
"send_multipart",
"(",
"[",
"REPLY",
",",
"]",
"+",
"list",
"(",
"args",
")",
"+",
"[",
"destination",
",",
"]",
")",
"self",
".",
"socket",
".",
"send_multipart",
"(",
"[",
"STATUS_DONE",
",",
"fid",
",",
"]",
")"
] | Send a REPLY directly to its destination. If it doesn't work, launch
it back to the broker. | [
"Send",
"a",
"REPLY",
"directly",
"to",
"its",
"destination",
".",
"If",
"it",
"doesn",
"t",
"work",
"launch",
"it",
"back",
"to",
"the",
"broker",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scoopzmq.py#L399-L426 | train |
soravux/scoop | scoop/futures.py | _startup | def _startup(rootFuture, *args, **kargs):
"""Initializes the SCOOP environment.
:param rootFuture: Any callable object (function or class object with *__call__*
method); this object will be called once and allows the use of parallel
calls inside this object.
:param args: A tuple of positional arguments that will be passed to the
callable object.
:param kargs: A dictionary of additional keyword arguments that will be
passed to the callable object.
:returns: The result of the root Future.
Be sure to launch your root Future using this method."""
import greenlet
global _controller
_controller = greenlet.greenlet(control.runController)
try:
result = _controller.switch(rootFuture, *args, **kargs)
except scoop._comm.Shutdown:
result = None
control.execQueue.shutdown()
return result | python | def _startup(rootFuture, *args, **kargs):
"""Initializes the SCOOP environment.
:param rootFuture: Any callable object (function or class object with *__call__*
method); this object will be called once and allows the use of parallel
calls inside this object.
:param args: A tuple of positional arguments that will be passed to the
callable object.
:param kargs: A dictionary of additional keyword arguments that will be
passed to the callable object.
:returns: The result of the root Future.
Be sure to launch your root Future using this method."""
import greenlet
global _controller
_controller = greenlet.greenlet(control.runController)
try:
result = _controller.switch(rootFuture, *args, **kargs)
except scoop._comm.Shutdown:
result = None
control.execQueue.shutdown()
return result | [
"def",
"_startup",
"(",
"rootFuture",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"import",
"greenlet",
"global",
"_controller",
"_controller",
"=",
"greenlet",
".",
"greenlet",
"(",
"control",
".",
"runController",
")",
"try",
":",
"result",
"=",
"_controller",
".",
"switch",
"(",
"rootFuture",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"except",
"scoop",
".",
"_comm",
".",
"Shutdown",
":",
"result",
"=",
"None",
"control",
".",
"execQueue",
".",
"shutdown",
"(",
")",
"return",
"result"
] | Initializes the SCOOP environment.
:param rootFuture: Any callable object (function or class object with *__call__*
method); this object will be called once and allows the use of parallel
calls inside this object.
:param args: A tuple of positional arguments that will be passed to the
callable object.
:param kargs: A dictionary of additional keyword arguments that will be
passed to the callable object.
:returns: The result of the root Future.
Be sure to launch your root Future using this method. | [
"Initializes",
"the",
"SCOOP",
"environment",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L47-L69 | train |
soravux/scoop | scoop/futures.py | _recursiveReduce | def _recursiveReduce(mapFunc, reductionFunc, scan, *iterables):
"""Generates the recursive reduction tree. Used by mapReduce."""
if iterables:
half = min(len(x) // 2 for x in iterables)
data_left = [list(x)[:half] for x in iterables]
data_right = [list(x)[half:] for x in iterables]
else:
data_left = data_right = [[]]
# Submit the left and right parts of the reduction
out_futures = [None, None]
out_results = [None, None]
for index, data in enumerate([data_left, data_right]):
if any(len(x) <= 1 for x in data):
out_results[index] = mapFunc(*list(zip(*data))[0])
else:
out_futures[index] = submit(
_recursiveReduce,
mapFunc,
reductionFunc,
scan,
*data
)
# Wait for the results
for index, future in enumerate(out_futures):
if future:
out_results[index] = future.result()
# Apply a scan if needed
if scan:
last_results = copy.copy(out_results)
if type(out_results[0]) is not list:
out_results[0] = [out_results[0]]
else:
last_results[0] = out_results[0][-1]
if type(out_results[1]) is list:
out_results[0].extend(out_results[1][:-1])
last_results[1] = out_results[1][-1]
out_results[0].append(reductionFunc(*last_results))
return out_results[0]
return reductionFunc(*out_results) | python | def _recursiveReduce(mapFunc, reductionFunc, scan, *iterables):
"""Generates the recursive reduction tree. Used by mapReduce."""
if iterables:
half = min(len(x) // 2 for x in iterables)
data_left = [list(x)[:half] for x in iterables]
data_right = [list(x)[half:] for x in iterables]
else:
data_left = data_right = [[]]
# Submit the left and right parts of the reduction
out_futures = [None, None]
out_results = [None, None]
for index, data in enumerate([data_left, data_right]):
if any(len(x) <= 1 for x in data):
out_results[index] = mapFunc(*list(zip(*data))[0])
else:
out_futures[index] = submit(
_recursiveReduce,
mapFunc,
reductionFunc,
scan,
*data
)
# Wait for the results
for index, future in enumerate(out_futures):
if future:
out_results[index] = future.result()
# Apply a scan if needed
if scan:
last_results = copy.copy(out_results)
if type(out_results[0]) is not list:
out_results[0] = [out_results[0]]
else:
last_results[0] = out_results[0][-1]
if type(out_results[1]) is list:
out_results[0].extend(out_results[1][:-1])
last_results[1] = out_results[1][-1]
out_results[0].append(reductionFunc(*last_results))
return out_results[0]
return reductionFunc(*out_results) | [
"def",
"_recursiveReduce",
"(",
"mapFunc",
",",
"reductionFunc",
",",
"scan",
",",
"*",
"iterables",
")",
":",
"if",
"iterables",
":",
"half",
"=",
"min",
"(",
"len",
"(",
"x",
")",
"//",
"2",
"for",
"x",
"in",
"iterables",
")",
"data_left",
"=",
"[",
"list",
"(",
"x",
")",
"[",
":",
"half",
"]",
"for",
"x",
"in",
"iterables",
"]",
"data_right",
"=",
"[",
"list",
"(",
"x",
")",
"[",
"half",
":",
"]",
"for",
"x",
"in",
"iterables",
"]",
"else",
":",
"data_left",
"=",
"data_right",
"=",
"[",
"[",
"]",
"]",
"# Submit the left and right parts of the reduction",
"out_futures",
"=",
"[",
"None",
",",
"None",
"]",
"out_results",
"=",
"[",
"None",
",",
"None",
"]",
"for",
"index",
",",
"data",
"in",
"enumerate",
"(",
"[",
"data_left",
",",
"data_right",
"]",
")",
":",
"if",
"any",
"(",
"len",
"(",
"x",
")",
"<=",
"1",
"for",
"x",
"in",
"data",
")",
":",
"out_results",
"[",
"index",
"]",
"=",
"mapFunc",
"(",
"*",
"list",
"(",
"zip",
"(",
"*",
"data",
")",
")",
"[",
"0",
"]",
")",
"else",
":",
"out_futures",
"[",
"index",
"]",
"=",
"submit",
"(",
"_recursiveReduce",
",",
"mapFunc",
",",
"reductionFunc",
",",
"scan",
",",
"*",
"data",
")",
"# Wait for the results",
"for",
"index",
",",
"future",
"in",
"enumerate",
"(",
"out_futures",
")",
":",
"if",
"future",
":",
"out_results",
"[",
"index",
"]",
"=",
"future",
".",
"result",
"(",
")",
"# Apply a scan if needed",
"if",
"scan",
":",
"last_results",
"=",
"copy",
".",
"copy",
"(",
"out_results",
")",
"if",
"type",
"(",
"out_results",
"[",
"0",
"]",
")",
"is",
"not",
"list",
":",
"out_results",
"[",
"0",
"]",
"=",
"[",
"out_results",
"[",
"0",
"]",
"]",
"else",
":",
"last_results",
"[",
"0",
"]",
"=",
"out_results",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"if",
"type",
"(",
"out_results",
"[",
"1",
"]",
")",
"is",
"list",
":",
"out_results",
"[",
"0",
"]",
".",
"extend",
"(",
"out_results",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
")",
"last_results",
"[",
"1",
"]",
"=",
"out_results",
"[",
"1",
"]",
"[",
"-",
"1",
"]",
"out_results",
"[",
"0",
"]",
".",
"append",
"(",
"reductionFunc",
"(",
"*",
"last_results",
")",
")",
"return",
"out_results",
"[",
"0",
"]",
"return",
"reductionFunc",
"(",
"*",
"out_results",
")"
] | Generates the recursive reduction tree. Used by mapReduce. | [
"Generates",
"the",
"recursive",
"reduction",
"tree",
".",
"Used",
"by",
"mapReduce",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L154-L196 | train |
soravux/scoop | scoop/futures.py | _createFuture | def _createFuture(func, *args, **kwargs):
"""Helper function to create a future."""
assert callable(func), (
"The provided func parameter is not a callable."
)
if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules:
sys.modules["SCOOP_WORKER"] = sys.modules["__main__"]
# If function is a lambda or class method, share it (or its parent object)
# beforehand
lambdaType = type(lambda: None)
funcIsLambda = isinstance(func, lambdaType) and func.__name__ == '<lambda>'
# Determine if function is a method. Methods derived from external
# languages such as C++ aren't detected by ismethod.
funcIsMethod = ismethod(func)
if funcIsLambda or funcIsMethod:
from .shared import SharedElementEncapsulation
func = SharedElementEncapsulation(func)
return Future(control.current.id, func, *args, **kwargs) | python | def _createFuture(func, *args, **kwargs):
"""Helper function to create a future."""
assert callable(func), (
"The provided func parameter is not a callable."
)
if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules:
sys.modules["SCOOP_WORKER"] = sys.modules["__main__"]
# If function is a lambda or class method, share it (or its parent object)
# beforehand
lambdaType = type(lambda: None)
funcIsLambda = isinstance(func, lambdaType) and func.__name__ == '<lambda>'
# Determine if function is a method. Methods derived from external
# languages such as C++ aren't detected by ismethod.
funcIsMethod = ismethod(func)
if funcIsLambda or funcIsMethod:
from .shared import SharedElementEncapsulation
func = SharedElementEncapsulation(func)
return Future(control.current.id, func, *args, **kwargs) | [
"def",
"_createFuture",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"callable",
"(",
"func",
")",
",",
"(",
"\"The provided func parameter is not a callable.\"",
")",
"if",
"scoop",
".",
"IS_ORIGIN",
"and",
"\"SCOOP_WORKER\"",
"not",
"in",
"sys",
".",
"modules",
":",
"sys",
".",
"modules",
"[",
"\"SCOOP_WORKER\"",
"]",
"=",
"sys",
".",
"modules",
"[",
"\"__main__\"",
"]",
"# If function is a lambda or class method, share it (or its parent object)",
"# beforehand",
"lambdaType",
"=",
"type",
"(",
"lambda",
":",
"None",
")",
"funcIsLambda",
"=",
"isinstance",
"(",
"func",
",",
"lambdaType",
")",
"and",
"func",
".",
"__name__",
"==",
"'<lambda>'",
"# Determine if function is a method. Methods derived from external",
"# languages such as C++ aren't detected by ismethod.",
"funcIsMethod",
"=",
"ismethod",
"(",
"func",
")",
"if",
"funcIsLambda",
"or",
"funcIsMethod",
":",
"from",
".",
"shared",
"import",
"SharedElementEncapsulation",
"func",
"=",
"SharedElementEncapsulation",
"(",
"func",
")",
"return",
"Future",
"(",
"control",
".",
"current",
".",
"id",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Helper function to create a future. | [
"Helper",
"function",
"to",
"create",
"a",
"future",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L259-L279 | train |
soravux/scoop | scoop/futures.py | _waitAny | def _waitAny(*children):
"""Waits on any child Future created by the calling Future.
:param children: A tuple of children Future objects spawned by the calling
Future.
:return: A generator function that iterates on futures that are done.
The generator produces results of the children in a non deterministic order
that depends on the particular parallel execution of the Futures. The
generator returns a tuple as soon as one becomes available."""
n = len(children)
# check for available results and index those unavailable
for index, future in enumerate(children):
if future.exceptionValue:
raise future.exceptionValue
if future._ended():
future._delete()
yield future
n -= 1
else:
future.index = index
future = control.current
while n > 0:
# wait for remaining results; switch to controller
future.stopWatch.halt()
childFuture = _controller.switch(future)
future.stopWatch.resume()
if childFuture.exceptionValue:
raise childFuture.exceptionValue
# Only yield if executed future was in children, otherwise loop
if childFuture in children:
childFuture._delete()
yield childFuture
n -= 1 | python | def _waitAny(*children):
"""Waits on any child Future created by the calling Future.
:param children: A tuple of children Future objects spawned by the calling
Future.
:return: A generator function that iterates on futures that are done.
The generator produces results of the children in a non deterministic order
that depends on the particular parallel execution of the Futures. The
generator returns a tuple as soon as one becomes available."""
n = len(children)
# check for available results and index those unavailable
for index, future in enumerate(children):
if future.exceptionValue:
raise future.exceptionValue
if future._ended():
future._delete()
yield future
n -= 1
else:
future.index = index
future = control.current
while n > 0:
# wait for remaining results; switch to controller
future.stopWatch.halt()
childFuture = _controller.switch(future)
future.stopWatch.resume()
if childFuture.exceptionValue:
raise childFuture.exceptionValue
# Only yield if executed future was in children, otherwise loop
if childFuture in children:
childFuture._delete()
yield childFuture
n -= 1 | [
"def",
"_waitAny",
"(",
"*",
"children",
")",
":",
"n",
"=",
"len",
"(",
"children",
")",
"# check for available results and index those unavailable",
"for",
"index",
",",
"future",
"in",
"enumerate",
"(",
"children",
")",
":",
"if",
"future",
".",
"exceptionValue",
":",
"raise",
"future",
".",
"exceptionValue",
"if",
"future",
".",
"_ended",
"(",
")",
":",
"future",
".",
"_delete",
"(",
")",
"yield",
"future",
"n",
"-=",
"1",
"else",
":",
"future",
".",
"index",
"=",
"index",
"future",
"=",
"control",
".",
"current",
"while",
"n",
">",
"0",
":",
"# wait for remaining results; switch to controller",
"future",
".",
"stopWatch",
".",
"halt",
"(",
")",
"childFuture",
"=",
"_controller",
".",
"switch",
"(",
"future",
")",
"future",
".",
"stopWatch",
".",
"resume",
"(",
")",
"if",
"childFuture",
".",
"exceptionValue",
":",
"raise",
"childFuture",
".",
"exceptionValue",
"# Only yield if executed future was in children, otherwise loop",
"if",
"childFuture",
"in",
"children",
":",
"childFuture",
".",
"_delete",
"(",
")",
"yield",
"childFuture",
"n",
"-=",
"1"
] | Waits on any child Future created by the calling Future.
:param children: A tuple of children Future objects spawned by the calling
Future.
:return: A generator function that iterates on futures that are done.
The generator produces results of the children in a non deterministic order
that depends on the particular parallel execution of the Futures. The
generator returns a tuple as soon as one becomes available. | [
"Waits",
"on",
"any",
"child",
"Future",
"created",
"by",
"the",
"calling",
"Future",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L308-L342 | train |
soravux/scoop | scoop/futures.py | wait | def wait(fs, timeout=-1, return_when=ALL_COMPLETED):
"""Wait for the futures in the given sequence to complete.
Using this function may prevent a worker from executing.
:param fs: The sequence of Futures to wait upon.
:param timeout: The maximum number of seconds to wait. If negative or not
specified, then there is no limit on the wait time.
:param return_when: Indicates when this function should return. The options
are:
=============== ================================================
FIRST_COMPLETED Return when any future finishes or is cancelled.
FIRST_EXCEPTION Return when any future finishes by raising an
exception. If no future raises an exception then
it is equivalent to ALL_COMPLETED.
ALL_COMPLETED Return when all futures finish or are cancelled.
=============== ================================================
:return: A named 2-tuple of sets. The first set, named 'done', contains the
futures that completed (is finished or cancelled) before the wait
completed. The second set, named 'not_done', contains uncompleted
futures."""
DoneAndNotDoneFutures = namedtuple('DoneAndNotDoneFutures', 'done not_done')
if timeout < 0:
# Negative timeout means blocking.
if return_when == FIRST_COMPLETED:
next(_waitAny(*fs))
elif return_when in [ALL_COMPLETED, FIRST_EXCEPTION]:
for _ in _waitAll(*fs):
pass
done = set(f for f in fs if f.done())
not_done = set(fs) - done
return DoneAndNotDoneFutures(done, not_done)
elif timeout == 0:
# Zero-value entry means non-blocking
control.execQueue.flush()
control.execQueue.updateQueue()
done = set(f for f in fs if f._ended())
not_done = set(fs) - done
return DoneAndNotDoneFutures(done, not_done)
else:
# Any other value means blocking for a given time.
done = set()
start_time = time.time()
while time.time() - start_time < timeout:
# Flush futures on local queue (to be executed remotely)
control.execQueue.flush()
# Block until data arrives (to free CPU time)
control.execQueue.socket._poll(time.time() - start_time)
# Update queue
control.execQueue.updateQueue()
for f in fs:
if f._ended():
done.add(f)
not_done = set(fs) - done
if return_when == FIRST_COMPLETED and len(done) > 0:
break
if len(not_done) == 0:
break
return DoneAndNotDoneFutures(done, not_done) | python | def wait(fs, timeout=-1, return_when=ALL_COMPLETED):
"""Wait for the futures in the given sequence to complete.
Using this function may prevent a worker from executing.
:param fs: The sequence of Futures to wait upon.
:param timeout: The maximum number of seconds to wait. If negative or not
specified, then there is no limit on the wait time.
:param return_when: Indicates when this function should return. The options
are:
=============== ================================================
FIRST_COMPLETED Return when any future finishes or is cancelled.
FIRST_EXCEPTION Return when any future finishes by raising an
exception. If no future raises an exception then
it is equivalent to ALL_COMPLETED.
ALL_COMPLETED Return when all futures finish or are cancelled.
=============== ================================================
:return: A named 2-tuple of sets. The first set, named 'done', contains the
futures that completed (is finished or cancelled) before the wait
completed. The second set, named 'not_done', contains uncompleted
futures."""
DoneAndNotDoneFutures = namedtuple('DoneAndNotDoneFutures', 'done not_done')
if timeout < 0:
# Negative timeout means blocking.
if return_when == FIRST_COMPLETED:
next(_waitAny(*fs))
elif return_when in [ALL_COMPLETED, FIRST_EXCEPTION]:
for _ in _waitAll(*fs):
pass
done = set(f for f in fs if f.done())
not_done = set(fs) - done
return DoneAndNotDoneFutures(done, not_done)
elif timeout == 0:
# Zero-value entry means non-blocking
control.execQueue.flush()
control.execQueue.updateQueue()
done = set(f for f in fs if f._ended())
not_done = set(fs) - done
return DoneAndNotDoneFutures(done, not_done)
else:
# Any other value means blocking for a given time.
done = set()
start_time = time.time()
while time.time() - start_time < timeout:
# Flush futures on local queue (to be executed remotely)
control.execQueue.flush()
# Block until data arrives (to free CPU time)
control.execQueue.socket._poll(time.time() - start_time)
# Update queue
control.execQueue.updateQueue()
for f in fs:
if f._ended():
done.add(f)
not_done = set(fs) - done
if return_when == FIRST_COMPLETED and len(done) > 0:
break
if len(not_done) == 0:
break
return DoneAndNotDoneFutures(done, not_done) | [
"def",
"wait",
"(",
"fs",
",",
"timeout",
"=",
"-",
"1",
",",
"return_when",
"=",
"ALL_COMPLETED",
")",
":",
"DoneAndNotDoneFutures",
"=",
"namedtuple",
"(",
"'DoneAndNotDoneFutures'",
",",
"'done not_done'",
")",
"if",
"timeout",
"<",
"0",
":",
"# Negative timeout means blocking.",
"if",
"return_when",
"==",
"FIRST_COMPLETED",
":",
"next",
"(",
"_waitAny",
"(",
"*",
"fs",
")",
")",
"elif",
"return_when",
"in",
"[",
"ALL_COMPLETED",
",",
"FIRST_EXCEPTION",
"]",
":",
"for",
"_",
"in",
"_waitAll",
"(",
"*",
"fs",
")",
":",
"pass",
"done",
"=",
"set",
"(",
"f",
"for",
"f",
"in",
"fs",
"if",
"f",
".",
"done",
"(",
")",
")",
"not_done",
"=",
"set",
"(",
"fs",
")",
"-",
"done",
"return",
"DoneAndNotDoneFutures",
"(",
"done",
",",
"not_done",
")",
"elif",
"timeout",
"==",
"0",
":",
"# Zero-value entry means non-blocking",
"control",
".",
"execQueue",
".",
"flush",
"(",
")",
"control",
".",
"execQueue",
".",
"updateQueue",
"(",
")",
"done",
"=",
"set",
"(",
"f",
"for",
"f",
"in",
"fs",
"if",
"f",
".",
"_ended",
"(",
")",
")",
"not_done",
"=",
"set",
"(",
"fs",
")",
"-",
"done",
"return",
"DoneAndNotDoneFutures",
"(",
"done",
",",
"not_done",
")",
"else",
":",
"# Any other value means blocking for a given time.",
"done",
"=",
"set",
"(",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"<",
"timeout",
":",
"# Flush futures on local queue (to be executed remotely)",
"control",
".",
"execQueue",
".",
"flush",
"(",
")",
"# Block until data arrives (to free CPU time)",
"control",
".",
"execQueue",
".",
"socket",
".",
"_poll",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"# Update queue",
"control",
".",
"execQueue",
".",
"updateQueue",
"(",
")",
"for",
"f",
"in",
"fs",
":",
"if",
"f",
".",
"_ended",
"(",
")",
":",
"done",
".",
"add",
"(",
"f",
")",
"not_done",
"=",
"set",
"(",
"fs",
")",
"-",
"done",
"if",
"return_when",
"==",
"FIRST_COMPLETED",
"and",
"len",
"(",
"done",
")",
">",
"0",
":",
"break",
"if",
"len",
"(",
"not_done",
")",
"==",
"0",
":",
"break",
"return",
"DoneAndNotDoneFutures",
"(",
"done",
",",
"not_done",
")"
] | Wait for the futures in the given sequence to complete.
Using this function may prevent a worker from executing.
:param fs: The sequence of Futures to wait upon.
:param timeout: The maximum number of seconds to wait. If negative or not
specified, then there is no limit on the wait time.
:param return_when: Indicates when this function should return. The options
are:
=============== ================================================
FIRST_COMPLETED Return when any future finishes or is cancelled.
FIRST_EXCEPTION Return when any future finishes by raising an
exception. If no future raises an exception then
it is equivalent to ALL_COMPLETED.
ALL_COMPLETED Return when all futures finish or are cancelled.
=============== ================================================
:return: A named 2-tuple of sets. The first set, named 'done', contains the
futures that completed (is finished or cancelled) before the wait
completed. The second set, named 'not_done', contains uncompleted
futures. | [
"Wait",
"for",
"the",
"futures",
"in",
"the",
"given",
"sequence",
"to",
"complete",
".",
"Using",
"this",
"function",
"may",
"prevent",
"a",
"worker",
"from",
"executing",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L364-L429 | train |
soravux/scoop | scoop/_control.py | advertiseBrokerWorkerDown | def advertiseBrokerWorkerDown(exctype, value, traceback):
"""Hook advertizing the broker if an impromptu shutdown is occuring."""
if not scoop.SHUTDOWN_REQUESTED:
execQueue.shutdown()
sys.__excepthook__(exctype, value, traceback) | python | def advertiseBrokerWorkerDown(exctype, value, traceback):
"""Hook advertizing the broker if an impromptu shutdown is occuring."""
if not scoop.SHUTDOWN_REQUESTED:
execQueue.shutdown()
sys.__excepthook__(exctype, value, traceback) | [
"def",
"advertiseBrokerWorkerDown",
"(",
"exctype",
",",
"value",
",",
"traceback",
")",
":",
"if",
"not",
"scoop",
".",
"SHUTDOWN_REQUESTED",
":",
"execQueue",
".",
"shutdown",
"(",
")",
"sys",
".",
"__excepthook__",
"(",
"exctype",
",",
"value",
",",
"traceback",
")"
] | Hook advertizing the broker if an impromptu shutdown is occuring. | [
"Hook",
"advertizing",
"the",
"broker",
"if",
"an",
"impromptu",
"shutdown",
"is",
"occuring",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L91-L95 | train |
soravux/scoop | scoop/_control.py | delFutureById | def delFutureById(futureId, parentId):
"""Delete future on id basis"""
try:
del futureDict[futureId]
except KeyError:
pass
try:
toDel = [a for a in futureDict[parentId].children if a.id == futureId]
for f in toDel:
del futureDict[parentId].children[f]
except KeyError:
pass | python | def delFutureById(futureId, parentId):
"""Delete future on id basis"""
try:
del futureDict[futureId]
except KeyError:
pass
try:
toDel = [a for a in futureDict[parentId].children if a.id == futureId]
for f in toDel:
del futureDict[parentId].children[f]
except KeyError:
pass | [
"def",
"delFutureById",
"(",
"futureId",
",",
"parentId",
")",
":",
"try",
":",
"del",
"futureDict",
"[",
"futureId",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"toDel",
"=",
"[",
"a",
"for",
"a",
"in",
"futureDict",
"[",
"parentId",
"]",
".",
"children",
"if",
"a",
".",
"id",
"==",
"futureId",
"]",
"for",
"f",
"in",
"toDel",
":",
"del",
"futureDict",
"[",
"parentId",
"]",
".",
"children",
"[",
"f",
"]",
"except",
"KeyError",
":",
"pass"
] | Delete future on id basis | [
"Delete",
"future",
"on",
"id",
"basis"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L108-L119 | train |
soravux/scoop | scoop/_control.py | delFuture | def delFuture(afuture):
"""Delete future afuture"""
try:
del futureDict[afuture.id]
except KeyError:
pass
try:
del futureDict[afuture.parentId].children[afuture]
except KeyError:
pass | python | def delFuture(afuture):
"""Delete future afuture"""
try:
del futureDict[afuture.id]
except KeyError:
pass
try:
del futureDict[afuture.parentId].children[afuture]
except KeyError:
pass | [
"def",
"delFuture",
"(",
"afuture",
")",
":",
"try",
":",
"del",
"futureDict",
"[",
"afuture",
".",
"id",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"del",
"futureDict",
"[",
"afuture",
".",
"parentId",
"]",
".",
"children",
"[",
"afuture",
"]",
"except",
"KeyError",
":",
"pass"
] | Delete future afuture | [
"Delete",
"future",
"afuture"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L122-L131 | train |
soravux/scoop | scoop/_control.py | runFuture | def runFuture(future):
"""Callable greenlet in charge of running tasks."""
global debug_stats
global QueueLength
if scoop.DEBUG:
init_debug() # in case _control is imported before scoop.DEBUG was set
debug_stats[future.id]['start_time'].append(time.time())
future.waitTime = future.stopWatch.get()
future.stopWatch.reset()
# Get callback Group ID and assign the broker-wide unique executor ID
try:
uniqueReference = [cb.groupID for cb in future.callback][0]
except IndexError:
uniqueReference = None
future.executor = (scoop.worker, uniqueReference)
try:
future.resultValue = future.callable(*future.args, **future.kargs)
except BaseException as err:
future.exceptionValue = err
future.exceptionTraceback = str(traceback.format_exc())
scoop.logger.debug(
"The following error occured on a worker:\n%r\n%s",
err,
traceback.format_exc(),
)
future.executionTime = future.stopWatch.get()
future.isDone = True
# Update the worker inner work statistics
if future.executionTime != 0. and hasattr(future.callable, '__name__'):
execStats[hash(future.callable)].appendleft(future.executionTime)
# Set debugging informations if needed
if scoop.DEBUG:
t = time.time()
debug_stats[future.id]['end_time'].append(t)
debug_stats[future.id].update({
'executionTime': future.executionTime,
'worker': scoop.worker,
'creationTime': future.creationTime,
'callable': str(future.callable.__name__)
if hasattr(future.callable, '__name__')
else 'No name',
'parent': future.parentId
})
QueueLength.append((t, len(execQueue), execQueue.timelen(execQueue)))
# Run callback (see http://www.python.org/dev/peps/pep-3148/#future-objects)
future._execute_callbacks(CallbackType.universal)
# Delete references to the future
future._delete()
return future | python | def runFuture(future):
"""Callable greenlet in charge of running tasks."""
global debug_stats
global QueueLength
if scoop.DEBUG:
init_debug() # in case _control is imported before scoop.DEBUG was set
debug_stats[future.id]['start_time'].append(time.time())
future.waitTime = future.stopWatch.get()
future.stopWatch.reset()
# Get callback Group ID and assign the broker-wide unique executor ID
try:
uniqueReference = [cb.groupID for cb in future.callback][0]
except IndexError:
uniqueReference = None
future.executor = (scoop.worker, uniqueReference)
try:
future.resultValue = future.callable(*future.args, **future.kargs)
except BaseException as err:
future.exceptionValue = err
future.exceptionTraceback = str(traceback.format_exc())
scoop.logger.debug(
"The following error occured on a worker:\n%r\n%s",
err,
traceback.format_exc(),
)
future.executionTime = future.stopWatch.get()
future.isDone = True
# Update the worker inner work statistics
if future.executionTime != 0. and hasattr(future.callable, '__name__'):
execStats[hash(future.callable)].appendleft(future.executionTime)
# Set debugging informations if needed
if scoop.DEBUG:
t = time.time()
debug_stats[future.id]['end_time'].append(t)
debug_stats[future.id].update({
'executionTime': future.executionTime,
'worker': scoop.worker,
'creationTime': future.creationTime,
'callable': str(future.callable.__name__)
if hasattr(future.callable, '__name__')
else 'No name',
'parent': future.parentId
})
QueueLength.append((t, len(execQueue), execQueue.timelen(execQueue)))
# Run callback (see http://www.python.org/dev/peps/pep-3148/#future-objects)
future._execute_callbacks(CallbackType.universal)
# Delete references to the future
future._delete()
return future | [
"def",
"runFuture",
"(",
"future",
")",
":",
"global",
"debug_stats",
"global",
"QueueLength",
"if",
"scoop",
".",
"DEBUG",
":",
"init_debug",
"(",
")",
"# in case _control is imported before scoop.DEBUG was set",
"debug_stats",
"[",
"future",
".",
"id",
"]",
"[",
"'start_time'",
"]",
".",
"append",
"(",
"time",
".",
"time",
"(",
")",
")",
"future",
".",
"waitTime",
"=",
"future",
".",
"stopWatch",
".",
"get",
"(",
")",
"future",
".",
"stopWatch",
".",
"reset",
"(",
")",
"# Get callback Group ID and assign the broker-wide unique executor ID",
"try",
":",
"uniqueReference",
"=",
"[",
"cb",
".",
"groupID",
"for",
"cb",
"in",
"future",
".",
"callback",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"uniqueReference",
"=",
"None",
"future",
".",
"executor",
"=",
"(",
"scoop",
".",
"worker",
",",
"uniqueReference",
")",
"try",
":",
"future",
".",
"resultValue",
"=",
"future",
".",
"callable",
"(",
"*",
"future",
".",
"args",
",",
"*",
"*",
"future",
".",
"kargs",
")",
"except",
"BaseException",
"as",
"err",
":",
"future",
".",
"exceptionValue",
"=",
"err",
"future",
".",
"exceptionTraceback",
"=",
"str",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"scoop",
".",
"logger",
".",
"debug",
"(",
"\"The following error occured on a worker:\\n%r\\n%s\"",
",",
"err",
",",
"traceback",
".",
"format_exc",
"(",
")",
",",
")",
"future",
".",
"executionTime",
"=",
"future",
".",
"stopWatch",
".",
"get",
"(",
")",
"future",
".",
"isDone",
"=",
"True",
"# Update the worker inner work statistics",
"if",
"future",
".",
"executionTime",
"!=",
"0.",
"and",
"hasattr",
"(",
"future",
".",
"callable",
",",
"'__name__'",
")",
":",
"execStats",
"[",
"hash",
"(",
"future",
".",
"callable",
")",
"]",
".",
"appendleft",
"(",
"future",
".",
"executionTime",
")",
"# Set debugging informations if needed",
"if",
"scoop",
".",
"DEBUG",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"debug_stats",
"[",
"future",
".",
"id",
"]",
"[",
"'end_time'",
"]",
".",
"append",
"(",
"t",
")",
"debug_stats",
"[",
"future",
".",
"id",
"]",
".",
"update",
"(",
"{",
"'executionTime'",
":",
"future",
".",
"executionTime",
",",
"'worker'",
":",
"scoop",
".",
"worker",
",",
"'creationTime'",
":",
"future",
".",
"creationTime",
",",
"'callable'",
":",
"str",
"(",
"future",
".",
"callable",
".",
"__name__",
")",
"if",
"hasattr",
"(",
"future",
".",
"callable",
",",
"'__name__'",
")",
"else",
"'No name'",
",",
"'parent'",
":",
"future",
".",
"parentId",
"}",
")",
"QueueLength",
".",
"append",
"(",
"(",
"t",
",",
"len",
"(",
"execQueue",
")",
",",
"execQueue",
".",
"timelen",
"(",
"execQueue",
")",
")",
")",
"# Run callback (see http://www.python.org/dev/peps/pep-3148/#future-objects)",
"future",
".",
"_execute_callbacks",
"(",
"CallbackType",
".",
"universal",
")",
"# Delete references to the future",
"future",
".",
"_delete",
"(",
")",
"return",
"future"
] | Callable greenlet in charge of running tasks. | [
"Callable",
"greenlet",
"in",
"charge",
"of",
"running",
"tasks",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L134-L187 | train |
soravux/scoop | scoop/_control.py | runController | def runController(callable_, *args, **kargs):
"""Callable greenlet implementing controller logic."""
global execQueue
# initialize and run root future
rootId = (-1, 0)
# initialise queue
if execQueue is None:
execQueue = FutureQueue()
sys.excepthook = advertiseBrokerWorkerDown
if scoop.DEBUG:
from scoop import _debug
_debug.redirectSTDOUTtoDebugFile()
# TODO: Make that a function
# Wait until we received the main module if we are a headless slave
headless = scoop.CONFIGURATION.get("headless", False)
if not scoop.MAIN_MODULE:
# If we're not the origin and still don't have our main_module,
# wait for it and then import it as module __main___
main = scoop.shared.getConst('__MAIN_MODULE__', timeout=float('inf'))
directory_name = tempfile.mkdtemp()
os.chdir(directory_name)
scoop.MAIN_MODULE = main.writeFile(directory_name)
from .bootstrap.__main__ import Bootstrap as SCOOPBootstrap
newModule = SCOOPBootstrap.setupEnvironment()
sys.modules['__main__'] = newModule
elif scoop.IS_ORIGIN and headless and scoop.MAIN_MODULE:
# We're the origin, share our main_module
scoop.shared.setConst(
__MAIN_MODULE__=scoop.encapsulation.ExternalEncapsulation(
scoop.MAIN_MODULE,
)
)
# TODO: use modulefinder to share every local dependency of
# main module
# launch future if origin or try to pickup a future if slave worker
if scoop.IS_ORIGIN:
future = Future(rootId, callable_, *args, **kargs)
else:
future = execQueue.pop()
future.greenlet = greenlet.greenlet(runFuture)
future = future._switch(future)
if scoop.DEBUG:
lastDebugTs = time.time()
while not scoop.IS_ORIGIN or future.parentId != rootId or not future._ended():
if scoop.DEBUG and time.time() - lastDebugTs > scoop.TIME_BETWEEN_PARTIALDEBUG:
_debug.writeWorkerDebug(
debug_stats,
QueueLength,
"debug/partial-{0}".format(
round(time.time(), -1)
)
)
lastDebugTs = time.time()
# process future
if future._ended():
# future is finished
if future.id[0] != scoop.worker:
# future is not local
execQueue.sendResult(future)
future = execQueue.pop()
else:
# future is local, parent is waiting
if future.index is not None:
try:
parent = futureDict[future.parentId]
except KeyError:
# Job has no parent here (probably children restart)
future = execQueue.pop()
else:
if parent.exceptionValue is None:
future = parent._switch(future)
else:
future = execQueue.pop()
else:
future = execQueue.pop()
else:
# future is in progress; run next future from pending execution queue.
future = execQueue.pop()
if not future._ended() and future.greenlet is None:
# initialize if the future hasn't started
future.greenlet = greenlet.greenlet(runFuture)
future = future._switch(future)
execQueue.shutdown()
if future.exceptionValue:
print(future.exceptionTraceback)
sys.exit(1)
return future.resultValue | python | def runController(callable_, *args, **kargs):
"""Callable greenlet implementing controller logic."""
global execQueue
# initialize and run root future
rootId = (-1, 0)
# initialise queue
if execQueue is None:
execQueue = FutureQueue()
sys.excepthook = advertiseBrokerWorkerDown
if scoop.DEBUG:
from scoop import _debug
_debug.redirectSTDOUTtoDebugFile()
# TODO: Make that a function
# Wait until we received the main module if we are a headless slave
headless = scoop.CONFIGURATION.get("headless", False)
if not scoop.MAIN_MODULE:
# If we're not the origin and still don't have our main_module,
# wait for it and then import it as module __main___
main = scoop.shared.getConst('__MAIN_MODULE__', timeout=float('inf'))
directory_name = tempfile.mkdtemp()
os.chdir(directory_name)
scoop.MAIN_MODULE = main.writeFile(directory_name)
from .bootstrap.__main__ import Bootstrap as SCOOPBootstrap
newModule = SCOOPBootstrap.setupEnvironment()
sys.modules['__main__'] = newModule
elif scoop.IS_ORIGIN and headless and scoop.MAIN_MODULE:
# We're the origin, share our main_module
scoop.shared.setConst(
__MAIN_MODULE__=scoop.encapsulation.ExternalEncapsulation(
scoop.MAIN_MODULE,
)
)
# TODO: use modulefinder to share every local dependency of
# main module
# launch future if origin or try to pickup a future if slave worker
if scoop.IS_ORIGIN:
future = Future(rootId, callable_, *args, **kargs)
else:
future = execQueue.pop()
future.greenlet = greenlet.greenlet(runFuture)
future = future._switch(future)
if scoop.DEBUG:
lastDebugTs = time.time()
while not scoop.IS_ORIGIN or future.parentId != rootId or not future._ended():
if scoop.DEBUG and time.time() - lastDebugTs > scoop.TIME_BETWEEN_PARTIALDEBUG:
_debug.writeWorkerDebug(
debug_stats,
QueueLength,
"debug/partial-{0}".format(
round(time.time(), -1)
)
)
lastDebugTs = time.time()
# process future
if future._ended():
# future is finished
if future.id[0] != scoop.worker:
# future is not local
execQueue.sendResult(future)
future = execQueue.pop()
else:
# future is local, parent is waiting
if future.index is not None:
try:
parent = futureDict[future.parentId]
except KeyError:
# Job has no parent here (probably children restart)
future = execQueue.pop()
else:
if parent.exceptionValue is None:
future = parent._switch(future)
else:
future = execQueue.pop()
else:
future = execQueue.pop()
else:
# future is in progress; run next future from pending execution queue.
future = execQueue.pop()
if not future._ended() and future.greenlet is None:
# initialize if the future hasn't started
future.greenlet = greenlet.greenlet(runFuture)
future = future._switch(future)
execQueue.shutdown()
if future.exceptionValue:
print(future.exceptionTraceback)
sys.exit(1)
return future.resultValue | [
"def",
"runController",
"(",
"callable_",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"global",
"execQueue",
"# initialize and run root future",
"rootId",
"=",
"(",
"-",
"1",
",",
"0",
")",
"# initialise queue",
"if",
"execQueue",
"is",
"None",
":",
"execQueue",
"=",
"FutureQueue",
"(",
")",
"sys",
".",
"excepthook",
"=",
"advertiseBrokerWorkerDown",
"if",
"scoop",
".",
"DEBUG",
":",
"from",
"scoop",
"import",
"_debug",
"_debug",
".",
"redirectSTDOUTtoDebugFile",
"(",
")",
"# TODO: Make that a function",
"# Wait until we received the main module if we are a headless slave",
"headless",
"=",
"scoop",
".",
"CONFIGURATION",
".",
"get",
"(",
"\"headless\"",
",",
"False",
")",
"if",
"not",
"scoop",
".",
"MAIN_MODULE",
":",
"# If we're not the origin and still don't have our main_module,",
"# wait for it and then import it as module __main___",
"main",
"=",
"scoop",
".",
"shared",
".",
"getConst",
"(",
"'__MAIN_MODULE__'",
",",
"timeout",
"=",
"float",
"(",
"'inf'",
")",
")",
"directory_name",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"os",
".",
"chdir",
"(",
"directory_name",
")",
"scoop",
".",
"MAIN_MODULE",
"=",
"main",
".",
"writeFile",
"(",
"directory_name",
")",
"from",
".",
"bootstrap",
".",
"__main__",
"import",
"Bootstrap",
"as",
"SCOOPBootstrap",
"newModule",
"=",
"SCOOPBootstrap",
".",
"setupEnvironment",
"(",
")",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"=",
"newModule",
"elif",
"scoop",
".",
"IS_ORIGIN",
"and",
"headless",
"and",
"scoop",
".",
"MAIN_MODULE",
":",
"# We're the origin, share our main_module",
"scoop",
".",
"shared",
".",
"setConst",
"(",
"__MAIN_MODULE__",
"=",
"scoop",
".",
"encapsulation",
".",
"ExternalEncapsulation",
"(",
"scoop",
".",
"MAIN_MODULE",
",",
")",
")",
"# TODO: use modulefinder to share every local dependency of",
"# main module",
"# launch future if origin or try to pickup a future if slave worker",
"if",
"scoop",
".",
"IS_ORIGIN",
":",
"future",
"=",
"Future",
"(",
"rootId",
",",
"callable_",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"else",
":",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"future",
".",
"greenlet",
"=",
"greenlet",
".",
"greenlet",
"(",
"runFuture",
")",
"future",
"=",
"future",
".",
"_switch",
"(",
"future",
")",
"if",
"scoop",
".",
"DEBUG",
":",
"lastDebugTs",
"=",
"time",
".",
"time",
"(",
")",
"while",
"not",
"scoop",
".",
"IS_ORIGIN",
"or",
"future",
".",
"parentId",
"!=",
"rootId",
"or",
"not",
"future",
".",
"_ended",
"(",
")",
":",
"if",
"scoop",
".",
"DEBUG",
"and",
"time",
".",
"time",
"(",
")",
"-",
"lastDebugTs",
">",
"scoop",
".",
"TIME_BETWEEN_PARTIALDEBUG",
":",
"_debug",
".",
"writeWorkerDebug",
"(",
"debug_stats",
",",
"QueueLength",
",",
"\"debug/partial-{0}\"",
".",
"format",
"(",
"round",
"(",
"time",
".",
"time",
"(",
")",
",",
"-",
"1",
")",
")",
")",
"lastDebugTs",
"=",
"time",
".",
"time",
"(",
")",
"# process future",
"if",
"future",
".",
"_ended",
"(",
")",
":",
"# future is finished",
"if",
"future",
".",
"id",
"[",
"0",
"]",
"!=",
"scoop",
".",
"worker",
":",
"# future is not local",
"execQueue",
".",
"sendResult",
"(",
"future",
")",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"else",
":",
"# future is local, parent is waiting",
"if",
"future",
".",
"index",
"is",
"not",
"None",
":",
"try",
":",
"parent",
"=",
"futureDict",
"[",
"future",
".",
"parentId",
"]",
"except",
"KeyError",
":",
"# Job has no parent here (probably children restart)",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"else",
":",
"if",
"parent",
".",
"exceptionValue",
"is",
"None",
":",
"future",
"=",
"parent",
".",
"_switch",
"(",
"future",
")",
"else",
":",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"else",
":",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"else",
":",
"# future is in progress; run next future from pending execution queue.",
"future",
"=",
"execQueue",
".",
"pop",
"(",
")",
"if",
"not",
"future",
".",
"_ended",
"(",
")",
"and",
"future",
".",
"greenlet",
"is",
"None",
":",
"# initialize if the future hasn't started",
"future",
".",
"greenlet",
"=",
"greenlet",
".",
"greenlet",
"(",
"runFuture",
")",
"future",
"=",
"future",
".",
"_switch",
"(",
"future",
")",
"execQueue",
".",
"shutdown",
"(",
")",
"if",
"future",
".",
"exceptionValue",
":",
"print",
"(",
"future",
".",
"exceptionTraceback",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"future",
".",
"resultValue"
] | Callable greenlet implementing controller logic. | [
"Callable",
"greenlet",
"implementing",
"controller",
"logic",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L190-L287 | train |
soravux/scoop | scoop/_control.py | _stat.mode | def mode(self):
"""Computes the mode of a log-normal distribution built with the stats data."""
mu = self.mean()
sigma = self.std()
ret_val = math.exp(mu - sigma**2)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val | python | def mode(self):
"""Computes the mode of a log-normal distribution built with the stats data."""
mu = self.mean()
sigma = self.std()
ret_val = math.exp(mu - sigma**2)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val | [
"def",
"mode",
"(",
"self",
")",
":",
"mu",
"=",
"self",
".",
"mean",
"(",
")",
"sigma",
"=",
"self",
".",
"std",
"(",
")",
"ret_val",
"=",
"math",
".",
"exp",
"(",
"mu",
"-",
"sigma",
"**",
"2",
")",
"if",
"math",
".",
"isnan",
"(",
"ret_val",
")",
":",
"ret_val",
"=",
"float",
"(",
"\"inf\"",
")",
"return",
"ret_val"
] | Computes the mode of a log-normal distribution built with the stats data. | [
"Computes",
"the",
"mode",
"of",
"a",
"log",
"-",
"normal",
"distribution",
"built",
"with",
"the",
"stats",
"data",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L73-L80 | train |
soravux/scoop | scoop/_control.py | _stat.median | def median(self):
"""Computes the median of a log-normal distribution built with the stats data."""
mu = self.mean()
ret_val = math.exp(mu)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val | python | def median(self):
"""Computes the median of a log-normal distribution built with the stats data."""
mu = self.mean()
ret_val = math.exp(mu)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val | [
"def",
"median",
"(",
"self",
")",
":",
"mu",
"=",
"self",
".",
"mean",
"(",
")",
"ret_val",
"=",
"math",
".",
"exp",
"(",
"mu",
")",
"if",
"math",
".",
"isnan",
"(",
"ret_val",
")",
":",
"ret_val",
"=",
"float",
"(",
"\"inf\"",
")",
"return",
"ret_val"
] | Computes the median of a log-normal distribution built with the stats data. | [
"Computes",
"the",
"median",
"of",
"a",
"log",
"-",
"normal",
"distribution",
"built",
"with",
"the",
"stats",
"data",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L82-L88 | train |
soravux/scoop | scoop/discovery/minusconf.py | _decode_string | def _decode_string(buf, pos):
""" Decodes a string in the buffer buf, starting at position pos.
Returns a tupel of the read string and the next byte to read.
"""
for i in range(pos, len(buf)):
if buf[i:i+1] == _compat_bytes('\x00'):
try:
return (buf[pos:i].decode(_CHARSET), i+1)
# Uncomment the following two lines for detailled information
#except UnicodeDecodeError as ude:
# raise MinusconfError(str(ude))
except UnicodeDecodeError:
raise MinusconfError('Not a valid ' + _CHARSET + ' string: ' + repr(buf[pos:i]))
raise MinusconfError("Premature end of string (Forgot trailing \\0?), buf=" + repr(buf)) | python | def _decode_string(buf, pos):
""" Decodes a string in the buffer buf, starting at position pos.
Returns a tupel of the read string and the next byte to read.
"""
for i in range(pos, len(buf)):
if buf[i:i+1] == _compat_bytes('\x00'):
try:
return (buf[pos:i].decode(_CHARSET), i+1)
# Uncomment the following two lines for detailled information
#except UnicodeDecodeError as ude:
# raise MinusconfError(str(ude))
except UnicodeDecodeError:
raise MinusconfError('Not a valid ' + _CHARSET + ' string: ' + repr(buf[pos:i]))
raise MinusconfError("Premature end of string (Forgot trailing \\0?), buf=" + repr(buf)) | [
"def",
"_decode_string",
"(",
"buf",
",",
"pos",
")",
":",
"for",
"i",
"in",
"range",
"(",
"pos",
",",
"len",
"(",
"buf",
")",
")",
":",
"if",
"buf",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"==",
"_compat_bytes",
"(",
"'\\x00'",
")",
":",
"try",
":",
"return",
"(",
"buf",
"[",
"pos",
":",
"i",
"]",
".",
"decode",
"(",
"_CHARSET",
")",
",",
"i",
"+",
"1",
")",
"# Uncomment the following two lines for detailled information",
"#except UnicodeDecodeError as ude:",
"# raise MinusconfError(str(ude))",
"except",
"UnicodeDecodeError",
":",
"raise",
"MinusconfError",
"(",
"'Not a valid '",
"+",
"_CHARSET",
"+",
"' string: '",
"+",
"repr",
"(",
"buf",
"[",
"pos",
":",
"i",
"]",
")",
")",
"raise",
"MinusconfError",
"(",
"\"Premature end of string (Forgot trailing \\\\0?), buf=\"",
"+",
"repr",
"(",
"buf",
")",
")"
] | Decodes a string in the buffer buf, starting at position pos.
Returns a tupel of the read string and the next byte to read. | [
"Decodes",
"a",
"string",
"in",
"the",
"buffer",
"buf",
"starting",
"at",
"position",
"pos",
".",
"Returns",
"a",
"tupel",
"of",
"the",
"read",
"string",
"and",
"the",
"next",
"byte",
"to",
"read",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L492-L506 | train |
soravux/scoop | scoop/discovery/minusconf.py | _find_sock | def _find_sock():
""" Create a UDP socket """
if socket.has_ipv6:
try:
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
except socket.gaierror:
pass # Platform lied about IPv6 support
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | python | def _find_sock():
""" Create a UDP socket """
if socket.has_ipv6:
try:
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
except socket.gaierror:
pass # Platform lied about IPv6 support
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | [
"def",
"_find_sock",
"(",
")",
":",
"if",
"socket",
".",
"has_ipv6",
":",
"try",
":",
"return",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET6",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"except",
"socket",
".",
"gaierror",
":",
"pass",
"# Platform lied about IPv6 support",
"return",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")"
] | Create a UDP socket | [
"Create",
"a",
"UDP",
"socket"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L556-L563 | train |
soravux/scoop | scoop/discovery/minusconf.py | _compat_inet_pton | def _compat_inet_pton(family, addr):
""" socket.inet_pton for platforms that don't have it """
if family == socket.AF_INET:
# inet_aton accepts some strange forms, so we use our own
res = _compat_bytes('')
parts = addr.split('.')
if len(parts) != 4:
raise ValueError('Expected 4 dot-separated numbers')
for part in parts:
intval = int(part, 10)
if intval < 0 or intval > 0xff:
raise ValueError("Invalid integer value in IPv4 address: " + str(intval))
res = res + struct.pack('!B', intval)
return res
elif family == socket.AF_INET6:
wordcount = 8
res = _compat_bytes('')
# IPv4 embedded?
dotpos = addr.find('.')
if dotpos >= 0:
v4start = addr.rfind(':', 0, dotpos)
if v4start == -1:
raise ValueException("Missing colons in an IPv6 address")
wordcount = 6
res = socket.inet_aton(addr[v4start+1:])
addr = addr[:v4start] + '!' # We leave a marker that the address is not finished
# Compact version?
compact_pos = addr.find('::')
if compact_pos >= 0:
if compact_pos == 0:
addr = '0' + addr
compact_pos += 1
if compact_pos == len(addr)-len('::'):
addr = addr + '0'
addr = (addr[:compact_pos] + ':' +
('0:' * (wordcount - (addr.count(':') - '::'.count(':')) - 2))
+ addr[compact_pos + len('::'):])
# Remove any dots we left
if addr.endswith('!'):
addr = addr[:-len('!')]
words = addr.split(':')
if len(words) != wordcount:
raise ValueError('Invalid number of IPv6 hextets, expected ' + str(wordcount) + ', got ' + str(len(words)))
for w in reversed(words):
# 0x and negative is not valid here, but accepted by int(,16)
if 'x' in w or '-' in w:
raise ValueError("Invalid character in IPv6 address")
intval = int(w, 16)
if intval > 0xffff:
raise ValueError("IPv6 address componenent too big")
res = struct.pack('!H', intval) + res
return res
else:
raise ValueError("Unknown protocol family " + family) | python | def _compat_inet_pton(family, addr):
""" socket.inet_pton for platforms that don't have it """
if family == socket.AF_INET:
# inet_aton accepts some strange forms, so we use our own
res = _compat_bytes('')
parts = addr.split('.')
if len(parts) != 4:
raise ValueError('Expected 4 dot-separated numbers')
for part in parts:
intval = int(part, 10)
if intval < 0 or intval > 0xff:
raise ValueError("Invalid integer value in IPv4 address: " + str(intval))
res = res + struct.pack('!B', intval)
return res
elif family == socket.AF_INET6:
wordcount = 8
res = _compat_bytes('')
# IPv4 embedded?
dotpos = addr.find('.')
if dotpos >= 0:
v4start = addr.rfind(':', 0, dotpos)
if v4start == -1:
raise ValueException("Missing colons in an IPv6 address")
wordcount = 6
res = socket.inet_aton(addr[v4start+1:])
addr = addr[:v4start] + '!' # We leave a marker that the address is not finished
# Compact version?
compact_pos = addr.find('::')
if compact_pos >= 0:
if compact_pos == 0:
addr = '0' + addr
compact_pos += 1
if compact_pos == len(addr)-len('::'):
addr = addr + '0'
addr = (addr[:compact_pos] + ':' +
('0:' * (wordcount - (addr.count(':') - '::'.count(':')) - 2))
+ addr[compact_pos + len('::'):])
# Remove any dots we left
if addr.endswith('!'):
addr = addr[:-len('!')]
words = addr.split(':')
if len(words) != wordcount:
raise ValueError('Invalid number of IPv6 hextets, expected ' + str(wordcount) + ', got ' + str(len(words)))
for w in reversed(words):
# 0x and negative is not valid here, but accepted by int(,16)
if 'x' in w or '-' in w:
raise ValueError("Invalid character in IPv6 address")
intval = int(w, 16)
if intval > 0xffff:
raise ValueError("IPv6 address componenent too big")
res = struct.pack('!H', intval) + res
return res
else:
raise ValueError("Unknown protocol family " + family) | [
"def",
"_compat_inet_pton",
"(",
"family",
",",
"addr",
")",
":",
"if",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"# inet_aton accepts some strange forms, so we use our own",
"res",
"=",
"_compat_bytes",
"(",
"''",
")",
"parts",
"=",
"addr",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"'Expected 4 dot-separated numbers'",
")",
"for",
"part",
"in",
"parts",
":",
"intval",
"=",
"int",
"(",
"part",
",",
"10",
")",
"if",
"intval",
"<",
"0",
"or",
"intval",
">",
"0xff",
":",
"raise",
"ValueError",
"(",
"\"Invalid integer value in IPv4 address: \"",
"+",
"str",
"(",
"intval",
")",
")",
"res",
"=",
"res",
"+",
"struct",
".",
"pack",
"(",
"'!B'",
",",
"intval",
")",
"return",
"res",
"elif",
"family",
"==",
"socket",
".",
"AF_INET6",
":",
"wordcount",
"=",
"8",
"res",
"=",
"_compat_bytes",
"(",
"''",
")",
"# IPv4 embedded?",
"dotpos",
"=",
"addr",
".",
"find",
"(",
"'.'",
")",
"if",
"dotpos",
">=",
"0",
":",
"v4start",
"=",
"addr",
".",
"rfind",
"(",
"':'",
",",
"0",
",",
"dotpos",
")",
"if",
"v4start",
"==",
"-",
"1",
":",
"raise",
"ValueException",
"(",
"\"Missing colons in an IPv6 address\"",
")",
"wordcount",
"=",
"6",
"res",
"=",
"socket",
".",
"inet_aton",
"(",
"addr",
"[",
"v4start",
"+",
"1",
":",
"]",
")",
"addr",
"=",
"addr",
"[",
":",
"v4start",
"]",
"+",
"'!'",
"# We leave a marker that the address is not finished",
"# Compact version?",
"compact_pos",
"=",
"addr",
".",
"find",
"(",
"'::'",
")",
"if",
"compact_pos",
">=",
"0",
":",
"if",
"compact_pos",
"==",
"0",
":",
"addr",
"=",
"'0'",
"+",
"addr",
"compact_pos",
"+=",
"1",
"if",
"compact_pos",
"==",
"len",
"(",
"addr",
")",
"-",
"len",
"(",
"'::'",
")",
":",
"addr",
"=",
"addr",
"+",
"'0'",
"addr",
"=",
"(",
"addr",
"[",
":",
"compact_pos",
"]",
"+",
"':'",
"+",
"(",
"'0:'",
"*",
"(",
"wordcount",
"-",
"(",
"addr",
".",
"count",
"(",
"':'",
")",
"-",
"'::'",
".",
"count",
"(",
"':'",
")",
")",
"-",
"2",
")",
")",
"+",
"addr",
"[",
"compact_pos",
"+",
"len",
"(",
"'::'",
")",
":",
"]",
")",
"# Remove any dots we left",
"if",
"addr",
".",
"endswith",
"(",
"'!'",
")",
":",
"addr",
"=",
"addr",
"[",
":",
"-",
"len",
"(",
"'!'",
")",
"]",
"words",
"=",
"addr",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"words",
")",
"!=",
"wordcount",
":",
"raise",
"ValueError",
"(",
"'Invalid number of IPv6 hextets, expected '",
"+",
"str",
"(",
"wordcount",
")",
"+",
"', got '",
"+",
"str",
"(",
"len",
"(",
"words",
")",
")",
")",
"for",
"w",
"in",
"reversed",
"(",
"words",
")",
":",
"# 0x and negative is not valid here, but accepted by int(,16)",
"if",
"'x'",
"in",
"w",
"or",
"'-'",
"in",
"w",
":",
"raise",
"ValueError",
"(",
"\"Invalid character in IPv6 address\"",
")",
"intval",
"=",
"int",
"(",
"w",
",",
"16",
")",
"if",
"intval",
">",
"0xffff",
":",
"raise",
"ValueError",
"(",
"\"IPv6 address componenent too big\"",
")",
"res",
"=",
"struct",
".",
"pack",
"(",
"'!H'",
",",
"intval",
")",
"+",
"res",
"return",
"res",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown protocol family \"",
"+",
"family",
")"
] | socket.inet_pton for platforms that don't have it | [
"socket",
".",
"inet_pton",
"for",
"platforms",
"that",
"don",
"t",
"have",
"it"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L623-L688 | train |
soravux/scoop | scoop/discovery/minusconf.py | ConcurrentAdvertiser.start_blocking | def start_blocking(self):
""" Start the advertiser in the background, but wait until it is ready """
self._cav_started.clear()
self.start()
self._cav_started.wait() | python | def start_blocking(self):
""" Start the advertiser in the background, but wait until it is ready """
self._cav_started.clear()
self.start()
self._cav_started.wait() | [
"def",
"start_blocking",
"(",
"self",
")",
":",
"self",
".",
"_cav_started",
".",
"clear",
"(",
")",
"self",
".",
"start",
"(",
")",
"self",
".",
"_cav_started",
".",
"wait",
"(",
")"
] | Start the advertiser in the background, but wait until it is ready | [
"Start",
"the",
"advertiser",
"in",
"the",
"background",
"but",
"wait",
"until",
"it",
"is",
"ready"
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L243-L248 | train |
soravux/scoop | scoop/discovery/minusconf.py | Seeker._send_queries | def _send_queries(self):
""" Sends queries to multiple addresses. Returns the number of successful queries. """
res = 0
addrs = _resolve_addrs(self.addresses, self.port, self.ignore_senderrors, [self._sock.family])
for addr in addrs:
try:
self._send_query(addr[1])
res += 1
except:
if not self.ignore_senderrors:
raise
return res | python | def _send_queries(self):
""" Sends queries to multiple addresses. Returns the number of successful queries. """
res = 0
addrs = _resolve_addrs(self.addresses, self.port, self.ignore_senderrors, [self._sock.family])
for addr in addrs:
try:
self._send_query(addr[1])
res += 1
except:
if not self.ignore_senderrors:
raise
return res | [
"def",
"_send_queries",
"(",
"self",
")",
":",
"res",
"=",
"0",
"addrs",
"=",
"_resolve_addrs",
"(",
"self",
".",
"addresses",
",",
"self",
".",
"port",
",",
"self",
".",
"ignore_senderrors",
",",
"[",
"self",
".",
"_sock",
".",
"family",
"]",
")",
"for",
"addr",
"in",
"addrs",
":",
"try",
":",
"self",
".",
"_send_query",
"(",
"addr",
"[",
"1",
"]",
")",
"res",
"+=",
"1",
"except",
":",
"if",
"not",
"self",
".",
"ignore_senderrors",
":",
"raise",
"return",
"res"
] | Sends queries to multiple addresses. Returns the number of successful queries. | [
"Sends",
"queries",
"to",
"multiple",
"addresses",
".",
"Returns",
"the",
"number",
"of",
"successful",
"queries",
"."
] | d391dfa62f47e49d48328ee9cf08aa114256fd33 | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L383-L397 | train |
dmpayton/django-admin-honeypot | admin_honeypot/forms.py | HoneypotLoginForm.clean | def clean(self):
"""
Always raise the default error message, because we don't
care what they entered here.
"""
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name}
) | python | def clean(self):
"""
Always raise the default error message, because we don't
care what they entered here.
"""
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name}
) | [
"def",
"clean",
"(",
"self",
")",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'invalid_login'",
"]",
",",
"code",
"=",
"'invalid_login'",
",",
"params",
"=",
"{",
"'username'",
":",
"self",
".",
"username_field",
".",
"verbose_name",
"}",
")"
] | Always raise the default error message, because we don't
care what they entered here. | [
"Always",
"raise",
"the",
"default",
"error",
"message",
"because",
"we",
"don",
"t",
"care",
"what",
"they",
"entered",
"here",
"."
] | 1308e5f794cd3b3b3c517e0ed96070bb1d656ce3 | https://github.com/dmpayton/django-admin-honeypot/blob/1308e5f794cd3b3b3c517e0ed96070bb1d656ce3/admin_honeypot/forms.py#L7-L16 | train |
deadpixi/contracts | dpcontracts.py | types | def types(**requirements):
"""
Specify a precondition based on the types of the function's
arguments.
"""
def predicate(args):
for name, kind in sorted(requirements.items()):
assert hasattr(args, name), "missing required argument `%s`" % name
if not isinstance(kind, tuple):
kind = (kind,)
if not any(isinstance(getattr(args, name), k) for k in kind):
return False
return True
return condition("the types of arguments must be valid", predicate, True) | python | def types(**requirements):
"""
Specify a precondition based on the types of the function's
arguments.
"""
def predicate(args):
for name, kind in sorted(requirements.items()):
assert hasattr(args, name), "missing required argument `%s`" % name
if not isinstance(kind, tuple):
kind = (kind,)
if not any(isinstance(getattr(args, name), k) for k in kind):
return False
return True
return condition("the types of arguments must be valid", predicate, True) | [
"def",
"types",
"(",
"*",
"*",
"requirements",
")",
":",
"def",
"predicate",
"(",
"args",
")",
":",
"for",
"name",
",",
"kind",
"in",
"sorted",
"(",
"requirements",
".",
"items",
"(",
")",
")",
":",
"assert",
"hasattr",
"(",
"args",
",",
"name",
")",
",",
"\"missing required argument `%s`\"",
"%",
"name",
"if",
"not",
"isinstance",
"(",
"kind",
",",
"tuple",
")",
":",
"kind",
"=",
"(",
"kind",
",",
")",
"if",
"not",
"any",
"(",
"isinstance",
"(",
"getattr",
"(",
"args",
",",
"name",
")",
",",
"k",
")",
"for",
"k",
"in",
"kind",
")",
":",
"return",
"False",
"return",
"True",
"return",
"condition",
"(",
"\"the types of arguments must be valid\"",
",",
"predicate",
",",
"True",
")"
] | Specify a precondition based on the types of the function's
arguments. | [
"Specify",
"a",
"precondition",
"based",
"on",
"the",
"types",
"of",
"the",
"function",
"s",
"arguments",
"."
] | 45cb8542272c2ebe095c6efb97aa9407ddc8bf3c | https://github.com/deadpixi/contracts/blob/45cb8542272c2ebe095c6efb97aa9407ddc8bf3c/dpcontracts.py#L701-L719 | train |
deadpixi/contracts | dpcontracts.py | ensure | def ensure(arg1, arg2=None):
"""
Specify a precondition described by `description` and tested by
`predicate`.
"""
assert (isinstance(arg1, str) and isfunction(arg2)) or (isfunction(arg1) and arg2 is None)
description = ""
predicate = lambda x: x
if isinstance(arg1, str):
description = arg1
predicate = arg2
else:
description = get_function_source(arg1)
predicate = arg1
return condition(description, predicate, False, True) | python | def ensure(arg1, arg2=None):
"""
Specify a precondition described by `description` and tested by
`predicate`.
"""
assert (isinstance(arg1, str) and isfunction(arg2)) or (isfunction(arg1) and arg2 is None)
description = ""
predicate = lambda x: x
if isinstance(arg1, str):
description = arg1
predicate = arg2
else:
description = get_function_source(arg1)
predicate = arg1
return condition(description, predicate, False, True) | [
"def",
"ensure",
"(",
"arg1",
",",
"arg2",
"=",
"None",
")",
":",
"assert",
"(",
"isinstance",
"(",
"arg1",
",",
"str",
")",
"and",
"isfunction",
"(",
"arg2",
")",
")",
"or",
"(",
"isfunction",
"(",
"arg1",
")",
"and",
"arg2",
"is",
"None",
")",
"description",
"=",
"\"\"",
"predicate",
"=",
"lambda",
"x",
":",
"x",
"if",
"isinstance",
"(",
"arg1",
",",
"str",
")",
":",
"description",
"=",
"arg1",
"predicate",
"=",
"arg2",
"else",
":",
"description",
"=",
"get_function_source",
"(",
"arg1",
")",
"predicate",
"=",
"arg1",
"return",
"condition",
"(",
"description",
",",
"predicate",
",",
"False",
",",
"True",
")"
] | Specify a precondition described by `description` and tested by
`predicate`. | [
"Specify",
"a",
"precondition",
"described",
"by",
"description",
"and",
"tested",
"by",
"predicate",
"."
] | 45cb8542272c2ebe095c6efb97aa9407ddc8bf3c | https://github.com/deadpixi/contracts/blob/45cb8542272c2ebe095c6efb97aa9407ddc8bf3c/dpcontracts.py#L721-L739 | train |
deadpixi/contracts | dpcontracts.py | invariant | def invariant(arg1, arg2=None):
"""
Specify a class invariant described by `description` and tested
by `predicate`.
"""
desc = ""
predicate = lambda x: x
if isinstance(arg1, str):
desc = arg1
predicate = arg2
else:
desc = get_function_source(arg1)
predicate = arg1
def invariant(c):
def check(name, func):
exceptions = ("__getitem__", "__setitem__", "__lt__", "__le__", "__eq__",
"__ne__", "__gt__", "__ge__", "__init__")
if name.startswith("__") and name.endswith("__") and name not in exceptions:
return False
if not ismethod(func) and not isfunction(func):
return False
if getattr(func, "__self__", None) is c:
return False
return True
class InvariantContractor(c):
pass
for name, value in [(name, getattr(c, name)) for name in dir(c)]:
if check(name, value):
setattr(InvariantContractor, name,
condition(desc, predicate, name != "__init__", True, True)(value))
return InvariantContractor
return invariant | python | def invariant(arg1, arg2=None):
"""
Specify a class invariant described by `description` and tested
by `predicate`.
"""
desc = ""
predicate = lambda x: x
if isinstance(arg1, str):
desc = arg1
predicate = arg2
else:
desc = get_function_source(arg1)
predicate = arg1
def invariant(c):
def check(name, func):
exceptions = ("__getitem__", "__setitem__", "__lt__", "__le__", "__eq__",
"__ne__", "__gt__", "__ge__", "__init__")
if name.startswith("__") and name.endswith("__") and name not in exceptions:
return False
if not ismethod(func) and not isfunction(func):
return False
if getattr(func, "__self__", None) is c:
return False
return True
class InvariantContractor(c):
pass
for name, value in [(name, getattr(c, name)) for name in dir(c)]:
if check(name, value):
setattr(InvariantContractor, name,
condition(desc, predicate, name != "__init__", True, True)(value))
return InvariantContractor
return invariant | [
"def",
"invariant",
"(",
"arg1",
",",
"arg2",
"=",
"None",
")",
":",
"desc",
"=",
"\"\"",
"predicate",
"=",
"lambda",
"x",
":",
"x",
"if",
"isinstance",
"(",
"arg1",
",",
"str",
")",
":",
"desc",
"=",
"arg1",
"predicate",
"=",
"arg2",
"else",
":",
"desc",
"=",
"get_function_source",
"(",
"arg1",
")",
"predicate",
"=",
"arg1",
"def",
"invariant",
"(",
"c",
")",
":",
"def",
"check",
"(",
"name",
",",
"func",
")",
":",
"exceptions",
"=",
"(",
"\"__getitem__\"",
",",
"\"__setitem__\"",
",",
"\"__lt__\"",
",",
"\"__le__\"",
",",
"\"__eq__\"",
",",
"\"__ne__\"",
",",
"\"__gt__\"",
",",
"\"__ge__\"",
",",
"\"__init__\"",
")",
"if",
"name",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"name",
".",
"endswith",
"(",
"\"__\"",
")",
"and",
"name",
"not",
"in",
"exceptions",
":",
"return",
"False",
"if",
"not",
"ismethod",
"(",
"func",
")",
"and",
"not",
"isfunction",
"(",
"func",
")",
":",
"return",
"False",
"if",
"getattr",
"(",
"func",
",",
"\"__self__\"",
",",
"None",
")",
"is",
"c",
":",
"return",
"False",
"return",
"True",
"class",
"InvariantContractor",
"(",
"c",
")",
":",
"pass",
"for",
"name",
",",
"value",
"in",
"[",
"(",
"name",
",",
"getattr",
"(",
"c",
",",
"name",
")",
")",
"for",
"name",
"in",
"dir",
"(",
"c",
")",
"]",
":",
"if",
"check",
"(",
"name",
",",
"value",
")",
":",
"setattr",
"(",
"InvariantContractor",
",",
"name",
",",
"condition",
"(",
"desc",
",",
"predicate",
",",
"name",
"!=",
"\"__init__\"",
",",
"True",
",",
"True",
")",
"(",
"value",
")",
")",
"return",
"InvariantContractor",
"return",
"invariant"
] | Specify a class invariant described by `description` and tested
by `predicate`. | [
"Specify",
"a",
"class",
"invariant",
"described",
"by",
"description",
"and",
"tested",
"by",
"predicate",
"."
] | 45cb8542272c2ebe095c6efb97aa9407ddc8bf3c | https://github.com/deadpixi/contracts/blob/45cb8542272c2ebe095c6efb97aa9407ddc8bf3c/dpcontracts.py#L741-L781 | train |
Gandi/gandi.cli | gandi/cli/core/utils/password.py | mkpassword | def mkpassword(length=16, chars=None, punctuation=None):
"""Generates a random ascii string - useful to generate authinfos
:param length: string wanted length
:type length: ``int``
:param chars: character population,
defaults to alphabet (lower & upper) + numbers
:type chars: ``str``, ``list``, ``set`` (sequence)
:param punctuation: number of punctuation signs to include in string
:type punctuation: ``int``
:rtype: ``str``
"""
if chars is None:
chars = string.ascii_letters + string.digits
# Generate string from population
data = [random.choice(chars) for _ in range(length)]
# If punctuation:
# - remove n chars from string
# - add random punctuation
# - shuffle chars :)
if punctuation:
data = data[:-punctuation]
for _ in range(punctuation):
data.append(random.choice(PUNCTUATION))
random.shuffle(data)
return ''.join(data) | python | def mkpassword(length=16, chars=None, punctuation=None):
"""Generates a random ascii string - useful to generate authinfos
:param length: string wanted length
:type length: ``int``
:param chars: character population,
defaults to alphabet (lower & upper) + numbers
:type chars: ``str``, ``list``, ``set`` (sequence)
:param punctuation: number of punctuation signs to include in string
:type punctuation: ``int``
:rtype: ``str``
"""
if chars is None:
chars = string.ascii_letters + string.digits
# Generate string from population
data = [random.choice(chars) for _ in range(length)]
# If punctuation:
# - remove n chars from string
# - add random punctuation
# - shuffle chars :)
if punctuation:
data = data[:-punctuation]
for _ in range(punctuation):
data.append(random.choice(PUNCTUATION))
random.shuffle(data)
return ''.join(data) | [
"def",
"mkpassword",
"(",
"length",
"=",
"16",
",",
"chars",
"=",
"None",
",",
"punctuation",
"=",
"None",
")",
":",
"if",
"chars",
"is",
"None",
":",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"# Generate string from population",
"data",
"=",
"[",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
"]",
"# If punctuation:",
"# - remove n chars from string",
"# - add random punctuation",
"# - shuffle chars :)",
"if",
"punctuation",
":",
"data",
"=",
"data",
"[",
":",
"-",
"punctuation",
"]",
"for",
"_",
"in",
"range",
"(",
"punctuation",
")",
":",
"data",
".",
"append",
"(",
"random",
".",
"choice",
"(",
"PUNCTUATION",
")",
")",
"random",
".",
"shuffle",
"(",
"data",
")",
"return",
"''",
".",
"join",
"(",
"data",
")"
] | Generates a random ascii string - useful to generate authinfos
:param length: string wanted length
:type length: ``int``
:param chars: character population,
defaults to alphabet (lower & upper) + numbers
:type chars: ``str``, ``list``, ``set`` (sequence)
:param punctuation: number of punctuation signs to include in string
:type punctuation: ``int``
:rtype: ``str`` | [
"Generates",
"a",
"random",
"ascii",
"string",
"-",
"useful",
"to",
"generate",
"authinfos"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/password.py#L12-L44 | train |
Gandi/gandi.cli | gandi/cli/core/utils/size.py | disk_check_size | def disk_check_size(ctx, param, value):
""" Validation callback for disk size parameter."""
if value:
# if we've got a prefix
if isinstance(value, tuple):
val = value[1]
else:
val = value
if val % 1024:
raise click.ClickException('Size must be a multiple of 1024.')
return value | python | def disk_check_size(ctx, param, value):
""" Validation callback for disk size parameter."""
if value:
# if we've got a prefix
if isinstance(value, tuple):
val = value[1]
else:
val = value
if val % 1024:
raise click.ClickException('Size must be a multiple of 1024.')
return value | [
"def",
"disk_check_size",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
":",
"# if we've got a prefix",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"val",
"=",
"value",
"[",
"1",
"]",
"else",
":",
"val",
"=",
"value",
"if",
"val",
"%",
"1024",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'Size must be a multiple of 1024.'",
")",
"return",
"value"
] | Validation callback for disk size parameter. | [
"Validation",
"callback",
"for",
"disk",
"size",
"parameter",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/size.py#L8-L18 | train |
Gandi/gandi.cli | gandi/cli/modules/dnssec.py | DNSSEC.create | def create(cls, fqdn, flags, algorithm, public_key):
"""Create a dnssec key."""
fqdn = fqdn.lower()
params = {
'flags': flags,
'algorithm': algorithm,
'public_key': public_key,
}
result = cls.call('domain.dnssec.create', fqdn, params)
return result | python | def create(cls, fqdn, flags, algorithm, public_key):
"""Create a dnssec key."""
fqdn = fqdn.lower()
params = {
'flags': flags,
'algorithm': algorithm,
'public_key': public_key,
}
result = cls.call('domain.dnssec.create', fqdn, params)
return result | [
"def",
"create",
"(",
"cls",
",",
"fqdn",
",",
"flags",
",",
"algorithm",
",",
"public_key",
")",
":",
"fqdn",
"=",
"fqdn",
".",
"lower",
"(",
")",
"params",
"=",
"{",
"'flags'",
":",
"flags",
",",
"'algorithm'",
":",
"algorithm",
",",
"'public_key'",
":",
"public_key",
",",
"}",
"result",
"=",
"cls",
".",
"call",
"(",
"'domain.dnssec.create'",
",",
"fqdn",
",",
"params",
")",
"return",
"result"
] | Create a dnssec key. | [
"Create",
"a",
"dnssec",
"key",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dnssec.py#L22-L34 | train |
Gandi/gandi.cli | gandi/cli/modules/snapshotprofile.py | SnapshotProfile.from_name | def from_name(cls, name):
""" Retrieve a snapshot profile accsociated to a name."""
snps = cls.list({'name': name})
if len(snps) == 1:
return snps[0]['id']
elif not snps:
return
raise DuplicateResults('snapshot profile name %s is ambiguous.' % name) | python | def from_name(cls, name):
""" Retrieve a snapshot profile accsociated to a name."""
snps = cls.list({'name': name})
if len(snps) == 1:
return snps[0]['id']
elif not snps:
return
raise DuplicateResults('snapshot profile name %s is ambiguous.' % name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"snps",
"=",
"cls",
".",
"list",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"if",
"len",
"(",
"snps",
")",
"==",
"1",
":",
"return",
"snps",
"[",
"0",
"]",
"[",
"'id'",
"]",
"elif",
"not",
"snps",
":",
"return",
"raise",
"DuplicateResults",
"(",
"'snapshot profile name %s is ambiguous.'",
"%",
"name",
")"
] | Retrieve a snapshot profile accsociated to a name. | [
"Retrieve",
"a",
"snapshot",
"profile",
"accsociated",
"to",
"a",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/snapshotprofile.py#L17-L25 | train |
Gandi/gandi.cli | gandi/cli/modules/snapshotprofile.py | SnapshotProfile.list | def list(cls, options=None, target=None):
""" List all snapshot profiles."""
options = options or {}
result = []
if not target or target == 'paas':
for profile in cls.safe_call('paas.snapshotprofile.list', options):
profile['target'] = 'paas'
result.append((profile['id'], profile))
if not target or target == 'vm':
for profile in cls.safe_call('hosting.snapshotprofile.list',
options):
profile['target'] = 'vm'
result.append((profile['id'], profile))
result = sorted(result, key=lambda item: item[0])
return [profile for id_, profile in result] | python | def list(cls, options=None, target=None):
""" List all snapshot profiles."""
options = options or {}
result = []
if not target or target == 'paas':
for profile in cls.safe_call('paas.snapshotprofile.list', options):
profile['target'] = 'paas'
result.append((profile['id'], profile))
if not target or target == 'vm':
for profile in cls.safe_call('hosting.snapshotprofile.list',
options):
profile['target'] = 'vm'
result.append((profile['id'], profile))
result = sorted(result, key=lambda item: item[0])
return [profile for id_, profile in result] | [
"def",
"list",
"(",
"cls",
",",
"options",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"result",
"=",
"[",
"]",
"if",
"not",
"target",
"or",
"target",
"==",
"'paas'",
":",
"for",
"profile",
"in",
"cls",
".",
"safe_call",
"(",
"'paas.snapshotprofile.list'",
",",
"options",
")",
":",
"profile",
"[",
"'target'",
"]",
"=",
"'paas'",
"result",
".",
"append",
"(",
"(",
"profile",
"[",
"'id'",
"]",
",",
"profile",
")",
")",
"if",
"not",
"target",
"or",
"target",
"==",
"'vm'",
":",
"for",
"profile",
"in",
"cls",
".",
"safe_call",
"(",
"'hosting.snapshotprofile.list'",
",",
"options",
")",
":",
"profile",
"[",
"'target'",
"]",
"=",
"'vm'",
"result",
".",
"append",
"(",
"(",
"profile",
"[",
"'id'",
"]",
",",
"profile",
")",
")",
"result",
"=",
"sorted",
"(",
"result",
",",
"key",
"=",
"lambda",
"item",
":",
"item",
"[",
"0",
"]",
")",
"return",
"[",
"profile",
"for",
"id_",
",",
"profile",
"in",
"result",
"]"
] | List all snapshot profiles. | [
"List",
"all",
"snapshot",
"profiles",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/snapshotprofile.py#L46-L63 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.records | def records(cls, fqdn, sort_by=None, text=False):
"""Display records information about a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
kwargs = {}
if text:
kwargs = {'headers': {'Accept': 'text/plain'}}
return cls.json_get(cls.get_sort_url(url, sort_by), **kwargs) | python | def records(cls, fqdn, sort_by=None, text=False):
"""Display records information about a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
kwargs = {}
if text:
kwargs = {'headers': {'Accept': 'text/plain'}}
return cls.json_get(cls.get_sort_url(url, sort_by), **kwargs) | [
"def",
"records",
"(",
"cls",
",",
"fqdn",
",",
"sort_by",
"=",
"None",
",",
"text",
"=",
"False",
")",
":",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"url",
"=",
"meta",
"[",
"'domain_records_href'",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"text",
":",
"kwargs",
"=",
"{",
"'headers'",
":",
"{",
"'Accept'",
":",
"'text/plain'",
"}",
"}",
"return",
"cls",
".",
"json_get",
"(",
"cls",
".",
"get_sort_url",
"(",
"url",
",",
"sort_by",
")",
",",
"*",
"*",
"kwargs",
")"
] | Display records information about a domain. | [
"Display",
"records",
"information",
"about",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L51-L58 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.add_record | def add_record(cls, fqdn, name, type, value, ttl):
"""Create record for a domain."""
data = {
"rrset_name": name,
"rrset_type": type,
"rrset_values": value,
}
if ttl:
data['rrset_ttl'] = int(ttl)
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
return cls.json_post(url, data=json.dumps(data)) | python | def add_record(cls, fqdn, name, type, value, ttl):
"""Create record for a domain."""
data = {
"rrset_name": name,
"rrset_type": type,
"rrset_values": value,
}
if ttl:
data['rrset_ttl'] = int(ttl)
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
return cls.json_post(url, data=json.dumps(data)) | [
"def",
"add_record",
"(",
"cls",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
")",
":",
"data",
"=",
"{",
"\"rrset_name\"",
":",
"name",
",",
"\"rrset_type\"",
":",
"type",
",",
"\"rrset_values\"",
":",
"value",
",",
"}",
"if",
"ttl",
":",
"data",
"[",
"'rrset_ttl'",
"]",
"=",
"int",
"(",
"ttl",
")",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"url",
"=",
"meta",
"[",
"'domain_records_href'",
"]",
"return",
"cls",
".",
"json_post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")"
] | Create record for a domain. | [
"Create",
"record",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L61-L72 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.update_record | def update_record(cls, fqdn, name, type, value, ttl, content):
"""Update all records for a domain."""
data = {
"rrset_name": name,
"rrset_type": type,
"rrset_values": value,
}
if ttl:
data['rrset_ttl'] = int(ttl)
meta = cls.get_fqdn_info(fqdn)
if content:
url = meta['domain_records_href']
kwargs = {'headers': {'Content-Type': 'text/plain'},
'data': content}
return cls.json_put(url, **kwargs)
url = '%s/domains/%s/records/%s/%s' % (cls.api_url, fqdn, name, type)
return cls.json_put(url, data=json.dumps(data)) | python | def update_record(cls, fqdn, name, type, value, ttl, content):
"""Update all records for a domain."""
data = {
"rrset_name": name,
"rrset_type": type,
"rrset_values": value,
}
if ttl:
data['rrset_ttl'] = int(ttl)
meta = cls.get_fqdn_info(fqdn)
if content:
url = meta['domain_records_href']
kwargs = {'headers': {'Content-Type': 'text/plain'},
'data': content}
return cls.json_put(url, **kwargs)
url = '%s/domains/%s/records/%s/%s' % (cls.api_url, fqdn, name, type)
return cls.json_put(url, data=json.dumps(data)) | [
"def",
"update_record",
"(",
"cls",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
",",
"content",
")",
":",
"data",
"=",
"{",
"\"rrset_name\"",
":",
"name",
",",
"\"rrset_type\"",
":",
"type",
",",
"\"rrset_values\"",
":",
"value",
",",
"}",
"if",
"ttl",
":",
"data",
"[",
"'rrset_ttl'",
"]",
"=",
"int",
"(",
"ttl",
")",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"if",
"content",
":",
"url",
"=",
"meta",
"[",
"'domain_records_href'",
"]",
"kwargs",
"=",
"{",
"'headers'",
":",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
",",
"'data'",
":",
"content",
"}",
"return",
"cls",
".",
"json_put",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"'%s/domains/%s/records/%s/%s'",
"%",
"(",
"cls",
".",
"api_url",
",",
"fqdn",
",",
"name",
",",
"type",
")",
"return",
"cls",
".",
"json_put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")"
] | Update all records for a domain. | [
"Update",
"all",
"records",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L75-L92 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.del_record | def del_record(cls, fqdn, name, type):
"""Delete record for a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
delete_url = url
if name:
delete_url = '%s/%s' % (delete_url, name)
if type:
delete_url = '%s/%s' % (delete_url, type)
return cls.json_delete(delete_url) | python | def del_record(cls, fqdn, name, type):
"""Delete record for a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
delete_url = url
if name:
delete_url = '%s/%s' % (delete_url, name)
if type:
delete_url = '%s/%s' % (delete_url, type)
return cls.json_delete(delete_url) | [
"def",
"del_record",
"(",
"cls",
",",
"fqdn",
",",
"name",
",",
"type",
")",
":",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"url",
"=",
"meta",
"[",
"'domain_records_href'",
"]",
"delete_url",
"=",
"url",
"if",
"name",
":",
"delete_url",
"=",
"'%s/%s'",
"%",
"(",
"delete_url",
",",
"name",
")",
"if",
"type",
":",
"delete_url",
"=",
"'%s/%s'",
"%",
"(",
"delete_url",
",",
"type",
")",
"return",
"cls",
".",
"json_delete",
"(",
"delete_url",
")"
] | Delete record for a domain. | [
"Delete",
"record",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L95-L104 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.keys | def keys(cls, fqdn, sort_by=None):
"""Display keys information about a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_keys_href']
return cls.json_get(cls.get_sort_url(url, sort_by)) | python | def keys(cls, fqdn, sort_by=None):
"""Display keys information about a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_keys_href']
return cls.json_get(cls.get_sort_url(url, sort_by)) | [
"def",
"keys",
"(",
"cls",
",",
"fqdn",
",",
"sort_by",
"=",
"None",
")",
":",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"url",
"=",
"meta",
"[",
"'domain_keys_href'",
"]",
"return",
"cls",
".",
"json_get",
"(",
"cls",
".",
"get_sort_url",
"(",
"url",
",",
"sort_by",
")",
")"
] | Display keys information about a domain. | [
"Display",
"keys",
"information",
"about",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L107-L111 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.keys_info | def keys_info(cls, fqdn, key):
"""Retrieve key information."""
return cls.json_get('%s/domains/%s/keys/%s' %
(cls.api_url, fqdn, key)) | python | def keys_info(cls, fqdn, key):
"""Retrieve key information."""
return cls.json_get('%s/domains/%s/keys/%s' %
(cls.api_url, fqdn, key)) | [
"def",
"keys_info",
"(",
"cls",
",",
"fqdn",
",",
"key",
")",
":",
"return",
"cls",
".",
"json_get",
"(",
"'%s/domains/%s/keys/%s'",
"%",
"(",
"cls",
".",
"api_url",
",",
"fqdn",
",",
"key",
")",
")"
] | Retrieve key information. | [
"Retrieve",
"key",
"information",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L114-L117 | train |
Gandi/gandi.cli | gandi/cli/modules/dns.py | Dns.keys_create | def keys_create(cls, fqdn, flag):
"""Create new key entry for a domain."""
data = {
"flags": flag,
}
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_keys_href']
ret, headers = cls.json_post(url, data=json.dumps(data),
return_header=True)
return cls.json_get(headers['location']) | python | def keys_create(cls, fqdn, flag):
"""Create new key entry for a domain."""
data = {
"flags": flag,
}
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_keys_href']
ret, headers = cls.json_post(url, data=json.dumps(data),
return_header=True)
return cls.json_get(headers['location']) | [
"def",
"keys_create",
"(",
"cls",
",",
"fqdn",
",",
"flag",
")",
":",
"data",
"=",
"{",
"\"flags\"",
":",
"flag",
",",
"}",
"meta",
"=",
"cls",
".",
"get_fqdn_info",
"(",
"fqdn",
")",
"url",
"=",
"meta",
"[",
"'domain_keys_href'",
"]",
"ret",
",",
"headers",
"=",
"cls",
".",
"json_post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"return_header",
"=",
"True",
")",
"return",
"cls",
".",
"json_get",
"(",
"headers",
"[",
"'location'",
"]",
")"
] | Create new key entry for a domain. | [
"Create",
"new",
"key",
"entry",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/dns.py#L120-L129 | train |
Gandi/gandi.cli | gandi/cli/commands/vlan.py | list | def list(gandi, datacenter, id, subnet, gateway):
"""List vlans."""
output_keys = ['name', 'state', 'dc']
if id:
output_keys.append('id')
if subnet:
output_keys.append('subnet')
if gateway:
output_keys.append('gateway')
datacenters = gandi.datacenter.list()
vlans = gandi.vlan.list(datacenter)
for num, vlan in enumerate(vlans):
if num:
gandi.separator_line()
output_vlan(gandi, vlan, datacenters, output_keys)
return vlans | python | def list(gandi, datacenter, id, subnet, gateway):
"""List vlans."""
output_keys = ['name', 'state', 'dc']
if id:
output_keys.append('id')
if subnet:
output_keys.append('subnet')
if gateway:
output_keys.append('gateway')
datacenters = gandi.datacenter.list()
vlans = gandi.vlan.list(datacenter)
for num, vlan in enumerate(vlans):
if num:
gandi.separator_line()
output_vlan(gandi, vlan, datacenters, output_keys)
return vlans | [
"def",
"list",
"(",
"gandi",
",",
"datacenter",
",",
"id",
",",
"subnet",
",",
"gateway",
")",
":",
"output_keys",
"=",
"[",
"'name'",
",",
"'state'",
",",
"'dc'",
"]",
"if",
"id",
":",
"output_keys",
".",
"append",
"(",
"'id'",
")",
"if",
"subnet",
":",
"output_keys",
".",
"append",
"(",
"'subnet'",
")",
"if",
"gateway",
":",
"output_keys",
".",
"append",
"(",
"'gateway'",
")",
"datacenters",
"=",
"gandi",
".",
"datacenter",
".",
"list",
"(",
")",
"vlans",
"=",
"gandi",
".",
"vlan",
".",
"list",
"(",
"datacenter",
")",
"for",
"num",
",",
"vlan",
"in",
"enumerate",
"(",
"vlans",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_vlan",
"(",
"gandi",
",",
"vlan",
",",
"datacenters",
",",
"output_keys",
")",
"return",
"vlans"
] | List vlans. | [
"List",
"vlans",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vlan.py#L27-L45 | train |
Gandi/gandi.cli | gandi/cli/commands/vlan.py | info | def info(gandi, resource, ip):
"""Display information about a vlan."""
output_keys = ['name', 'state', 'dc', 'subnet', 'gateway']
datacenters = gandi.datacenter.list()
vlan = gandi.vlan.info(resource)
gateway = vlan['gateway']
if not ip:
output_vlan(gandi, vlan, datacenters, output_keys, justify=11)
return vlan
gateway_exists = False
vms = dict([(vm_['id'], vm_) for vm_ in gandi.iaas.list()])
ifaces = gandi.vlan.ifaces(resource)
for iface in ifaces:
for ip in iface['ips']:
if gateway == ip['ip']:
gateway_exists = True
if gateway_exists:
vlan.pop('gateway')
else:
vlan['gateway'] = ("%s don't exists" % gateway if gateway
else 'none')
output_vlan(gandi, vlan, datacenters, output_keys, justify=11)
output_keys = ['vm', 'bandwidth']
for iface in ifaces:
gandi.separator_line()
output_iface(gandi, iface, datacenters, vms, output_keys,
justify=11)
for ip in iface['ips']:
output_ip(gandi, ip, None, None, None, ['ip'])
if gateway == ip['ip']:
output_line(gandi, 'gateway', 'true', justify=11)
return vlan | python | def info(gandi, resource, ip):
"""Display information about a vlan."""
output_keys = ['name', 'state', 'dc', 'subnet', 'gateway']
datacenters = gandi.datacenter.list()
vlan = gandi.vlan.info(resource)
gateway = vlan['gateway']
if not ip:
output_vlan(gandi, vlan, datacenters, output_keys, justify=11)
return vlan
gateway_exists = False
vms = dict([(vm_['id'], vm_) for vm_ in gandi.iaas.list()])
ifaces = gandi.vlan.ifaces(resource)
for iface in ifaces:
for ip in iface['ips']:
if gateway == ip['ip']:
gateway_exists = True
if gateway_exists:
vlan.pop('gateway')
else:
vlan['gateway'] = ("%s don't exists" % gateway if gateway
else 'none')
output_vlan(gandi, vlan, datacenters, output_keys, justify=11)
output_keys = ['vm', 'bandwidth']
for iface in ifaces:
gandi.separator_line()
output_iface(gandi, iface, datacenters, vms, output_keys,
justify=11)
for ip in iface['ips']:
output_ip(gandi, ip, None, None, None, ['ip'])
if gateway == ip['ip']:
output_line(gandi, 'gateway', 'true', justify=11)
return vlan | [
"def",
"info",
"(",
"gandi",
",",
"resource",
",",
"ip",
")",
":",
"output_keys",
"=",
"[",
"'name'",
",",
"'state'",
",",
"'dc'",
",",
"'subnet'",
",",
"'gateway'",
"]",
"datacenters",
"=",
"gandi",
".",
"datacenter",
".",
"list",
"(",
")",
"vlan",
"=",
"gandi",
".",
"vlan",
".",
"info",
"(",
"resource",
")",
"gateway",
"=",
"vlan",
"[",
"'gateway'",
"]",
"if",
"not",
"ip",
":",
"output_vlan",
"(",
"gandi",
",",
"vlan",
",",
"datacenters",
",",
"output_keys",
",",
"justify",
"=",
"11",
")",
"return",
"vlan",
"gateway_exists",
"=",
"False",
"vms",
"=",
"dict",
"(",
"[",
"(",
"vm_",
"[",
"'id'",
"]",
",",
"vm_",
")",
"for",
"vm_",
"in",
"gandi",
".",
"iaas",
".",
"list",
"(",
")",
"]",
")",
"ifaces",
"=",
"gandi",
".",
"vlan",
".",
"ifaces",
"(",
"resource",
")",
"for",
"iface",
"in",
"ifaces",
":",
"for",
"ip",
"in",
"iface",
"[",
"'ips'",
"]",
":",
"if",
"gateway",
"==",
"ip",
"[",
"'ip'",
"]",
":",
"gateway_exists",
"=",
"True",
"if",
"gateway_exists",
":",
"vlan",
".",
"pop",
"(",
"'gateway'",
")",
"else",
":",
"vlan",
"[",
"'gateway'",
"]",
"=",
"(",
"\"%s don't exists\"",
"%",
"gateway",
"if",
"gateway",
"else",
"'none'",
")",
"output_vlan",
"(",
"gandi",
",",
"vlan",
",",
"datacenters",
",",
"output_keys",
",",
"justify",
"=",
"11",
")",
"output_keys",
"=",
"[",
"'vm'",
",",
"'bandwidth'",
"]",
"for",
"iface",
"in",
"ifaces",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_iface",
"(",
"gandi",
",",
"iface",
",",
"datacenters",
",",
"vms",
",",
"output_keys",
",",
"justify",
"=",
"11",
")",
"for",
"ip",
"in",
"iface",
"[",
"'ips'",
"]",
":",
"output_ip",
"(",
"gandi",
",",
"ip",
",",
"None",
",",
"None",
",",
"None",
",",
"[",
"'ip'",
"]",
")",
"if",
"gateway",
"==",
"ip",
"[",
"'ip'",
"]",
":",
"output_line",
"(",
"gandi",
",",
"'gateway'",
",",
"'true'",
",",
"justify",
"=",
"11",
")",
"return",
"vlan"
] | Display information about a vlan. | [
"Display",
"information",
"about",
"a",
"vlan",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vlan.py#L52-L93 | train |
Gandi/gandi.cli | gandi/cli/commands/vlan.py | create | def create(gandi, name, datacenter, subnet, gateway, background):
""" Create a new vlan """
try:
gandi.datacenter.is_opened(datacenter, 'iaas')
except DatacenterLimited as exc:
gandi.echo('/!\ Datacenter %s will be closed on %s, '
'please consider using another datacenter.' %
(datacenter, exc.date))
result = gandi.vlan.create(name, datacenter, subnet, gateway, background)
if background:
gandi.pretty_echo(result)
return result | python | def create(gandi, name, datacenter, subnet, gateway, background):
""" Create a new vlan """
try:
gandi.datacenter.is_opened(datacenter, 'iaas')
except DatacenterLimited as exc:
gandi.echo('/!\ Datacenter %s will be closed on %s, '
'please consider using another datacenter.' %
(datacenter, exc.date))
result = gandi.vlan.create(name, datacenter, subnet, gateway, background)
if background:
gandi.pretty_echo(result)
return result | [
"def",
"create",
"(",
"gandi",
",",
"name",
",",
"datacenter",
",",
"subnet",
",",
"gateway",
",",
"background",
")",
":",
"try",
":",
"gandi",
".",
"datacenter",
".",
"is_opened",
"(",
"datacenter",
",",
"'iaas'",
")",
"except",
"DatacenterLimited",
"as",
"exc",
":",
"gandi",
".",
"echo",
"(",
"'/!\\ Datacenter %s will be closed on %s, '",
"'please consider using another datacenter.'",
"%",
"(",
"datacenter",
",",
"exc",
".",
"date",
")",
")",
"result",
"=",
"gandi",
".",
"vlan",
".",
"create",
"(",
"name",
",",
"datacenter",
",",
"subnet",
",",
"gateway",
",",
"background",
")",
"if",
"background",
":",
"gandi",
".",
"pretty_echo",
"(",
"result",
")",
"return",
"result"
] | Create a new vlan | [
"Create",
"a",
"new",
"vlan"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vlan.py#L144-L158 | train |
Gandi/gandi.cli | gandi/cli/commands/vlan.py | update | def update(gandi, resource, name, gateway, create, bandwidth):
""" Update a vlan
``gateway`` can be a vm name or id, or an ip.
"""
params = {}
if name:
params['name'] = name
vlan_id = gandi.vlan.usable_id(resource)
try:
if gateway:
IP(gateway)
params['gateway'] = gateway
except ValueError:
vm = gandi.iaas.info(gateway)
ips = [ip for sublist in
[[ip['ip'] for ip in iface['ips'] if ip['version'] == 4]
for iface in vm['ifaces']
if iface['vlan'] and iface['vlan'].get('id') == vlan_id]
for ip in sublist]
if len(ips) > 1:
gandi.echo("This vm has two ips in the vlan, don't know which one"
' to choose (%s)' % (', '.join(ips)))
return
if not ips and not create:
gandi.echo("Can't find '%s' in '%s' vlan" % (gateway, resource))
return
if not ips and create:
gandi.echo('Will create a new ip in this vlan for vm %s' % gateway)
oper = gandi.ip.create('4', vm['datacenter_id'], bandwidth,
vm['hostname'], resource)
iface_id = oper['iface_id']
iface = gandi.iface.info(iface_id)
ips = [ip['ip'] for ip in iface['ips'] if ip['version'] == 4]
params['gateway'] = ips[0]
result = gandi.vlan.update(resource, params)
return result | python | def update(gandi, resource, name, gateway, create, bandwidth):
""" Update a vlan
``gateway`` can be a vm name or id, or an ip.
"""
params = {}
if name:
params['name'] = name
vlan_id = gandi.vlan.usable_id(resource)
try:
if gateway:
IP(gateway)
params['gateway'] = gateway
except ValueError:
vm = gandi.iaas.info(gateway)
ips = [ip for sublist in
[[ip['ip'] for ip in iface['ips'] if ip['version'] == 4]
for iface in vm['ifaces']
if iface['vlan'] and iface['vlan'].get('id') == vlan_id]
for ip in sublist]
if len(ips) > 1:
gandi.echo("This vm has two ips in the vlan, don't know which one"
' to choose (%s)' % (', '.join(ips)))
return
if not ips and not create:
gandi.echo("Can't find '%s' in '%s' vlan" % (gateway, resource))
return
if not ips and create:
gandi.echo('Will create a new ip in this vlan for vm %s' % gateway)
oper = gandi.ip.create('4', vm['datacenter_id'], bandwidth,
vm['hostname'], resource)
iface_id = oper['iface_id']
iface = gandi.iface.info(iface_id)
ips = [ip['ip'] for ip in iface['ips'] if ip['version'] == 4]
params['gateway'] = ips[0]
result = gandi.vlan.update(resource, params)
return result | [
"def",
"update",
"(",
"gandi",
",",
"resource",
",",
"name",
",",
"gateway",
",",
"create",
",",
"bandwidth",
")",
":",
"params",
"=",
"{",
"}",
"if",
"name",
":",
"params",
"[",
"'name'",
"]",
"=",
"name",
"vlan_id",
"=",
"gandi",
".",
"vlan",
".",
"usable_id",
"(",
"resource",
")",
"try",
":",
"if",
"gateway",
":",
"IP",
"(",
"gateway",
")",
"params",
"[",
"'gateway'",
"]",
"=",
"gateway",
"except",
"ValueError",
":",
"vm",
"=",
"gandi",
".",
"iaas",
".",
"info",
"(",
"gateway",
")",
"ips",
"=",
"[",
"ip",
"for",
"sublist",
"in",
"[",
"[",
"ip",
"[",
"'ip'",
"]",
"for",
"ip",
"in",
"iface",
"[",
"'ips'",
"]",
"if",
"ip",
"[",
"'version'",
"]",
"==",
"4",
"]",
"for",
"iface",
"in",
"vm",
"[",
"'ifaces'",
"]",
"if",
"iface",
"[",
"'vlan'",
"]",
"and",
"iface",
"[",
"'vlan'",
"]",
".",
"get",
"(",
"'id'",
")",
"==",
"vlan_id",
"]",
"for",
"ip",
"in",
"sublist",
"]",
"if",
"len",
"(",
"ips",
")",
">",
"1",
":",
"gandi",
".",
"echo",
"(",
"\"This vm has two ips in the vlan, don't know which one\"",
"' to choose (%s)'",
"%",
"(",
"', '",
".",
"join",
"(",
"ips",
")",
")",
")",
"return",
"if",
"not",
"ips",
"and",
"not",
"create",
":",
"gandi",
".",
"echo",
"(",
"\"Can't find '%s' in '%s' vlan\"",
"%",
"(",
"gateway",
",",
"resource",
")",
")",
"return",
"if",
"not",
"ips",
"and",
"create",
":",
"gandi",
".",
"echo",
"(",
"'Will create a new ip in this vlan for vm %s'",
"%",
"gateway",
")",
"oper",
"=",
"gandi",
".",
"ip",
".",
"create",
"(",
"'4'",
",",
"vm",
"[",
"'datacenter_id'",
"]",
",",
"bandwidth",
",",
"vm",
"[",
"'hostname'",
"]",
",",
"resource",
")",
"iface_id",
"=",
"oper",
"[",
"'iface_id'",
"]",
"iface",
"=",
"gandi",
".",
"iface",
".",
"info",
"(",
"iface_id",
")",
"ips",
"=",
"[",
"ip",
"[",
"'ip'",
"]",
"for",
"ip",
"in",
"iface",
"[",
"'ips'",
"]",
"if",
"ip",
"[",
"'version'",
"]",
"==",
"4",
"]",
"params",
"[",
"'gateway'",
"]",
"=",
"ips",
"[",
"0",
"]",
"result",
"=",
"gandi",
".",
"vlan",
".",
"update",
"(",
"resource",
",",
"params",
")",
"return",
"result"
] | Update a vlan
``gateway`` can be a vm name or id, or an ip. | [
"Update",
"a",
"vlan"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vlan.py#L172-L217 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.list_migration_choice | def list_migration_choice(cls, datacenter):
"""List available datacenters for migration from given datacenter."""
datacenter_id = cls.usable_id(datacenter)
dc_list = cls.list()
available_dcs = [dc for dc in dc_list
if dc['id'] == datacenter_id][0]['can_migrate_to']
choices = [dc for dc in dc_list
if dc['id'] in available_dcs]
return choices | python | def list_migration_choice(cls, datacenter):
"""List available datacenters for migration from given datacenter."""
datacenter_id = cls.usable_id(datacenter)
dc_list = cls.list()
available_dcs = [dc for dc in dc_list
if dc['id'] == datacenter_id][0]['can_migrate_to']
choices = [dc for dc in dc_list
if dc['id'] in available_dcs]
return choices | [
"def",
"list_migration_choice",
"(",
"cls",
",",
"datacenter",
")",
":",
"datacenter_id",
"=",
"cls",
".",
"usable_id",
"(",
"datacenter",
")",
"dc_list",
"=",
"cls",
".",
"list",
"(",
")",
"available_dcs",
"=",
"[",
"dc",
"for",
"dc",
"in",
"dc_list",
"if",
"dc",
"[",
"'id'",
"]",
"==",
"datacenter_id",
"]",
"[",
"0",
"]",
"[",
"'can_migrate_to'",
"]",
"choices",
"=",
"[",
"dc",
"for",
"dc",
"in",
"dc_list",
"if",
"dc",
"[",
"'id'",
"]",
"in",
"available_dcs",
"]",
"return",
"choices"
] | List available datacenters for migration from given datacenter. | [
"List",
"available",
"datacenters",
"for",
"migration",
"from",
"given",
"datacenter",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L22-L30 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.is_opened | def is_opened(cls, dc_code, type_):
"""List opened datacenters for given type."""
options = {'dc_code': dc_code, '%s_opened' % type_: True}
datacenters = cls.safe_call('hosting.datacenter.list', options)
if not datacenters:
# try with ISO code
options = {'iso': dc_code, '%s_opened' % type_: True}
datacenters = cls.safe_call('hosting.datacenter.list', options)
if not datacenters:
raise DatacenterClosed(r'/!\ Datacenter %s is closed, please '
'choose another datacenter.' % dc_code)
datacenter = datacenters[0]
if datacenter.get('%s_closed_for' % type_) == 'NEW':
dc_close_date = datacenter.get('deactivate_at', '')
if dc_close_date:
dc_close_date = dc_close_date.strftime('%d/%m/%Y')
raise DatacenterLimited(dc_close_date) | python | def is_opened(cls, dc_code, type_):
"""List opened datacenters for given type."""
options = {'dc_code': dc_code, '%s_opened' % type_: True}
datacenters = cls.safe_call('hosting.datacenter.list', options)
if not datacenters:
# try with ISO code
options = {'iso': dc_code, '%s_opened' % type_: True}
datacenters = cls.safe_call('hosting.datacenter.list', options)
if not datacenters:
raise DatacenterClosed(r'/!\ Datacenter %s is closed, please '
'choose another datacenter.' % dc_code)
datacenter = datacenters[0]
if datacenter.get('%s_closed_for' % type_) == 'NEW':
dc_close_date = datacenter.get('deactivate_at', '')
if dc_close_date:
dc_close_date = dc_close_date.strftime('%d/%m/%Y')
raise DatacenterLimited(dc_close_date) | [
"def",
"is_opened",
"(",
"cls",
",",
"dc_code",
",",
"type_",
")",
":",
"options",
"=",
"{",
"'dc_code'",
":",
"dc_code",
",",
"'%s_opened'",
"%",
"type_",
":",
"True",
"}",
"datacenters",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.datacenter.list'",
",",
"options",
")",
"if",
"not",
"datacenters",
":",
"# try with ISO code",
"options",
"=",
"{",
"'iso'",
":",
"dc_code",
",",
"'%s_opened'",
"%",
"type_",
":",
"True",
"}",
"datacenters",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.datacenter.list'",
",",
"options",
")",
"if",
"not",
"datacenters",
":",
"raise",
"DatacenterClosed",
"(",
"r'/!\\ Datacenter %s is closed, please '",
"'choose another datacenter.'",
"%",
"dc_code",
")",
"datacenter",
"=",
"datacenters",
"[",
"0",
"]",
"if",
"datacenter",
".",
"get",
"(",
"'%s_closed_for'",
"%",
"type_",
")",
"==",
"'NEW'",
":",
"dc_close_date",
"=",
"datacenter",
".",
"get",
"(",
"'deactivate_at'",
",",
"''",
")",
"if",
"dc_close_date",
":",
"dc_close_date",
"=",
"dc_close_date",
".",
"strftime",
"(",
"'%d/%m/%Y'",
")",
"raise",
"DatacenterLimited",
"(",
"dc_close_date",
")"
] | List opened datacenters for given type. | [
"List",
"opened",
"datacenters",
"for",
"given",
"type",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L33-L50 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.filtered_list | def filtered_list(cls, name=None, obj=None):
"""List datacenters matching name and compatible
with obj"""
options = {}
if name:
options['id'] = cls.usable_id(name)
def obj_ok(dc, obj):
if not obj or obj['datacenter_id'] == dc['id']:
return True
return False
return [x for x in cls.list(options) if obj_ok(x, obj)] | python | def filtered_list(cls, name=None, obj=None):
"""List datacenters matching name and compatible
with obj"""
options = {}
if name:
options['id'] = cls.usable_id(name)
def obj_ok(dc, obj):
if not obj or obj['datacenter_id'] == dc['id']:
return True
return False
return [x for x in cls.list(options) if obj_ok(x, obj)] | [
"def",
"filtered_list",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"if",
"name",
":",
"options",
"[",
"'id'",
"]",
"=",
"cls",
".",
"usable_id",
"(",
"name",
")",
"def",
"obj_ok",
"(",
"dc",
",",
"obj",
")",
":",
"if",
"not",
"obj",
"or",
"obj",
"[",
"'datacenter_id'",
"]",
"==",
"dc",
"[",
"'id'",
"]",
":",
"return",
"True",
"return",
"False",
"return",
"[",
"x",
"for",
"x",
"in",
"cls",
".",
"list",
"(",
"options",
")",
"if",
"obj_ok",
"(",
"x",
",",
"obj",
")",
"]"
] | List datacenters matching name and compatible
with obj | [
"List",
"datacenters",
"matching",
"name",
"and",
"compatible",
"with",
"obj"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L53-L65 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.from_iso | def from_iso(cls, iso):
"""Retrieve the first datacenter id associated to an ISO."""
result = cls.list({'sort_by': 'id ASC'})
dc_isos = {}
for dc in result:
if dc['iso'] not in dc_isos:
dc_isos[dc['iso']] = dc['id']
return dc_isos.get(iso) | python | def from_iso(cls, iso):
"""Retrieve the first datacenter id associated to an ISO."""
result = cls.list({'sort_by': 'id ASC'})
dc_isos = {}
for dc in result:
if dc['iso'] not in dc_isos:
dc_isos[dc['iso']] = dc['id']
return dc_isos.get(iso) | [
"def",
"from_iso",
"(",
"cls",
",",
"iso",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"{",
"'sort_by'",
":",
"'id ASC'",
"}",
")",
"dc_isos",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"if",
"dc",
"[",
"'iso'",
"]",
"not",
"in",
"dc_isos",
":",
"dc_isos",
"[",
"dc",
"[",
"'iso'",
"]",
"]",
"=",
"dc",
"[",
"'id'",
"]",
"return",
"dc_isos",
".",
"get",
"(",
"iso",
")"
] | Retrieve the first datacenter id associated to an ISO. | [
"Retrieve",
"the",
"first",
"datacenter",
"id",
"associated",
"to",
"an",
"ISO",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L68-L76 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.from_name | def from_name(cls, name):
"""Retrieve datacenter id associated to a name."""
result = cls.list()
dc_names = {}
for dc in result:
dc_names[dc['name']] = dc['id']
return dc_names.get(name) | python | def from_name(cls, name):
"""Retrieve datacenter id associated to a name."""
result = cls.list()
dc_names = {}
for dc in result:
dc_names[dc['name']] = dc['id']
return dc_names.get(name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
")",
"dc_names",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"dc_names",
"[",
"dc",
"[",
"'name'",
"]",
"]",
"=",
"dc",
"[",
"'id'",
"]",
"return",
"dc_names",
".",
"get",
"(",
"name",
")"
] | Retrieve datacenter id associated to a name. | [
"Retrieve",
"datacenter",
"id",
"associated",
"to",
"a",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L79-L86 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.from_country | def from_country(cls, country):
"""Retrieve the first datacenter id associated to a country."""
result = cls.list({'sort_by': 'id ASC'})
dc_countries = {}
for dc in result:
if dc['country'] not in dc_countries:
dc_countries[dc['country']] = dc['id']
return dc_countries.get(country) | python | def from_country(cls, country):
"""Retrieve the first datacenter id associated to a country."""
result = cls.list({'sort_by': 'id ASC'})
dc_countries = {}
for dc in result:
if dc['country'] not in dc_countries:
dc_countries[dc['country']] = dc['id']
return dc_countries.get(country) | [
"def",
"from_country",
"(",
"cls",
",",
"country",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"{",
"'sort_by'",
":",
"'id ASC'",
"}",
")",
"dc_countries",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"if",
"dc",
"[",
"'country'",
"]",
"not",
"in",
"dc_countries",
":",
"dc_countries",
"[",
"dc",
"[",
"'country'",
"]",
"]",
"=",
"dc",
"[",
"'id'",
"]",
"return",
"dc_countries",
".",
"get",
"(",
"country",
")"
] | Retrieve the first datacenter id associated to a country. | [
"Retrieve",
"the",
"first",
"datacenter",
"id",
"associated",
"to",
"a",
"country",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L89-L97 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.from_dc_code | def from_dc_code(cls, dc_code):
"""Retrieve the datacenter id associated to a dc_code"""
result = cls.list()
dc_codes = {}
for dc in result:
if dc.get('dc_code'):
dc_codes[dc['dc_code']] = dc['id']
return dc_codes.get(dc_code) | python | def from_dc_code(cls, dc_code):
"""Retrieve the datacenter id associated to a dc_code"""
result = cls.list()
dc_codes = {}
for dc in result:
if dc.get('dc_code'):
dc_codes[dc['dc_code']] = dc['id']
return dc_codes.get(dc_code) | [
"def",
"from_dc_code",
"(",
"cls",
",",
"dc_code",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
")",
"dc_codes",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"if",
"dc",
".",
"get",
"(",
"'dc_code'",
")",
":",
"dc_codes",
"[",
"dc",
"[",
"'dc_code'",
"]",
"]",
"=",
"dc",
"[",
"'id'",
"]",
"return",
"dc_codes",
".",
"get",
"(",
"dc_code",
")"
] | Retrieve the datacenter id associated to a dc_code | [
"Retrieve",
"the",
"datacenter",
"id",
"associated",
"to",
"a",
"dc_code"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L100-L108 | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | Datacenter.usable_id | def usable_id(cls, id):
""" Retrieve id from input which can be ISO, name, country, dc_code."""
try:
# id is maybe a dc_code
qry_id = cls.from_dc_code(id)
if not qry_id:
# id is maybe a ISO
qry_id = cls.from_iso(id)
if qry_id:
cls.deprecated('ISO code for datacenter filter use '
'dc_code instead')
if not qry_id:
# id is maybe a country
qry_id = cls.from_country(id)
if not qry_id:
qry_id = int(id)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | python | def usable_id(cls, id):
""" Retrieve id from input which can be ISO, name, country, dc_code."""
try:
# id is maybe a dc_code
qry_id = cls.from_dc_code(id)
if not qry_id:
# id is maybe a ISO
qry_id = cls.from_iso(id)
if qry_id:
cls.deprecated('ISO code for datacenter filter use '
'dc_code instead')
if not qry_id:
# id is maybe a country
qry_id = cls.from_country(id)
if not qry_id:
qry_id = int(id)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | [
"def",
"usable_id",
"(",
"cls",
",",
"id",
")",
":",
"try",
":",
"# id is maybe a dc_code",
"qry_id",
"=",
"cls",
".",
"from_dc_code",
"(",
"id",
")",
"if",
"not",
"qry_id",
":",
"# id is maybe a ISO",
"qry_id",
"=",
"cls",
".",
"from_iso",
"(",
"id",
")",
"if",
"qry_id",
":",
"cls",
".",
"deprecated",
"(",
"'ISO code for datacenter filter use '",
"'dc_code instead'",
")",
"if",
"not",
"qry_id",
":",
"# id is maybe a country",
"qry_id",
"=",
"cls",
".",
"from_country",
"(",
"id",
")",
"if",
"not",
"qry_id",
":",
"qry_id",
"=",
"int",
"(",
"id",
")",
"except",
"Exception",
":",
"qry_id",
"=",
"None",
"if",
"not",
"qry_id",
":",
"msg",
"=",
"'unknown identifier %s'",
"%",
"id",
"cls",
".",
"error",
"(",
"msg",
")",
"return",
"qry_id"
] | Retrieve id from input which can be ISO, name, country, dc_code. | [
"Retrieve",
"id",
"from",
"input",
"which",
"can",
"be",
"ISO",
"name",
"country",
"dc_code",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L111-L134 | train |
Gandi/gandi.cli | gandi/cli/core/utils/unixpipe.py | find_port | def find_port(addr, user):
"""Find local port in existing tunnels"""
import pwd
home = pwd.getpwuid(os.getuid()).pw_dir
for name in os.listdir('%s/.ssh/' % home):
if name.startswith('unixpipe_%s@%s_' % (user, addr,)):
return int(name.split('_')[2]) | python | def find_port(addr, user):
"""Find local port in existing tunnels"""
import pwd
home = pwd.getpwuid(os.getuid()).pw_dir
for name in os.listdir('%s/.ssh/' % home):
if name.startswith('unixpipe_%s@%s_' % (user, addr,)):
return int(name.split('_')[2]) | [
"def",
"find_port",
"(",
"addr",
",",
"user",
")",
":",
"import",
"pwd",
"home",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
".",
"pw_dir",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"'%s/.ssh/'",
"%",
"home",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'unixpipe_%s@%s_'",
"%",
"(",
"user",
",",
"addr",
",",
")",
")",
":",
"return",
"int",
"(",
"name",
".",
"split",
"(",
"'_'",
")",
"[",
"2",
"]",
")"
] | Find local port in existing tunnels | [
"Find",
"local",
"port",
"in",
"existing",
"tunnels"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/unixpipe.py#L128-L134 | train |
Gandi/gandi.cli | gandi/cli/core/utils/unixpipe.py | new_port | def new_port():
"""Find a free local port and allocate it"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
for i in range(12042, 16042):
try:
s.bind(('127.0.0.1', i))
s.close()
return i
except socket.error:
pass
raise Exception('No local port available') | python | def new_port():
"""Find a free local port and allocate it"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
for i in range(12042, 16042):
try:
s.bind(('127.0.0.1', i))
s.close()
return i
except socket.error:
pass
raise Exception('No local port available') | [
"def",
"new_port",
"(",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
",",
"socket",
".",
"IPPROTO_TCP",
")",
"for",
"i",
"in",
"range",
"(",
"12042",
",",
"16042",
")",
":",
"try",
":",
"s",
".",
"bind",
"(",
"(",
"'127.0.0.1'",
",",
"i",
")",
")",
"s",
".",
"close",
"(",
")",
"return",
"i",
"except",
"socket",
".",
"error",
":",
"pass",
"raise",
"Exception",
"(",
"'No local port available'",
")"
] | Find a free local port and allocate it | [
"Find",
"a",
"free",
"local",
"port",
"and",
"allocate",
"it"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/unixpipe.py#L137-L147 | train |
Gandi/gandi.cli | gandi/cli/core/utils/unixpipe.py | _ssh_master_cmd | def _ssh_master_cmd(addr, user, command, local_key=None):
"""Exit or check ssh mux"""
ssh_call = ['ssh', '-qNfL%d:127.0.0.1:12042' % find_port(addr, user),
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' %
find_port(addr, user),
'-O', command, '%s@%s' % (user, addr,)]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, '-i')
return subprocess.call(ssh_call) | python | def _ssh_master_cmd(addr, user, command, local_key=None):
"""Exit or check ssh mux"""
ssh_call = ['ssh', '-qNfL%d:127.0.0.1:12042' % find_port(addr, user),
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' %
find_port(addr, user),
'-O', command, '%s@%s' % (user, addr,)]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, '-i')
return subprocess.call(ssh_call) | [
"def",
"_ssh_master_cmd",
"(",
"addr",
",",
"user",
",",
"command",
",",
"local_key",
"=",
"None",
")",
":",
"ssh_call",
"=",
"[",
"'ssh'",
",",
"'-qNfL%d:127.0.0.1:12042'",
"%",
"find_port",
"(",
"addr",
",",
"user",
")",
",",
"'-o'",
",",
"'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d'",
"%",
"find_port",
"(",
"addr",
",",
"user",
")",
",",
"'-O'",
",",
"command",
",",
"'%s@%s'",
"%",
"(",
"user",
",",
"addr",
",",
")",
"]",
"if",
"local_key",
":",
"ssh_call",
".",
"insert",
"(",
"1",
",",
"local_key",
")",
"ssh_call",
".",
"insert",
"(",
"1",
",",
"'-i'",
")",
"return",
"subprocess",
".",
"call",
"(",
"ssh_call",
")"
] | Exit or check ssh mux | [
"Exit",
"or",
"check",
"ssh",
"mux"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/unixpipe.py#L150-L161 | train |
Gandi/gandi.cli | gandi/cli/core/utils/unixpipe.py | setup | def setup(addr, user, remote_path, local_key=None):
"""Setup the tunnel"""
port = find_port(addr, user)
if not port or not is_alive(addr, user):
port = new_port()
scp(addr, user, __file__, '~/unixpipe', local_key)
ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
'-o', 'ControlMaster=auto',
'%s@%s' % (user, addr,), 'python', '~/unixpipe',
'server', remote_path]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, '-i')
subprocess.call(ssh_call)
# XXX Sleep is a bad way to wait for the tunnel endpoint
time.sleep(1)
return port | python | def setup(addr, user, remote_path, local_key=None):
"""Setup the tunnel"""
port = find_port(addr, user)
if not port or not is_alive(addr, user):
port = new_port()
scp(addr, user, __file__, '~/unixpipe', local_key)
ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
'-o', 'ControlMaster=auto',
'%s@%s' % (user, addr,), 'python', '~/unixpipe',
'server', remote_path]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, '-i')
subprocess.call(ssh_call)
# XXX Sleep is a bad way to wait for the tunnel endpoint
time.sleep(1)
return port | [
"def",
"setup",
"(",
"addr",
",",
"user",
",",
"remote_path",
",",
"local_key",
"=",
"None",
")",
":",
"port",
"=",
"find_port",
"(",
"addr",
",",
"user",
")",
"if",
"not",
"port",
"or",
"not",
"is_alive",
"(",
"addr",
",",
"user",
")",
":",
"port",
"=",
"new_port",
"(",
")",
"scp",
"(",
"addr",
",",
"user",
",",
"__file__",
",",
"'~/unixpipe'",
",",
"local_key",
")",
"ssh_call",
"=",
"[",
"'ssh'",
",",
"'-fL%d:127.0.0.1:12042'",
"%",
"port",
",",
"'-o'",
",",
"'ExitOnForwardFailure=yes'",
",",
"'-o'",
",",
"'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d'",
"%",
"port",
",",
"'-o'",
",",
"'ControlMaster=auto'",
",",
"'%s@%s'",
"%",
"(",
"user",
",",
"addr",
",",
")",
",",
"'python'",
",",
"'~/unixpipe'",
",",
"'server'",
",",
"remote_path",
"]",
"if",
"local_key",
":",
"ssh_call",
".",
"insert",
"(",
"1",
",",
"local_key",
")",
"ssh_call",
".",
"insert",
"(",
"1",
",",
"'-i'",
")",
"subprocess",
".",
"call",
"(",
"ssh_call",
")",
"# XXX Sleep is a bad way to wait for the tunnel endpoint",
"time",
".",
"sleep",
"(",
"1",
")",
"return",
"port"
] | Setup the tunnel | [
"Setup",
"the",
"tunnel"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/unixpipe.py#L169-L192 | train |
Gandi/gandi.cli | gandi/cli/commands/oper.py | list | def list(gandi, limit, step):
"""List operations."""
output_keys = ['id', 'type', 'step']
options = {
'step': step,
'items_per_page': limit,
'sort_by': 'date_created DESC'
}
result = gandi.oper.list(options)
for num, oper in enumerate(reversed(result)):
if num:
gandi.separator_line()
output_generic(gandi, oper, output_keys)
return result | python | def list(gandi, limit, step):
"""List operations."""
output_keys = ['id', 'type', 'step']
options = {
'step': step,
'items_per_page': limit,
'sort_by': 'date_created DESC'
}
result = gandi.oper.list(options)
for num, oper in enumerate(reversed(result)):
if num:
gandi.separator_line()
output_generic(gandi, oper, output_keys)
return result | [
"def",
"list",
"(",
"gandi",
",",
"limit",
",",
"step",
")",
":",
"output_keys",
"=",
"[",
"'id'",
",",
"'type'",
",",
"'step'",
"]",
"options",
"=",
"{",
"'step'",
":",
"step",
",",
"'items_per_page'",
":",
"limit",
",",
"'sort_by'",
":",
"'date_created DESC'",
"}",
"result",
"=",
"gandi",
".",
"oper",
".",
"list",
"(",
"options",
")",
"for",
"num",
",",
"oper",
"in",
"enumerate",
"(",
"reversed",
"(",
"result",
")",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_generic",
"(",
"gandi",
",",
"oper",
",",
"output_keys",
")",
"return",
"result"
] | List operations. | [
"List",
"operations",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/oper.py#L23-L39 | train |
Gandi/gandi.cli | gandi/cli/commands/oper.py | info | def info(gandi, id):
"""Display information about an operation."""
output_keys = ['id', 'type', 'step', 'last_error']
oper = gandi.oper.info(id)
output_generic(gandi, oper, output_keys)
return oper | python | def info(gandi, id):
"""Display information about an operation."""
output_keys = ['id', 'type', 'step', 'last_error']
oper = gandi.oper.info(id)
output_generic(gandi, oper, output_keys)
return oper | [
"def",
"info",
"(",
"gandi",
",",
"id",
")",
":",
"output_keys",
"=",
"[",
"'id'",
",",
"'type'",
",",
"'step'",
",",
"'last_error'",
"]",
"oper",
"=",
"gandi",
".",
"oper",
".",
"info",
"(",
"id",
")",
"output_generic",
"(",
"gandi",
",",
"oper",
",",
"output_keys",
")",
"return",
"oper"
] | Display information about an operation. | [
"Display",
"information",
"about",
"an",
"operation",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/oper.py#L45-L52 | train |
Gandi/gandi.cli | gandi/cli/commands/dnssec.py | create | def create(gandi, resource, flags, algorithm, public_key):
"""Create DNSSEC key."""
result = gandi.dnssec.create(resource, flags, algorithm, public_key)
return result | python | def create(gandi, resource, flags, algorithm, public_key):
"""Create DNSSEC key."""
result = gandi.dnssec.create(resource, flags, algorithm, public_key)
return result | [
"def",
"create",
"(",
"gandi",
",",
"resource",
",",
"flags",
",",
"algorithm",
",",
"public_key",
")",
":",
"result",
"=",
"gandi",
".",
"dnssec",
".",
"create",
"(",
"resource",
",",
"flags",
",",
"algorithm",
",",
"public_key",
")",
"return",
"result"
] | Create DNSSEC key. | [
"Create",
"DNSSEC",
"key",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dnssec.py#L23-L28 | train |
Gandi/gandi.cli | gandi/cli/commands/dnssec.py | list | def list(gandi, resource):
"""List DNSSEC keys."""
keys = gandi.dnssec.list(resource)
gandi.pretty_echo(keys)
return keys | python | def list(gandi, resource):
"""List DNSSEC keys."""
keys = gandi.dnssec.list(resource)
gandi.pretty_echo(keys)
return keys | [
"def",
"list",
"(",
"gandi",
",",
"resource",
")",
":",
"keys",
"=",
"gandi",
".",
"dnssec",
".",
"list",
"(",
"resource",
")",
"gandi",
".",
"pretty_echo",
"(",
"keys",
")",
"return",
"keys"
] | List DNSSEC keys. | [
"List",
"DNSSEC",
"keys",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dnssec.py#L34-L39 | train |
Gandi/gandi.cli | gandi/cli/commands/dnssec.py | delete | def delete(gandi, resource):
"""Delete DNSSEC key.
"""
result = gandi.dnssec.delete(resource)
gandi.echo('Delete successful.')
return result | python | def delete(gandi, resource):
"""Delete DNSSEC key.
"""
result = gandi.dnssec.delete(resource)
gandi.echo('Delete successful.')
return result | [
"def",
"delete",
"(",
"gandi",
",",
"resource",
")",
":",
"result",
"=",
"gandi",
".",
"dnssec",
".",
"delete",
"(",
"resource",
")",
"gandi",
".",
"echo",
"(",
"'Delete successful.'",
")",
"return",
"result"
] | Delete DNSSEC key. | [
"Delete",
"DNSSEC",
"key",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dnssec.py#L45-L52 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.load_config | def load_config(cls):
""" Load global and local configuration files and update if needed."""
config_file = os.path.expanduser(cls.home_config)
global_conf = cls.load(config_file, 'global')
cls.load(cls.local_config, 'local')
# update global configuration if needed
cls.update_config(config_file, global_conf) | python | def load_config(cls):
""" Load global and local configuration files and update if needed."""
config_file = os.path.expanduser(cls.home_config)
global_conf = cls.load(config_file, 'global')
cls.load(cls.local_config, 'local')
# update global configuration if needed
cls.update_config(config_file, global_conf) | [
"def",
"load_config",
"(",
"cls",
")",
":",
"config_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"cls",
".",
"home_config",
")",
"global_conf",
"=",
"cls",
".",
"load",
"(",
"config_file",
",",
"'global'",
")",
"cls",
".",
"load",
"(",
"cls",
".",
"local_config",
",",
"'local'",
")",
"# update global configuration if needed",
"cls",
".",
"update_config",
"(",
"config_file",
",",
"global_conf",
")"
] | Load global and local configuration files and update if needed. | [
"Load",
"global",
"and",
"local",
"configuration",
"files",
"and",
"update",
"if",
"needed",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L40-L46 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.update_config | def update_config(cls, config_file, config):
""" Update configuration if needed. """
need_save = False
# delete old env key
if 'api' in config and 'env' in config['api']:
del config['api']['env']
need_save = True
# convert old ssh_key configuration entry
ssh_key = config.get('ssh_key')
sshkeys = config.get('sshkey')
if ssh_key and not sshkeys:
config.update({'sshkey': [ssh_key]})
need_save = True
elif ssh_key and sshkeys:
config.update({'sshkey': sshkeys.append(ssh_key)})
need_save = True
# remove old value
if ssh_key:
del config['ssh_key']
need_save = True
# save to disk
if need_save:
cls.save(config_file, config) | python | def update_config(cls, config_file, config):
""" Update configuration if needed. """
need_save = False
# delete old env key
if 'api' in config and 'env' in config['api']:
del config['api']['env']
need_save = True
# convert old ssh_key configuration entry
ssh_key = config.get('ssh_key')
sshkeys = config.get('sshkey')
if ssh_key and not sshkeys:
config.update({'sshkey': [ssh_key]})
need_save = True
elif ssh_key and sshkeys:
config.update({'sshkey': sshkeys.append(ssh_key)})
need_save = True
# remove old value
if ssh_key:
del config['ssh_key']
need_save = True
# save to disk
if need_save:
cls.save(config_file, config) | [
"def",
"update_config",
"(",
"cls",
",",
"config_file",
",",
"config",
")",
":",
"need_save",
"=",
"False",
"# delete old env key",
"if",
"'api'",
"in",
"config",
"and",
"'env'",
"in",
"config",
"[",
"'api'",
"]",
":",
"del",
"config",
"[",
"'api'",
"]",
"[",
"'env'",
"]",
"need_save",
"=",
"True",
"# convert old ssh_key configuration entry",
"ssh_key",
"=",
"config",
".",
"get",
"(",
"'ssh_key'",
")",
"sshkeys",
"=",
"config",
".",
"get",
"(",
"'sshkey'",
")",
"if",
"ssh_key",
"and",
"not",
"sshkeys",
":",
"config",
".",
"update",
"(",
"{",
"'sshkey'",
":",
"[",
"ssh_key",
"]",
"}",
")",
"need_save",
"=",
"True",
"elif",
"ssh_key",
"and",
"sshkeys",
":",
"config",
".",
"update",
"(",
"{",
"'sshkey'",
":",
"sshkeys",
".",
"append",
"(",
"ssh_key",
")",
"}",
")",
"need_save",
"=",
"True",
"# remove old value",
"if",
"ssh_key",
":",
"del",
"config",
"[",
"'ssh_key'",
"]",
"need_save",
"=",
"True",
"# save to disk",
"if",
"need_save",
":",
"cls",
".",
"save",
"(",
"config_file",
",",
"config",
")"
] | Update configuration if needed. | [
"Update",
"configuration",
"if",
"needed",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L49-L72 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.load | def load(cls, filename, name=None):
""" Load yaml configuration from filename. """
if not os.path.exists(filename):
return {}
name = name or filename
if name not in cls._conffiles:
with open(filename) as fdesc:
content = yaml.load(fdesc, YAMLLoader)
# in case the file is empty
if content is None:
content = {}
cls._conffiles[name] = content
return cls._conffiles[name] | python | def load(cls, filename, name=None):
""" Load yaml configuration from filename. """
if not os.path.exists(filename):
return {}
name = name or filename
if name not in cls._conffiles:
with open(filename) as fdesc:
content = yaml.load(fdesc, YAMLLoader)
# in case the file is empty
if content is None:
content = {}
cls._conffiles[name] = content
return cls._conffiles[name] | [
"def",
"load",
"(",
"cls",
",",
"filename",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"{",
"}",
"name",
"=",
"name",
"or",
"filename",
"if",
"name",
"not",
"in",
"cls",
".",
"_conffiles",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fdesc",
":",
"content",
"=",
"yaml",
".",
"load",
"(",
"fdesc",
",",
"YAMLLoader",
")",
"# in case the file is empty",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"{",
"}",
"cls",
".",
"_conffiles",
"[",
"name",
"]",
"=",
"content",
"return",
"cls",
".",
"_conffiles",
"[",
"name",
"]"
] | Load yaml configuration from filename. | [
"Load",
"yaml",
"configuration",
"from",
"filename",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L75-L89 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.save | def save(cls, filename, config):
""" Save configuration to yaml file. """
mode = os.O_WRONLY | os.O_TRUNC | os.O_CREAT
with os.fdopen(os.open(filename, mode, 0o600), 'w') as fname:
yaml.safe_dump(config, fname, indent=4, default_flow_style=False) | python | def save(cls, filename, config):
""" Save configuration to yaml file. """
mode = os.O_WRONLY | os.O_TRUNC | os.O_CREAT
with os.fdopen(os.open(filename, mode, 0o600), 'w') as fname:
yaml.safe_dump(config, fname, indent=4, default_flow_style=False) | [
"def",
"save",
"(",
"cls",
",",
"filename",
",",
"config",
")",
":",
"mode",
"=",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_TRUNC",
"|",
"os",
".",
"O_CREAT",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"filename",
",",
"mode",
",",
"0o600",
")",
",",
"'w'",
")",
"as",
"fname",
":",
"yaml",
".",
"safe_dump",
"(",
"config",
",",
"fname",
",",
"indent",
"=",
"4",
",",
"default_flow_style",
"=",
"False",
")"
] | Save configuration to yaml file. | [
"Save",
"configuration",
"to",
"yaml",
"file",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L92-L96 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.get | def get(cls, key, default=None, separator='.', global_=False):
""" Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration
"""
# first check environnment variables
# if we're not in global scope
if not global_:
ret = os.environ.get(key.upper().replace('.', '_'))
if ret is not None:
return ret
# then check in local and global configuration unless global_=True
scopes = ['global'] if global_ else ['local', 'global']
for scope in scopes:
ret = cls._get(scope, key, default, separator)
if ret is not None and ret != default:
return ret
if ret is None or ret == default:
return default | python | def get(cls, key, default=None, separator='.', global_=False):
""" Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration
"""
# first check environnment variables
# if we're not in global scope
if not global_:
ret = os.environ.get(key.upper().replace('.', '_'))
if ret is not None:
return ret
# then check in local and global configuration unless global_=True
scopes = ['global'] if global_ else ['local', 'global']
for scope in scopes:
ret = cls._get(scope, key, default, separator)
if ret is not None and ret != default:
return ret
if ret is None or ret == default:
return default | [
"def",
"get",
"(",
"cls",
",",
"key",
",",
"default",
"=",
"None",
",",
"separator",
"=",
"'.'",
",",
"global_",
"=",
"False",
")",
":",
"# first check environnment variables",
"# if we're not in global scope",
"if",
"not",
"global_",
":",
"ret",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"key",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"return",
"ret",
"# then check in local and global configuration unless global_=True",
"scopes",
"=",
"[",
"'global'",
"]",
"if",
"global_",
"else",
"[",
"'local'",
",",
"'global'",
"]",
"for",
"scope",
"in",
"scopes",
":",
"ret",
"=",
"cls",
".",
"_get",
"(",
"scope",
",",
"key",
",",
"default",
",",
"separator",
")",
"if",
"ret",
"is",
"not",
"None",
"and",
"ret",
"!=",
"default",
":",
"return",
"ret",
"if",
"ret",
"is",
"None",
"or",
"ret",
"==",
"default",
":",
"return",
"default"
] | Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration | [
"Retrieve",
"a",
"key",
"value",
"from",
"loaded",
"configuration",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L165-L188 | train |
Gandi/gandi.cli | gandi/cli/core/conf.py | GandiConfig.configure | def configure(cls, global_, key, val):
""" Update and save configuration value to file. """
# first retrieve current configuration
scope = 'global' if global_ else 'local'
if scope not in cls._conffiles:
cls._conffiles[scope] = {}
config = cls._conffiles.get(scope, {})
# apply modification to fields
cls._set(scope, key, val)
conf_file = cls.home_config if global_ else cls.local_config
# save configuration to file
cls.save(os.path.expanduser(conf_file), config) | python | def configure(cls, global_, key, val):
""" Update and save configuration value to file. """
# first retrieve current configuration
scope = 'global' if global_ else 'local'
if scope not in cls._conffiles:
cls._conffiles[scope] = {}
config = cls._conffiles.get(scope, {})
# apply modification to fields
cls._set(scope, key, val)
conf_file = cls.home_config if global_ else cls.local_config
# save configuration to file
cls.save(os.path.expanduser(conf_file), config) | [
"def",
"configure",
"(",
"cls",
",",
"global_",
",",
"key",
",",
"val",
")",
":",
"# first retrieve current configuration",
"scope",
"=",
"'global'",
"if",
"global_",
"else",
"'local'",
"if",
"scope",
"not",
"in",
"cls",
".",
"_conffiles",
":",
"cls",
".",
"_conffiles",
"[",
"scope",
"]",
"=",
"{",
"}",
"config",
"=",
"cls",
".",
"_conffiles",
".",
"get",
"(",
"scope",
",",
"{",
"}",
")",
"# apply modification to fields",
"cls",
".",
"_set",
"(",
"scope",
",",
"key",
",",
"val",
")",
"conf_file",
"=",
"cls",
".",
"home_config",
"if",
"global_",
"else",
"cls",
".",
"local_config",
"# save configuration to file",
"cls",
".",
"save",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"conf_file",
")",
",",
"config",
")"
] | Update and save configuration value to file. | [
"Update",
"and",
"save",
"configuration",
"value",
"to",
"file",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L191-L202 | train |
Gandi/gandi.cli | gandi/cli/commands/account.py | info | def info(gandi):
"""Display information about hosting account.
"""
output_keys = ['handle', 'credit', 'prepaid']
account = gandi.account.all()
account['prepaid_info'] = gandi.contact.balance().get('prepaid', {})
output_account(gandi, account, output_keys)
return account | python | def info(gandi):
"""Display information about hosting account.
"""
output_keys = ['handle', 'credit', 'prepaid']
account = gandi.account.all()
account['prepaid_info'] = gandi.contact.balance().get('prepaid', {})
output_account(gandi, account, output_keys)
return account | [
"def",
"info",
"(",
"gandi",
")",
":",
"output_keys",
"=",
"[",
"'handle'",
",",
"'credit'",
",",
"'prepaid'",
"]",
"account",
"=",
"gandi",
".",
"account",
".",
"all",
"(",
")",
"account",
"[",
"'prepaid_info'",
"]",
"=",
"gandi",
".",
"contact",
".",
"balance",
"(",
")",
".",
"get",
"(",
"'prepaid'",
",",
"{",
"}",
")",
"output_account",
"(",
"gandi",
",",
"account",
",",
"output_keys",
")",
"return",
"account"
] | Display information about hosting account. | [
"Display",
"information",
"about",
"hosting",
"account",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/account.py#L16-L24 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Ip.create | def create(cls, ip_version, datacenter, bandwidth, vm=None, vlan=None,
ip=None, background=False):
""" Create a public ip and attach it if vm is given. """
return Iface.create(ip_version, datacenter, bandwidth, vlan, vm, ip,
background) | python | def create(cls, ip_version, datacenter, bandwidth, vm=None, vlan=None,
ip=None, background=False):
""" Create a public ip and attach it if vm is given. """
return Iface.create(ip_version, datacenter, bandwidth, vlan, vm, ip,
background) | [
"def",
"create",
"(",
"cls",
",",
"ip_version",
",",
"datacenter",
",",
"bandwidth",
",",
"vm",
"=",
"None",
",",
"vlan",
"=",
"None",
",",
"ip",
"=",
"None",
",",
"background",
"=",
"False",
")",
":",
"return",
"Iface",
".",
"create",
"(",
"ip_version",
",",
"datacenter",
",",
"bandwidth",
",",
"vlan",
",",
"vm",
",",
"ip",
",",
"background",
")"
] | Create a public ip and attach it if vm is given. | [
"Create",
"a",
"public",
"ip",
"and",
"attach",
"it",
"if",
"vm",
"is",
"given",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L39-L43 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Ip.update | def update(cls, resource, params, background=False):
""" Update this IP """
cls.echo('Updating your IP')
result = cls.call('hosting.ip.update', cls.usable_id(resource),
params)
if not background:
cls.display_progress(result)
return result | python | def update(cls, resource, params, background=False):
""" Update this IP """
cls.echo('Updating your IP')
result = cls.call('hosting.ip.update', cls.usable_id(resource),
params)
if not background:
cls.display_progress(result)
return result | [
"def",
"update",
"(",
"cls",
",",
"resource",
",",
"params",
",",
"background",
"=",
"False",
")",
":",
"cls",
".",
"echo",
"(",
"'Updating your IP'",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.ip.update'",
",",
"cls",
".",
"usable_id",
"(",
"resource",
")",
",",
"params",
")",
"if",
"not",
"background",
":",
"cls",
".",
"display_progress",
"(",
"result",
")",
"return",
"result"
] | Update this IP | [
"Update",
"this",
"IP"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L46-L53 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Ip.delete | def delete(cls, resources, background=False, force=False):
"""Delete an ip by deleting the iface"""
if not isinstance(resources, (list, tuple)):
resources = [resources]
ifaces = []
for item in resources:
try:
ip_ = cls.info(item)
except UsageError:
cls.error("Can't find this ip %s" % item)
iface = Iface.info(ip_['iface_id'])
ifaces.append(iface['id'])
return Iface.delete(ifaces, background) | python | def delete(cls, resources, background=False, force=False):
"""Delete an ip by deleting the iface"""
if not isinstance(resources, (list, tuple)):
resources = [resources]
ifaces = []
for item in resources:
try:
ip_ = cls.info(item)
except UsageError:
cls.error("Can't find this ip %s" % item)
iface = Iface.info(ip_['iface_id'])
ifaces.append(iface['id'])
return Iface.delete(ifaces, background) | [
"def",
"delete",
"(",
"cls",
",",
"resources",
",",
"background",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"resources",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"resources",
"=",
"[",
"resources",
"]",
"ifaces",
"=",
"[",
"]",
"for",
"item",
"in",
"resources",
":",
"try",
":",
"ip_",
"=",
"cls",
".",
"info",
"(",
"item",
")",
"except",
"UsageError",
":",
"cls",
".",
"error",
"(",
"\"Can't find this ip %s\"",
"%",
"item",
")",
"iface",
"=",
"Iface",
".",
"info",
"(",
"ip_",
"[",
"'iface_id'",
"]",
")",
"ifaces",
".",
"append",
"(",
"iface",
"[",
"'id'",
"]",
")",
"return",
"Iface",
".",
"delete",
"(",
"ifaces",
",",
"background",
")"
] | Delete an ip by deleting the iface | [
"Delete",
"an",
"ip",
"by",
"deleting",
"the",
"iface"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L113-L128 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Ip.from_ip | def from_ip(cls, ip):
"""Retrieve ip id associated to an ip."""
ips = dict([(ip_['ip'], ip_['id'])
for ip_ in cls.list({'items_per_page': 500})])
return ips.get(ip) | python | def from_ip(cls, ip):
"""Retrieve ip id associated to an ip."""
ips = dict([(ip_['ip'], ip_['id'])
for ip_ in cls.list({'items_per_page': 500})])
return ips.get(ip) | [
"def",
"from_ip",
"(",
"cls",
",",
"ip",
")",
":",
"ips",
"=",
"dict",
"(",
"[",
"(",
"ip_",
"[",
"'ip'",
"]",
",",
"ip_",
"[",
"'id'",
"]",
")",
"for",
"ip_",
"in",
"cls",
".",
"list",
"(",
"{",
"'items_per_page'",
":",
"500",
"}",
")",
"]",
")",
"return",
"ips",
".",
"get",
"(",
"ip",
")"
] | Retrieve ip id associated to an ip. | [
"Retrieve",
"ip",
"id",
"associated",
"to",
"an",
"ip",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L131-L135 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.list | def list(cls, datacenter=None):
"""List virtual machine vlan
(in the future it should also handle PaaS vlan)."""
options = {}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
return cls.call('hosting.vlan.list', options) | python | def list(cls, datacenter=None):
"""List virtual machine vlan
(in the future it should also handle PaaS vlan)."""
options = {}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
return cls.call('hosting.vlan.list', options) | [
"def",
"list",
"(",
"cls",
",",
"datacenter",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"if",
"datacenter",
":",
"datacenter_id",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"options",
"[",
"'datacenter_id'",
"]",
"=",
"datacenter_id",
"return",
"cls",
".",
"call",
"(",
"'hosting.vlan.list'",
",",
"options",
")"
] | List virtual machine vlan
(in the future it should also handle PaaS vlan). | [
"List",
"virtual",
"machine",
"vlan"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L168-L177 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.ifaces | def ifaces(cls, name):
""" Get vlan attached ifaces. """
ifaces = Iface.list({'vlan_id': cls.usable_id(name)})
ret = []
for iface in ifaces:
ret.append(Iface.info(iface['id']))
return ret | python | def ifaces(cls, name):
""" Get vlan attached ifaces. """
ifaces = Iface.list({'vlan_id': cls.usable_id(name)})
ret = []
for iface in ifaces:
ret.append(Iface.info(iface['id']))
return ret | [
"def",
"ifaces",
"(",
"cls",
",",
"name",
")",
":",
"ifaces",
"=",
"Iface",
".",
"list",
"(",
"{",
"'vlan_id'",
":",
"cls",
".",
"usable_id",
"(",
"name",
")",
"}",
")",
"ret",
"=",
"[",
"]",
"for",
"iface",
"in",
"ifaces",
":",
"ret",
".",
"append",
"(",
"Iface",
".",
"info",
"(",
"iface",
"[",
"'id'",
"]",
")",
")",
"return",
"ret"
] | Get vlan attached ifaces. | [
"Get",
"vlan",
"attached",
"ifaces",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L188-L194 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.delete | def delete(cls, resources, background=False):
"""Delete a vlan."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
opers = []
for item in resources:
oper = cls.call('hosting.vlan.delete', cls.usable_id(item))
if not oper:
continue
if isinstance(oper, list):
opers.extend(oper)
else:
opers.append(oper)
if background:
return opers
# interactive mode, run a progress bar
cls.echo('Deleting your vlan.')
if opers:
cls.display_progress(opers) | python | def delete(cls, resources, background=False):
"""Delete a vlan."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
opers = []
for item in resources:
oper = cls.call('hosting.vlan.delete', cls.usable_id(item))
if not oper:
continue
if isinstance(oper, list):
opers.extend(oper)
else:
opers.append(oper)
if background:
return opers
# interactive mode, run a progress bar
cls.echo('Deleting your vlan.')
if opers:
cls.display_progress(opers) | [
"def",
"delete",
"(",
"cls",
",",
"resources",
",",
"background",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"resources",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"resources",
"=",
"[",
"resources",
"]",
"opers",
"=",
"[",
"]",
"for",
"item",
"in",
"resources",
":",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.vlan.delete'",
",",
"cls",
".",
"usable_id",
"(",
"item",
")",
")",
"if",
"not",
"oper",
":",
"continue",
"if",
"isinstance",
"(",
"oper",
",",
"list",
")",
":",
"opers",
".",
"extend",
"(",
"oper",
")",
"else",
":",
"opers",
".",
"append",
"(",
"oper",
")",
"if",
"background",
":",
"return",
"opers",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Deleting your vlan.'",
")",
"if",
"opers",
":",
"cls",
".",
"display_progress",
"(",
"opers",
")"
] | Delete a vlan. | [
"Delete",
"a",
"vlan",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L207-L229 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.create | def create(cls, name, datacenter, subnet=None, gateway=None,
background=False):
"""Create a new vlan."""
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
vlan_params = {
'name': name,
'datacenter_id': datacenter_id_,
}
if subnet:
vlan_params['subnet'] = subnet
if gateway:
vlan_params['gateway'] = gateway
result = cls.call('hosting.vlan.create', vlan_params)
if not background:
# interactive mode, run a progress bar
cls.echo('Creating your vlan.')
cls.display_progress(result)
cls.echo('Your vlan %s has been created.' % name)
return result | python | def create(cls, name, datacenter, subnet=None, gateway=None,
background=False):
"""Create a new vlan."""
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
vlan_params = {
'name': name,
'datacenter_id': datacenter_id_,
}
if subnet:
vlan_params['subnet'] = subnet
if gateway:
vlan_params['gateway'] = gateway
result = cls.call('hosting.vlan.create', vlan_params)
if not background:
# interactive mode, run a progress bar
cls.echo('Creating your vlan.')
cls.display_progress(result)
cls.echo('Your vlan %s has been created.' % name)
return result | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"datacenter",
",",
"subnet",
"=",
"None",
",",
"gateway",
"=",
"None",
",",
"background",
"=",
"False",
")",
":",
"if",
"not",
"background",
"and",
"not",
"cls",
".",
"intty",
"(",
")",
":",
"background",
"=",
"True",
"datacenter_id_",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"vlan_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'datacenter_id'",
":",
"datacenter_id_",
",",
"}",
"if",
"subnet",
":",
"vlan_params",
"[",
"'subnet'",
"]",
"=",
"subnet",
"if",
"gateway",
":",
"vlan_params",
"[",
"'gateway'",
"]",
"=",
"gateway",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.vlan.create'",
",",
"vlan_params",
")",
"if",
"not",
"background",
":",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Creating your vlan.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"cls",
".",
"echo",
"(",
"'Your vlan %s has been created.'",
"%",
"name",
")",
"return",
"result"
] | Create a new vlan. | [
"Create",
"a",
"new",
"vlan",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L232-L258 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.update | def update(cls, id, params):
"""Update an existing vlan."""
cls.echo('Updating your vlan.')
result = cls.call('hosting.vlan.update', cls.usable_id(id), params)
return result | python | def update(cls, id, params):
"""Update an existing vlan."""
cls.echo('Updating your vlan.')
result = cls.call('hosting.vlan.update', cls.usable_id(id), params)
return result | [
"def",
"update",
"(",
"cls",
",",
"id",
",",
"params",
")",
":",
"cls",
".",
"echo",
"(",
"'Updating your vlan.'",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.vlan.update'",
",",
"cls",
".",
"usable_id",
"(",
"id",
")",
",",
"params",
")",
"return",
"result"
] | Update an existing vlan. | [
"Update",
"an",
"existing",
"vlan",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L261-L265 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Vlan.from_name | def from_name(cls, name):
"""Retrieve vlan id associated to a name."""
result = cls.list()
vlans = {}
for vlan in result:
vlans[vlan['name']] = vlan['id']
return vlans.get(name) | python | def from_name(cls, name):
"""Retrieve vlan id associated to a name."""
result = cls.list()
vlans = {}
for vlan in result:
vlans[vlan['name']] = vlan['id']
return vlans.get(name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
")",
"vlans",
"=",
"{",
"}",
"for",
"vlan",
"in",
"result",
":",
"vlans",
"[",
"vlan",
"[",
"'name'",
"]",
"]",
"=",
"vlan",
"[",
"'id'",
"]",
"return",
"vlans",
".",
"get",
"(",
"name",
")"
] | Retrieve vlan id associated to a name. | [
"Retrieve",
"vlan",
"id",
"associated",
"to",
"a",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L268-L275 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Iface.usable_id | def usable_id(cls, id):
""" Retrieve id from input which can be num or id."""
try:
qry_id = int(id)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | python | def usable_id(cls, id):
""" Retrieve id from input which can be num or id."""
try:
qry_id = int(id)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | [
"def",
"usable_id",
"(",
"cls",
",",
"id",
")",
":",
"try",
":",
"qry_id",
"=",
"int",
"(",
"id",
")",
"except",
"Exception",
":",
"qry_id",
"=",
"None",
"if",
"not",
"qry_id",
":",
"msg",
"=",
"'unknown identifier %s'",
"%",
"id",
"cls",
".",
"error",
"(",
"msg",
")",
"return",
"qry_id"
] | Retrieve id from input which can be num or id. | [
"Retrieve",
"id",
"from",
"input",
"which",
"can",
"be",
"num",
"or",
"id",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L324-L335 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Iface._attach | def _attach(cls, iface_id, vm_id):
""" Attach an iface to a vm. """
oper = cls.call('hosting.vm.iface_attach', vm_id, iface_id)
return oper | python | def _attach(cls, iface_id, vm_id):
""" Attach an iface to a vm. """
oper = cls.call('hosting.vm.iface_attach', vm_id, iface_id)
return oper | [
"def",
"_attach",
"(",
"cls",
",",
"iface_id",
",",
"vm_id",
")",
":",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.vm.iface_attach'",
",",
"vm_id",
",",
"iface_id",
")",
"return",
"oper"
] | Attach an iface to a vm. | [
"Attach",
"an",
"iface",
"to",
"a",
"vm",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L338-L341 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Iface.create | def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip,
background):
""" Create a new iface """
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
iface_params = {
'ip_version': ip_version,
'datacenter_id': datacenter_id_,
'bandwidth': bandwidth,
}
if vlan:
iface_params['vlan'] = Vlan.usable_id(vlan)
if ip:
iface_params['ip'] = ip
result = cls.call('hosting.iface.create', iface_params)
if background and not vm:
return result
# interactive mode, run a progress bar
cls.echo('Creating your iface.')
cls.display_progress(result)
iface_info = cls._info(result['iface_id'])
cls.echo('Your iface has been created with the following IP '
'addresses:')
for _ip in iface_info['ips']:
cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip']))
if not vm:
return result
vm_id = Iaas.usable_id(vm)
result = cls._attach(result['iface_id'], vm_id)
if background:
return result
cls.echo('Attaching your iface.')
cls.display_progress(result)
return result | python | def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip,
background):
""" Create a new iface """
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
iface_params = {
'ip_version': ip_version,
'datacenter_id': datacenter_id_,
'bandwidth': bandwidth,
}
if vlan:
iface_params['vlan'] = Vlan.usable_id(vlan)
if ip:
iface_params['ip'] = ip
result = cls.call('hosting.iface.create', iface_params)
if background and not vm:
return result
# interactive mode, run a progress bar
cls.echo('Creating your iface.')
cls.display_progress(result)
iface_info = cls._info(result['iface_id'])
cls.echo('Your iface has been created with the following IP '
'addresses:')
for _ip in iface_info['ips']:
cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip']))
if not vm:
return result
vm_id = Iaas.usable_id(vm)
result = cls._attach(result['iface_id'], vm_id)
if background:
return result
cls.echo('Attaching your iface.')
cls.display_progress(result)
return result | [
"def",
"create",
"(",
"cls",
",",
"ip_version",
",",
"datacenter",
",",
"bandwidth",
",",
"vlan",
",",
"vm",
",",
"ip",
",",
"background",
")",
":",
"if",
"not",
"background",
"and",
"not",
"cls",
".",
"intty",
"(",
")",
":",
"background",
"=",
"True",
"datacenter_id_",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"iface_params",
"=",
"{",
"'ip_version'",
":",
"ip_version",
",",
"'datacenter_id'",
":",
"datacenter_id_",
",",
"'bandwidth'",
":",
"bandwidth",
",",
"}",
"if",
"vlan",
":",
"iface_params",
"[",
"'vlan'",
"]",
"=",
"Vlan",
".",
"usable_id",
"(",
"vlan",
")",
"if",
"ip",
":",
"iface_params",
"[",
"'ip'",
"]",
"=",
"ip",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.iface.create'",
",",
"iface_params",
")",
"if",
"background",
"and",
"not",
"vm",
":",
"return",
"result",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Creating your iface.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"iface_info",
"=",
"cls",
".",
"_info",
"(",
"result",
"[",
"'iface_id'",
"]",
")",
"cls",
".",
"echo",
"(",
"'Your iface has been created with the following IP '",
"'addresses:'",
")",
"for",
"_ip",
"in",
"iface_info",
"[",
"'ips'",
"]",
":",
"cls",
".",
"echo",
"(",
"'ip%d:\\t%s'",
"%",
"(",
"_ip",
"[",
"'version'",
"]",
",",
"_ip",
"[",
"'ip'",
"]",
")",
")",
"if",
"not",
"vm",
":",
"return",
"result",
"vm_id",
"=",
"Iaas",
".",
"usable_id",
"(",
"vm",
")",
"result",
"=",
"cls",
".",
"_attach",
"(",
"result",
"[",
"'iface_id'",
"]",
",",
"vm_id",
")",
"if",
"background",
":",
"return",
"result",
"cls",
".",
"echo",
"(",
"'Attaching your iface.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"return",
"result"
] | Create a new iface | [
"Create",
"a",
"new",
"iface"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L344-L387 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Iface._detach | def _detach(cls, iface_id):
""" Detach an iface from a vm. """
iface = cls._info(iface_id)
opers = []
vm_id = iface.get('vm_id')
if vm_id:
cls.echo('The iface is still attached to the vm %s.' % vm_id)
cls.echo('Will detach it.')
opers.append(cls.call('hosting.vm.iface_detach', vm_id, iface_id))
return opers | python | def _detach(cls, iface_id):
""" Detach an iface from a vm. """
iface = cls._info(iface_id)
opers = []
vm_id = iface.get('vm_id')
if vm_id:
cls.echo('The iface is still attached to the vm %s.' % vm_id)
cls.echo('Will detach it.')
opers.append(cls.call('hosting.vm.iface_detach', vm_id, iface_id))
return opers | [
"def",
"_detach",
"(",
"cls",
",",
"iface_id",
")",
":",
"iface",
"=",
"cls",
".",
"_info",
"(",
"iface_id",
")",
"opers",
"=",
"[",
"]",
"vm_id",
"=",
"iface",
".",
"get",
"(",
"'vm_id'",
")",
"if",
"vm_id",
":",
"cls",
".",
"echo",
"(",
"'The iface is still attached to the vm %s.'",
"%",
"vm_id",
")",
"cls",
".",
"echo",
"(",
"'Will detach it.'",
")",
"opers",
".",
"append",
"(",
"cls",
".",
"call",
"(",
"'hosting.vm.iface_detach'",
",",
"vm_id",
",",
"iface_id",
")",
")",
"return",
"opers"
] | Detach an iface from a vm. | [
"Detach",
"an",
"iface",
"from",
"a",
"vm",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L390-L399 | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | Iface.update | def update(cls, id, bandwidth, vm, background):
""" Update this iface. """
if not background and not cls.intty():
background = True
iface_params = {}
iface_id = cls.usable_id(id)
if bandwidth:
iface_params['bandwidth'] = bandwidth
if iface_params:
result = cls.call('hosting.iface.update', iface_id, iface_params)
if background:
return result
# interactive mode, run a progress bar
cls.echo('Updating your iface %s.' % id)
cls.display_progress(result)
if not vm:
return
vm_id = Iaas.usable_id(vm)
opers = cls._detach(iface_id)
if opers:
cls.echo('Detaching iface.')
cls.display_progress(opers)
result = cls._attach(iface_id, vm_id)
if background:
return result
cls.echo('Attaching your iface.')
cls.display_progress(result) | python | def update(cls, id, bandwidth, vm, background):
""" Update this iface. """
if not background and not cls.intty():
background = True
iface_params = {}
iface_id = cls.usable_id(id)
if bandwidth:
iface_params['bandwidth'] = bandwidth
if iface_params:
result = cls.call('hosting.iface.update', iface_id, iface_params)
if background:
return result
# interactive mode, run a progress bar
cls.echo('Updating your iface %s.' % id)
cls.display_progress(result)
if not vm:
return
vm_id = Iaas.usable_id(vm)
opers = cls._detach(iface_id)
if opers:
cls.echo('Detaching iface.')
cls.display_progress(opers)
result = cls._attach(iface_id, vm_id)
if background:
return result
cls.echo('Attaching your iface.')
cls.display_progress(result) | [
"def",
"update",
"(",
"cls",
",",
"id",
",",
"bandwidth",
",",
"vm",
",",
"background",
")",
":",
"if",
"not",
"background",
"and",
"not",
"cls",
".",
"intty",
"(",
")",
":",
"background",
"=",
"True",
"iface_params",
"=",
"{",
"}",
"iface_id",
"=",
"cls",
".",
"usable_id",
"(",
"id",
")",
"if",
"bandwidth",
":",
"iface_params",
"[",
"'bandwidth'",
"]",
"=",
"bandwidth",
"if",
"iface_params",
":",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.iface.update'",
",",
"iface_id",
",",
"iface_params",
")",
"if",
"background",
":",
"return",
"result",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Updating your iface %s.'",
"%",
"id",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"if",
"not",
"vm",
":",
"return",
"vm_id",
"=",
"Iaas",
".",
"usable_id",
"(",
"vm",
")",
"opers",
"=",
"cls",
".",
"_detach",
"(",
"iface_id",
")",
"if",
"opers",
":",
"cls",
".",
"echo",
"(",
"'Detaching iface.'",
")",
"cls",
".",
"display_progress",
"(",
"opers",
")",
"result",
"=",
"cls",
".",
"_attach",
"(",
"iface_id",
",",
"vm_id",
")",
"if",
"background",
":",
"return",
"result",
"cls",
".",
"echo",
"(",
"'Attaching your iface.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")"
] | Update this iface. | [
"Update",
"this",
"iface",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L430-L466 | train |
Gandi/gandi.cli | gandi/cli/modules/forward.py | Forward.get_destinations | def get_destinations(cls, domain, source):
"""Retrieve forward information."""
forwards = cls.list(domain, {'items_per_page': 500})
for fwd in forwards:
if fwd['source'] == source:
return fwd['destinations']
return [] | python | def get_destinations(cls, domain, source):
"""Retrieve forward information."""
forwards = cls.list(domain, {'items_per_page': 500})
for fwd in forwards:
if fwd['source'] == source:
return fwd['destinations']
return [] | [
"def",
"get_destinations",
"(",
"cls",
",",
"domain",
",",
"source",
")",
":",
"forwards",
"=",
"cls",
".",
"list",
"(",
"domain",
",",
"{",
"'items_per_page'",
":",
"500",
"}",
")",
"for",
"fwd",
"in",
"forwards",
":",
"if",
"fwd",
"[",
"'source'",
"]",
"==",
"source",
":",
"return",
"fwd",
"[",
"'destinations'",
"]",
"return",
"[",
"]"
] | Retrieve forward information. | [
"Retrieve",
"forward",
"information",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/forward.py#L37-L44 | train |
Gandi/gandi.cli | gandi/cli/modules/forward.py | Forward.update | def update(cls, domain, source, dest_add, dest_del):
"""Update a domain mail forward destinations."""
result = None
if dest_add or dest_del:
current_destinations = cls.get_destinations(domain, source)
fwds = current_destinations[:]
if dest_add:
for dest in dest_add:
if dest not in fwds:
fwds.append(dest)
if dest_del:
for dest in dest_del:
if dest in fwds:
fwds.remove(dest)
if ((len(current_destinations) != len(fwds))
or (current_destinations != fwds)):
cls.echo('Updating mail forward %s@%s' % (source, domain))
options = {'destinations': fwds}
result = cls.call('domain.forward.update', domain, source,
options)
return result | python | def update(cls, domain, source, dest_add, dest_del):
"""Update a domain mail forward destinations."""
result = None
if dest_add or dest_del:
current_destinations = cls.get_destinations(domain, source)
fwds = current_destinations[:]
if dest_add:
for dest in dest_add:
if dest not in fwds:
fwds.append(dest)
if dest_del:
for dest in dest_del:
if dest in fwds:
fwds.remove(dest)
if ((len(current_destinations) != len(fwds))
or (current_destinations != fwds)):
cls.echo('Updating mail forward %s@%s' % (source, domain))
options = {'destinations': fwds}
result = cls.call('domain.forward.update', domain, source,
options)
return result | [
"def",
"update",
"(",
"cls",
",",
"domain",
",",
"source",
",",
"dest_add",
",",
"dest_del",
")",
":",
"result",
"=",
"None",
"if",
"dest_add",
"or",
"dest_del",
":",
"current_destinations",
"=",
"cls",
".",
"get_destinations",
"(",
"domain",
",",
"source",
")",
"fwds",
"=",
"current_destinations",
"[",
":",
"]",
"if",
"dest_add",
":",
"for",
"dest",
"in",
"dest_add",
":",
"if",
"dest",
"not",
"in",
"fwds",
":",
"fwds",
".",
"append",
"(",
"dest",
")",
"if",
"dest_del",
":",
"for",
"dest",
"in",
"dest_del",
":",
"if",
"dest",
"in",
"fwds",
":",
"fwds",
".",
"remove",
"(",
"dest",
")",
"if",
"(",
"(",
"len",
"(",
"current_destinations",
")",
"!=",
"len",
"(",
"fwds",
")",
")",
"or",
"(",
"current_destinations",
"!=",
"fwds",
")",
")",
":",
"cls",
".",
"echo",
"(",
"'Updating mail forward %s@%s'",
"%",
"(",
"source",
",",
"domain",
")",
")",
"options",
"=",
"{",
"'destinations'",
":",
"fwds",
"}",
"result",
"=",
"cls",
".",
"call",
"(",
"'domain.forward.update'",
",",
"domain",
",",
"source",
",",
"options",
")",
"return",
"result"
] | Update a domain mail forward destinations. | [
"Update",
"a",
"domain",
"mail",
"forward",
"destinations",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/forward.py#L47-L70 | train |
Gandi/gandi.cli | gandi/cli/commands/mail.py | list | def list(gandi, domain, limit):
"""List mailboxes created on a domain."""
options = {'items_per_page': limit}
mailboxes = gandi.mail.list(domain, options)
output_list(gandi, [mbox['login'] for mbox in mailboxes])
return mailboxes | python | def list(gandi, domain, limit):
"""List mailboxes created on a domain."""
options = {'items_per_page': limit}
mailboxes = gandi.mail.list(domain, options)
output_list(gandi, [mbox['login'] for mbox in mailboxes])
return mailboxes | [
"def",
"list",
"(",
"gandi",
",",
"domain",
",",
"limit",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
"}",
"mailboxes",
"=",
"gandi",
".",
"mail",
".",
"list",
"(",
"domain",
",",
"options",
")",
"output_list",
"(",
"gandi",
",",
"[",
"mbox",
"[",
"'login'",
"]",
"for",
"mbox",
"in",
"mailboxes",
"]",
")",
"return",
"mailboxes"
] | List mailboxes created on a domain. | [
"List",
"mailboxes",
"created",
"on",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/mail.py#L21-L26 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.