repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
ask/redish | redish/types.py | SortedSet.remove | def remove(self, member):
"""Remove member."""
if not self.client.zrem(self.name, member):
raise KeyError(member) | python | def remove(self, member):
"""Remove member."""
if not self.client.zrem(self.name, member):
raise KeyError(member) | [
"def",
"remove",
"(",
"self",
",",
"member",
")",
":",
"if",
"not",
"self",
".",
"client",
".",
"zrem",
"(",
"self",
".",
"name",
",",
"member",
")",
":",
"raise",
"KeyError",
"(",
"member",
")"
] | Remove member. | [
"Remove",
"member",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L293-L296 |
ask/redish | redish/types.py | SortedSet.increment | def increment(self, member, amount=1):
"""Increment the score of ``member`` by ``amount``."""
return self.client.zincrby(self.name, member, amount) | python | def increment(self, member, amount=1):
"""Increment the score of ``member`` by ``amount``."""
return self.client.zincrby(self.name, member, amount) | [
"def",
"increment",
"(",
"self",
",",
"member",
",",
"amount",
"=",
"1",
")",
":",
"return",
"self",
".",
"client",
".",
"zincrby",
"(",
"self",
".",
"name",
",",
"member",
",",
"amount",
")"
] | Increment the score of ``member`` by ``amount``. | [
"Increment",
"the",
"score",
"of",
"member",
"by",
"amount",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L306-L308 |
ask/redish | redish/types.py | SortedSet.range_by_score | def range_by_score(self, min, max, num=None, withscores=False):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
return self.client.zrangebyscore(self.name, min, max, num=num,
withscores=withscores) | python | def range_by_score(self, min, max, num=None, withscores=False):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
return self.client.zrangebyscore(self.name, min, max, num=num,
withscores=withscores) | [
"def",
"range_by_score",
"(",
"self",
",",
"min",
",",
"max",
",",
"num",
"=",
"None",
",",
"withscores",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"zrangebyscore",
"(",
"self",
".",
"name",
",",
"min",
",",
"max",
",",
"num",
"... | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | [
"Return",
"all",
"the",
"elements",
"with",
"score",
">",
"=",
"min",
"and",
"score",
"<",
"=",
"max",
"(",
"a",
"range",
"query",
")",
"from",
"the",
"sorted",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L322-L326 |
ask/redish | redish/types.py | Dict.pop | def pop(self, key, *args, **kwargs):
"""Remove specified key and return the corresponding value.
:keyword default: If key is not found, ``default`` is returned if given,
otherwise :exc:`KeyError` is raised.
"""
try:
val = self[key]
except KeyError:
if len(args):
return args[0]
if "default" in kwargs:
return kwargs["default"]
raise
try:
del(self[key])
except KeyError:
pass
return val | python | def pop(self, key, *args, **kwargs):
"""Remove specified key and return the corresponding value.
:keyword default: If key is not found, ``default`` is returned if given,
otherwise :exc:`KeyError` is raised.
"""
try:
val = self[key]
except KeyError:
if len(args):
return args[0]
if "default" in kwargs:
return kwargs["default"]
raise
try:
del(self[key])
except KeyError:
pass
return val | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"len",
"(",
"args",
")",
":",
"return",
"args",
"[",
"0",
"]",
"if",... | Remove specified key and return the corresponding value.
:keyword default: If key is not found, ``default`` is returned if given,
otherwise :exc:`KeyError` is raised. | [
"Remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L439-L460 |
ask/redish | redish/types.py | Queue.full | def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False | python | def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False | [
"def",
"full",
"(",
"self",
")",
":",
"return",
"self",
".",
"maxsize",
"and",
"len",
"(",
"self",
".",
"list",
")",
">=",
"self",
".",
"maxsize",
"or",
"False"
] | Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set. | [
"Return",
"True",
"if",
"the",
"queue",
"is",
"full",
"False",
"otherwise",
"(",
"not",
"reliable!",
")",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L491-L498 |
ask/redish | redish/types.py | Queue.get | def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeout`` seconds and raises the :exc:`Queue.Empty` exception
if no item was available within that time. Otherwise (``block`` is
``False``), return an item if one is immediately available, else
raise the :exc:`Queue.Empty` exception (``timeout`` is ignored
in that case).
"""
if not block:
return self.get_nowait()
item = self._bpop([self.name], timeout=timeout)
if item is not None:
return item
raise Empty | python | def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeout`` seconds and raises the :exc:`Queue.Empty` exception
if no item was available within that time. Otherwise (``block`` is
``False``), return an item if one is immediately available, else
raise the :exc:`Queue.Empty` exception (``timeout`` is ignored
in that case).
"""
if not block:
return self.get_nowait()
item = self._bpop([self.name], timeout=timeout)
if item is not None:
return item
raise Empty | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"block",
":",
"return",
"self",
".",
"get_nowait",
"(",
")",
"item",
"=",
"self",
".",
"_bpop",
"(",
"[",
"self",
".",
"name",
"]",
",",
"... | Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeout`` seconds and raises the :exc:`Queue.Empty` exception
if no item was available within that time. Otherwise (``block`` is
``False``), return an item if one is immediately available, else
raise the :exc:`Queue.Empty` exception (``timeout`` is ignored
in that case). | [
"Remove",
"and",
"return",
"an",
"item",
"from",
"the",
"queue",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L500-L518 |
ask/redish | redish/types.py | Queue.put | def put(self, item, **kwargs):
"""Put an item into the queue."""
if self.full():
raise Full()
self._append(item) | python | def put(self, item, **kwargs):
"""Put an item into the queue."""
if self.full():
raise Full()
self._append(item) | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"full",
"(",
")",
":",
"raise",
"Full",
"(",
")",
"self",
".",
"_append",
"(",
"item",
")"
] | Put an item into the queue. | [
"Put",
"an",
"item",
"into",
"the",
"queue",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L531-L535 |
ask/redish | redish/types.py | ZSet.increment | def increment(self, member, amount=1):
"""Increment the score of ``member`` by ``amount``."""
self._dict[member] += amount
return self._dict[member] | python | def increment(self, member, amount=1):
"""Increment the score of ``member`` by ``amount``."""
self._dict[member] += amount
return self._dict[member] | [
"def",
"increment",
"(",
"self",
",",
"member",
",",
"amount",
"=",
"1",
")",
":",
"self",
".",
"_dict",
"[",
"member",
"]",
"+=",
"amount",
"return",
"self",
".",
"_dict",
"[",
"member",
"]"
] | Increment the score of ``member`` by ``amount``. | [
"Increment",
"the",
"score",
"of",
"member",
"by",
"amount",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L771-L774 |
ask/redish | redish/types.py | ZSet.range_by_score | def range_by_score(self, min, max):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
data = self.items()
keys = [r[1] for r in data]
start = bisect.bisect_left(keys, min)
end = bisect.bisect_right(keys, max, start)
return self._as_set()[start:end] | python | def range_by_score(self, min, max):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
data = self.items()
keys = [r[1] for r in data]
start = bisect.bisect_left(keys, min)
end = bisect.bisect_right(keys, max, start)
return self._as_set()[start:end] | [
"def",
"range_by_score",
"(",
"self",
",",
"min",
",",
"max",
")",
":",
"data",
"=",
"self",
".",
"items",
"(",
")",
"keys",
"=",
"[",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"data",
"]",
"start",
"=",
"bisect",
".",
"bisect_left",
"(",
"keys",
"... | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | [
"Return",
"all",
"the",
"elements",
"with",
"score",
">",
"=",
"min",
"and",
"score",
"<",
"=",
"max",
"(",
"a",
"range",
"query",
")",
"from",
"the",
"sorted",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L788-L795 |
noahgoldman/adbpy | adbpy/socket.py | Socket.connect | def connect(self):
"""Connect to the given socket"""
if not self.connected:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(self.address)
self.connected = True | python | def connect(self):
"""Connect to the given socket"""
if not self.connected:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(self.address)
self.connected = True | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"socket",
".",
"connect",
"(... | Connect to the given socket | [
"Connect",
"to",
"the",
"given",
"socket"
] | train | https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L30-L35 |
noahgoldman/adbpy | adbpy/socket.py | Socket.send | def send(self, data):
"""Send a formatted message to the ADB server"""
self._send_data(int_to_hex(len(data)))
self._send_data(data) | python | def send(self, data):
"""Send a formatted message to the ADB server"""
self._send_data(int_to_hex(len(data)))
self._send_data(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_send_data",
"(",
"int_to_hex",
"(",
"len",
"(",
"data",
")",
")",
")",
"self",
".",
"_send_data",
"(",
"data",
")"
] | Send a formatted message to the ADB server | [
"Send",
"a",
"formatted",
"message",
"to",
"the",
"ADB",
"server"
] | train | https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L42-L46 |
noahgoldman/adbpy | adbpy/socket.py | Socket._send_data | def _send_data(self, data):
"""Send data to the ADB server"""
total_sent = 0
while total_sent < len(data):
# Send only the bytes that haven't been
# sent yet
sent = self.socket.send(data[total_sent:].encode("ascii"))
if sent == 0:
self.close()
raise RuntimeError("Socket connection dropped, "
"send failed")
total_sent += sent | python | def _send_data(self, data):
"""Send data to the ADB server"""
total_sent = 0
while total_sent < len(data):
# Send only the bytes that haven't been
# sent yet
sent = self.socket.send(data[total_sent:].encode("ascii"))
if sent == 0:
self.close()
raise RuntimeError("Socket connection dropped, "
"send failed")
total_sent += sent | [
"def",
"_send_data",
"(",
"self",
",",
"data",
")",
":",
"total_sent",
"=",
"0",
"while",
"total_sent",
"<",
"len",
"(",
"data",
")",
":",
"# Send only the bytes that haven't been",
"# sent yet",
"sent",
"=",
"self",
".",
"socket",
".",
"send",
"(",
"data",
... | Send data to the ADB server | [
"Send",
"data",
"to",
"the",
"ADB",
"server"
] | train | https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L48-L61 |
noahgoldman/adbpy | adbpy/socket.py | Socket.receive_until_end | def receive_until_end(self, timeout=None):
"""
Reads and blocks until the socket closes
Used for the "shell" command, where STDOUT and STDERR
are just redirected to the terminal with no length
"""
if self.receive_fixed_length(4) != "OKAY":
raise SocketError("Socket communication failed: "
"the server did not return a valid response")
# The time at which the receive starts
start_time = time.clock()
output = ""
while True:
if timeout is not None:
self.socket.settimeout(timeout - (time.clock() - start_time))
chunk = ''
try:
chunk = self.socket.recv(4096).decode("ascii")
except socket.timeout:
return output
if not chunk:
return output
output += chunk | python | def receive_until_end(self, timeout=None):
"""
Reads and blocks until the socket closes
Used for the "shell" command, where STDOUT and STDERR
are just redirected to the terminal with no length
"""
if self.receive_fixed_length(4) != "OKAY":
raise SocketError("Socket communication failed: "
"the server did not return a valid response")
# The time at which the receive starts
start_time = time.clock()
output = ""
while True:
if timeout is not None:
self.socket.settimeout(timeout - (time.clock() - start_time))
chunk = ''
try:
chunk = self.socket.recv(4096).decode("ascii")
except socket.timeout:
return output
if not chunk:
return output
output += chunk | [
"def",
"receive_until_end",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"receive_fixed_length",
"(",
"4",
")",
"!=",
"\"OKAY\"",
":",
"raise",
"SocketError",
"(",
"\"Socket communication failed: \"",
"\"the server did not return a valid resp... | Reads and blocks until the socket closes
Used for the "shell" command, where STDOUT and STDERR
are just redirected to the terminal with no length | [
"Reads",
"and",
"blocks",
"until",
"the",
"socket",
"closes"
] | train | https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L102-L131 |
bitprophet/botox | botox/aws.py | defaults | def defaults(f, self, *args, **kwargs):
"""
For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values.
Should be applied on the top of any decorator stack so other decorators see
the "right" kwargs.
Will also apply transformations found in ``TRANSFORMS``.
"""
for name, data in PARAMETERS.iteritems():
kwargs[name] = kwargs.get(name) or getattr(self, name)
if 'transform' in data:
kwargs[name] = data['transform'](kwargs[name])
return f(self, *args, **kwargs) | python | def defaults(f, self, *args, **kwargs):
"""
For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values.
Should be applied on the top of any decorator stack so other decorators see
the "right" kwargs.
Will also apply transformations found in ``TRANSFORMS``.
"""
for name, data in PARAMETERS.iteritems():
kwargs[name] = kwargs.get(name) or getattr(self, name)
if 'transform' in data:
kwargs[name] = data['transform'](kwargs[name])
return f(self, *args, **kwargs) | [
"def",
"defaults",
"(",
"f",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"data",
"in",
"PARAMETERS",
".",
"iteritems",
"(",
")",
":",
"kwargs",
"[",
"name",
"]",
"=",
"kwargs",
".",
"get",
"(",
"name",
... | For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values.
Should be applied on the top of any decorator stack so other decorators see
the "right" kwargs.
Will also apply transformations found in ``TRANSFORMS``. | [
"For",
"PARAMETERS",
"keys",
"replace",
"None",
"kwargs",
"with",
"self",
"attr",
"values",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L81-L94 |
bitprophet/botox | botox/aws.py | requires | def requires(*params):
"""
Raise ValueError if any ``params`` are omitted from the decorated kwargs.
None values are considered omissions.
Example usage on an AWS() method:
@requires('zone', 'security_groups')
def my_aws_method(self, custom_args, **kwargs):
# We'll only get here if 'kwargs' contained non-None values for
# both 'zone' and 'security_groups'.
"""
def requires(f, self, *args, **kwargs):
missing = filter(lambda x: kwargs.get(x) is None, params)
if missing:
msgs = ", ".join([PARAMETERS[x]['msg'] for x in missing])
raise ValueError("Missing the following parameters: %s" % msgs)
return f(self, *args, **kwargs)
return decorator(requires) | python | def requires(*params):
"""
Raise ValueError if any ``params`` are omitted from the decorated kwargs.
None values are considered omissions.
Example usage on an AWS() method:
@requires('zone', 'security_groups')
def my_aws_method(self, custom_args, **kwargs):
# We'll only get here if 'kwargs' contained non-None values for
# both 'zone' and 'security_groups'.
"""
def requires(f, self, *args, **kwargs):
missing = filter(lambda x: kwargs.get(x) is None, params)
if missing:
msgs = ", ".join([PARAMETERS[x]['msg'] for x in missing])
raise ValueError("Missing the following parameters: %s" % msgs)
return f(self, *args, **kwargs)
return decorator(requires) | [
"def",
"requires",
"(",
"*",
"params",
")",
":",
"def",
"requires",
"(",
"f",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"missing",
"=",
"filter",
"(",
"lambda",
"x",
":",
"kwargs",
".",
"get",
"(",
"x",
")",
"is",
"None"... | Raise ValueError if any ``params`` are omitted from the decorated kwargs.
None values are considered omissions.
Example usage on an AWS() method:
@requires('zone', 'security_groups')
def my_aws_method(self, custom_args, **kwargs):
# We'll only get here if 'kwargs' contained non-None values for
# both 'zone' and 'security_groups'. | [
"Raise",
"ValueError",
"if",
"any",
"params",
"are",
"omitted",
"from",
"the",
"decorated",
"kwargs",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L97-L116 |
bitprophet/botox | botox/aws.py | AWS.get_security_group_id | def get_security_group_id(self, name):
"""
Take name string, give back security group ID.
To get around VPC's API being stupid.
"""
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in self.get_all_security_groups():
self._security_groups[group.name] = group.id
return self._security_groups[name] | python | def get_security_group_id(self, name):
"""
Take name string, give back security group ID.
To get around VPC's API being stupid.
"""
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in self.get_all_security_groups():
self._security_groups[group.name] = group.id
return self._security_groups[name] | [
"def",
"get_security_group_id",
"(",
"self",
",",
"name",
")",
":",
"# Memoize entire list of groups",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_security_groups'",
")",
":",
"self",
".",
"_security_groups",
"=",
"{",
"}",
"for",
"group",
"in",
"self",
".",
... | Take name string, give back security group ID.
To get around VPC's API being stupid. | [
"Take",
"name",
"string",
"give",
"back",
"security",
"group",
"ID",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L188-L199 |
bitprophet/botox | botox/aws.py | AWS.get_instance_subnet_name | def get_instance_subnet_name(self, instance):
"""
Return a human readable name for given instance's subnet, or None.
Uses stored config mapping of subnet IDs to names.
"""
# TODO: we have to do this here since we are monkeypatching Instance.
# If we switch to custom Instance (sub)class then we could do it in the
# object, provided it has access to the configuration data.
if instance.subnet_id:
# Account for omitted 'subnet-'
subnet = self.config['subnets'][instance.subnet_id[7:]]
else:
subnet = BLANK
return subnet | python | def get_instance_subnet_name(self, instance):
"""
Return a human readable name for given instance's subnet, or None.
Uses stored config mapping of subnet IDs to names.
"""
# TODO: we have to do this here since we are monkeypatching Instance.
# If we switch to custom Instance (sub)class then we could do it in the
# object, provided it has access to the configuration data.
if instance.subnet_id:
# Account for omitted 'subnet-'
subnet = self.config['subnets'][instance.subnet_id[7:]]
else:
subnet = BLANK
return subnet | [
"def",
"get_instance_subnet_name",
"(",
"self",
",",
"instance",
")",
":",
"# TODO: we have to do this here since we are monkeypatching Instance.",
"# If we switch to custom Instance (sub)class then we could do it in the",
"# object, provided it has access to the configuration data.",
"if",
... | Return a human readable name for given instance's subnet, or None.
Uses stored config mapping of subnet IDs to names. | [
"Return",
"a",
"human",
"readable",
"name",
"for",
"given",
"instance",
"s",
"subnet",
"or",
"None",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L201-L215 |
bitprophet/botox | botox/aws.py | AWS.get_subnet_id | def get_subnet_id(self, name):
"""
Return subnet ID for given ``name``, if it exists.
E.g. with a subnet mapping of ``{'abc123': 'ops', '67fd56': 'prod'}``,
``get_subnet_id('ops')`` would return ``'abc123'``. If the map has
non-unique values, the first matching key will be returned.
If no match is found, the given ``name`` is returned as-is. This works
well for e.g. normalizing names-or-IDs to just IDs.
"""
for subnet_id, subnet_name in self.config['subnets'].iteritems():
if subnet_name == name:
return subnet_id
return name | python | def get_subnet_id(self, name):
"""
Return subnet ID for given ``name``, if it exists.
E.g. with a subnet mapping of ``{'abc123': 'ops', '67fd56': 'prod'}``,
``get_subnet_id('ops')`` would return ``'abc123'``. If the map has
non-unique values, the first matching key will be returned.
If no match is found, the given ``name`` is returned as-is. This works
well for e.g. normalizing names-or-IDs to just IDs.
"""
for subnet_id, subnet_name in self.config['subnets'].iteritems():
if subnet_name == name:
return subnet_id
return name | [
"def",
"get_subnet_id",
"(",
"self",
",",
"name",
")",
":",
"for",
"subnet_id",
",",
"subnet_name",
"in",
"self",
".",
"config",
"[",
"'subnets'",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"subnet_name",
"==",
"name",
":",
"return",
"subnet_id",
"retur... | Return subnet ID for given ``name``, if it exists.
E.g. with a subnet mapping of ``{'abc123': 'ops', '67fd56': 'prod'}``,
``get_subnet_id('ops')`` would return ``'abc123'``. If the map has
non-unique values, the first matching key will be returned.
If no match is found, the given ``name`` is returned as-is. This works
well for e.g. normalizing names-or-IDs to just IDs. | [
"Return",
"subnet",
"ID",
"for",
"given",
"name",
"if",
"it",
"exists",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L217-L231 |
bitprophet/botox | botox/aws.py | AWS.create | def create(self, hostname, **kwargs):
"""
Create new EC2 instance named ``hostname``.
You may specify keyword arguments matching those of ``__init__`` (e.g.
``size``, ``ami``) to override any defaults given when the object was
created, or to fill in parameters not given at initialization time.
Additional parameters that are instance-specific:
* ``ip``: The static private IP address for the new host.
This method returns a ``boto.EC2.instance.Instance`` object.
"""
# Create
creating = "Creating '%s' (a %s instance of %s)" % (
hostname, kwargs['size'], kwargs['ami']
)
with self.msg(creating):
instance = self._create(hostname, kwargs)
# Name
with self.msg("Tagging as '%s'" % hostname):
try:
instance.rename(hostname)
# One-time retry for API errors when setting tags
except _ResponseError:
time.sleep(1)
instance.rename(hostname)
# Wait for it to finish booting
with self.msg("Waiting for boot: "):
tick = 5
while instance.state != 'running':
self.log(".", end='')
time.sleep(tick)
instance.update()
return instance | python | def create(self, hostname, **kwargs):
"""
Create new EC2 instance named ``hostname``.
You may specify keyword arguments matching those of ``__init__`` (e.g.
``size``, ``ami``) to override any defaults given when the object was
created, or to fill in parameters not given at initialization time.
Additional parameters that are instance-specific:
* ``ip``: The static private IP address for the new host.
This method returns a ``boto.EC2.instance.Instance`` object.
"""
# Create
creating = "Creating '%s' (a %s instance of %s)" % (
hostname, kwargs['size'], kwargs['ami']
)
with self.msg(creating):
instance = self._create(hostname, kwargs)
# Name
with self.msg("Tagging as '%s'" % hostname):
try:
instance.rename(hostname)
# One-time retry for API errors when setting tags
except _ResponseError:
time.sleep(1)
instance.rename(hostname)
# Wait for it to finish booting
with self.msg("Waiting for boot: "):
tick = 5
while instance.state != 'running':
self.log(".", end='')
time.sleep(tick)
instance.update()
return instance | [
"def",
"create",
"(",
"self",
",",
"hostname",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create",
"creating",
"=",
"\"Creating '%s' (a %s instance of %s)\"",
"%",
"(",
"hostname",
",",
"kwargs",
"[",
"'size'",
"]",
",",
"kwargs",
"[",
"'ami'",
"]",
")",
"with"... | Create new EC2 instance named ``hostname``.
You may specify keyword arguments matching those of ``__init__`` (e.g.
``size``, ``ami``) to override any defaults given when the object was
created, or to fill in parameters not given at initialization time.
Additional parameters that are instance-specific:
* ``ip``: The static private IP address for the new host.
This method returns a ``boto.EC2.instance.Instance`` object. | [
"Create",
"new",
"EC2",
"instance",
"named",
"hostname",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L257-L295 |
bitprophet/botox | botox/aws.py | AWS.get | def get(self, arg):
"""
Return instance object with given EC2 ID or nametag.
"""
try:
reservations = self.get_all_instances(filters={'tag:Name': [arg]})
instance = reservations[0].instances[0]
except IndexError:
try:
instance = self.get_all_instances([arg])[0].instances[0]
except (_ResponseError, IndexError):
# TODO: encapsulate actual exception for debugging
err = "Can't find any instance with name or ID '%s'" % arg
raise ValueError(err)
return instance | python | def get(self, arg):
"""
Return instance object with given EC2 ID or nametag.
"""
try:
reservations = self.get_all_instances(filters={'tag:Name': [arg]})
instance = reservations[0].instances[0]
except IndexError:
try:
instance = self.get_all_instances([arg])[0].instances[0]
except (_ResponseError, IndexError):
# TODO: encapsulate actual exception for debugging
err = "Can't find any instance with name or ID '%s'" % arg
raise ValueError(err)
return instance | [
"def",
"get",
"(",
"self",
",",
"arg",
")",
":",
"try",
":",
"reservations",
"=",
"self",
".",
"get_all_instances",
"(",
"filters",
"=",
"{",
"'tag:Name'",
":",
"[",
"arg",
"]",
"}",
")",
"instance",
"=",
"reservations",
"[",
"0",
"]",
".",
"instance... | Return instance object with given EC2 ID or nametag. | [
"Return",
"instance",
"object",
"with",
"given",
"EC2",
"ID",
"or",
"nametag",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L324-L338 |
bitprophet/botox | botox/aws.py | AWS.get_volumes_for_instance | def get_volumes_for_instance(self, arg, device=None):
"""
Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device.
"""
instance = self.get(arg)
filters = {'attachment.instance-id': instance.id}
if device is not None:
filters['attachment.device'] = device
return self.get_all_volumes(filters=filters) | python | def get_volumes_for_instance(self, arg, device=None):
"""
Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device.
"""
instance = self.get(arg)
filters = {'attachment.instance-id': instance.id}
if device is not None:
filters['attachment.device'] = device
return self.get_all_volumes(filters=filters) | [
"def",
"get_volumes_for_instance",
"(",
"self",
",",
"arg",
",",
"device",
"=",
"None",
")",
":",
"instance",
"=",
"self",
".",
"get",
"(",
"arg",
")",
"filters",
"=",
"{",
"'attachment.instance-id'",
":",
"instance",
".",
"id",
"}",
"if",
"device",
"is"... | Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device. | [
"Return",
"all",
"EC2",
"Volume",
"objects",
"attached",
"to",
"arg",
"instance",
"name",
"or",
"ID",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L340-L351 |
bitprophet/botox | botox/aws.py | AWS.terminate | def terminate(self, arg):
"""
Terminate instance with given EC2 ID or nametag.
"""
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
while instance.state != 'terminated':
time.sleep(5)
self.log(".", end='')
instance.update() | python | def terminate(self, arg):
"""
Terminate instance with given EC2 ID or nametag.
"""
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
while instance.state != 'terminated':
time.sleep(5)
self.log(".", end='')
instance.update() | [
"def",
"terminate",
"(",
"self",
",",
"arg",
")",
":",
"instance",
"=",
"self",
".",
"get",
"(",
"arg",
")",
"with",
"self",
".",
"msg",
"(",
"\"Terminating %s (%s): \"",
"%",
"(",
"instance",
".",
"name",
",",
"instance",
".",
"id",
")",
")",
":",
... | Terminate instance with given EC2 ID or nametag. | [
"Terminate",
"instance",
"with",
"given",
"EC2",
"ID",
"or",
"nametag",
"."
] | train | https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L353-L364 |
mwhooker/jones | jones/jones.py | ZNodeMap._get | def _get(self):
"""get and parse data stored in self.path."""
data, stat = self.zk.get(self.path)
if not len(data):
return {}, stat.version
if self.OLD_SEPARATOR in data:
return self._get_old()
return json.loads(data), stat.version | python | def _get(self):
"""get and parse data stored in self.path."""
data, stat = self.zk.get(self.path)
if not len(data):
return {}, stat.version
if self.OLD_SEPARATOR in data:
return self._get_old()
return json.loads(data), stat.version | [
"def",
"_get",
"(",
"self",
")",
":",
"data",
",",
"stat",
"=",
"self",
".",
"zk",
".",
"get",
"(",
"self",
".",
"path",
")",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"{",
"}",
",",
"stat",
".",
"version",
"if",
"self",
".",
"OLD_... | get and parse data stored in self.path. | [
"get",
"and",
"parse",
"data",
"stored",
"in",
"self",
".",
"path",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L55-L63 |
mwhooker/jones | jones/jones.py | ZNodeMap._set | def _set(self, data, version):
"""serialize and set data to self.path."""
self.zk.set(self.path, json.dumps(data), version) | python | def _set(self, data, version):
"""serialize and set data to self.path."""
self.zk.set(self.path, json.dumps(data), version) | [
"def",
"_set",
"(",
"self",
",",
"data",
",",
"version",
")",
":",
"self",
".",
"zk",
".",
"set",
"(",
"self",
".",
"path",
",",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"version",
")"
] | serialize and set data to self.path. | [
"serialize",
"and",
"set",
"data",
"to",
"self",
".",
"path",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L65-L68 |
mwhooker/jones | jones/jones.py | ZNodeMap._get_old | def _get_old(self):
"""get and parse data stored in self.path."""
def _deserialize(d):
if not len(d):
return {}
return dict(l.split(self.OLD_SEPARATOR) for l in d.split('\n'))
data, stat = self.zk.get(self.path)
return _deserialize(data.decode('utf8')), stat.version | python | def _get_old(self):
"""get and parse data stored in self.path."""
def _deserialize(d):
if not len(d):
return {}
return dict(l.split(self.OLD_SEPARATOR) for l in d.split('\n'))
data, stat = self.zk.get(self.path)
return _deserialize(data.decode('utf8')), stat.version | [
"def",
"_get_old",
"(",
"self",
")",
":",
"def",
"_deserialize",
"(",
"d",
")",
":",
"if",
"not",
"len",
"(",
"d",
")",
":",
"return",
"{",
"}",
"return",
"dict",
"(",
"l",
".",
"split",
"(",
"self",
".",
"OLD_SEPARATOR",
")",
"for",
"l",
"in",
... | get and parse data stored in self.path. | [
"get",
"and",
"parse",
"data",
"stored",
"in",
"self",
".",
"path",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L70-L79 |
mwhooker/jones | jones/jones.py | Jones.create_config | def create_config(self, env, conf):
"""
Set conf to env under service.
pass None to env for root.
"""
if not isinstance(conf, collections.Mapping):
raise ValueError("conf must be a collections.Mapping")
self.zk.ensure_path(self.view_path)
self._create(
self._get_env_path(env),
conf
)
self._update_view(env) | python | def create_config(self, env, conf):
"""
Set conf to env under service.
pass None to env for root.
"""
if not isinstance(conf, collections.Mapping):
raise ValueError("conf must be a collections.Mapping")
self.zk.ensure_path(self.view_path)
self._create(
self._get_env_path(env),
conf
)
self._update_view(env) | [
"def",
"create_config",
"(",
"self",
",",
"env",
",",
"conf",
")",
":",
"if",
"not",
"isinstance",
"(",
"conf",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"\"conf must be a collections.Mapping\"",
")",
"self",
".",
"zk",
".",
... | Set conf to env under service.
pass None to env for root. | [
"Set",
"conf",
"to",
"env",
"under",
"service",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L134-L151 |
mwhooker/jones | jones/jones.py | Jones.set_config | def set_config(self, env, conf, version):
"""
Set conf to env under service.
pass None to env for root.
"""
if not isinstance(conf, collections.Mapping):
raise ValueError("conf must be a collections.Mapping")
self._set(
self._get_env_path(env),
conf,
version
)
path = self._get_env_path(env)
"""Update env's children with new config."""
for child in zkutil.walk(self.zk, path):
self._update_view(Env(child[len(self.conf_path)+1:])) | python | def set_config(self, env, conf, version):
"""
Set conf to env under service.
pass None to env for root.
"""
if not isinstance(conf, collections.Mapping):
raise ValueError("conf must be a collections.Mapping")
self._set(
self._get_env_path(env),
conf,
version
)
path = self._get_env_path(env)
"""Update env's children with new config."""
for child in zkutil.walk(self.zk, path):
self._update_view(Env(child[len(self.conf_path)+1:])) | [
"def",
"set_config",
"(",
"self",
",",
"env",
",",
"conf",
",",
"version",
")",
":",
"if",
"not",
"isinstance",
"(",
"conf",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"\"conf must be a collections.Mapping\"",
")",
"self",
".",... | Set conf to env under service.
pass None to env for root. | [
"Set",
"conf",
"to",
"env",
"under",
"service",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L153-L171 |
mwhooker/jones | jones/jones.py | Jones.get_config | def get_config(self, hostname):
"""
Returns a configuration for hostname.
"""
version, config = self._get(
self.associations.get(hostname)
)
return config | python | def get_config(self, hostname):
"""
Returns a configuration for hostname.
"""
version, config = self._get(
self.associations.get(hostname)
)
return config | [
"def",
"get_config",
"(",
"self",
",",
"hostname",
")",
":",
"version",
",",
"config",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"associations",
".",
"get",
"(",
"hostname",
")",
")",
"return",
"config"
] | Returns a configuration for hostname. | [
"Returns",
"a",
"configuration",
"for",
"hostname",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L183-L191 |
mwhooker/jones | jones/jones.py | Jones.get_view_by_env | def get_view_by_env(self, env):
"""
Returns the view of `env`.
"""
version, data = self._get(self._get_view_path(env))
return data | python | def get_view_by_env(self, env):
"""
Returns the view of `env`.
"""
version, data = self._get(self._get_view_path(env))
return data | [
"def",
"get_view_by_env",
"(",
"self",
",",
"env",
")",
":",
"version",
",",
"data",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_get_view_path",
"(",
"env",
")",
")",
"return",
"data"
] | Returns the view of `env`. | [
"Returns",
"the",
"view",
"of",
"env",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L204-L210 |
mwhooker/jones | jones/jones.py | Jones.assoc_host | def assoc_host(self, hostname, env):
"""
Associate a host with an environment.
hostname is opaque to Jones.
Any string which uniquely identifies a host is acceptable.
"""
dest = self._get_view_path(env)
self.associations.set(hostname, dest) | python | def assoc_host(self, hostname, env):
"""
Associate a host with an environment.
hostname is opaque to Jones.
Any string which uniquely identifies a host is acceptable.
"""
dest = self._get_view_path(env)
self.associations.set(hostname, dest) | [
"def",
"assoc_host",
"(",
"self",
",",
"hostname",
",",
"env",
")",
":",
"dest",
"=",
"self",
".",
"_get_view_path",
"(",
"env",
")",
"self",
".",
"associations",
".",
"set",
"(",
"hostname",
",",
"dest",
")"
] | Associate a host with an environment.
hostname is opaque to Jones.
Any string which uniquely identifies a host is acceptable. | [
"Associate",
"a",
"host",
"with",
"an",
"environment",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L212-L221 |
mwhooker/jones | jones/jones.py | Jones.get_associations | def get_associations(self, env):
"""
Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments.
"""
if env.is_root:
return None
associations = self.associations.get_all()
return [assoc for assoc in associations
if associations[assoc] == self._get_view_path(env)] | python | def get_associations(self, env):
"""
Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments.
"""
if env.is_root:
return None
associations = self.associations.get_all()
return [assoc for assoc in associations
if associations[assoc] == self._get_view_path(env)] | [
"def",
"get_associations",
"(",
"self",
",",
"env",
")",
":",
"if",
"env",
".",
"is_root",
":",
"return",
"None",
"associations",
"=",
"self",
".",
"associations",
".",
"get_all",
"(",
")",
"return",
"[",
"assoc",
"for",
"assoc",
"in",
"associations",
"i... | Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments. | [
"Get",
"all",
"the",
"associations",
"for",
"this",
"env",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L223-L237 |
mwhooker/jones | jones/jones.py | Jones._flatten_from_root | def _flatten_from_root(self, env):
"""
Flatten values from root down in to new view.
"""
nodes = env.components
# Path through the znode graph from root ('') to env
path = [nodes[:n] for n in xrange(len(nodes) + 1)]
# Expand path and map it to the root
path = map(
self._get_env_path,
[Env('/'.join(p)) for p in path]
)
data = {}
for n in path:
_, config = self._get(n)
data.update(config)
return data | python | def _flatten_from_root(self, env):
"""
Flatten values from root down in to new view.
"""
nodes = env.components
# Path through the znode graph from root ('') to env
path = [nodes[:n] for n in xrange(len(nodes) + 1)]
# Expand path and map it to the root
path = map(
self._get_env_path,
[Env('/'.join(p)) for p in path]
)
data = {}
for n in path:
_, config = self._get(n)
data.update(config)
return data | [
"def",
"_flatten_from_root",
"(",
"self",
",",
"env",
")",
":",
"nodes",
"=",
"env",
".",
"components",
"# Path through the znode graph from root ('') to env",
"path",
"=",
"[",
"nodes",
"[",
":",
"n",
"]",
"for",
"n",
"in",
"xrange",
"(",
"len",
"(",
"nodes... | Flatten values from root down in to new view. | [
"Flatten",
"values",
"from",
"root",
"down",
"in",
"to",
"new",
"view",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/jones.py#L257-L278 |
ask/redish | redish/serialization.py | Serializer.encode | def encode(self, value):
"""Encode value."""
value = self.serialize(value)
if self.encoding:
value = value.encode(self.encoding)
return value | python | def encode(self, value):
"""Encode value."""
value = self.serialize(value)
if self.encoding:
value = value.encode(self.encoding)
return value | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"serialize",
"(",
"value",
")",
"if",
"self",
".",
"encoding",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"return",
"value"
] | Encode value. | [
"Encode",
"value",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/serialization.py#L32-L37 |
ask/redish | redish/serialization.py | Serializer.decode | def decode(self, value):
"""Decode value."""
if self.encoding:
value = value.decode(self.encoding)
return self.deserialize(value) | python | def decode(self, value):
"""Decode value."""
if self.encoding:
value = value.decode(self.encoding)
return self.deserialize(value) | [
"def",
"decode",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"encoding",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"return",
"self",
".",
"deserialize",
"(",
"value",
")"
] | Decode value. | [
"Decode",
"value",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/serialization.py#L39-L43 |
rmad17/pyreqs | pyreqs.py | install | def install(packagename, save, save_dev, save_test, filename):
"""
Install the package via pip, pin the package only to requirements file.
Use option to decide which file the package will be pinned to.
"""
print('Installing ', packagename)
print(sh_pip.install(packagename))
if not filename:
filename = get_filename(save, save_dev, save_test)
try:
add_requirements(packagename, filename)
except AssertionError:
print('Package already pinned in ', filename) | python | def install(packagename, save, save_dev, save_test, filename):
"""
Install the package via pip, pin the package only to requirements file.
Use option to decide which file the package will be pinned to.
"""
print('Installing ', packagename)
print(sh_pip.install(packagename))
if not filename:
filename = get_filename(save, save_dev, save_test)
try:
add_requirements(packagename, filename)
except AssertionError:
print('Package already pinned in ', filename) | [
"def",
"install",
"(",
"packagename",
",",
"save",
",",
"save_dev",
",",
"save_test",
",",
"filename",
")",
":",
"print",
"(",
"'Installing '",
",",
"packagename",
")",
"print",
"(",
"sh_pip",
".",
"install",
"(",
"packagename",
")",
")",
"if",
"not",
"f... | Install the package via pip, pin the package only to requirements file.
Use option to decide which file the package will be pinned to. | [
"Install",
"the",
"package",
"via",
"pip",
"pin",
"the",
"package",
"only",
"to",
"requirements",
"file",
".",
"Use",
"option",
"to",
"decide",
"which",
"file",
"the",
"package",
"will",
"be",
"pinned",
"to",
"."
] | train | https://github.com/rmad17/pyreqs/blob/16897d35cbe1d90bc51015a5d97f7ac25483cfb5/pyreqs.py#L38-L50 |
rmad17/pyreqs | pyreqs.py | remove | def remove(packagename, save, save_dev, save_test, filename):
"""
Uninstall the package and remove it from requirements file.
"""
print(sh_pip.uninstall(packagename, "-y"))
if not filename:
filename = get_filename(save, save_dev, save_test)
remove_requirements(packagename, filename) | python | def remove(packagename, save, save_dev, save_test, filename):
"""
Uninstall the package and remove it from requirements file.
"""
print(sh_pip.uninstall(packagename, "-y"))
if not filename:
filename = get_filename(save, save_dev, save_test)
remove_requirements(packagename, filename) | [
"def",
"remove",
"(",
"packagename",
",",
"save",
",",
"save_dev",
",",
"save_test",
",",
"filename",
")",
":",
"print",
"(",
"sh_pip",
".",
"uninstall",
"(",
"packagename",
",",
"\"-y\"",
")",
")",
"if",
"not",
"filename",
":",
"filename",
"=",
"get_fil... | Uninstall the package and remove it from requirements file. | [
"Uninstall",
"the",
"package",
"and",
"remove",
"it",
"from",
"requirements",
"file",
"."
] | train | https://github.com/rmad17/pyreqs/blob/16897d35cbe1d90bc51015a5d97f7ac25483cfb5/pyreqs.py#L61-L68 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.os_path_split_asunder | def os_path_split_asunder(path, debug=False):
"""
http://stackoverflow.com/a/4580931/171094
"""
parts = []
while True:
newpath, tail = os.path.split(path)
if debug: print repr(path), (newpath, tail)
if newpath == path:
assert not tail
if path: parts.append(path)
break
parts.append(tail)
path = newpath
parts.reverse()
return parts | python | def os_path_split_asunder(path, debug=False):
"""
http://stackoverflow.com/a/4580931/171094
"""
parts = []
while True:
newpath, tail = os.path.split(path)
if debug: print repr(path), (newpath, tail)
if newpath == path:
assert not tail
if path: parts.append(path)
break
parts.append(tail)
path = newpath
parts.reverse()
return parts | [
"def",
"os_path_split_asunder",
"(",
"path",
",",
"debug",
"=",
"False",
")",
":",
"parts",
"=",
"[",
"]",
"while",
"True",
":",
"newpath",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"debug",
":",
"print",
"repr",
"(... | http://stackoverflow.com/a/4580931/171094 | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"4580931",
"/",
"171094"
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L547-L562 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.is_subdirectory | def is_subdirectory(potential_subdirectory, expected_parent_directory):
"""
Is the first argument a sub-directory of the second argument?
:param potential_subdirectory:
:param expected_parent_directory:
:return: True if the potential_subdirectory is a child of the expected parent directory
"""
def _get_normalized_parts(path):
return DKCloudCommandRunner.os_path_split_asunder(os.path.realpath(os.path.abspath(os.path.normpath(path))))
# make absolute and handle symbolic links, split into components
sub_parts = _get_normalized_parts(potential_subdirectory)
parent_parts = _get_normalized_parts(expected_parent_directory)
if len(parent_parts) > len(sub_parts):
# a parent directory never has more path segments than its child
return False
# we expect the zip to end with the short path, which we know to be the parent
return all(part1 == part2 for part1, part2 in zip(sub_parts, parent_parts)) | python | def is_subdirectory(potential_subdirectory, expected_parent_directory):
"""
Is the first argument a sub-directory of the second argument?
:param potential_subdirectory:
:param expected_parent_directory:
:return: True if the potential_subdirectory is a child of the expected parent directory
"""
def _get_normalized_parts(path):
return DKCloudCommandRunner.os_path_split_asunder(os.path.realpath(os.path.abspath(os.path.normpath(path))))
# make absolute and handle symbolic links, split into components
sub_parts = _get_normalized_parts(potential_subdirectory)
parent_parts = _get_normalized_parts(expected_parent_directory)
if len(parent_parts) > len(sub_parts):
# a parent directory never has more path segments than its child
return False
# we expect the zip to end with the short path, which we know to be the parent
return all(part1 == part2 for part1, part2 in zip(sub_parts, parent_parts)) | [
"def",
"is_subdirectory",
"(",
"potential_subdirectory",
",",
"expected_parent_directory",
")",
":",
"def",
"_get_normalized_parts",
"(",
"path",
")",
":",
"return",
"DKCloudCommandRunner",
".",
"os_path_split_asunder",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
... | Is the first argument a sub-directory of the second argument?
:param potential_subdirectory:
:param expected_parent_directory:
:return: True if the potential_subdirectory is a child of the expected parent directory | [
"Is",
"the",
"first",
"argument",
"a",
"sub",
"-",
"directory",
"of",
"the",
"second",
"argument?"
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L566-L588 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.update_all_files | def update_all_files(dk_api, kitchen, recipe_name, recipe_dir, message, dryrun=False):
"""
reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param recipe_dir: string - path to the root of the directory
:param message: string message -- commit message, string
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
rc = dk_api.recipe_status(kitchen, recipe_name, recipe_dir)
if not rc.ok():
rs = 'DKCloudCommand.update_all_files failed\nmessage: %s' % rc.get_message()
rc.set_message(rs)
return rc
rl = rc.get_payload()
if (len(rl['different']) + len(rl['only_local']) + len(rl['only_remote'])) == 0:
rs = 'DKCloudCommand.update_all_files no files changed.'
rc.set_message(rs)
return rc
rc = DKCloudCommandRunner._update_changed_files(dk_api, rl['different'], kitchen, recipe_name, message, dryrun)
if not rc.ok():
return rc
msg_differences = rc.get_message()
rc = DKCloudCommandRunner._add_new_files(dk_api, rl['only_local'], kitchen, recipe_name, message, dryrun)
if not rc.ok():
return rc
msg_additions = rc.get_message()
rc = DKCloudCommandRunner._remove_deleted_files(dk_api, rl['only_remote'], kitchen, recipe_name, message,
dryrun)
if not rc.ok():
return rc
msg_deletions = rc.get_message()
msg = ''
if len(msg_differences) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_differences + '\n'
if len(msg_additions) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_additions + '\n'
if len(msg_deletions) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_deletions + '\n'
rc.set_message(msg)
return rc | python | def update_all_files(dk_api, kitchen, recipe_name, recipe_dir, message, dryrun=False):
"""
reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param recipe_dir: string - path to the root of the directory
:param message: string message -- commit message, string
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
rc = dk_api.recipe_status(kitchen, recipe_name, recipe_dir)
if not rc.ok():
rs = 'DKCloudCommand.update_all_files failed\nmessage: %s' % rc.get_message()
rc.set_message(rs)
return rc
rl = rc.get_payload()
if (len(rl['different']) + len(rl['only_local']) + len(rl['only_remote'])) == 0:
rs = 'DKCloudCommand.update_all_files no files changed.'
rc.set_message(rs)
return rc
rc = DKCloudCommandRunner._update_changed_files(dk_api, rl['different'], kitchen, recipe_name, message, dryrun)
if not rc.ok():
return rc
msg_differences = rc.get_message()
rc = DKCloudCommandRunner._add_new_files(dk_api, rl['only_local'], kitchen, recipe_name, message, dryrun)
if not rc.ok():
return rc
msg_additions = rc.get_message()
rc = DKCloudCommandRunner._remove_deleted_files(dk_api, rl['only_remote'], kitchen, recipe_name, message,
dryrun)
if not rc.ok():
return rc
msg_deletions = rc.get_message()
msg = ''
if len(msg_differences) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_differences + '\n'
if len(msg_additions) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_additions + '\n'
if len(msg_deletions) > 0:
if len(msg) > 0:
msg += '\n'
msg += msg_deletions + '\n'
rc.set_message(msg)
return rc | [
"def",
"update_all_files",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"recipe_dir",
",",
"message",
",",
"dryrun",
"=",
"False",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
... | reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param recipe_dir: string - path to the root of the directory
:param message: string message -- commit message, string
:rtype: DKReturnCode | [
"reutrns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"param",
"recipe_dir",
":",
"string",
"-",
"pat... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L753-L811 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.update_file | def update_file(dk_api, kitchen, recipe_name, message, files_to_update_param):
"""
reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_update_param: string -- file system directory where the recipe file lives
:rtype: string
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or files_to_update_param is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
# Take a simple string or an array
if isinstance(files_to_update_param, basestring):
files_to_update = [files_to_update_param]
else:
files_to_update = files_to_update_param
msg = ''
for file_to_update in files_to_update:
try:
with open(file_to_update, 'r') as f:
file_contents = f.read()
except IOError as e:
if len(msg) != 0:
msg += '\n'
msg += '%s' % (str(e))
rc.set(rc.DK_FAIL, msg)
return rc
except ValueError as e:
if len(msg) != 0:
msg += '\n'
msg += 'ERROR: %s' % e.message
rc.set(rc.DK_FAIL, msg)
return rc
rc = dk_api.update_file(kitchen, recipe_name, message, file_to_update, file_contents)
if not rc.ok():
if len(msg) != 0:
msg += '\n'
msg += 'DKCloudCommand.update_file for %s failed\n\tmessage: %s' % (file_to_update, rc.get_message())
rc.set_message(msg)
return rc
else:
if len(msg) != 0:
msg += '\n'
msg += 'DKCloudCommand.update_file for %s succeeded' % file_to_update
rc.set_message(msg)
return rc | python | def update_file(dk_api, kitchen, recipe_name, message, files_to_update_param):
"""
reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_update_param: string -- file system directory where the recipe file lives
:rtype: string
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or files_to_update_param is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
# Take a simple string or an array
if isinstance(files_to_update_param, basestring):
files_to_update = [files_to_update_param]
else:
files_to_update = files_to_update_param
msg = ''
for file_to_update in files_to_update:
try:
with open(file_to_update, 'r') as f:
file_contents = f.read()
except IOError as e:
if len(msg) != 0:
msg += '\n'
msg += '%s' % (str(e))
rc.set(rc.DK_FAIL, msg)
return rc
except ValueError as e:
if len(msg) != 0:
msg += '\n'
msg += 'ERROR: %s' % e.message
rc.set(rc.DK_FAIL, msg)
return rc
rc = dk_api.update_file(kitchen, recipe_name, message, file_to_update, file_contents)
if not rc.ok():
if len(msg) != 0:
msg += '\n'
msg += 'DKCloudCommand.update_file for %s failed\n\tmessage: %s' % (file_to_update, rc.get_message())
rc.set_message(msg)
return rc
else:
if len(msg) != 0:
msg += '\n'
msg += 'DKCloudCommand.update_file for %s succeeded' % file_to_update
rc.set_message(msg)
return rc | [
"def",
"update_file",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"message",
",",
"files_to_update_param",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
"or",
"message",
"is",
"... | reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_update_param: string -- file system directory where the recipe file lives
:rtype: string | [
"reutrns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"param",
"message",
":",
"string",
"message",
"... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L968-L1020 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.add_file | def add_file(dk_api, kitchen, recipe_name, message, api_file_key):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string
:param message: string -- commit message, string
:param api_file_key: string -- directory where the recipe file lives
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or api_file_key is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
ig = DKIgnore()
if ig.ignore(api_file_key):
rs = 'DKCloudCommand.add_file ignoring %s' % api_file_key
rc.set_message(rs)
return rc
if not os.path.exists(api_file_key):
s = "'%s' does not exist" % api_file_key
rc.set(rc.DK_FAIL, s)
return rc
try:
with open(api_file_key, 'r') as f:
file_contents = f.read()
except ValueError as e:
s = 'ERROR: %s' % e.message
rc.set(rc.DK_FAIL, s)
return rc
rc = dk_api.add_file(kitchen, recipe_name, message, api_file_key, file_contents)
if rc.ok():
rs = 'DKCloudCommand.add_file for %s succeed' % api_file_key
else:
rs = 'DKCloudCommand.add_file for %s failed\nmessage: %s' % (api_file_key, rc.get_message())
rc.set_message(rs)
return rc | python | def add_file(dk_api, kitchen, recipe_name, message, api_file_key):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string
:param message: string -- commit message, string
:param api_file_key: string -- directory where the recipe file lives
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or api_file_key is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
ig = DKIgnore()
if ig.ignore(api_file_key):
rs = 'DKCloudCommand.add_file ignoring %s' % api_file_key
rc.set_message(rs)
return rc
if not os.path.exists(api_file_key):
s = "'%s' does not exist" % api_file_key
rc.set(rc.DK_FAIL, s)
return rc
try:
with open(api_file_key, 'r') as f:
file_contents = f.read()
except ValueError as e:
s = 'ERROR: %s' % e.message
rc.set(rc.DK_FAIL, s)
return rc
rc = dk_api.add_file(kitchen, recipe_name, message, api_file_key, file_contents)
if rc.ok():
rs = 'DKCloudCommand.add_file for %s succeed' % api_file_key
else:
rs = 'DKCloudCommand.add_file for %s failed\nmessage: %s' % (api_file_key, rc.get_message())
rc.set_message(rs)
return rc | [
"def",
"add_file",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"message",
",",
"api_file_key",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
"or",
"message",
"is",
"None",
"or... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string
:param message: string -- commit message, string
:param api_file_key: string -- directory where the recipe file lives
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
":",
"param",
"message",
":",
"string",
"--",
"commit",
"message",
"string",
":",
"para... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1024-L1064 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.delete_file | def delete_file(dk_api, kitchen, recipe_name, message, files_to_delete_param):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_delete_param: path to the files to delete
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or files_to_delete_param is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
# Take a simple string or an array
if isinstance(files_to_delete_param, basestring):
files_to_delete = [files_to_delete_param]
else:
files_to_delete = files_to_delete_param
msg = ''
for file_to_delete in files_to_delete:
basename = os.path.basename(file_to_delete)
rc = dk_api.delete_file(kitchen, recipe_name, message, file_to_delete, basename)
if not rc.ok():
msg += '\nDKCloudCommand.delete_file for %s failed\nmessage: %s' % (file_to_delete, rc.get_message())
rc.set_message(msg)
return rc
else:
msg += 'DKCloudCommand.delete_file for %s succeed' % file_to_delete
rc.set_message(msg)
return rc | python | def delete_file(dk_api, kitchen, recipe_name, message, files_to_delete_param):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_delete_param: path to the files to delete
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or recipe_name is None or message is None or files_to_delete_param is None:
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc.set(rc.DK_FAIL, s)
return rc
# Take a simple string or an array
if isinstance(files_to_delete_param, basestring):
files_to_delete = [files_to_delete_param]
else:
files_to_delete = files_to_delete_param
msg = ''
for file_to_delete in files_to_delete:
basename = os.path.basename(file_to_delete)
rc = dk_api.delete_file(kitchen, recipe_name, message, file_to_delete, basename)
if not rc.ok():
msg += '\nDKCloudCommand.delete_file for %s failed\nmessage: %s' % (file_to_delete, rc.get_message())
rc.set_message(msg)
return rc
else:
msg += 'DKCloudCommand.delete_file for %s succeed' % file_to_delete
rc.set_message(msg)
return rc | [
"def",
"delete_file",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"message",
",",
"files_to_delete_param",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
"or",
"message",
"is",
"... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:param files_to_delete_param: path to the files to delete
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"param",
"message",
":",
"string",
"message",
"... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1068-L1100 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.watch_active_servings | def watch_active_servings(dk_api, kitchen, period):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param period: integer
:rtype: string
"""
print 'period', period
# try:
# p = int(period)
# except ValueError:
# return 'DKCloudCommand.watch_active_servings requires an integer for the period'
if period <= 0:
return 'DKCloudCommand.watch_active_servings requires a positive period'
DKActiveServingWatcherSingleton().set_sleep_time(period)
DKActiveServingWatcherSingleton().set_api(dk_api)
DKActiveServingWatcherSingleton().set_kitchen(kitchen)
DKActiveServingWatcherSingleton().start_watcher()
return "" | python | def watch_active_servings(dk_api, kitchen, period):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param period: integer
:rtype: string
"""
print 'period', period
# try:
# p = int(period)
# except ValueError:
# return 'DKCloudCommand.watch_active_servings requires an integer for the period'
if period <= 0:
return 'DKCloudCommand.watch_active_servings requires a positive period'
DKActiveServingWatcherSingleton().set_sleep_time(period)
DKActiveServingWatcherSingleton().set_api(dk_api)
DKActiveServingWatcherSingleton().set_kitchen(kitchen)
DKActiveServingWatcherSingleton().start_watcher()
return "" | [
"def",
"watch_active_servings",
"(",
"dk_api",
",",
"kitchen",
",",
"period",
")",
":",
"print",
"'period'",
",",
"period",
"# try:",
"# p = int(period)",
"# except ValueError:",
"# return 'DKCloudCommand.watch_active_servings requires an integer for the period'",
"if",
... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param period: integer
:rtype: string | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"period",
":",
"integer",
":",
"rtype",
":",
"string"
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1104-L1125 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.get_compiled_serving | def get_compiled_serving(dk_api, kitchen, recipe_name, variation_name):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be used
:rtype: DKReturnCode
"""
rc = dk_api.get_compiled_serving(kitchen, recipe_name, variation_name)
if rc.ok():
rs = 'DKCloudCommand.get_compiled_serving succeeded %s\n' % json.dumps(rc.get_payload(), indent=4)
else:
m = rc.get_message()
e = m.split('the logfile errors are:nn')
if len(e) > 1:
e2 = DKCloudCommandRunner._decompress(e[len(e) - 1])
errors = e2.split('|')
re = e[0] + " " + 'the logfile errors are: '
for e in errors:
re += '\n%s' % e
else:
re = m
rs = 'DKCloudCommand.get_compiled_serving failed\nmessage: %s\n' % re
rc.set_message(rs)
return rc | python | def get_compiled_serving(dk_api, kitchen, recipe_name, variation_name):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be used
:rtype: DKReturnCode
"""
rc = dk_api.get_compiled_serving(kitchen, recipe_name, variation_name)
if rc.ok():
rs = 'DKCloudCommand.get_compiled_serving succeeded %s\n' % json.dumps(rc.get_payload(), indent=4)
else:
m = rc.get_message()
e = m.split('the logfile errors are:nn')
if len(e) > 1:
e2 = DKCloudCommandRunner._decompress(e[len(e) - 1])
errors = e2.split('|')
re = e[0] + " " + 'the logfile errors are: '
for e in errors:
re += '\n%s' % e
else:
re = m
rs = 'DKCloudCommand.get_compiled_serving failed\nmessage: %s\n' % re
rc.set_message(rs)
return rc | [
"def",
"get_compiled_serving",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"variation_name",
")",
":",
"rc",
"=",
"dk_api",
".",
"get_compiled_serving",
"(",
"kitchen",
",",
"recipe_name",
",",
"variation_name",
")",
"if",
"rc",
".",
"ok",
"(",
"... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be used
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"param",
"variation_name",
":",
"string",
"--",
... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1147-L1172 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.merge_kitchens_improved | def merge_kitchens_improved(dk_api, from_kitchen, to_kitchen):
"""
returns a string.
:param dk_api: -- api object
:param from_kitchen: string
:param to_kitchen: string -- kitchen name, string
:rtype: DKReturnCode
"""
unresolved_conflicts = DKKitchenDisk.get_unresolved_conflicts(from_kitchen, to_kitchen)
if unresolved_conflicts is not None and len(unresolved_conflicts) != 0:
msg = DKCloudCommandRunner._print_unresolved_conflicts(unresolved_conflicts)
rc = DKReturnCode()
rc.set(DKReturnCode.DK_FAIL, msg)
return rc
resolved_conflicts = DKKitchenDisk.get_resolved_conflicts(from_kitchen, to_kitchen)
# if resolved_conflicts is not None and len(resolved_conflicts) != 0:
md = dk_api.merge_kitchens_improved(from_kitchen, to_kitchen, resolved_conflicts)
if not md.ok():
md.set_message('merge_kitchens_improved error from %s to Kitchen %s\nmessage: %s' %
(from_kitchen, to_kitchen, md.get_message()))
return md
merge_no_conflicts = DKCloudCommandRunner._check_no_merge_conflicts(md.get_payload())
if merge_no_conflicts:
msg = DKCloudCommandRunner._print_merge_success(md.get_payload())
current_kitchen = DKKitchenDisk.find_kitchen_name()
md.set_message(msg)
else:
# Found conflicts
recipe_name = DKRecipeDisk.find_recipe_name()
kitchen_name = DKKitchenDisk.find_kitchen_name()
if recipe_name is None and kitchen_name is None:
# We are not in a kitchen or recipe folder, so just report the findings
rs = DKCloudCommandRunner.print_merge_conflicts(md.get_payload())
md.set_message(rs)
else:
# We are in a recipe folder, so let's write out the conflicted files.
rc = DKCloudCommandRunner.write_merge_conflicts(md.get_payload())
if rc.ok():
md.set_message(rc.get_message())
else:
md = rc
return md | python | def merge_kitchens_improved(dk_api, from_kitchen, to_kitchen):
"""
returns a string.
:param dk_api: -- api object
:param from_kitchen: string
:param to_kitchen: string -- kitchen name, string
:rtype: DKReturnCode
"""
unresolved_conflicts = DKKitchenDisk.get_unresolved_conflicts(from_kitchen, to_kitchen)
if unresolved_conflicts is not None and len(unresolved_conflicts) != 0:
msg = DKCloudCommandRunner._print_unresolved_conflicts(unresolved_conflicts)
rc = DKReturnCode()
rc.set(DKReturnCode.DK_FAIL, msg)
return rc
resolved_conflicts = DKKitchenDisk.get_resolved_conflicts(from_kitchen, to_kitchen)
# if resolved_conflicts is not None and len(resolved_conflicts) != 0:
md = dk_api.merge_kitchens_improved(from_kitchen, to_kitchen, resolved_conflicts)
if not md.ok():
md.set_message('merge_kitchens_improved error from %s to Kitchen %s\nmessage: %s' %
(from_kitchen, to_kitchen, md.get_message()))
return md
merge_no_conflicts = DKCloudCommandRunner._check_no_merge_conflicts(md.get_payload())
if merge_no_conflicts:
msg = DKCloudCommandRunner._print_merge_success(md.get_payload())
current_kitchen = DKKitchenDisk.find_kitchen_name()
md.set_message(msg)
else:
# Found conflicts
recipe_name = DKRecipeDisk.find_recipe_name()
kitchen_name = DKKitchenDisk.find_kitchen_name()
if recipe_name is None and kitchen_name is None:
# We are not in a kitchen or recipe folder, so just report the findings
rs = DKCloudCommandRunner.print_merge_conflicts(md.get_payload())
md.set_message(rs)
else:
# We are in a recipe folder, so let's write out the conflicted files.
rc = DKCloudCommandRunner.write_merge_conflicts(md.get_payload())
if rc.ok():
md.set_message(rc.get_message())
else:
md = rc
return md | [
"def",
"merge_kitchens_improved",
"(",
"dk_api",
",",
"from_kitchen",
",",
"to_kitchen",
")",
":",
"unresolved_conflicts",
"=",
"DKKitchenDisk",
".",
"get_unresolved_conflicts",
"(",
"from_kitchen",
",",
"to_kitchen",
")",
"if",
"unresolved_conflicts",
"is",
"not",
"N... | returns a string.
:param dk_api: -- api object
:param from_kitchen: string
:param to_kitchen: string -- kitchen name, string
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"from_kitchen",
":",
"string",
":",
"param",
"to_kitchen",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"rtype",
":",
"DKReturnCode"
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1214-L1257 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.create_order | def create_order(dk_api, kitchen, recipe_name, variation_name, node_name=None):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be run
:param node_name: string -- name of the single node to run
:rtype: DKReturnCode
"""
rc = dk_api.create_order(kitchen, recipe_name, variation_name, node_name)
if rc.ok():
s = 'Order ID is: %s' % rc.get_payload()
else:
m = rc.get_message().replace('\\n','\n')
e = m.split('the logfile errors are:')
if len(e) > 1:
e2 = DKCloudCommandRunner._decompress(e[-1])
errors = e2.split('|')
re = e[0] + " " + 'the logfile errors are: '
for e in errors:
re += '\n%s' % e
else:
re = m
s = 'DKCloudCommand.create_order failed\nmessage: %s\n' % re
rc.set_message(s)
return rc | python | def create_order(dk_api, kitchen, recipe_name, variation_name, node_name=None):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be run
:param node_name: string -- name of the single node to run
:rtype: DKReturnCode
"""
rc = dk_api.create_order(kitchen, recipe_name, variation_name, node_name)
if rc.ok():
s = 'Order ID is: %s' % rc.get_payload()
else:
m = rc.get_message().replace('\\n','\n')
e = m.split('the logfile errors are:')
if len(e) > 1:
e2 = DKCloudCommandRunner._decompress(e[-1])
errors = e2.split('|')
re = e[0] + " " + 'the logfile errors are: '
for e in errors:
re += '\n%s' % e
else:
re = m
s = 'DKCloudCommand.create_order failed\nmessage: %s\n' % re
rc.set_message(s)
return rc | [
"def",
"create_order",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"variation_name",
",",
"node_name",
"=",
"None",
")",
":",
"rc",
"=",
"dk_api",
".",
"create_order",
"(",
"kitchen",
",",
"recipe_name",
",",
"variation_name",
",",
"node_name",
"... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param variation_name: string -- name of the recipe variation_name to be run
:param node_name: string -- name of the single node to run
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"recipe_name",
":",
"string",
"--",
"kitchen",
"name",
"string",
":",
"param",
"variation_name",
":",
"string",
"--",
... | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1385-L1411 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner.orderrun_detail | def orderrun_detail(dk_api, kitchen, pd):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode
"""
if DKCloudCommandRunner.SUMMARY in pd:
display_summary = True
else:
display_summary = False
# always get summary information
pd[DKCloudCommandRunner.SUMMARY] = True
rc = dk_api.orderrun_detail(kitchen, pd)
s = ''
if not rc.ok() or not isinstance(rc.get_payload(), list):
s = 'Issue with getting order run details\nmessage: %s' % rc.get_message()
rc.set_message(s)
return rc
# we have a list of servings, find the right dict
serving_list = rc.get_payload()
serving = None
if DKCloudCommandRunner.ORDER_RUN_ID in pd:
order_run_id = pd[DKCloudCommandRunner.ORDER_RUN_ID]
for serv in serving_list:
if serv[DKCloudCommandRunner.ORDER_RUN_ID] == order_run_id:
serving = serv
break
elif DKCloudCommandRunner.ORDER_ID in pd:
order_id = pd[DKCloudCommandRunner.ORDER_ID]
for serv in serving_list:
if serv[DKCloudCommandRunner.ORDER_ID] == order_id:
serving = serv
break
else:
# find the newest serving
dex = -1
latest = None
for i, serving in enumerate(serving_list):
if DKCloudCommandRunner.ORDER_ID in serving and serving[DKCloudCommandRunner.ORDER_ID] > latest:
latest = serving[DKCloudCommandRunner.ORDER_ID]
dex = i
if dex != -1:
serving = serving_list[dex]
if serving is None:
rc.set(rc.DK_FAIL,
"No OrderRun information. Try using 'dk order-list -k %s' to see what is available." % kitchen)
return rc
# serving now contains the dictionary of the serving to display
# pull out the information and put it in the message string of the rc
if serving and display_summary:
s += '\nORDER RUN SUMMARY\n\n'
summary = None
if DKCloudCommandRunner.SUMMARY in serving:
summary = serving[DKCloudCommandRunner.SUMMARY]
pass
s += 'Order ID:\t%s\n' % serving[DKCloudCommandRunner.ORDER_ID]
orid_from_serving = serving[DKCloudCommandRunner.ORDER_RUN_ID]
s += 'Order Run ID:\t%s\n' % orid_from_serving
s += 'Status:\t\t%s\n' % serving['status']
s += 'Kitchen:\t%s\n' % kitchen
if summary and 'name' in summary:
s += 'Recipe:\t\t%s\n' % summary['name']
else:
s += 'Recipe:\t\t%s\n' % 'Not available'
# variation name is inside the order id, pull it out
s += 'Variation:\t%s\n' % orid_from_serving.split('#')[3]
if summary and 'start-time' in summary:
start_time = summary['start-time']
if isinstance(start_time, basestring):
s += 'Start time:\t%s\n' % summary['start-time'].split('.')[0]
else:
s += 'Start time:\t%s\n' % 'Not available 1'
else:
s += 'Start time:\t%s\n' % 'Not available 2'
run_time = None
if summary and 'total-recipe-time' in summary:
run_time = summary['total-recipe-time']
if isinstance(run_time, basestring): # Active recipes don't have a run-duration
s += 'Run duration:\t%s (H:M:S)\n' % run_time.split('.')[0]
else:
s += 'Run duration:\t%s\n' % 'Not available'
if serving and DKCloudCommandRunner.TESTRESULTS in serving and \
isinstance(serving[DKCloudCommandRunner.TESTRESULTS], basestring):
s += '\nTEST RESULTS'
s += serving[DKCloudCommandRunner.TESTRESULTS]
if serving and DKCloudCommandRunner.TIMINGRESULTS in serving and \
isinstance(serving[DKCloudCommandRunner.TIMINGRESULTS], basestring):
s += '\n\nTIMING RESULTS\n\n'
s += serving[DKCloudCommandRunner.TIMINGRESULTS]
if serving and DKCloudCommandRunner.LOGS in serving and \
isinstance(serving[DKCloudCommandRunner.LOGS], basestring):
s += '\n\nLOG\n\n'
s += DKCloudCommandRunner._decompress(serving[DKCloudCommandRunner.LOGS])
if 'status' in pd and serving and DKCloudCommandRunner.SUMMARY in serving and \
isinstance(serving[DKCloudCommandRunner.SUMMARY], dict):
s += '\nSTEP STATUS\n\n'
summary = serving[DKCloudCommandRunner.SUMMARY]
# loop through the sorted keys
for key in sorted(summary):
value = summary[key]
if isinstance(value, dict):
# node/step info is stored as a dictionary, print the node name (key) and status
if 'status' in value:
status = value['status']
else:
status = 'unknown'
s += '%s\t%s\n' % (key, status)
if serving and 'runstatus' in pd:
s += serving['status']
if serving and 'disp_order_id' in pd and DKCloudCommandRunner.ORDER_ID in serving:
s += serving[DKCloudCommandRunner.ORDER_ID]
if serving and 'disp_order_run_id' in pd and DKCloudCommandRunner.ORDER_RUN_ID in serving:
s += serving[DKCloudCommandRunner.ORDER_RUN_ID]
rc.set_message(s)
return rc | python | def orderrun_detail(dk_api, kitchen, pd):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode
"""
if DKCloudCommandRunner.SUMMARY in pd:
display_summary = True
else:
display_summary = False
# always get summary information
pd[DKCloudCommandRunner.SUMMARY] = True
rc = dk_api.orderrun_detail(kitchen, pd)
s = ''
if not rc.ok() or not isinstance(rc.get_payload(), list):
s = 'Issue with getting order run details\nmessage: %s' % rc.get_message()
rc.set_message(s)
return rc
# we have a list of servings, find the right dict
serving_list = rc.get_payload()
serving = None
if DKCloudCommandRunner.ORDER_RUN_ID in pd:
order_run_id = pd[DKCloudCommandRunner.ORDER_RUN_ID]
for serv in serving_list:
if serv[DKCloudCommandRunner.ORDER_RUN_ID] == order_run_id:
serving = serv
break
elif DKCloudCommandRunner.ORDER_ID in pd:
order_id = pd[DKCloudCommandRunner.ORDER_ID]
for serv in serving_list:
if serv[DKCloudCommandRunner.ORDER_ID] == order_id:
serving = serv
break
else:
# find the newest serving
dex = -1
latest = None
for i, serving in enumerate(serving_list):
if DKCloudCommandRunner.ORDER_ID in serving and serving[DKCloudCommandRunner.ORDER_ID] > latest:
latest = serving[DKCloudCommandRunner.ORDER_ID]
dex = i
if dex != -1:
serving = serving_list[dex]
if serving is None:
rc.set(rc.DK_FAIL,
"No OrderRun information. Try using 'dk order-list -k %s' to see what is available." % kitchen)
return rc
# serving now contains the dictionary of the serving to display
# pull out the information and put it in the message string of the rc
if serving and display_summary:
s += '\nORDER RUN SUMMARY\n\n'
summary = None
if DKCloudCommandRunner.SUMMARY in serving:
summary = serving[DKCloudCommandRunner.SUMMARY]
pass
s += 'Order ID:\t%s\n' % serving[DKCloudCommandRunner.ORDER_ID]
orid_from_serving = serving[DKCloudCommandRunner.ORDER_RUN_ID]
s += 'Order Run ID:\t%s\n' % orid_from_serving
s += 'Status:\t\t%s\n' % serving['status']
s += 'Kitchen:\t%s\n' % kitchen
if summary and 'name' in summary:
s += 'Recipe:\t\t%s\n' % summary['name']
else:
s += 'Recipe:\t\t%s\n' % 'Not available'
# variation name is inside the order id, pull it out
s += 'Variation:\t%s\n' % orid_from_serving.split('#')[3]
if summary and 'start-time' in summary:
start_time = summary['start-time']
if isinstance(start_time, basestring):
s += 'Start time:\t%s\n' % summary['start-time'].split('.')[0]
else:
s += 'Start time:\t%s\n' % 'Not available 1'
else:
s += 'Start time:\t%s\n' % 'Not available 2'
run_time = None
if summary and 'total-recipe-time' in summary:
run_time = summary['total-recipe-time']
if isinstance(run_time, basestring): # Active recipes don't have a run-duration
s += 'Run duration:\t%s (H:M:S)\n' % run_time.split('.')[0]
else:
s += 'Run duration:\t%s\n' % 'Not available'
if serving and DKCloudCommandRunner.TESTRESULTS in serving and \
isinstance(serving[DKCloudCommandRunner.TESTRESULTS], basestring):
s += '\nTEST RESULTS'
s += serving[DKCloudCommandRunner.TESTRESULTS]
if serving and DKCloudCommandRunner.TIMINGRESULTS in serving and \
isinstance(serving[DKCloudCommandRunner.TIMINGRESULTS], basestring):
s += '\n\nTIMING RESULTS\n\n'
s += serving[DKCloudCommandRunner.TIMINGRESULTS]
if serving and DKCloudCommandRunner.LOGS in serving and \
isinstance(serving[DKCloudCommandRunner.LOGS], basestring):
s += '\n\nLOG\n\n'
s += DKCloudCommandRunner._decompress(serving[DKCloudCommandRunner.LOGS])
if 'status' in pd and serving and DKCloudCommandRunner.SUMMARY in serving and \
isinstance(serving[DKCloudCommandRunner.SUMMARY], dict):
s += '\nSTEP STATUS\n\n'
summary = serving[DKCloudCommandRunner.SUMMARY]
# loop through the sorted keys
for key in sorted(summary):
value = summary[key]
if isinstance(value, dict):
# node/step info is stored as a dictionary, print the node name (key) and status
if 'status' in value:
status = value['status']
else:
status = 'unknown'
s += '%s\t%s\n' % (key, status)
if serving and 'runstatus' in pd:
s += serving['status']
if serving and 'disp_order_id' in pd and DKCloudCommandRunner.ORDER_ID in serving:
s += serving[DKCloudCommandRunner.ORDER_ID]
if serving and 'disp_order_run_id' in pd and DKCloudCommandRunner.ORDER_RUN_ID in serving:
s += serving[DKCloudCommandRunner.ORDER_RUN_ID]
rc.set_message(s)
return rc | [
"def",
"orderrun_detail",
"(",
"dk_api",
",",
"kitchen",
",",
"pd",
")",
":",
"if",
"DKCloudCommandRunner",
".",
"SUMMARY",
"in",
"pd",
":",
"display_summary",
"=",
"True",
"else",
":",
"display_summary",
"=",
"False",
"# always get summary information",
"pd",
"... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode | [
"returns",
"a",
"string",
".",
":",
"param",
"dk_api",
":",
"--",
"api",
"object",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"pd",
":",
"dict",
":",
"rtype",
":",
"DKReturnCode"
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1472-L1601 |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudCommandRunner.py | DKCloudCommandRunner._split_one_end | def _split_one_end(path):
"""
Utility function for splitting off the very end part of a path.
"""
s = path.rsplit('/', 1)
if len(s) == 1:
return s[0], ''
else:
return tuple(s) | python | def _split_one_end(path):
"""
Utility function for splitting off the very end part of a path.
"""
s = path.rsplit('/', 1)
if len(s) == 1:
return s[0], ''
else:
return tuple(s) | [
"def",
"_split_one_end",
"(",
"path",
")",
":",
"s",
"=",
"path",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"return",
"s",
"[",
"0",
"]",
",",
"''",
"else",
":",
"return",
"tuple",
"(",
"s",
")"
] | Utility function for splitting off the very end part of a path. | [
"Utility",
"function",
"for",
"splitting",
"off",
"the",
"very",
"end",
"part",
"of",
"a",
"path",
"."
] | train | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudCommandRunner.py#L1820-L1828 |
arubertoson/maya-launcher | mayalauncher.py | get_system_config_directory | def get_system_config_directory():
"""
Return platform specific config directory.
"""
if platform.system().lower() == 'windows':
_cfg_directory = Path(os.getenv('APPDATA') or '~')
elif platform.system().lower() == 'darwin':
_cfg_directory = Path('~', 'Library', 'Preferences')
else:
_cfg_directory = Path(os.getenv('XDG_CONFIG_HOME') or '~/.config')
logger.debug('Fetching configt directory for {}.'
.format(platform.system()))
return _cfg_directory.joinpath(Path('mayalauncher/.config')) | python | def get_system_config_directory():
"""
Return platform specific config directory.
"""
if platform.system().lower() == 'windows':
_cfg_directory = Path(os.getenv('APPDATA') or '~')
elif platform.system().lower() == 'darwin':
_cfg_directory = Path('~', 'Library', 'Preferences')
else:
_cfg_directory = Path(os.getenv('XDG_CONFIG_HOME') or '~/.config')
logger.debug('Fetching configt directory for {}.'
.format(platform.system()))
return _cfg_directory.joinpath(Path('mayalauncher/.config')) | [
"def",
"get_system_config_directory",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'windows'",
":",
"_cfg_directory",
"=",
"Path",
"(",
"os",
".",
"getenv",
"(",
"'APPDATA'",
")",
"or",
"'~'",
")",
"elif",
"p... | Return platform specific config directory. | [
"Return",
"platform",
"specific",
"config",
"directory",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L36-L49 |
arubertoson/maya-launcher | mayalauncher.py | get_version_exec_mapping_from_path | def get_version_exec_mapping_from_path(path):
"""
Find valid application version from given path object and return
a mapping of version, executable.
"""
version_executable = {}
logger.debug('Getting exes from path: {}'.format(path))
for sub_dir in path.iterdir():
if not sub_dir.name.startswith(APPLICATION_NAME):
continue
release = sub_dir.name.split(APPLICATION_NAME)[-1]
executable = Path(sub_dir, 'bin').glob('maya.exe').next()
version_executable[release] = str(executable)
logger.debug('Found exes for: {}'.format(version_executable.keys()))
return version_executable | python | def get_version_exec_mapping_from_path(path):
"""
Find valid application version from given path object and return
a mapping of version, executable.
"""
version_executable = {}
logger.debug('Getting exes from path: {}'.format(path))
for sub_dir in path.iterdir():
if not sub_dir.name.startswith(APPLICATION_NAME):
continue
release = sub_dir.name.split(APPLICATION_NAME)[-1]
executable = Path(sub_dir, 'bin').glob('maya.exe').next()
version_executable[release] = str(executable)
logger.debug('Found exes for: {}'.format(version_executable.keys()))
return version_executable | [
"def",
"get_version_exec_mapping_from_path",
"(",
"path",
")",
":",
"version_executable",
"=",
"{",
"}",
"logger",
".",
"debug",
"(",
"'Getting exes from path: {}'",
".",
"format",
"(",
"path",
")",
")",
"for",
"sub_dir",
"in",
"path",
".",
"iterdir",
"(",
")"... | Find valid application version from given path object and return
a mapping of version, executable. | [
"Find",
"valid",
"application",
"version",
"from",
"given",
"path",
"object",
"and",
"return",
"a",
"mapping",
"of",
"version",
"executable",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L52-L68 |
arubertoson/maya-launcher | mayalauncher.py | find_applications_on_system | def find_applications_on_system():
"""
Collect maya version from Autodesk PATH if exists, else try looking
for custom executable paths from config file.
"""
# First we collect maya versions from the Autodesk folder we presume
# is addeed to the system environment "PATH"
path_env = os.getenv('PATH').split(os.pathsep)
versions = {}
for each in path_env:
path = Path(os.path.expandvars(each))
if not path.exists():
continue
if path.name.endswith(DEVELOPER_NAME):
if not path.exists():
continue
versions.update(get_version_exec_mapping_from_path(path))
return versions | python | def find_applications_on_system():
"""
Collect maya version from Autodesk PATH if exists, else try looking
for custom executable paths from config file.
"""
# First we collect maya versions from the Autodesk folder we presume
# is addeed to the system environment "PATH"
path_env = os.getenv('PATH').split(os.pathsep)
versions = {}
for each in path_env:
path = Path(os.path.expandvars(each))
if not path.exists():
continue
if path.name.endswith(DEVELOPER_NAME):
if not path.exists():
continue
versions.update(get_version_exec_mapping_from_path(path))
return versions | [
"def",
"find_applications_on_system",
"(",
")",
":",
"# First we collect maya versions from the Autodesk folder we presume\r",
"# is addeed to the system environment \"PATH\"\r",
"path_env",
"=",
"os",
".",
"getenv",
"(",
"'PATH'",
")",
".",
"split",
"(",
"os",
".",
"pathsep"... | Collect maya version from Autodesk PATH if exists, else try looking
for custom executable paths from config file. | [
"Collect",
"maya",
"version",
"from",
"Autodesk",
"PATH",
"if",
"exists",
"else",
"try",
"looking",
"for",
"custom",
"executable",
"paths",
"from",
"config",
"file",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L71-L88 |
arubertoson/maya-launcher | mayalauncher.py | build_config | def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions found
# in the config file takes precedence over versions found in PATH.
for item in application_versions.iteritems():
if not config.has_option(Config.EXECUTABLES, item[0]):
config.set(Config.EXECUTABLES, item[0], item[1])
return config | python | def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions found
# in the config file takes precedence over versions found in PATH.
for item in application_versions.iteritems():
if not config.has_option(Config.EXECUTABLES, item[0]):
config.set(Config.EXECUTABLES, item[0], item[1])
return config | [
"def",
"build_config",
"(",
"config_file",
"=",
"get_system_config_directory",
"(",
")",
")",
":",
"config",
"=",
"Config",
"(",
"config_file",
",",
"allow_no_value",
"=",
"True",
")",
"application_versions",
"=",
"find_applications_on_system",
"(",
")",
"# Add foun... | Construct the config object from necessary elements. | [
"Construct",
"the",
"config",
"object",
"from",
"necessary",
"elements",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L167-L179 |
arubertoson/maya-launcher | mayalauncher.py | get_environment_paths | def get_environment_paths(config, env):
"""
Get environment paths from given environment variable.
"""
if env is None:
return config.get(Config.DEFAULTS, 'environment')
# Config option takes precedence over environment key.
if config.has_option(Config.ENVIRONMENTS, env):
env = config.get(Config.ENVIRONMENTS, env).replace(' ', '').split(';')
else:
env = os.getenv(env)
if env:
env = env.split(os.pathsep)
return [i for i in env if i] | python | def get_environment_paths(config, env):
"""
Get environment paths from given environment variable.
"""
if env is None:
return config.get(Config.DEFAULTS, 'environment')
# Config option takes precedence over environment key.
if config.has_option(Config.ENVIRONMENTS, env):
env = config.get(Config.ENVIRONMENTS, env).replace(' ', '').split(';')
else:
env = os.getenv(env)
if env:
env = env.split(os.pathsep)
return [i for i in env if i] | [
"def",
"get_environment_paths",
"(",
"config",
",",
"env",
")",
":",
"if",
"env",
"is",
"None",
":",
"return",
"config",
".",
"get",
"(",
"Config",
".",
"DEFAULTS",
",",
"'environment'",
")",
"# Config option takes precedence over environment key.\r",
"if",
"confi... | Get environment paths from given environment variable. | [
"Get",
"environment",
"paths",
"from",
"given",
"environment",
"variable",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L350-L364 |
arubertoson/maya-launcher | mayalauncher.py | build_maya_environment | def build_maya_environment(config, env=None, arg_paths=None):
"""
Construct maya environment.
"""
maya_env = MayaEnvironment()
maya_env.exclude_pattern = config.get_list(Config.PATTERNS, 'exclude')
maya_env.icon_extensions = config.get_list(Config.PATTERNS, 'icon_ext')
env = get_environment_paths(config, env)
if not env and arg_paths is None:
return logger.info('Using maya factory environment setup.')
logger.debug('Launching with addon paths: {}'.format(arg_paths))
logger.debug('Launching with environment paths: {}'.format(env))
if arg_paths:
arg_paths = arg_paths.split(' ')
for directory in flatten_combine_lists(env, arg_paths or ''):
maya_env.traverse_path_for_valid_application_paths(directory)
return maya_env | python | def build_maya_environment(config, env=None, arg_paths=None):
"""
Construct maya environment.
"""
maya_env = MayaEnvironment()
maya_env.exclude_pattern = config.get_list(Config.PATTERNS, 'exclude')
maya_env.icon_extensions = config.get_list(Config.PATTERNS, 'icon_ext')
env = get_environment_paths(config, env)
if not env and arg_paths is None:
return logger.info('Using maya factory environment setup.')
logger.debug('Launching with addon paths: {}'.format(arg_paths))
logger.debug('Launching with environment paths: {}'.format(env))
if arg_paths:
arg_paths = arg_paths.split(' ')
for directory in flatten_combine_lists(env, arg_paths or ''):
maya_env.traverse_path_for_valid_application_paths(directory)
return maya_env | [
"def",
"build_maya_environment",
"(",
"config",
",",
"env",
"=",
"None",
",",
"arg_paths",
"=",
"None",
")",
":",
"maya_env",
"=",
"MayaEnvironment",
"(",
")",
"maya_env",
".",
"exclude_pattern",
"=",
"config",
".",
"get_list",
"(",
"Config",
".",
"PATTERNS"... | Construct maya environment. | [
"Construct",
"maya",
"environment",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L367-L386 |
arubertoson/maya-launcher | mayalauncher.py | launch | def launch(exec_, args):
"""
Launches application.
"""
if not exec_:
raise RuntimeError(
'Mayalauncher could not find a maya executable, please specify'
'a path in the config file (-e) or add the {} directory location'
'to your PATH system environment.'.format(DEVELOPER_NAME)
)
# Launch Maya
if args.debug:
return
watched = WatchFile()
cmd = [exec_] if args.file is None else [exec_, args.file]
cmd.extend(['-hideConsole', '-log', watched.path])
if args.debug:
cmd.append('-noAutoloadPlugins')
maya = subprocess.Popen(cmd)
# Maya 2016 stupid clic ipm
# os.environ['MAYA_DISABLE_CLIC_IPM'] = '1'
# os.environ['MAYA_DISABLE_CIP'] = '1'
# os.environ['MAYA_OPENCL_IGNORE_DRIVER_VERSION'] = '1'
while True:
time.sleep(1)
maya.poll()
watched.check()
if maya.returncode is not None:
if not maya.returncode == 0:
maya = subprocess.Popen(cmd)
else:
watched.stop()
break | python | def launch(exec_, args):
"""
Launches application.
"""
if not exec_:
raise RuntimeError(
'Mayalauncher could not find a maya executable, please specify'
'a path in the config file (-e) or add the {} directory location'
'to your PATH system environment.'.format(DEVELOPER_NAME)
)
# Launch Maya
if args.debug:
return
watched = WatchFile()
cmd = [exec_] if args.file is None else [exec_, args.file]
cmd.extend(['-hideConsole', '-log', watched.path])
if args.debug:
cmd.append('-noAutoloadPlugins')
maya = subprocess.Popen(cmd)
# Maya 2016 stupid clic ipm
# os.environ['MAYA_DISABLE_CLIC_IPM'] = '1'
# os.environ['MAYA_DISABLE_CIP'] = '1'
# os.environ['MAYA_OPENCL_IGNORE_DRIVER_VERSION'] = '1'
while True:
time.sleep(1)
maya.poll()
watched.check()
if maya.returncode is not None:
if not maya.returncode == 0:
maya = subprocess.Popen(cmd)
else:
watched.stop()
break | [
"def",
"launch",
"(",
"exec_",
",",
"args",
")",
":",
"if",
"not",
"exec_",
":",
"raise",
"RuntimeError",
"(",
"'Mayalauncher could not find a maya executable, please specify'",
"'a path in the config file (-e) or add the {} directory location'",
"'to your PATH system environment.'... | Launches application. | [
"Launches",
"application",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L443-L481 |
arubertoson/maya-launcher | mayalauncher.py | main | def main():
"""
Main function of maya launcher. Parses the arguments and tries to
launch maya with given them.
"""
config = build_config()
parser = argparse.ArgumentParser(
description="""
Maya Launcher is a useful script that tries to deal with all
important system environments maya uses when starting up.
It aims to streamline the setup process of maya to a simple string
instead of constantly having to make sure paths are setup correctly.
"""
)
parser.add_argument(
'file',
nargs='?',
default=None,
help="""
file is an optional argument telling maya what file to open with
the launcher.
""")
parser.add_argument(
'-v', '--version',
type=str,
choices=get_executable_choices(dict(config.items(
Config.EXECUTABLES))),
help="""
Launch Maya with given version.
""")
parser.add_argument(
'-env', '--environment',
metavar='env',
type=str,
default=config.get(Config.DEFAULTS, 'environment'),
help="""
Launch maya with given environemnt, if no environment is specified
will try to use default value. If not default value is specified
Maya will behave with factory environment setup.
""")
parser.add_argument(
'-p', '--path',
metavar='path',
type=str,
nargs='+',
help="""
Path is an optional argument that takes an unlimited number of paths
to use for environment creation.
Useful if you don't want to create a environment variable. Just
pass the path you want to use.
""")
parser.add_argument(
'-e', '--edit',
action='store_true',
help="""
Edit config file.
""")
parser.add_argument(
'-d', '--debug',
action='store_true',
help="""
Start maya in dev mode, autoload on plugins are turned off.
""")
# Parse the arguments
args = parser.parse_args()
if args.edit:
return config.edit()
if args.debug:
logger.setLevel(logging.DEBUG)
# Get executable from either default value in config or given value.
# If neither exists exit launcher.
if args.version is None:
exec_default = config.get(Config.DEFAULTS, 'executable')
if not exec_default and config.items(Config.EXECUTABLES):
items = dict(config.items(Config.EXECUTABLES))
exec_ = items[sorted(items.keys(), reverse=True)[0]]
else:
exec_ = exec_default
else:
exec_ = config.get(Config.EXECUTABLES, args.version)
build_maya_environment(config, args.environment, args.path)
logger.info('\nDone building maya environment, launching: \n{}\n'.format(exec_))
launch(exec_, args) | python | def main():
"""
Main function of maya launcher. Parses the arguments and tries to
launch maya with given them.
"""
config = build_config()
parser = argparse.ArgumentParser(
description="""
Maya Launcher is a useful script that tries to deal with all
important system environments maya uses when starting up.
It aims to streamline the setup process of maya to a simple string
instead of constantly having to make sure paths are setup correctly.
"""
)
parser.add_argument(
'file',
nargs='?',
default=None,
help="""
file is an optional argument telling maya what file to open with
the launcher.
""")
parser.add_argument(
'-v', '--version',
type=str,
choices=get_executable_choices(dict(config.items(
Config.EXECUTABLES))),
help="""
Launch Maya with given version.
""")
parser.add_argument(
'-env', '--environment',
metavar='env',
type=str,
default=config.get(Config.DEFAULTS, 'environment'),
help="""
Launch maya with given environemnt, if no environment is specified
will try to use default value. If not default value is specified
Maya will behave with factory environment setup.
""")
parser.add_argument(
'-p', '--path',
metavar='path',
type=str,
nargs='+',
help="""
Path is an optional argument that takes an unlimited number of paths
to use for environment creation.
Useful if you don't want to create a environment variable. Just
pass the path you want to use.
""")
parser.add_argument(
'-e', '--edit',
action='store_true',
help="""
Edit config file.
""")
parser.add_argument(
'-d', '--debug',
action='store_true',
help="""
Start maya in dev mode, autoload on plugins are turned off.
""")
# Parse the arguments
args = parser.parse_args()
if args.edit:
return config.edit()
if args.debug:
logger.setLevel(logging.DEBUG)
# Get executable from either default value in config or given value.
# If neither exists exit launcher.
if args.version is None:
exec_default = config.get(Config.DEFAULTS, 'executable')
if not exec_default and config.items(Config.EXECUTABLES):
items = dict(config.items(Config.EXECUTABLES))
exec_ = items[sorted(items.keys(), reverse=True)[0]]
else:
exec_ = exec_default
else:
exec_ = config.get(Config.EXECUTABLES, args.version)
build_maya_environment(config, args.environment, args.path)
logger.info('\nDone building maya environment, launching: \n{}\n'.format(exec_))
launch(exec_, args) | [
"def",
"main",
"(",
")",
":",
"config",
"=",
"build_config",
"(",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"\r\n Maya Launcher is a useful script that tries to deal with all\r\n important system environments maya uses whe... | Main function of maya launcher. Parses the arguments and tries to
launch maya with given them. | [
"Main",
"function",
"of",
"maya",
"launcher",
".",
"Parses",
"the",
"arguments",
"and",
"tries",
"to",
"launch",
"maya",
"with",
"given",
"them",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L484-L579 |
arubertoson/maya-launcher | mayalauncher.py | Config._create_default_config_file | def _create_default_config_file(self):
"""
If config file does not exists create and set default values.
"""
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(self.ENVIRONMENTS)
self.add_section(self.EXECUTABLES)
self.set(self.DEFAULTS, 'executable', None)
self.set(self.DEFAULTS, 'environment', None)
self.set(self.PATTERNS, 'exclude', ', '.join(self.EXLUDE_PATTERNS))
self.set(self.PATTERNS, 'icon_ext', ', '.join(self.ICON_EXTENSIONS))
self.config_file.parent.mkdir(exist_ok=True)
self.config_file.touch()
with self.config_file.open('wb') as f:
self.write(f)
# If this function is run inform the user that a new file has been
# created.
sys.exit('Maya launcher has successfully created config file at:\n'
' "{}"'.format(str(self.config_file))) | python | def _create_default_config_file(self):
"""
If config file does not exists create and set default values.
"""
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(self.ENVIRONMENTS)
self.add_section(self.EXECUTABLES)
self.set(self.DEFAULTS, 'executable', None)
self.set(self.DEFAULTS, 'environment', None)
self.set(self.PATTERNS, 'exclude', ', '.join(self.EXLUDE_PATTERNS))
self.set(self.PATTERNS, 'icon_ext', ', '.join(self.ICON_EXTENSIONS))
self.config_file.parent.mkdir(exist_ok=True)
self.config_file.touch()
with self.config_file.open('wb') as f:
self.write(f)
# If this function is run inform the user that a new file has been
# created.
sys.exit('Maya launcher has successfully created config file at:\n'
' "{}"'.format(str(self.config_file))) | [
"def",
"_create_default_config_file",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Initialize Maya launcher, creating config file...\\n'",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"DEFAULTS",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"PA... | If config file does not exists create and set default values. | [
"If",
"config",
"file",
"does",
"not",
"exists",
"create",
"and",
"set",
"default",
"values",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L113-L135 |
arubertoson/maya-launcher | mayalauncher.py | Config.get_list | def get_list(self, section, option):
"""
Convert string value to list object.
"""
if self.has_option(section, option):
return self.get(section, option).replace(' ', '').split(',')
else:
raise KeyError('{} with {} does not exist.'.format(section,
option)) | python | def get_list(self, section, option):
"""
Convert string value to list object.
"""
if self.has_option(section, option):
return self.get(section, option).replace(' ', '').split(',')
else:
raise KeyError('{} with {} does not exist.'.format(section,
option)) | [
"def",
"get_list",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"self",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"return",
"self",
".",
"get",
"(",
"section",
",",
"option",
")",
".",
"replace",
"(",
"' '",
",",
"'... | Convert string value to list object. | [
"Convert",
"string",
"value",
"to",
"list",
"object",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L137-L145 |
arubertoson/maya-launcher | mayalauncher.py | Config.edit | def edit(self):
"""
Edit file with default os application.
"""
if platform.system().lower() == 'windows':
os.startfile(str(self.config_file))
else:
if platform.system().lower() == 'darwin':
call = 'open'
else:
call = 'xdg-open'
subprocess.call([call, self.config_file]) | python | def edit(self):
"""
Edit file with default os application.
"""
if platform.system().lower() == 'windows':
os.startfile(str(self.config_file))
else:
if platform.system().lower() == 'darwin':
call = 'open'
else:
call = 'xdg-open'
subprocess.call([call, self.config_file]) | [
"def",
"edit",
"(",
"self",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'windows'",
":",
"os",
".",
"startfile",
"(",
"str",
"(",
"self",
".",
"config_file",
")",
")",
"else",
":",
"if",
"platform",
".",
"s... | Edit file with default os application. | [
"Edit",
"file",
"with",
"default",
"os",
"application",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L153-L164 |
arubertoson/maya-launcher | mayalauncher.py | MayaEnvironment.is_excluded | def is_excluded(self, path, exclude=None):
"""
Return if path is in exclude pattern.
"""
for pattern in (exclude or self.exclude_pattern):
if path.match(pattern):
return True
else:
return False | python | def is_excluded(self, path, exclude=None):
"""
Return if path is in exclude pattern.
"""
for pattern in (exclude or self.exclude_pattern):
if path.match(pattern):
return True
else:
return False | [
"def",
"is_excluded",
"(",
"self",
",",
"path",
",",
"exclude",
"=",
"None",
")",
":",
"for",
"pattern",
"in",
"(",
"exclude",
"or",
"self",
".",
"exclude_pattern",
")",
":",
"if",
"path",
".",
"match",
"(",
"pattern",
")",
":",
"return",
"True",
"el... | Return if path is in exclude pattern. | [
"Return",
"if",
"path",
"is",
"in",
"exclude",
"pattern",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L258-L266 |
arubertoson/maya-launcher | mayalauncher.py | MayaEnvironment.get_directories_with_extensions | def get_directories_with_extensions(self, start, extensions=None):
"""
Look for directories with image extensions in given directory and
return a list with found dirs.
.. note:: In deep file structures this might get pretty slow.
"""
return set([p.parent for ext in extensions for p in start.rglob(ext)]) | python | def get_directories_with_extensions(self, start, extensions=None):
"""
Look for directories with image extensions in given directory and
return a list with found dirs.
.. note:: In deep file structures this might get pretty slow.
"""
return set([p.parent for ext in extensions for p in start.rglob(ext)]) | [
"def",
"get_directories_with_extensions",
"(",
"self",
",",
"start",
",",
"extensions",
"=",
"None",
")",
":",
"return",
"set",
"(",
"[",
"p",
".",
"parent",
"for",
"ext",
"in",
"extensions",
"for",
"p",
"in",
"start",
".",
"rglob",
"(",
"ext",
")",
"]... | Look for directories with image extensions in given directory and
return a list with found dirs.
.. note:: In deep file structures this might get pretty slow. | [
"Look",
"for",
"directories",
"with",
"image",
"extensions",
"in",
"given",
"directory",
"and",
"return",
"a",
"list",
"with",
"found",
"dirs",
".",
"..",
"note",
"::",
"In",
"deep",
"file",
"structures",
"this",
"might",
"get",
"pretty",
"slow",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L288-L295 |
arubertoson/maya-launcher | mayalauncher.py | MayaEnvironment.put_path | def put_path(self, path):
"""
Given path identify in which environment the path belong to and
append it.
"""
if self.is_package(path):
logger.debug('PYTHON PACKAGE: {}'.format(path))
self.python_paths.append(path.parent)
site.addsitedir(str(path.parent))
xbmdirs = self.get_directories_with_extensions(
path,
self.icon_extensions,
)
self.xbmlang_paths.extend(xbmdirs)
return
if self.has_next(path.glob('*.' + self.MEL)):
logger.debug('MEL: {}'.format(str(path)))
self.script_paths.append(path)
if self.has_next(path.glob('*.' + self.PYTHON)):
logger.debug('PYTHONPATH: {}'.format(str(path)))
self.python_paths.append(path)
site.addsitedir(str(path))
if self.PLUGIN in list(path.iterdir()):
logger.debug('PLUG-IN: {}'.format(str(path)))
self.plug_in_paths.append(path)
for ext in self.icon_extensions:
if self.has_next(path.glob('*.' + ext)):
logger.debug('XBM: {}.'.format(str(path)))
self.xbmlang_paths.append(path)
break | python | def put_path(self, path):
"""
Given path identify in which environment the path belong to and
append it.
"""
if self.is_package(path):
logger.debug('PYTHON PACKAGE: {}'.format(path))
self.python_paths.append(path.parent)
site.addsitedir(str(path.parent))
xbmdirs = self.get_directories_with_extensions(
path,
self.icon_extensions,
)
self.xbmlang_paths.extend(xbmdirs)
return
if self.has_next(path.glob('*.' + self.MEL)):
logger.debug('MEL: {}'.format(str(path)))
self.script_paths.append(path)
if self.has_next(path.glob('*.' + self.PYTHON)):
logger.debug('PYTHONPATH: {}'.format(str(path)))
self.python_paths.append(path)
site.addsitedir(str(path))
if self.PLUGIN in list(path.iterdir()):
logger.debug('PLUG-IN: {}'.format(str(path)))
self.plug_in_paths.append(path)
for ext in self.icon_extensions:
if self.has_next(path.glob('*.' + ext)):
logger.debug('XBM: {}.'.format(str(path)))
self.xbmlang_paths.append(path)
break | [
"def",
"put_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"is_package",
"(",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"'PYTHON PACKAGE: {}'",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"python_paths",
".",
"append",
"(",
... | Given path identify in which environment the path belong to and
append it. | [
"Given",
"path",
"identify",
"in",
"which",
"environment",
"the",
"path",
"belong",
"to",
"and",
"append",
"it",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L297-L330 |
arubertoson/maya-launcher | mayalauncher.py | MayaEnvironment.traverse_path_for_valid_application_paths | def traverse_path_for_valid_application_paths(self, top_path):
"""
For every path beneath top path that does not contain the exclude
pattern look for python, mel and images and place them in their
corresponding system environments.
"""
self.put_path(Path(top_path))
for p in self._walk(top_path):
self.put_path(p) | python | def traverse_path_for_valid_application_paths(self, top_path):
"""
For every path beneath top path that does not contain the exclude
pattern look for python, mel and images and place them in their
corresponding system environments.
"""
self.put_path(Path(top_path))
for p in self._walk(top_path):
self.put_path(p) | [
"def",
"traverse_path_for_valid_application_paths",
"(",
"self",
",",
"top_path",
")",
":",
"self",
".",
"put_path",
"(",
"Path",
"(",
"top_path",
")",
")",
"for",
"p",
"in",
"self",
".",
"_walk",
"(",
"top_path",
")",
":",
"self",
".",
"put_path",
"(",
... | For every path beneath top path that does not contain the exclude
pattern look for python, mel and images and place them in their
corresponding system environments. | [
"For",
"every",
"path",
"beneath",
"top",
"path",
"that",
"does",
"not",
"contain",
"the",
"exclude",
"pattern",
"look",
"for",
"python",
"mel",
"and",
"images",
"and",
"place",
"them",
"in",
"their",
"corresponding",
"system",
"environments",
"."
] | train | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L332-L340 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.check_correct_host | def check_correct_host(self):
"""The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com """
if self._host == 'knoema.com':
return
url = self._get_url('/api/1.0/frontend/tags')
req = urllib.request.Request(url)
try:
resp = urllib.request.urlopen(req)
except:
raise ValueError('The specified host {} does not exist'.format(self._host)) | python | def check_correct_host(self):
"""The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com """
if self._host == 'knoema.com':
return
url = self._get_url('/api/1.0/frontend/tags')
req = urllib.request.Request(url)
try:
resp = urllib.request.urlopen(req)
except:
raise ValueError('The specified host {} does not exist'.format(self._host)) | [
"def",
"check_correct_host",
"(",
"self",
")",
":",
"if",
"self",
".",
"_host",
"==",
"'knoema.com'",
":",
"return",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'/api/1.0/frontend/tags'",
")",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"url"... | The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com | [
"The",
"method",
"checks",
"whether",
"the",
"host",
"is",
"correctly",
"set",
"and",
"whether",
"it",
"can",
"configure",
"the",
"connection",
"to",
"this",
"host",
".",
"Does",
"not",
"check",
"the",
"base",
"host",
"knoema",
".",
"com"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L87-L96 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_dataset | def get_dataset(self, datasetid):
"""The method is getting information about dataset byt it's id"""
path = '/api/1.0/meta/dataset/{}'
return self._api_get(definition.Dataset, path.format(datasetid)) | python | def get_dataset(self, datasetid):
"""The method is getting information about dataset byt it's id"""
path = '/api/1.0/meta/dataset/{}'
return self._api_get(definition.Dataset, path.format(datasetid)) | [
"def",
"get_dataset",
"(",
"self",
",",
"datasetid",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"Dataset",
",",
"path",
".",
"format",
"(",
"datasetid",
")",
")"
] | The method is getting information about dataset byt it's id | [
"The",
"method",
"is",
"getting",
"information",
"about",
"dataset",
"byt",
"it",
"s",
"id"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L98-L102 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_dimension | def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | python | def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | [
"def",
"get_dimension",
"(",
"self",
",",
"dataset",
",",
"dimension",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}/dimension/{}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"Dimension",
",",
"path",
".",
"format",
"(",
"dataset",
",",
"d... | The method is getting information about dimension with items | [
"The",
"method",
"is",
"getting",
"information",
"about",
"dimension",
"with",
"items"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L104-L108 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_daterange | def get_daterange(self, dataset):
"""The method is getting information about date range of dataset"""
path = '/api/1.0/meta/dataset/{}/daterange'
return self._api_get(definition.DateRange, path.format(dataset)) | python | def get_daterange(self, dataset):
"""The method is getting information about date range of dataset"""
path = '/api/1.0/meta/dataset/{}/daterange'
return self._api_get(definition.DateRange, path.format(dataset)) | [
"def",
"get_daterange",
"(",
"self",
",",
"dataset",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}/daterange'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"DateRange",
",",
"path",
".",
"format",
"(",
"dataset",
")",
")"
] | The method is getting information about date range of dataset | [
"The",
"method",
"is",
"getting",
"information",
"about",
"date",
"range",
"of",
"dataset"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L110-L114 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_data | def get_data(self, pivotrequest):
"""The method is getting data by pivot request"""
path = '/api/1.0/data/pivot/'
return self._api_post(definition.PivotResponse, path, pivotrequest) | python | def get_data(self, pivotrequest):
"""The method is getting data by pivot request"""
path = '/api/1.0/data/pivot/'
return self._api_post(definition.PivotResponse, path, pivotrequest) | [
"def",
"get_data",
"(",
"self",
",",
"pivotrequest",
")",
":",
"path",
"=",
"'/api/1.0/data/pivot/'",
"return",
"self",
".",
"_api_post",
"(",
"definition",
".",
"PivotResponse",
",",
"path",
",",
"pivotrequest",
")"
] | The method is getting data by pivot request | [
"The",
"method",
"is",
"getting",
"data",
"by",
"pivot",
"request"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L116-L120 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_data_raw | def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, request)
token = res.continuation_token
while token is not None:
res2 = self.get_data_raw_with_token(token)
res.series += res2.series
token = res2.continuation_token
return res | python | def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, request)
token = res.continuation_token
while token is not None:
res2 = self.get_data_raw_with_token(token)
res.series += res2.series
token = res2.continuation_token
return res | [
"def",
"get_data_raw",
"(",
"self",
",",
"request",
")",
":",
"path",
"=",
"'/api/1.0/data/raw/'",
"res",
"=",
"self",
".",
"_api_post",
"(",
"definition",
".",
"RawDataResponse",
",",
"path",
",",
"request",
")",
"token",
"=",
"res",
".",
"continuation_toke... | The method is getting data by raw request | [
"The",
"method",
"is",
"getting",
"data",
"by",
"raw",
"request"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L122-L131 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.get_mnemonics | def get_mnemonics (self, mnemonics):
"""The method get series by mnemonics"""
path = '/api/1.0/data/mnemonics?mnemonics={0}'
return self._api_get(definition.MnemonicsResponseList, path.format(mnemonics)) | python | def get_mnemonics (self, mnemonics):
"""The method get series by mnemonics"""
path = '/api/1.0/data/mnemonics?mnemonics={0}'
return self._api_get(definition.MnemonicsResponseList, path.format(mnemonics)) | [
"def",
"get_mnemonics",
"(",
"self",
",",
"mnemonics",
")",
":",
"path",
"=",
"'/api/1.0/data/mnemonics?mnemonics={0}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"MnemonicsResponseList",
",",
"path",
".",
"format",
"(",
"mnemonics",
")",
")"
] | The method get series by mnemonics | [
"The",
"method",
"get",
"series",
"by",
"mnemonics"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L137-L140 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.upload_file | def upload_file(self, file):
"""The method is posting file to the remote server"""
url = self._get_url('/api/1.0/upload/post')
fcontent = FileContent(file)
binary_data = fcontent.get_binary()
headers = self._get_request_headers()
req = urllib.request.Request(url, binary_data, headers)
req.add_header('Content-type', fcontent.get_content_type())
req.add_header('Content-length', len(binary_data))
resp = urllib.request.urlopen(req)
return definition.UploadPostResponse(_response_to_json(resp)) | python | def upload_file(self, file):
"""The method is posting file to the remote server"""
url = self._get_url('/api/1.0/upload/post')
fcontent = FileContent(file)
binary_data = fcontent.get_binary()
headers = self._get_request_headers()
req = urllib.request.Request(url, binary_data, headers)
req.add_header('Content-type', fcontent.get_content_type())
req.add_header('Content-length', len(binary_data))
resp = urllib.request.urlopen(req)
return definition.UploadPostResponse(_response_to_json(resp)) | [
"def",
"upload_file",
"(",
"self",
",",
"file",
")",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'/api/1.0/upload/post'",
")",
"fcontent",
"=",
"FileContent",
"(",
"file",
")",
"binary_data",
"=",
"fcontent",
".",
"get_binary",
"(",
")",
"headers",
"="... | The method is posting file to the remote server | [
"The",
"method",
"is",
"posting",
"file",
"to",
"the",
"remote",
"server"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L142-L156 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.upload_verify | def upload_verify(self, file_location, dataset=None):
"""This method is verifiing posted file on server"""
path = '/api/1.0/upload/verify'
query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
if dataset:
query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, dataset)
return self._api_get(definition.UploadVerifyResponse, path, query) | python | def upload_verify(self, file_location, dataset=None):
"""This method is verifiing posted file on server"""
path = '/api/1.0/upload/verify'
query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
if dataset:
query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, dataset)
return self._api_get(definition.UploadVerifyResponse, path, query) | [
"def",
"upload_verify",
"(",
"self",
",",
"file_location",
",",
"dataset",
"=",
"None",
")",
":",
"path",
"=",
"'/api/1.0/upload/verify'",
"query",
"=",
"'doNotGenerateAdvanceReport=true&filePath={}'",
".",
"format",
"(",
"file_location",
")",
"if",
"dataset",
":",
... | This method is verifiing posted file on server | [
"This",
"method",
"is",
"verifiing",
"posted",
"file",
"on",
"server"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L158-L166 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.upload_submit | def upload_submit(self, upload_request):
"""The method is submitting dataset upload"""
path = '/api/1.0/upload/save'
return self._api_post(definition.DatasetUploadResponse, path, upload_request) | python | def upload_submit(self, upload_request):
"""The method is submitting dataset upload"""
path = '/api/1.0/upload/save'
return self._api_post(definition.DatasetUploadResponse, path, upload_request) | [
"def",
"upload_submit",
"(",
"self",
",",
"upload_request",
")",
":",
"path",
"=",
"'/api/1.0/upload/save'",
"return",
"self",
".",
"_api_post",
"(",
"definition",
".",
"DatasetUploadResponse",
",",
"path",
",",
"upload_request",
")"
] | The method is submitting dataset upload | [
"The",
"method",
"is",
"submitting",
"dataset",
"upload"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L168-L172 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.upload_status | def upload_status(self, upload_id):
"""The method is checking status of uploaded dataset"""
path = '/api/1.0/upload/status'
query = 'id={}'.format(upload_id)
return self._api_get(definition.DatasetUploadStatusResponse, path, query) | python | def upload_status(self, upload_id):
"""The method is checking status of uploaded dataset"""
path = '/api/1.0/upload/status'
query = 'id={}'.format(upload_id)
return self._api_get(definition.DatasetUploadStatusResponse, path, query) | [
"def",
"upload_status",
"(",
"self",
",",
"upload_id",
")",
":",
"path",
"=",
"'/api/1.0/upload/status'",
"query",
"=",
"'id={}'",
".",
"format",
"(",
"upload_id",
")",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"DatasetUploadStatusResponse",
","... | The method is checking status of uploaded dataset | [
"The",
"method",
"is",
"checking",
"status",
"of",
"uploaded",
"dataset"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L174-L179 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.upload | def upload(self, file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
upload_status = self.upload_file(file_path)
err_msg = 'Dataset has not been uploaded to the remote host'
if not upload_status.successful:
msg = '{}, because of the following error: {}'.format(err_msg, upload_status.error)
raise ValueError(msg)
err_msg = 'File has not been verified'
upload_ver_status = self.upload_verify(upload_status.properties.location, dataset)
if not upload_ver_status.successful:
ver_err = '\r\n'.join(upload_ver_status.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
ds_upload = definition.DatasetUpload(upload_ver_status, upload_status, dataset, public)
ds_upload_submit_result = self.upload_submit(ds_upload)
err_msg = 'Dataset has not been saved to the database'
if ds_upload_submit_result.status == 'failed':
ver_err = '\r\n'.join(ds_upload_submit_result.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
ds_upload_result = None
while True:
ds_upload_result = self.upload_status(ds_upload_submit_result.submit_id)
if ds_upload_result.status == 'pending' or ds_upload_result.status == 'processing':
time.sleep(5)
else:
break
if ds_upload_result.status != 'successful':
ver_err = '\r\n'.join(ds_upload_result.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
return ds_upload_result.dataset | python | def upload(self, file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
upload_status = self.upload_file(file_path)
err_msg = 'Dataset has not been uploaded to the remote host'
if not upload_status.successful:
msg = '{}, because of the following error: {}'.format(err_msg, upload_status.error)
raise ValueError(msg)
err_msg = 'File has not been verified'
upload_ver_status = self.upload_verify(upload_status.properties.location, dataset)
if not upload_ver_status.successful:
ver_err = '\r\n'.join(upload_ver_status.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
ds_upload = definition.DatasetUpload(upload_ver_status, upload_status, dataset, public)
ds_upload_submit_result = self.upload_submit(ds_upload)
err_msg = 'Dataset has not been saved to the database'
if ds_upload_submit_result.status == 'failed':
ver_err = '\r\n'.join(ds_upload_submit_result.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
ds_upload_result = None
while True:
ds_upload_result = self.upload_status(ds_upload_submit_result.submit_id)
if ds_upload_result.status == 'pending' or ds_upload_result.status == 'processing':
time.sleep(5)
else:
break
if ds_upload_result.status != 'successful':
ver_err = '\r\n'.join(ds_upload_result.errors)
msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err)
raise ValueError(msg)
return ds_upload_result.dataset | [
"def",
"upload",
"(",
"self",
",",
"file_path",
",",
"dataset",
"=",
"None",
",",
"public",
"=",
"False",
")",
":",
"upload_status",
"=",
"self",
".",
"upload_file",
"(",
"file_path",
")",
"err_msg",
"=",
"'Dataset has not been uploaded to the remote host'",
"if... | Use this function to upload data to Knoema dataset. | [
"Use",
"this",
"function",
"to",
"upload",
"data",
"to",
"Knoema",
"dataset",
"."
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L181-L218 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.delete | def delete(self, dataset):
"""The method is deleting dataset by it's id"""
url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))
json_data = ''
binary_data = json_data.encode()
headers = self._get_request_headers()
req = urllib.request.Request(url, binary_data, headers)
resp = urllib.request.urlopen(req)
str_response = resp.read().decode('utf-8')
if str_response != '"successful"' or resp.status < 200 or resp.status >= 300:
msg = 'Dataset has not been deleted, because of the following error(s): {}'.format(str_response)
raise ValueError(msg) | python | def delete(self, dataset):
"""The method is deleting dataset by it's id"""
url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))
json_data = ''
binary_data = json_data.encode()
headers = self._get_request_headers()
req = urllib.request.Request(url, binary_data, headers)
resp = urllib.request.urlopen(req)
str_response = resp.read().decode('utf-8')
if str_response != '"successful"' or resp.status < 200 or resp.status >= 300:
msg = 'Dataset has not been deleted, because of the following error(s): {}'.format(str_response)
raise ValueError(msg) | [
"def",
"delete",
"(",
"self",
",",
"dataset",
")",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'/api/1.0/meta/dataset/{}/delete'",
".",
"format",
"(",
"dataset",
")",
")",
"json_data",
"=",
"''",
"binary_data",
"=",
"json_data",
".",
"encode",
"(",
")"... | The method is deleting dataset by it's id | [
"The",
"method",
"is",
"deleting",
"dataset",
"by",
"it",
"s",
"id"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L220-L234 |
Knoema/knoema-python-driver | knoema/api_client.py | ApiClient.verify | def verify(self, dataset, publication_date, source, refernce_url):
"""The method is verifying dataset by it's id"""
path = '/api/1.0/meta/verifydataset'
req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url)
result = self._api_post(definition.DatasetVerifyResponse, path, req)
if result.status == 'failed':
ver_err = '\r\n'.join(result.errors)
msg = 'Dataset has not been verified, because of the following error(s): {}'.format(ver_err)
raise ValueError(msg) | python | def verify(self, dataset, publication_date, source, refernce_url):
"""The method is verifying dataset by it's id"""
path = '/api/1.0/meta/verifydataset'
req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url)
result = self._api_post(definition.DatasetVerifyResponse, path, req)
if result.status == 'failed':
ver_err = '\r\n'.join(result.errors)
msg = 'Dataset has not been verified, because of the following error(s): {}'.format(ver_err)
raise ValueError(msg) | [
"def",
"verify",
"(",
"self",
",",
"dataset",
",",
"publication_date",
",",
"source",
",",
"refernce_url",
")",
":",
"path",
"=",
"'/api/1.0/meta/verifydataset'",
"req",
"=",
"definition",
".",
"DatasetVerifyRequest",
"(",
"dataset",
",",
"publication_date",
",",
... | The method is verifying dataset by it's id | [
"The",
"method",
"is",
"verifying",
"dataset",
"by",
"it",
"s",
"id"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L236-L245 |
Knoema/knoema-python-driver | knoema/api_client.py | FileContent.get_binary | def get_binary(self):
"""Return a binary buffer containing the file content"""
content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"'
stream = io.BytesIO()
stream.write(_string_to_binary('--{}'.format(self.boundary)))
stream.write(_crlf())
stream.write(_string_to_binary(content_disp.format(self.file_name)))
stream.write(_crlf())
stream.write(_crlf())
stream.write(self.body)
stream.write(_crlf())
stream.write(_string_to_binary('--{}--'.format(self.boundary)))
stream.write(_crlf())
return stream.getvalue() | python | def get_binary(self):
"""Return a binary buffer containing the file content"""
content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"'
stream = io.BytesIO()
stream.write(_string_to_binary('--{}'.format(self.boundary)))
stream.write(_crlf())
stream.write(_string_to_binary(content_disp.format(self.file_name)))
stream.write(_crlf())
stream.write(_crlf())
stream.write(self.body)
stream.write(_crlf())
stream.write(_string_to_binary('--{}--'.format(self.boundary)))
stream.write(_crlf())
return stream.getvalue() | [
"def",
"get_binary",
"(",
"self",
")",
":",
"content_disp",
"=",
"'Content-Disposition: form-data; name=\"file\"; filename=\"{}\"'",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
")",
"stream",
".",
"write",
"(",
"_string_to_binary",
"(",
"'--{}'",
".",
"format",
"(",
... | Return a binary buffer containing the file content | [
"Return",
"a",
"binary",
"buffer",
"containing",
"the",
"file",
"content"
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L260-L276 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache._scratch_stream_name | def _scratch_stream_name(self):
"""
A unique cache stream name for this QueryCache.
Hashes the necessary facts about this QueryCache to generate a
unique cache stream name. Different `query_function`
implementations at different `bucket_width` values will be cached
to different streams.
TODO(marcua): This approach won't work for dynamically-generated
functions. We will want to either:
1) Hash the function closure/containing scope.
2) Ditch this approach and rely on the caller to tell us all the
information that makes this function unique.
"""
query_details = [
str(QueryCache.QUERY_CACHE_VERSION),
str(self._bucket_width),
binascii.b2a_hex(marshal.dumps(self._query_function.func_code)),
str(self._query_function_args),
str(self._query_function_kwargs),
]
return hashlib.sha512('$'.join(query_details)).hexdigest()[:20] | python | def _scratch_stream_name(self):
"""
A unique cache stream name for this QueryCache.
Hashes the necessary facts about this QueryCache to generate a
unique cache stream name. Different `query_function`
implementations at different `bucket_width` values will be cached
to different streams.
TODO(marcua): This approach won't work for dynamically-generated
functions. We will want to either:
1) Hash the function closure/containing scope.
2) Ditch this approach and rely on the caller to tell us all the
information that makes this function unique.
"""
query_details = [
str(QueryCache.QUERY_CACHE_VERSION),
str(self._bucket_width),
binascii.b2a_hex(marshal.dumps(self._query_function.func_code)),
str(self._query_function_args),
str(self._query_function_kwargs),
]
return hashlib.sha512('$'.join(query_details)).hexdigest()[:20] | [
"def",
"_scratch_stream_name",
"(",
"self",
")",
":",
"query_details",
"=",
"[",
"str",
"(",
"QueryCache",
".",
"QUERY_CACHE_VERSION",
")",
",",
"str",
"(",
"self",
".",
"_bucket_width",
")",
",",
"binascii",
".",
"b2a_hex",
"(",
"marshal",
".",
"dumps",
"... | A unique cache stream name for this QueryCache.
Hashes the necessary facts about this QueryCache to generate a
unique cache stream name. Different `query_function`
implementations at different `bucket_width` values will be cached
to different streams.
TODO(marcua): This approach won't work for dynamically-generated
functions. We will want to either:
1) Hash the function closure/containing scope.
2) Ditch this approach and rely on the caller to tell us all the
information that makes this function unique. | [
"A",
"unique",
"cache",
"stream",
"name",
"for",
"this",
"QueryCache",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L86-L108 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache._bucket_time | def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day.
"""
event_time = kronos_time_to_epoch_time(event_time)
return event_time - (event_time % self._bucket_width) | python | def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day.
"""
event_time = kronos_time_to_epoch_time(event_time)
return event_time - (event_time % self._bucket_width) | [
"def",
"_bucket_time",
"(",
"self",
",",
"event_time",
")",
":",
"event_time",
"=",
"kronos_time_to_epoch_time",
"(",
"event_time",
")",
"return",
"event_time",
"-",
"(",
"event_time",
"%",
"self",
".",
"_bucket_width",
")"
] | The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day. | [
"The",
"seconds",
"since",
"epoch",
"that",
"represent",
"a",
"computed",
"bucket",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L120-L130 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache._bucket_events | def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
current_bucket_time = None
current_bucket_events = None
for event in event_iterable:
event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
if current_bucket_time is None or current_bucket_time < event_bucket_time:
if current_bucket_events is not None:
yield current_bucket_events
current_bucket_time = event_bucket_time
current_bucket_events = []
current_bucket_events.append(event)
if current_bucket_events is not None and current_bucket_events != []:
yield current_bucket_events | python | def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
current_bucket_time = None
current_bucket_events = None
for event in event_iterable:
event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
if current_bucket_time is None or current_bucket_time < event_bucket_time:
if current_bucket_events is not None:
yield current_bucket_events
current_bucket_time = event_bucket_time
current_bucket_events = []
current_bucket_events.append(event)
if current_bucket_events is not None and current_bucket_events != []:
yield current_bucket_events | [
"def",
"_bucket_events",
"(",
"self",
",",
"event_iterable",
")",
":",
"current_bucket_time",
"=",
"None",
"current_bucket_events",
"=",
"None",
"for",
"event",
"in",
"event_iterable",
":",
"event_bucket_time",
"=",
"self",
".",
"_bucket_time",
"(",
"event",
"[",
... | Convert an iterable of events into an iterable of lists of events
per bucket. | [
"Convert",
"an",
"iterable",
"of",
"events",
"into",
"an",
"iterable",
"of",
"lists",
"of",
"events",
"per",
"bucket",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L132-L149 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache._cached_results | def _cached_results(self, start_time, end_time):
"""
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it might be safe to
return one of the cached results if there are multiple, we
currently do the safe thing and pretend we have no previously
computed data for this bucket.
"""
cached_buckets = self._bucket_events(
self._client.get(self._scratch_stream, start_time, end_time,
namespace=self._scratch_namespace))
for bucket_events in cached_buckets:
# If we have multiple cache entries for the same bucket, pretend
# we have no results for that bucket.
if len(bucket_events) == 1:
first_result = bucket_events[0]
yield (kronos_time_to_epoch_time(first_result[TIMESTAMP_FIELD]),
first_result[QueryCache.CACHE_KEY]) | python | def _cached_results(self, start_time, end_time):
"""
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it might be safe to
return one of the cached results if there are multiple, we
currently do the safe thing and pretend we have no previously
computed data for this bucket.
"""
cached_buckets = self._bucket_events(
self._client.get(self._scratch_stream, start_time, end_time,
namespace=self._scratch_namespace))
for bucket_events in cached_buckets:
# If we have multiple cache entries for the same bucket, pretend
# we have no results for that bucket.
if len(bucket_events) == 1:
first_result = bucket_events[0]
yield (kronos_time_to_epoch_time(first_result[TIMESTAMP_FIELD]),
first_result[QueryCache.CACHE_KEY]) | [
"def",
"_cached_results",
"(",
"self",
",",
"start_time",
",",
"end_time",
")",
":",
"cached_buckets",
"=",
"self",
".",
"_bucket_events",
"(",
"self",
".",
"_client",
".",
"get",
"(",
"self",
".",
"_scratch_stream",
",",
"start_time",
",",
"end_time",
",",
... | Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it might be safe to
return one of the cached results if there are multiple, we
currently do the safe thing and pretend we have no previously
computed data for this bucket. | [
"Retrieves",
"cached",
"results",
"for",
"any",
"bucket",
"that",
"has",
"a",
"single",
"cache",
"entry",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L151-L171 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache.compute_and_cache_missing_buckets | def compute_and_cache_missing_buckets(self, start_time, end_time,
untrusted_time, force_recompute=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation. For any buckets
where all events would have occurred before `untrusted_time`,
cache the results.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param untrusted_time: A datetime after which to not trust that
computed data is stable. Any buckets that overlap with or follow
this untrusted_time will not be cached.
:param force_recompute: A boolean that, if True, will force
recompute and recaching of even previously cached data.
"""
if untrusted_time and not untrusted_time.tzinfo:
untrusted_time = untrusted_time.replace(tzinfo=tzutc())
events = self._compute_buckets(start_time, end_time, compute_missing=True,
cache=True, untrusted_time=untrusted_time,
force_recompute=force_recompute)
for event in events:
yield event | python | def compute_and_cache_missing_buckets(self, start_time, end_time,
untrusted_time, force_recompute=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation. For any buckets
where all events would have occurred before `untrusted_time`,
cache the results.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param untrusted_time: A datetime after which to not trust that
computed data is stable. Any buckets that overlap with or follow
this untrusted_time will not be cached.
:param force_recompute: A boolean that, if True, will force
recompute and recaching of even previously cached data.
"""
if untrusted_time and not untrusted_time.tzinfo:
untrusted_time = untrusted_time.replace(tzinfo=tzutc())
events = self._compute_buckets(start_time, end_time, compute_missing=True,
cache=True, untrusted_time=untrusted_time,
force_recompute=force_recompute)
for event in events:
yield event | [
"def",
"compute_and_cache_missing_buckets",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"untrusted_time",
",",
"force_recompute",
"=",
"False",
")",
":",
"if",
"untrusted_time",
"and",
"not",
"untrusted_time",
".",
"tzinfo",
":",
"untrusted_time",
"=",
"... | Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation. For any buckets
where all events would have occurred before `untrusted_time`,
cache the results.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param untrusted_time: A datetime after which to not trust that
computed data is stable. Any buckets that overlap with or follow
this untrusted_time will not be cached.
:param force_recompute: A boolean that, if True, will force
recompute and recaching of even previously cached data. | [
"Return",
"the",
"results",
"for",
"query_function",
"on",
"every",
"bucket_width",
"time",
"period",
"between",
"start_time",
"and",
"end_time",
".",
"Look",
"for",
"previously",
"cached",
"results",
"to",
"avoid",
"recomputation",
".",
"For",
"any",
"buckets",
... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L237-L264 |
Locu/chronology | pykronos/pykronos/utils/cache.py | QueryCache.retrieve_interval | def retrieve_interval(self, start_time, end_time, compute_missing=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param compute_missing: A boolean that, if True, will compute any
non-cached results.
"""
events = self._compute_buckets(start_time, end_time,
compute_missing=compute_missing)
for event in events:
yield event | python | def retrieve_interval(self, start_time, end_time, compute_missing=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param compute_missing: A boolean that, if True, will compute any
non-cached results.
"""
events = self._compute_buckets(start_time, end_time,
compute_missing=compute_missing)
for event in events:
yield event | [
"def",
"retrieve_interval",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"compute_missing",
"=",
"False",
")",
":",
"events",
"=",
"self",
".",
"_compute_buckets",
"(",
"start_time",
",",
"end_time",
",",
"compute_missing",
"=",
"compute_missing",
")",
... | Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the end of the range, aligned with
`bucket_width`.
:param compute_missing: A boolean that, if True, will compute any
non-cached results. | [
"Return",
"the",
"results",
"for",
"query_function",
"on",
"every",
"bucket_width",
"time",
"period",
"between",
"start_time",
"and",
"end_time",
".",
"Look",
"for",
"previously",
"cached",
"results",
"to",
"avoid",
"recomputation",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L266-L283 |
Locu/chronology | jia/scheduler/scheduler.py | _execute | def _execute(task):
"""A wrapper around exec
This exists outside the Scheduler class because it is pickled after it is
sent to the executor.
"""
print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id'])
try:
with get_app().app_context():
exec task['code'] in {}, {}
print "[%s] -- %s -- COMPLETE" % (datetime.datetime.now(), task['id'])
except Exception as e:
if isinstance(e, PyCodeError):
err_msg = "%s: %s\n%s" % (e.data['name'], e.data['message'],
''.join(e.data['traceback']))
else:
err_msg = traceback.format_exc()
sys.stderr.write(err_msg)
sys.stderr.write("[%s] -- %s -- FAIL\n" % (datetime.datetime.now(),
task['id']))
email_msg = 'Task %s failed at %s\n\n%s' % (task['id'],
datetime.datetime.now(),
err_msg)
send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
'Scheduler Failure', email_msg)
finally:
return task | python | def _execute(task):
"""A wrapper around exec
This exists outside the Scheduler class because it is pickled after it is
sent to the executor.
"""
print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id'])
try:
with get_app().app_context():
exec task['code'] in {}, {}
print "[%s] -- %s -- COMPLETE" % (datetime.datetime.now(), task['id'])
except Exception as e:
if isinstance(e, PyCodeError):
err_msg = "%s: %s\n%s" % (e.data['name'], e.data['message'],
''.join(e.data['traceback']))
else:
err_msg = traceback.format_exc()
sys.stderr.write(err_msg)
sys.stderr.write("[%s] -- %s -- FAIL\n" % (datetime.datetime.now(),
task['id']))
email_msg = 'Task %s failed at %s\n\n%s' % (task['id'],
datetime.datetime.now(),
err_msg)
send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
'Scheduler Failure', email_msg)
finally:
return task | [
"def",
"_execute",
"(",
"task",
")",
":",
"print",
"\"[%s] -- %s -- START\"",
"%",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"task",
"[",
"'id'",
"]",
")",
"try",
":",
"with",
"get_app",
"(",
")",
".",
"app_context",
"(",
")",
":",... | A wrapper around exec
This exists outside the Scheduler class because it is pickled after it is
sent to the executor. | [
"A",
"wrapper",
"around",
"exec"
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/scheduler/scheduler.py#L149-L175 |
Locu/chronology | jia/scheduler/scheduler.py | Scheduler._loop | def _loop(self, reader):
"""Main execution loop of the scheduler.
The loop runs every second. Between iterations, the loop listens for
schedule or cancel requests coming from Flask via over the gipc pipe
(reader) and modifies the queue accordingly.
When a task completes, it is rescheduled
"""
results = set()
while True:
now = datetime.datetime.now()
if self._task_queue and self._task_queue[0][0] <= now:
task = heappop(self._task_queue)[1]
if task['id'] not in self._pending_cancels:
result = self._executor.submit(_execute, task)
results.add(result)
else:
self._pending_cancels.remove(task['id'])
else:
# Check for new tasks coming from HTTP
with gevent.Timeout(0.5, False) as t:
message = reader.get(timeout=t)
if message[0] == 'schedule':
self._schedule(message[1], next_run=now)
elif message[0] == 'cancel':
self._cancel(message[1])
# Reschedule completed tasks
if not results:
gevent.sleep(0.5)
continue
ready = self._executor.wait(results, num=1, timeout=0.5)
for result in ready:
results.remove(result)
if result.value:
task = result.value
interval = int(task['interval'])
if interval:
run_at = now + datetime.timedelta(seconds=int(task['interval']))
self._schedule(task, next_run=run_at)
else:
err_msg = result.exception
sys.stderr.write("ERROR: %s" % err_msg)
email_msg = 'Task %s failed at %s\n\n%s' % (
task['id'],
datetime.datetime.now(),
err_msg
)
send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
'Scheduler Failure',
email_msg) | python | def _loop(self, reader):
"""Main execution loop of the scheduler.
The loop runs every second. Between iterations, the loop listens for
schedule or cancel requests coming from Flask via over the gipc pipe
(reader) and modifies the queue accordingly.
When a task completes, it is rescheduled
"""
results = set()
while True:
now = datetime.datetime.now()
if self._task_queue and self._task_queue[0][0] <= now:
task = heappop(self._task_queue)[1]
if task['id'] not in self._pending_cancels:
result = self._executor.submit(_execute, task)
results.add(result)
else:
self._pending_cancels.remove(task['id'])
else:
# Check for new tasks coming from HTTP
with gevent.Timeout(0.5, False) as t:
message = reader.get(timeout=t)
if message[0] == 'schedule':
self._schedule(message[1], next_run=now)
elif message[0] == 'cancel':
self._cancel(message[1])
# Reschedule completed tasks
if not results:
gevent.sleep(0.5)
continue
ready = self._executor.wait(results, num=1, timeout=0.5)
for result in ready:
results.remove(result)
if result.value:
task = result.value
interval = int(task['interval'])
if interval:
run_at = now + datetime.timedelta(seconds=int(task['interval']))
self._schedule(task, next_run=run_at)
else:
err_msg = result.exception
sys.stderr.write("ERROR: %s" % err_msg)
email_msg = 'Task %s failed at %s\n\n%s' % (
task['id'],
datetime.datetime.now(),
err_msg
)
send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
'Scheduler Failure',
email_msg) | [
"def",
"_loop",
"(",
"self",
",",
"reader",
")",
":",
"results",
"=",
"set",
"(",
")",
"while",
"True",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"self",
".",
"_task_queue",
"and",
"self",
".",
"_task_queue",
"[",
"0... | Main execution loop of the scheduler.
The loop runs every second. Between iterations, the loop listens for
schedule or cancel requests coming from Flask via over the gipc pipe
(reader) and modifies the queue accordingly.
When a task completes, it is rescheduled | [
"Main",
"execution",
"loop",
"of",
"the",
"scheduler",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/scheduler/scheduler.py#L95-L146 |
Locu/chronology | jia/scheduler/decorators.py | token_protected_endpoint | def token_protected_endpoint(function):
"""Requires valid auth_token in POST to access
An auth_token is built by sending a dictionary built from a
Werkzeug.Request.form to the scheduler.auth.create_token function.
"""
@wraps(function)
def decorated(*args, **kwargs):
auth_token = request.form.get('auth_token')
if not auth_token:
return json.dumps({
'status': 'fail',
'reason': 'You must provide an auth_token',
})
data = dict(request.form)
del data['auth_token']
correct_token = create_token(current_app.config['SECRET_KEY'], data)
if _compare_digest(auth_token, correct_token):
return function(*args, **kwargs)
else:
return json.dumps({
'status': 'fail',
'reason': 'Incorrect auth_token',
})
return decorated | python | def token_protected_endpoint(function):
"""Requires valid auth_token in POST to access
An auth_token is built by sending a dictionary built from a
Werkzeug.Request.form to the scheduler.auth.create_token function.
"""
@wraps(function)
def decorated(*args, **kwargs):
auth_token = request.form.get('auth_token')
if not auth_token:
return json.dumps({
'status': 'fail',
'reason': 'You must provide an auth_token',
})
data = dict(request.form)
del data['auth_token']
correct_token = create_token(current_app.config['SECRET_KEY'], data)
if _compare_digest(auth_token, correct_token):
return function(*args, **kwargs)
else:
return json.dumps({
'status': 'fail',
'reason': 'Incorrect auth_token',
})
return decorated | [
"def",
"token_protected_endpoint",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_token",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'auth_token'",
")",
... | Requires valid auth_token in POST to access
An auth_token is built by sending a dictionary built from a
Werkzeug.Request.form to the scheduler.auth.create_token function. | [
"Requires",
"valid",
"auth_token",
"in",
"POST",
"to",
"access"
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/scheduler/decorators.py#L33-L61 |
bovee/Aston | aston/trace/math_chromatograms.py | molmz | def molmz(df, noise=10000):
"""
The mz of the molecular ion.
"""
d = ((df.values > noise) * df.columns).max(axis=1)
return Trace(d, df.index, name='molmz') | python | def molmz(df, noise=10000):
"""
The mz of the molecular ion.
"""
d = ((df.values > noise) * df.columns).max(axis=1)
return Trace(d, df.index, name='molmz') | [
"def",
"molmz",
"(",
"df",
",",
"noise",
"=",
"10000",
")",
":",
"d",
"=",
"(",
"(",
"df",
".",
"values",
">",
"noise",
")",
"*",
"df",
".",
"columns",
")",
".",
"max",
"(",
"axis",
"=",
"1",
")",
"return",
"Trace",
"(",
"d",
",",
"df",
"."... | The mz of the molecular ion. | [
"The",
"mz",
"of",
"the",
"molecular",
"ion",
"."
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_chromatograms.py#L6-L11 |
bovee/Aston | aston/trace/math_chromatograms.py | mzminus | def mzminus(df, minus=0, noise=10000):
"""
The abundances of ions which are minus below the molecular ion.
"""
mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus
mol_ions[np.abs(mol_ions) < 0] = 0
d = np.abs(np.ones(df.shape) * df.columns -
(mol_ions[np.newaxis].T * np.ones(df.shape))) < 1
d = (df.values * d).sum(axis=1)
return Trace(d, df.index, name='m-' + str(minus)) | python | def mzminus(df, minus=0, noise=10000):
"""
The abundances of ions which are minus below the molecular ion.
"""
mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus
mol_ions[np.abs(mol_ions) < 0] = 0
d = np.abs(np.ones(df.shape) * df.columns -
(mol_ions[np.newaxis].T * np.ones(df.shape))) < 1
d = (df.values * d).sum(axis=1)
return Trace(d, df.index, name='m-' + str(minus)) | [
"def",
"mzminus",
"(",
"df",
",",
"minus",
"=",
"0",
",",
"noise",
"=",
"10000",
")",
":",
"mol_ions",
"=",
"(",
"(",
"df",
".",
"values",
">",
"noise",
")",
"*",
"df",
".",
"columns",
")",
".",
"max",
"(",
"axis",
"=",
"1",
")",
"-",
"minus"... | The abundances of ions which are minus below the molecular ion. | [
"The",
"abundances",
"of",
"ions",
"which",
"are",
"minus",
"below",
"the",
"molecular",
"ion",
"."
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_chromatograms.py#L14-L23 |
bovee/Aston | aston/trace/math_chromatograms.py | basemz | def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | python | def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | [
"def",
"basemz",
"(",
"df",
")",
":",
"# returns the",
"d",
"=",
"np",
".",
"array",
"(",
"df",
".",
"columns",
")",
"[",
"df",
".",
"values",
".",
"argmax",
"(",
"axis",
"=",
"1",
")",
"]",
"return",
"Trace",
"(",
"d",
",",
"df",
".",
"index",... | The mz of the most abundant ion. | [
"The",
"mz",
"of",
"the",
"most",
"abundant",
"ion",
"."
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_chromatograms.py#L26-L32 |
bovee/Aston | aston/trace/math_chromatograms.py | coda | def coda(df, window, level):
"""
CODA processing from Windig, Phalp, & Payne 1996 Anal Chem
"""
# pull out the data
d = df.values
# smooth the data and standardize it
smooth_data = movingaverage(d, df.index, window)[0]
stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std()
# scale the data to have unit length
scale_data = d / np.sqrt(np.sum(d ** 2, axis=0))
# calculate the "mass chromatographic quality" (MCQ) index
mcq = np.sum(stand_data * scale_data, axis=0) / np.sqrt(d.shape[0] - 1)
# filter out ions with an mcq below level
good_ions = [i for i, q in zip(df.columns, mcq) if q >= level]
return good_ions | python | def coda(df, window, level):
"""
CODA processing from Windig, Phalp, & Payne 1996 Anal Chem
"""
# pull out the data
d = df.values
# smooth the data and standardize it
smooth_data = movingaverage(d, df.index, window)[0]
stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std()
# scale the data to have unit length
scale_data = d / np.sqrt(np.sum(d ** 2, axis=0))
# calculate the "mass chromatographic quality" (MCQ) index
mcq = np.sum(stand_data * scale_data, axis=0) / np.sqrt(d.shape[0] - 1)
# filter out ions with an mcq below level
good_ions = [i for i, q in zip(df.columns, mcq) if q >= level]
return good_ions | [
"def",
"coda",
"(",
"df",
",",
"window",
",",
"level",
")",
":",
"# pull out the data",
"d",
"=",
"df",
".",
"values",
"# smooth the data and standardize it",
"smooth_data",
"=",
"movingaverage",
"(",
"d",
",",
"df",
".",
"index",
",",
"window",
")",
"[",
... | CODA processing from Windig, Phalp, & Payne 1996 Anal Chem | [
"CODA",
"processing",
"from",
"Windig",
"Phalp",
"&",
"Payne",
"1996",
"Anal",
"Chem"
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_chromatograms.py#L35-L54 |
bovee/Aston | aston/tracefile/mime.py | tfclasses | def tfclasses():
"""
A mapping of mimetypes to every class for reading data files.
"""
# automatically find any subclasses of TraceFile in the same
# directory as me
classes = {}
mydir = op.dirname(op.abspath(inspect.getfile(get_mimetype)))
tfcls = {"<class 'aston.tracefile.TraceFile'>",
"<class 'aston.tracefile.ScanListFile'>"}
for filename in glob(op.join(mydir, '*.py')):
name = op.splitext(op.basename(filename))[0]
module = import_module('aston.tracefile.' + name)
for clsname in dir(module):
cls = getattr(module, clsname)
if hasattr(cls, '__base__'):
if str(cls.__base__) in tfcls:
classes[cls.mime] = cls
return classes | python | def tfclasses():
"""
A mapping of mimetypes to every class for reading data files.
"""
# automatically find any subclasses of TraceFile in the same
# directory as me
classes = {}
mydir = op.dirname(op.abspath(inspect.getfile(get_mimetype)))
tfcls = {"<class 'aston.tracefile.TraceFile'>",
"<class 'aston.tracefile.ScanListFile'>"}
for filename in glob(op.join(mydir, '*.py')):
name = op.splitext(op.basename(filename))[0]
module = import_module('aston.tracefile.' + name)
for clsname in dir(module):
cls = getattr(module, clsname)
if hasattr(cls, '__base__'):
if str(cls.__base__) in tfcls:
classes[cls.mime] = cls
return classes | [
"def",
"tfclasses",
"(",
")",
":",
"# automatically find any subclasses of TraceFile in the same",
"# directory as me",
"classes",
"=",
"{",
"}",
"mydir",
"=",
"op",
".",
"dirname",
"(",
"op",
".",
"abspath",
"(",
"inspect",
".",
"getfile",
"(",
"get_mimetype",
")... | A mapping of mimetypes to every class for reading data files. | [
"A",
"mapping",
"of",
"mimetypes",
"to",
"every",
"class",
"for",
"reading",
"data",
"files",
"."
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/tracefile/mime.py#L95-L113 |
bovee/Aston | aston/peak/peak_fitting.py | guess_initc | def guess_initc(ts, f, rts=[]):
"""
ts - An AstonSeries that's being fitted with peaks
f - The functional form of the peaks (e.g. gaussian)
rts - peak maxima to fit; each number corresponds to one peak
"""
def find_side(y, loc=None):
if loc is None:
loc = y.argmax()
ddy = np.diff(np.diff(y))
lft_loc, rgt_loc = loc - 2, loc + 1
while rgt_loc >= 0 and rgt_loc < len(ddy):
if ddy[rgt_loc] < ddy[rgt_loc - 1]:
break
rgt_loc += 1
while lft_loc >= 0 and lft_loc < len(ddy):
if ddy[lft_loc] < ddy[lft_loc + 1]:
break
lft_loc -= 1
return lft_loc + 1, rgt_loc + 1
# weight_mom = lambda m, a, w: \
# np.sum(w * (a - np.sum(w * a) / np.sum(w)) ** m) / np.sum(w)
# sig = np.sqrt(weight_mom(2, ts.index, ts.values)) # sigma
# peak_params['s'] = weight_mom(3, ts.index, ts.values) / sig ** 3
# peak_params['e'] = weight_mom(4, ts.index, ts.values) / sig ** 4 - 3
# TODO: better method of calculation of these?
all_params = []
for rt in rts:
peak_params = {'x': rt} # ts.index[ts.values.argmax()]
top_idx = np.abs(ts.index - rt).argmin()
side_idx = find_side(ts.values, top_idx)
peak_params['h'] = ts.values[top_idx]
# - min(ts.y[side_idx[0]], ts.y[side_idx[1]])
peak_params['w'] = ts.index[side_idx[1]] - ts.index[side_idx[0]]
peak_params['s'] = 1.1
peak_params['e'] = 1.
peak_params['a'] = 1.
all_params.append(peak_params)
return all_params | python | def guess_initc(ts, f, rts=[]):
"""
ts - An AstonSeries that's being fitted with peaks
f - The functional form of the peaks (e.g. gaussian)
rts - peak maxima to fit; each number corresponds to one peak
"""
def find_side(y, loc=None):
if loc is None:
loc = y.argmax()
ddy = np.diff(np.diff(y))
lft_loc, rgt_loc = loc - 2, loc + 1
while rgt_loc >= 0 and rgt_loc < len(ddy):
if ddy[rgt_loc] < ddy[rgt_loc - 1]:
break
rgt_loc += 1
while lft_loc >= 0 and lft_loc < len(ddy):
if ddy[lft_loc] < ddy[lft_loc + 1]:
break
lft_loc -= 1
return lft_loc + 1, rgt_loc + 1
# weight_mom = lambda m, a, w: \
# np.sum(w * (a - np.sum(w * a) / np.sum(w)) ** m) / np.sum(w)
# sig = np.sqrt(weight_mom(2, ts.index, ts.values)) # sigma
# peak_params['s'] = weight_mom(3, ts.index, ts.values) / sig ** 3
# peak_params['e'] = weight_mom(4, ts.index, ts.values) / sig ** 4 - 3
# TODO: better method of calculation of these?
all_params = []
for rt in rts:
peak_params = {'x': rt} # ts.index[ts.values.argmax()]
top_idx = np.abs(ts.index - rt).argmin()
side_idx = find_side(ts.values, top_idx)
peak_params['h'] = ts.values[top_idx]
# - min(ts.y[side_idx[0]], ts.y[side_idx[1]])
peak_params['w'] = ts.index[side_idx[1]] - ts.index[side_idx[0]]
peak_params['s'] = 1.1
peak_params['e'] = 1.
peak_params['a'] = 1.
all_params.append(peak_params)
return all_params | [
"def",
"guess_initc",
"(",
"ts",
",",
"f",
",",
"rts",
"=",
"[",
"]",
")",
":",
"def",
"find_side",
"(",
"y",
",",
"loc",
"=",
"None",
")",
":",
"if",
"loc",
"is",
"None",
":",
"loc",
"=",
"y",
".",
"argmax",
"(",
")",
"ddy",
"=",
"np",
"."... | ts - An AstonSeries that's being fitted with peaks
f - The functional form of the peaks (e.g. gaussian)
rts - peak maxima to fit; each number corresponds to one peak | [
"ts",
"-",
"An",
"AstonSeries",
"that",
"s",
"being",
"fitted",
"with",
"peaks",
"f",
"-",
"The",
"functional",
"form",
"of",
"the",
"peaks",
"(",
"e",
".",
"g",
".",
"gaussian",
")",
"rts",
"-",
"peak",
"maxima",
"to",
"fit",
";",
"each",
"number",
... | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/peak/peak_fitting.py#L46-L85 |
bovee/Aston | aston/peak/peak_fitting.py | fit | def fit(ts, fs=[], all_params=[], fit_vars=None,
alg='leastsq', make_bounded=True):
"""
Use a minimization algorithm to fit a AstonSeries with
analytical functions.
"""
if fit_vars is None:
fit_vars = [f._peakargs for f in fs]
initc = [min(ts.values)]
for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
if 'v' in to_fit:
to_fit.remove('v')
if make_bounded and hasattr(f, '_pbounds'):
new_v = _to_unbnd_p({i: peak_params[i] for i in to_fit},
f._pbounds)
initc += [new_v[i] for i in to_fit]
else:
initc += [peak_params[i] for i in to_fit]
def errfunc_lsq(fit_params, t, y, all_params):
# first value in fit_params is baseline
# fit_y = np.ones(len(t)) * fit_params[0]
fit_y = np.zeros(len(t))
param_i = 1
for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
for k in to_fit:
peak_params[k] = fit_params[param_i]
param_i += 1
if make_bounded and hasattr(f, '_pbounds'):
fit_y += f(t, **_to_bound_p(peak_params, f._pbounds))
else:
fit_y += f(t, **peak_params)
return fit_y - y
def errfunc(p, t, y, all_params):
return np.sum(errfunc_lsq(p, t, y, all_params) ** 2)
if alg == 'simplex':
fit_p, _ = fmin(errfunc, initc, args=(ts.index, ts.values,
peak_params))
# elif alg == 'anneal':
# fit_p, _ = anneal(errfunc, initc, args=(ts.index, ts.values,
# peak_params))
elif alg == 'lbfgsb':
# TODO: use bounds param
fitp, _ = fmin_l_bfgs_b(errfunc, fit_p,
args=(ts.index, ts.values, peak_params),
approx_grad=True)
elif alg == 'leastsq':
fit_p, _ = leastsq(errfunc_lsq, initc, args=(ts.index, ts.values,
all_params))
# else:
# r = minimize(errfunc, initc, \
# args=(ts.index, ts.values, all_params), \
# jac=False, gtol=1e-2)
# #if not r['success']:
# # print('Fail:' + str(f))
# # print(r)
# #if np.nan in r['x']: # not r['success']?
# # fit_p = initc
# #else:
# # fit_p = r['x']
fit_pl = fit_p.tolist()
v = fit_pl.pop(0) # noqa
fitted_params = []
for f, to_fit in zip(fs, fit_vars):
fit_p_dict = {v: fit_pl.pop(0) for v in to_fit}
# fit_p_dict['v'] = v
if make_bounded and hasattr(f, '_pbounds'):
fitted_params.append(_to_bound_p(fit_p_dict, f._pbounds))
else:
fitted_params.append(fit_p_dict)
# calculate r^2 of the fit
ss_err = errfunc(fit_p, ts.index, ts.values, fitted_params)
ss_tot = np.sum((ts.values - np.mean(ts.values)) ** 2)
r2 = 1 - ss_err / ss_tot
res = {'r^2': r2}
return fitted_params, res | python | def fit(ts, fs=[], all_params=[], fit_vars=None,
alg='leastsq', make_bounded=True):
"""
Use a minimization algorithm to fit a AstonSeries with
analytical functions.
"""
if fit_vars is None:
fit_vars = [f._peakargs for f in fs]
initc = [min(ts.values)]
for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
if 'v' in to_fit:
to_fit.remove('v')
if make_bounded and hasattr(f, '_pbounds'):
new_v = _to_unbnd_p({i: peak_params[i] for i in to_fit},
f._pbounds)
initc += [new_v[i] for i in to_fit]
else:
initc += [peak_params[i] for i in to_fit]
def errfunc_lsq(fit_params, t, y, all_params):
# first value in fit_params is baseline
# fit_y = np.ones(len(t)) * fit_params[0]
fit_y = np.zeros(len(t))
param_i = 1
for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
for k in to_fit:
peak_params[k] = fit_params[param_i]
param_i += 1
if make_bounded and hasattr(f, '_pbounds'):
fit_y += f(t, **_to_bound_p(peak_params, f._pbounds))
else:
fit_y += f(t, **peak_params)
return fit_y - y
def errfunc(p, t, y, all_params):
return np.sum(errfunc_lsq(p, t, y, all_params) ** 2)
if alg == 'simplex':
fit_p, _ = fmin(errfunc, initc, args=(ts.index, ts.values,
peak_params))
# elif alg == 'anneal':
# fit_p, _ = anneal(errfunc, initc, args=(ts.index, ts.values,
# peak_params))
elif alg == 'lbfgsb':
# TODO: use bounds param
fitp, _ = fmin_l_bfgs_b(errfunc, fit_p,
args=(ts.index, ts.values, peak_params),
approx_grad=True)
elif alg == 'leastsq':
fit_p, _ = leastsq(errfunc_lsq, initc, args=(ts.index, ts.values,
all_params))
# else:
# r = minimize(errfunc, initc, \
# args=(ts.index, ts.values, all_params), \
# jac=False, gtol=1e-2)
# #if not r['success']:
# # print('Fail:' + str(f))
# # print(r)
# #if np.nan in r['x']: # not r['success']?
# # fit_p = initc
# #else:
# # fit_p = r['x']
fit_pl = fit_p.tolist()
v = fit_pl.pop(0) # noqa
fitted_params = []
for f, to_fit in zip(fs, fit_vars):
fit_p_dict = {v: fit_pl.pop(0) for v in to_fit}
# fit_p_dict['v'] = v
if make_bounded and hasattr(f, '_pbounds'):
fitted_params.append(_to_bound_p(fit_p_dict, f._pbounds))
else:
fitted_params.append(fit_p_dict)
# calculate r^2 of the fit
ss_err = errfunc(fit_p, ts.index, ts.values, fitted_params)
ss_tot = np.sum((ts.values - np.mean(ts.values)) ** 2)
r2 = 1 - ss_err / ss_tot
res = {'r^2': r2}
return fitted_params, res | [
"def",
"fit",
"(",
"ts",
",",
"fs",
"=",
"[",
"]",
",",
"all_params",
"=",
"[",
"]",
",",
"fit_vars",
"=",
"None",
",",
"alg",
"=",
"'leastsq'",
",",
"make_bounded",
"=",
"True",
")",
":",
"if",
"fit_vars",
"is",
"None",
":",
"fit_vars",
"=",
"["... | Use a minimization algorithm to fit a AstonSeries with
analytical functions. | [
"Use",
"a",
"minimization",
"algorithm",
"to",
"fit",
"a",
"AstonSeries",
"with",
"analytical",
"functions",
"."
] | train | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/peak/peak_fitting.py#L88-L169 |
Locu/chronology | kronos/kronos/core/executor.py | execute_greenlet_async | def execute_greenlet_async(func, *args, **kwargs):
"""
Executes `func` in a separate greenlet in the same process. Memory and other
resources are available (e.g. TCP connections etc.) `args` and `kwargs` are
passed to `func`.
"""
global _GREENLET_EXECUTOR
if _GREENLET_EXECUTOR is None:
_GREENLET_EXECUTOR = GreenletExecutor(
num_greenlets=settings.node.greenlet_pool_size)
return _GREENLET_EXECUTOR.submit(func, *args, **kwargs) | python | def execute_greenlet_async(func, *args, **kwargs):
"""
Executes `func` in a separate greenlet in the same process. Memory and other
resources are available (e.g. TCP connections etc.) `args` and `kwargs` are
passed to `func`.
"""
global _GREENLET_EXECUTOR
if _GREENLET_EXECUTOR is None:
_GREENLET_EXECUTOR = GreenletExecutor(
num_greenlets=settings.node.greenlet_pool_size)
return _GREENLET_EXECUTOR.submit(func, *args, **kwargs) | [
"def",
"execute_greenlet_async",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_GREENLET_EXECUTOR",
"if",
"_GREENLET_EXECUTOR",
"is",
"None",
":",
"_GREENLET_EXECUTOR",
"=",
"GreenletExecutor",
"(",
"num_greenlets",
"=",
"settings",
... | Executes `func` in a separate greenlet in the same process. Memory and other
resources are available (e.g. TCP connections etc.) `args` and `kwargs` are
passed to `func`. | [
"Executes",
"func",
"in",
"a",
"separate",
"greenlet",
"in",
"the",
"same",
"process",
".",
"Memory",
"and",
"other",
"resources",
"are",
"available",
"(",
"e",
".",
"g",
".",
"TCP",
"connections",
"etc",
".",
")",
"args",
"and",
"kwargs",
"are",
"passed... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/executor.py#L10-L20 |
Locu/chronology | kronos/kronos/core/executor.py | execute_process_async | def execute_process_async(func, *args, **kwargs):
"""
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
"""
global _GIPC_EXECUTOR
if _GIPC_EXECUTOR is None:
_GIPC_EXECUTOR = GIPCExecutor(
num_procs=settings.node.gipc_pool_size,
num_greenlets=settings.node.greenlet_pool_size)
return _GIPC_EXECUTOR.submit(func, *args, **kwargs) | python | def execute_process_async(func, *args, **kwargs):
"""
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
"""
global _GIPC_EXECUTOR
if _GIPC_EXECUTOR is None:
_GIPC_EXECUTOR = GIPCExecutor(
num_procs=settings.node.gipc_pool_size,
num_greenlets=settings.node.greenlet_pool_size)
return _GIPC_EXECUTOR.submit(func, *args, **kwargs) | [
"def",
"execute_process_async",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_GIPC_EXECUTOR",
"if",
"_GIPC_EXECUTOR",
"is",
"None",
":",
"_GIPC_EXECUTOR",
"=",
"GIPCExecutor",
"(",
"num_procs",
"=",
"settings",
".",
"node",
".... | Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are | [
"Executes",
"func",
"in",
"a",
"separate",
"process",
".",
"Memory",
"and",
"other",
"resources",
"are",
"not",
"available",
".",
"This",
"gives",
"true",
"concurrency",
"at",
"the",
"cost",
"of",
"losing",
"access",
"to",
"these",
"resources",
".",
"args",
... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/executor.py#L23-L34 |
Locu/chronology | kronos/kronos/core/executor.py | wait | def wait(results, num=None, timeout=None):
"""
Wait for results of async executions to become available/ready.
`results`: List of AsyncResult instances returned by one of
`execute_greenlet_async` or `execute_process_async`.
`num`: Number of results to wait for. None implies wait for all results.
`timeout`: Number of seconds to wait for `num` of the `results` to become
ready.
"""
return AbstractExecutor.wait(results, num=num, timeout=timeout) | python | def wait(results, num=None, timeout=None):
"""
Wait for results of async executions to become available/ready.
`results`: List of AsyncResult instances returned by one of
`execute_greenlet_async` or `execute_process_async`.
`num`: Number of results to wait for. None implies wait for all results.
`timeout`: Number of seconds to wait for `num` of the `results` to become
ready.
"""
return AbstractExecutor.wait(results, num=num, timeout=timeout) | [
"def",
"wait",
"(",
"results",
",",
"num",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"AbstractExecutor",
".",
"wait",
"(",
"results",
",",
"num",
"=",
"num",
",",
"timeout",
"=",
"timeout",
")"
] | Wait for results of async executions to become available/ready.
`results`: List of AsyncResult instances returned by one of
`execute_greenlet_async` or `execute_process_async`.
`num`: Number of results to wait for. None implies wait for all results.
`timeout`: Number of seconds to wait for `num` of the `results` to become
ready. | [
"Wait",
"for",
"results",
"of",
"async",
"executions",
"to",
"become",
"available",
"/",
"ready",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/executor.py#L37-L47 |
jessamynsmith/twitterbot | twitter_bot/messages/markov_chain.py | MarkovChainMessageProvider.create | def create(self, mention, max_message_length):
"""
Create a message
:param mention: JSON object containing mention details from Twitter (or an empty dict {})
:param max_message_length: Maximum allowable length for created message
:return: A random message created using a Markov chain generator
"""
message = []
def message_len():
return sum([len(w) + 1 for w in message])
while message_len() < max_message_length:
message.append(self.a_random_word(message[-1] if message else None))
return ' '.join(message[:-1]) | python | def create(self, mention, max_message_length):
"""
Create a message
:param mention: JSON object containing mention details from Twitter (or an empty dict {})
:param max_message_length: Maximum allowable length for created message
:return: A random message created using a Markov chain generator
"""
message = []
def message_len():
return sum([len(w) + 1 for w in message])
while message_len() < max_message_length:
message.append(self.a_random_word(message[-1] if message else None))
return ' '.join(message[:-1]) | [
"def",
"create",
"(",
"self",
",",
"mention",
",",
"max_message_length",
")",
":",
"message",
"=",
"[",
"]",
"def",
"message_len",
"(",
")",
":",
"return",
"sum",
"(",
"[",
"len",
"(",
"w",
")",
"+",
"1",
"for",
"w",
"in",
"message",
"]",
")",
"w... | Create a message
:param mention: JSON object containing mention details from Twitter (or an empty dict {})
:param max_message_length: Maximum allowable length for created message
:return: A random message created using a Markov chain generator | [
"Create",
"a",
"message",
":",
"param",
"mention",
":",
"JSON",
"object",
"containing",
"mention",
"details",
"from",
"Twitter",
"(",
"or",
"an",
"empty",
"dict",
"{}",
")",
":",
"param",
"max_message_length",
":",
"Maximum",
"allowable",
"length",
"for",
"c... | train | https://github.com/jessamynsmith/twitterbot/blob/10a5d07b9eda659057ef86241823b0672f0f219f/twitter_bot/messages/markov_chain.py#L40-L55 |
LasLabs/python-helpscout | helpscout/web_hook/__init__.py | HelpScoutWebHook.receive | def receive(self, event_type, signature, data_str):
"""Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, which serves as
authentication (from the request ``X-HelpScout-Signature``
header).
data_str (str): The raw data that was posted by HelpScout
to the web hook. This must be the raw string, because if it
is parsed with JSON it will lose its ordering and not pass
signature validation.
Raises:
helpscout.exceptions.HelpScoutSecurityException: If an invalid
signature is provided, and ``raise_if_invalid`` is ``True``.
Returns:
helpscout.web_hook.WebHookEvent: The authenticated web hook
request.
"""
if not self.validate_signature(signature, data_str):
raise HelpScoutSecurityException(
'The signature provided by this request was invalid.',
)
return HelpScoutWebHookEvent(
event_type=event_type,
record=json.loads(data_str),
) | python | def receive(self, event_type, signature, data_str):
"""Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, which serves as
authentication (from the request ``X-HelpScout-Signature``
header).
data_str (str): The raw data that was posted by HelpScout
to the web hook. This must be the raw string, because if it
is parsed with JSON it will lose its ordering and not pass
signature validation.
Raises:
helpscout.exceptions.HelpScoutSecurityException: If an invalid
signature is provided, and ``raise_if_invalid`` is ``True``.
Returns:
helpscout.web_hook.WebHookEvent: The authenticated web hook
request.
"""
if not self.validate_signature(signature, data_str):
raise HelpScoutSecurityException(
'The signature provided by this request was invalid.',
)
return HelpScoutWebHookEvent(
event_type=event_type,
record=json.loads(data_str),
) | [
"def",
"receive",
"(",
"self",
",",
"event_type",
",",
"signature",
",",
"data_str",
")",
":",
"if",
"not",
"self",
".",
"validate_signature",
"(",
"signature",
",",
"data_str",
")",
":",
"raise",
"HelpScoutSecurityException",
"(",
"'The signature provided by this... | Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, which serves as
authentication (from the request ``X-HelpScout-Signature``
header).
data_str (str): The raw data that was posted by HelpScout
to the web hook. This must be the raw string, because if it
is parsed with JSON it will lose its ordering and not pass
signature validation.
Raises:
helpscout.exceptions.HelpScoutSecurityException: If an invalid
signature is provided, and ``raise_if_invalid`` is ``True``.
Returns:
helpscout.web_hook.WebHookEvent: The authenticated web hook
request. | [
"Receive",
"a",
"web",
"hook",
"for",
"the",
"event",
"and",
"signature",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/web_hook/__init__.py#L39-L70 |
LasLabs/python-helpscout | helpscout/web_hook/__init__.py | HelpScoutWebHook.validate_signature | def validate_signature(self, signature, data, encoding='utf8'):
"""Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate against
the signature.
encoding (str, optional): If a string was provided for ``data`` or
``signature``, this is the character encoding.
Returns:
bool: Whether the signature is valid for the provided data.
"""
if isinstance(data, string_types):
data = bytearray(data, encoding)
if isinstance(signature, string_types):
signature = bytearray(signature, encoding)
secret_key = bytearray(self.secret_key, 'utf8')
hashed = hmac.new(secret_key, data, sha1)
encoded = b64encode(hashed.digest())
return encoded.strip() == signature.strip() | python | def validate_signature(self, signature, data, encoding='utf8'):
"""Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate against
the signature.
encoding (str, optional): If a string was provided for ``data`` or
``signature``, this is the character encoding.
Returns:
bool: Whether the signature is valid for the provided data.
"""
if isinstance(data, string_types):
data = bytearray(data, encoding)
if isinstance(signature, string_types):
signature = bytearray(signature, encoding)
secret_key = bytearray(self.secret_key, 'utf8')
hashed = hmac.new(secret_key, data, sha1)
encoded = b64encode(hashed.digest())
return encoded.strip() == signature.strip() | [
"def",
"validate_signature",
"(",
"self",
",",
"signature",
",",
"data",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"data",
"=",
"bytearray",
"(",
"data",
",",
"encoding",
")",
"if",
"isinsta... | Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate against
the signature.
encoding (str, optional): If a string was provided for ``data`` or
``signature``, this is the character encoding.
Returns:
bool: Whether the signature is valid for the provided data. | [
"Validate",
"the",
"signature",
"for",
"the",
"provided",
"data",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/web_hook/__init__.py#L72-L96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.