repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mezz64/pyHik
|
pyhik/hikvision.py
|
HikCamera.publish_changes
|
def publish_changes(self, etype, echid):
"""Post updates for specified event type."""
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signal=signal, sender=sender)
self._do_update_callback('{}.{}.{}'.format(self.cam_id, etype, echid))
|
python
|
def publish_changes(self, etype, echid):
"""Post updates for specified event type."""
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signal=signal, sender=sender)
self._do_update_callback('{}.{}.{}'.format(self.cam_id, etype, echid))
|
[
"def",
"publish_changes",
"(",
"self",
",",
"etype",
",",
"echid",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'%s Update: %s, %s'",
",",
"self",
".",
"name",
",",
"etype",
",",
"self",
".",
"fetch_attributes",
"(",
"etype",
",",
"echid",
")",
")",
"signal",
"=",
"'ValueChanged.{}'",
".",
"format",
"(",
"self",
".",
"cam_id",
")",
"sender",
"=",
"'{}.{}'",
".",
"format",
"(",
"etype",
",",
"echid",
")",
"if",
"dispatcher",
":",
"dispatcher",
".",
"send",
"(",
"signal",
"=",
"signal",
",",
"sender",
"=",
"sender",
")",
"self",
".",
"_do_update_callback",
"(",
"'{}.{}.{}'",
".",
"format",
"(",
"self",
".",
"cam_id",
",",
"etype",
",",
"echid",
")",
")"
] |
Post updates for specified event type.
|
[
"Post",
"updates",
"for",
"specified",
"event",
"type",
"."
] |
1e7afca926e2b045257a43cbf8b1236a435493c2
|
https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L592-L601
|
train
|
mezz64/pyHik
|
pyhik/watchdog.py
|
Watchdog.start
|
def start(self):
""" Starts the watchdog timer. """
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return
|
python
|
def start(self):
""" Starts the watchdog timer. """
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return
|
[
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_timer",
"=",
"Timer",
"(",
"self",
".",
"time",
",",
"self",
".",
"handler",
")",
"self",
".",
"_timer",
".",
"daemon",
"=",
"True",
"self",
".",
"_timer",
".",
"start",
"(",
")",
"return"
] |
Starts the watchdog timer.
|
[
"Starts",
"the",
"watchdog",
"timer",
"."
] |
1e7afca926e2b045257a43cbf8b1236a435493c2
|
https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/watchdog.py#L21-L26
|
train
|
mezz64/pyHik
|
examples/basic_usage.py
|
HikCamObject.flip_motion
|
def flip_motion(self, value):
"""Toggle motion detection"""
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection()
|
python
|
def flip_motion(self, value):
"""Toggle motion detection"""
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection()
|
[
"def",
"flip_motion",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"self",
".",
"cam",
".",
"enable_motion_detection",
"(",
")",
"else",
":",
"self",
".",
"cam",
".",
"disable_motion_detection",
"(",
")"
] |
Toggle motion detection
|
[
"Toggle",
"motion",
"detection"
] |
1e7afca926e2b045257a43cbf8b1236a435493c2
|
https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L47-L52
|
train
|
mezz64/pyHik
|
examples/basic_usage.py
|
HikSensor.update_callback
|
def update_callback(self, msg):
""" get updates. """
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update()))
|
python
|
def update_callback(self, msg):
""" get updates. """
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update()))
|
[
"def",
"update_callback",
"(",
"self",
",",
"msg",
")",
":",
"print",
"(",
"'Callback: {}'",
".",
"format",
"(",
"msg",
")",
")",
"print",
"(",
"'{}:{} @ {}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"_sensor_state",
"(",
")",
",",
"self",
".",
"_sensor_last_update",
"(",
")",
")",
")"
] |
get updates.
|
[
"get",
"updates",
"."
] |
1e7afca926e2b045257a43cbf8b1236a435493c2
|
https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L91-L94
|
train
|
mbr/flask-nav
|
flask_nav/elements.py
|
NavigationItem.render
|
def render(self, renderer=None, **kwargs):
"""Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
"""
return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
self))
|
python
|
def render(self, renderer=None, **kwargs):
"""Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
"""
return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
self))
|
[
"def",
"render",
"(",
"self",
",",
"renderer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Markup",
"(",
"get_renderer",
"(",
"current_app",
",",
"renderer",
")",
"(",
"*",
"*",
"kwargs",
")",
".",
"visit",
"(",
"self",
")",
")"
] |
Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
|
[
"Render",
"the",
"navigational",
"item",
"using",
"a",
"renderer",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/elements.py#L16-L24
|
train
|
mbr/flask-nav
|
flask_nav/renderers.py
|
Renderer.visit_object
|
def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
"""
if current_app.debug:
return tags.comment('no implementation in {} to render {}'.format(
self.__class__.__name__,
node.__class__.__name__, ))
return ''
|
python
|
def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
"""
if current_app.debug:
return tags.comment('no implementation in {} to render {}'.format(
self.__class__.__name__,
node.__class__.__name__, ))
return ''
|
[
"def",
"visit_object",
"(",
"self",
",",
"node",
")",
":",
"if",
"current_app",
".",
"debug",
":",
"return",
"tags",
".",
"comment",
"(",
"'no implementation in {} to render {}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"node",
".",
"__class__",
".",
"__name__",
",",
")",
")",
"return",
"''"
] |
Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
|
[
"Fallback",
"rendering",
"for",
"objects",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/renderers.py#L13-L27
|
train
|
mbr/flask-nav
|
flask_nav/__init__.py
|
register_renderer
|
def register_renderer(app, id, renderer, force=True):
"""Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether or not to overwrite the renderer if a different one
is already registered for ``id``
"""
renderers = app.extensions.setdefault('nav_renderers', {})
if force:
renderers[id] = renderer
else:
renderers.setdefault(id, renderer)
|
python
|
def register_renderer(app, id, renderer, force=True):
"""Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether or not to overwrite the renderer if a different one
is already registered for ``id``
"""
renderers = app.extensions.setdefault('nav_renderers', {})
if force:
renderers[id] = renderer
else:
renderers.setdefault(id, renderer)
|
[
"def",
"register_renderer",
"(",
"app",
",",
"id",
",",
"renderer",
",",
"force",
"=",
"True",
")",
":",
"renderers",
"=",
"app",
".",
"extensions",
".",
"setdefault",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"if",
"force",
":",
"renderers",
"[",
"id",
"]",
"=",
"renderer",
"else",
":",
"renderers",
".",
"setdefault",
"(",
"id",
",",
"renderer",
")"
] |
Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether or not to overwrite the renderer if a different one
is already registered for ``id``
|
[
"Registers",
"a",
"renderer",
"on",
"the",
"application",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L6-L21
|
train
|
mbr/flask-nav
|
flask_nav/__init__.py
|
get_renderer
|
def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
"""
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = renderer
mod = import_module(mod_name)
cls = mod
for name in cls_name.split('.'):
cls = getattr(cls, name)
return cls
return renderer
|
python
|
def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
"""
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = renderer
mod = import_module(mod_name)
cls = mod
for name in cls_name.split('.'):
cls = getattr(cls, name)
return cls
return renderer
|
[
"def",
"get_renderer",
"(",
"app",
",",
"id",
")",
":",
"renderer",
"=",
"app",
".",
"extensions",
".",
"get",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"[",
"id",
"]",
"if",
"isinstance",
"(",
"renderer",
",",
"tuple",
")",
":",
"mod_name",
",",
"cls_name",
"=",
"renderer",
"mod",
"=",
"import_module",
"(",
"mod_name",
")",
"cls",
"=",
"mod",
"for",
"name",
"in",
"cls_name",
".",
"split",
"(",
"'.'",
")",
":",
"cls",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"return",
"cls",
"return",
"renderer"
] |
Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
|
[
"Retrieve",
"a",
"renderer",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L24-L42
|
train
|
mbr/flask-nav
|
flask_nav/__init__.py
|
Nav.init_app
|
def init_app(self, app):
"""Initialize an application.
:param app: A :class:`~flask.Flask` app.
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some renderers
for args in self._renderers:
register_renderer(app, *args)
|
python
|
def init_app(self, app):
"""Initialize an application.
:param app: A :class:`~flask.Flask` app.
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some renderers
for args in self._renderers:
register_renderer(app, *args)
|
[
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'nav'",
"]",
"=",
"self",
"app",
".",
"add_template_global",
"(",
"self",
".",
"elems",
",",
"'nav'",
")",
"# register some renderers",
"for",
"args",
"in",
"self",
".",
"_renderers",
":",
"register_renderer",
"(",
"app",
",",
"*",
"args",
")"
] |
Initialize an application.
:param app: A :class:`~flask.Flask` app.
|
[
"Initialize",
"an",
"application",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L99-L112
|
train
|
mbr/flask-nav
|
flask_nav/__init__.py
|
Nav.navigation
|
def navigation(self, id=None):
"""Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name.
"""
def wrapper(f):
self.register_element(id or f.__name__, f)
return f
return wrapper
|
python
|
def navigation(self, id=None):
"""Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name.
"""
def wrapper(f):
self.register_element(id or f.__name__, f)
return f
return wrapper
|
[
"def",
"navigation",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"self",
".",
"register_element",
"(",
"id",
"or",
"f",
".",
"__name__",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] |
Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name.
|
[
"Function",
"decorator",
"for",
"navbar",
"registration",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L114-L128
|
train
|
mbr/flask-nav
|
flask_nav/__init__.py
|
Nav.renderer
|
def renderer(self, id=None, force=True):
"""Class decorator for Renderers.
The decorated class will be added to the list of renderers kept by this
instance that will be registered on the app upon app initialization.
:param id: Id for the renderer, defaults to the class name in snake
case.
:param force: Whether or not to overwrite existing renderers.
"""
def _(cls):
name = cls.__name__
sn = name[0] + re.sub(r'([A-Z])', r'_\1', name[1:])
self._renderers.append((id or sn.lower(), cls, force))
return cls
return _
|
python
|
def renderer(self, id=None, force=True):
"""Class decorator for Renderers.
The decorated class will be added to the list of renderers kept by this
instance that will be registered on the app upon app initialization.
:param id: Id for the renderer, defaults to the class name in snake
case.
:param force: Whether or not to overwrite existing renderers.
"""
def _(cls):
name = cls.__name__
sn = name[0] + re.sub(r'([A-Z])', r'_\1', name[1:])
self._renderers.append((id or sn.lower(), cls, force))
return cls
return _
|
[
"def",
"renderer",
"(",
"self",
",",
"id",
"=",
"None",
",",
"force",
"=",
"True",
")",
":",
"def",
"_",
"(",
"cls",
")",
":",
"name",
"=",
"cls",
".",
"__name__",
"sn",
"=",
"name",
"[",
"0",
"]",
"+",
"re",
".",
"sub",
"(",
"r'([A-Z])'",
",",
"r'_\\1'",
",",
"name",
"[",
"1",
":",
"]",
")",
"self",
".",
"_renderers",
".",
"append",
"(",
"(",
"id",
"or",
"sn",
".",
"lower",
"(",
")",
",",
"cls",
",",
"force",
")",
")",
"return",
"cls",
"return",
"_"
] |
Class decorator for Renderers.
The decorated class will be added to the list of renderers kept by this
instance that will be registered on the app upon app initialization.
:param id: Id for the renderer, defaults to the class name in snake
case.
:param force: Whether or not to overwrite existing renderers.
|
[
"Class",
"decorator",
"for",
"Renderers",
"."
] |
06f3b5b2addad29c2fc531a7e8e74958e9e4b793
|
https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L148-L166
|
train
|
tonyseek/openvpn-status
|
openvpn_status/utils.py
|
parse_time
|
def parse_time(time):
"""Parses date and time from input string in OpenVPN logging format."""
if isinstance(time, datetime.datetime):
return time
return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN)
|
python
|
def parse_time(time):
"""Parses date and time from input string in OpenVPN logging format."""
if isinstance(time, datetime.datetime):
return time
return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN)
|
[
"def",
"parse_time",
"(",
"time",
")",
":",
"if",
"isinstance",
"(",
"time",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"time",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"time",
",",
"DATETIME_FORMAT_OPENVPN",
")"
] |
Parses date and time from input string in OpenVPN logging format.
|
[
"Parses",
"date",
"and",
"time",
"from",
"input",
"string",
"in",
"OpenVPN",
"logging",
"format",
"."
] |
b8f5ec5f79933605af2301c42e4e7ec230334237
|
https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/utils.py#L19-L23
|
train
|
jieter/python-lora
|
lora/payload.py
|
LoRaPayload.decrypt
|
def decrypt(self, key, dev_addr):
"""
Decrypt the actual payload in this LoraPayload.
key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)
dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)
"""
sequence_counter = int(self.FCntUp)
return loramac_decrypt(self.payload_hex, sequence_counter, key, dev_addr)
|
python
|
def decrypt(self, key, dev_addr):
"""
Decrypt the actual payload in this LoraPayload.
key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)
dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)
"""
sequence_counter = int(self.FCntUp)
return loramac_decrypt(self.payload_hex, sequence_counter, key, dev_addr)
|
[
"def",
"decrypt",
"(",
"self",
",",
"key",
",",
"dev_addr",
")",
":",
"sequence_counter",
"=",
"int",
"(",
"self",
".",
"FCntUp",
")",
"return",
"loramac_decrypt",
"(",
"self",
".",
"payload_hex",
",",
"sequence_counter",
",",
"key",
",",
"dev_addr",
")"
] |
Decrypt the actual payload in this LoraPayload.
key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)
dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)
|
[
"Decrypt",
"the",
"actual",
"payload",
"in",
"this",
"LoraPayload",
"."
] |
0edb8dbad771da1e2b455571c7a9b064ba67fbcd
|
https://github.com/jieter/python-lora/blob/0edb8dbad771da1e2b455571c7a9b064ba67fbcd/lora/payload.py#L38-L47
|
train
|
tonyseek/openvpn-status
|
openvpn_status/parser.py
|
LogParser.parse
|
def parse(self):
"""Parses the status log.
:raises ParsingError: if syntax error found in the log.
:return: The :class:`.models.Status` with filled data.
"""
status = Status()
self.expect_line(Status.client_list.label)
status.updated_at = self.expect_tuple(Status.updated_at.label)
status.client_list.update({
text_type(c.real_address): c
for c in self._parse_fields(Client, Status.routing_table.label)})
status.routing_table.update({
text_type(r.virtual_address): r
for r in self._parse_fields(Routing, Status.global_stats.label)})
status.global_stats = GlobalStats()
status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
GlobalStats.max_bcast_mcast_queue_len.label)
self.expect_line(self.terminator)
return status
|
python
|
def parse(self):
"""Parses the status log.
:raises ParsingError: if syntax error found in the log.
:return: The :class:`.models.Status` with filled data.
"""
status = Status()
self.expect_line(Status.client_list.label)
status.updated_at = self.expect_tuple(Status.updated_at.label)
status.client_list.update({
text_type(c.real_address): c
for c in self._parse_fields(Client, Status.routing_table.label)})
status.routing_table.update({
text_type(r.virtual_address): r
for r in self._parse_fields(Routing, Status.global_stats.label)})
status.global_stats = GlobalStats()
status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
GlobalStats.max_bcast_mcast_queue_len.label)
self.expect_line(self.terminator)
return status
|
[
"def",
"parse",
"(",
"self",
")",
":",
"status",
"=",
"Status",
"(",
")",
"self",
".",
"expect_line",
"(",
"Status",
".",
"client_list",
".",
"label",
")",
"status",
".",
"updated_at",
"=",
"self",
".",
"expect_tuple",
"(",
"Status",
".",
"updated_at",
".",
"label",
")",
"status",
".",
"client_list",
".",
"update",
"(",
"{",
"text_type",
"(",
"c",
".",
"real_address",
")",
":",
"c",
"for",
"c",
"in",
"self",
".",
"_parse_fields",
"(",
"Client",
",",
"Status",
".",
"routing_table",
".",
"label",
")",
"}",
")",
"status",
".",
"routing_table",
".",
"update",
"(",
"{",
"text_type",
"(",
"r",
".",
"virtual_address",
")",
":",
"r",
"for",
"r",
"in",
"self",
".",
"_parse_fields",
"(",
"Routing",
",",
"Status",
".",
"global_stats",
".",
"label",
")",
"}",
")",
"status",
".",
"global_stats",
"=",
"GlobalStats",
"(",
")",
"status",
".",
"global_stats",
".",
"max_bcast_mcast_queue_len",
"=",
"self",
".",
"expect_tuple",
"(",
"GlobalStats",
".",
"max_bcast_mcast_queue_len",
".",
"label",
")",
"self",
".",
"expect_line",
"(",
"self",
".",
"terminator",
")",
"return",
"status"
] |
Parses the status log.
:raises ParsingError: if syntax error found in the log.
:return: The :class:`.models.Status` with filled data.
|
[
"Parses",
"the",
"status",
"log",
"."
] |
b8f5ec5f79933605af2301c42e4e7ec230334237
|
https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/parser.py#L77-L98
|
train
|
tonyseek/openvpn-status
|
openvpn_status/shortcuts.py
|
parse_status
|
def parse_status(status_log, encoding='utf-8'):
"""Parses the status log of OpenVPN.
:param status_log: The content of status log.
:type status_log: :class:`str`
:param encoding: Optional. The encoding of status log.
:type encoding: :class:`str`
:return: The instance of :class:`.models.Status`
"""
if isinstance(status_log, bytes):
status_log = status_log.decode(encoding)
parser = LogParser.fromstring(status_log)
return parser.parse()
|
python
|
def parse_status(status_log, encoding='utf-8'):
"""Parses the status log of OpenVPN.
:param status_log: The content of status log.
:type status_log: :class:`str`
:param encoding: Optional. The encoding of status log.
:type encoding: :class:`str`
:return: The instance of :class:`.models.Status`
"""
if isinstance(status_log, bytes):
status_log = status_log.decode(encoding)
parser = LogParser.fromstring(status_log)
return parser.parse()
|
[
"def",
"parse_status",
"(",
"status_log",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"status_log",
",",
"bytes",
")",
":",
"status_log",
"=",
"status_log",
".",
"decode",
"(",
"encoding",
")",
"parser",
"=",
"LogParser",
".",
"fromstring",
"(",
"status_log",
")",
"return",
"parser",
".",
"parse",
"(",
")"
] |
Parses the status log of OpenVPN.
:param status_log: The content of status log.
:type status_log: :class:`str`
:param encoding: Optional. The encoding of status log.
:type encoding: :class:`str`
:return: The instance of :class:`.models.Status`
|
[
"Parses",
"the",
"status",
"log",
"of",
"OpenVPN",
"."
] |
b8f5ec5f79933605af2301c42e4e7ec230334237
|
https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/shortcuts.py#L6-L18
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.version
|
def version(self):
"""Return version of the TR DWE."""
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]])
|
python
|
def version(self):
"""Return version of the TR DWE."""
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]])
|
[
"def",
"version",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Version",
"(",
")",
"return",
"'.'",
".",
"join",
"(",
"[",
"ustr",
"(",
"x",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"]",
"]",
")"
] |
Return version of the TR DWE.
|
[
"Return",
"version",
"of",
"the",
"TR",
"DWE",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L119-L122
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.system_info
|
def system_info(self):
"""Return system information."""
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
res['Version'] = to_str(res['Version'])
res['Name'] = ustr(res['Name'])
res['Server'] = ustr(res['Server'])
res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
res['UserHostAddress'] = ustr(res['UserHostAddress'])
return res
|
python
|
def system_info(self):
"""Return system information."""
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
res['Version'] = to_str(res['Version'])
res['Name'] = ustr(res['Name'])
res['Server'] = ustr(res['Server'])
res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
res['UserHostAddress'] = ustr(res['UserHostAddress'])
return res
|
[
"def",
"system_info",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"SystemInfo",
"(",
")",
"res",
"=",
"{",
"ustr",
"(",
"x",
"[",
"0",
"]",
")",
":",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"res",
"[",
"0",
"]",
"}",
"to_str",
"=",
"lambda",
"arr",
":",
"'.'",
".",
"join",
"(",
"[",
"ustr",
"(",
"x",
")",
"for",
"x",
"in",
"arr",
"[",
"0",
"]",
"]",
")",
"res",
"[",
"'OSVersion'",
"]",
"=",
"to_str",
"(",
"res",
"[",
"'OSVersion'",
"]",
")",
"res",
"[",
"'RuntimeVersion'",
"]",
"=",
"to_str",
"(",
"res",
"[",
"'RuntimeVersion'",
"]",
")",
"res",
"[",
"'Version'",
"]",
"=",
"to_str",
"(",
"res",
"[",
"'Version'",
"]",
")",
"res",
"[",
"'Name'",
"]",
"=",
"ustr",
"(",
"res",
"[",
"'Name'",
"]",
")",
"res",
"[",
"'Server'",
"]",
"=",
"ustr",
"(",
"res",
"[",
"'Server'",
"]",
")",
"res",
"[",
"'LocalNameCheck'",
"]",
"=",
"ustr",
"(",
"res",
"[",
"'LocalNameCheck'",
"]",
")",
"res",
"[",
"'UserHostAddress'",
"]",
"=",
"ustr",
"(",
"res",
"[",
"'UserHostAddress'",
"]",
")",
"return",
"res"
] |
Return system information.
|
[
"Return",
"system",
"information",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L124-L139
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.sources
|
def sources(self):
"""Return available sources of data."""
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]]
|
python
|
def sources(self):
"""Return available sources of data."""
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]]
|
[
"def",
"sources",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Sources",
"(",
"self",
".",
"userdata",
",",
"0",
")",
"return",
"[",
"ustr",
"(",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"]",
"]"
] |
Return available sources of data.
|
[
"Return",
"available",
"sources",
"of",
"data",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L141-L144
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.status
|
def status(self, record=None):
"""Extract status from the retrieved data and save it as a property of an object.
If record with data is not specified then the status of previous operation is
returned.
status - dictionary with data source, string with request and status type,
code and message.
status['StatusType']: 'Connected' - the data is fine
'Stale' - the source is unavailable. It may be
worthwhile to try again later
'Failure' - data could not be obtained (e.g. the
instrument is incorrect)
'Pending' - for internal use only
status['StatusCode']: 0 - 'No Error'
1 - 'Disconnected'
2 - 'Source Fault'
3 - 'Network Fault'
4 - 'Access Denied' (user does not have permissions)
5 - 'No Such Item' (no instrument with given name)
11 - 'Blocking Timeout'
12 - 'Internal'
"""
if record is not None:
self.last_status = {'Source': ustr(record['Source']),
'StatusType': ustr(record['StatusType']),
'StatusCode': record['StatusCode'],
'StatusMessage': ustr(record['StatusMessage']),
'Request': ustr(record['Instrument'])}
return self.last_status
|
python
|
def status(self, record=None):
"""Extract status from the retrieved data and save it as a property of an object.
If record with data is not specified then the status of previous operation is
returned.
status - dictionary with data source, string with request and status type,
code and message.
status['StatusType']: 'Connected' - the data is fine
'Stale' - the source is unavailable. It may be
worthwhile to try again later
'Failure' - data could not be obtained (e.g. the
instrument is incorrect)
'Pending' - for internal use only
status['StatusCode']: 0 - 'No Error'
1 - 'Disconnected'
2 - 'Source Fault'
3 - 'Network Fault'
4 - 'Access Denied' (user does not have permissions)
5 - 'No Such Item' (no instrument with given name)
11 - 'Blocking Timeout'
12 - 'Internal'
"""
if record is not None:
self.last_status = {'Source': ustr(record['Source']),
'StatusType': ustr(record['StatusType']),
'StatusCode': record['StatusCode'],
'StatusMessage': ustr(record['StatusMessage']),
'Request': ustr(record['Instrument'])}
return self.last_status
|
[
"def",
"status",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"if",
"record",
"is",
"not",
"None",
":",
"self",
".",
"last_status",
"=",
"{",
"'Source'",
":",
"ustr",
"(",
"record",
"[",
"'Source'",
"]",
")",
",",
"'StatusType'",
":",
"ustr",
"(",
"record",
"[",
"'StatusType'",
"]",
")",
",",
"'StatusCode'",
":",
"record",
"[",
"'StatusCode'",
"]",
",",
"'StatusMessage'",
":",
"ustr",
"(",
"record",
"[",
"'StatusMessage'",
"]",
")",
",",
"'Request'",
":",
"ustr",
"(",
"record",
"[",
"'Instrument'",
"]",
")",
"}",
"return",
"self",
".",
"last_status"
] |
Extract status from the retrieved data and save it as a property of an object.
If record with data is not specified then the status of previous operation is
returned.
status - dictionary with data source, string with request and status type,
code and message.
status['StatusType']: 'Connected' - the data is fine
'Stale' - the source is unavailable. It may be
worthwhile to try again later
'Failure' - data could not be obtained (e.g. the
instrument is incorrect)
'Pending' - for internal use only
status['StatusCode']: 0 - 'No Error'
1 - 'Disconnected'
2 - 'Source Fault'
3 - 'Network Fault'
4 - 'Access Denied' (user does not have permissions)
5 - 'No Such Item' (no instrument with given name)
11 - 'Blocking Timeout'
12 - 'Internal'
|
[
"Extract",
"status",
"from",
"the",
"retrieved",
"data",
"and",
"save",
"it",
"as",
"a",
"property",
"of",
"an",
"object",
".",
"If",
"record",
"with",
"data",
"is",
"not",
"specified",
"then",
"the",
"status",
"of",
"previous",
"operation",
"is",
"returned",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L230-L259
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.construct_request
|
def construct_request(ticker, fields=None, date=None,
date_from=None, date_to=None, freq=None):
"""Construct a request string for querying TR DWE.
tickers - ticker or symbol
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
Use here 'REP' for static requests
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if isinstance(ticker, basestring):
request = ticker
elif hasattr(ticker, '__len__'):
request = ','.join(ticker)
else:
raise ValueError('ticker should be either string or list/array of strings')
if fields is not None:
if isinstance(fields, basestring):
request += '~=' + fields
elif isinstance(fields, list) and len(fields) > 0:
request += '~=' + ','.join(fields)
if date is not None:
request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d')
else:
if date_from is not None:
request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d')
if date_to is not None:
request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d')
if freq is not None:
request += '~' + freq
return request
|
python
|
def construct_request(ticker, fields=None, date=None,
date_from=None, date_to=None, freq=None):
"""Construct a request string for querying TR DWE.
tickers - ticker or symbol
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
Use here 'REP' for static requests
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if isinstance(ticker, basestring):
request = ticker
elif hasattr(ticker, '__len__'):
request = ','.join(ticker)
else:
raise ValueError('ticker should be either string or list/array of strings')
if fields is not None:
if isinstance(fields, basestring):
request += '~=' + fields
elif isinstance(fields, list) and len(fields) > 0:
request += '~=' + ','.join(fields)
if date is not None:
request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d')
else:
if date_from is not None:
request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d')
if date_to is not None:
request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d')
if freq is not None:
request += '~' + freq
return request
|
[
"def",
"construct_request",
"(",
"ticker",
",",
"fields",
"=",
"None",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
",",
"freq",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ticker",
",",
"basestring",
")",
":",
"request",
"=",
"ticker",
"elif",
"hasattr",
"(",
"ticker",
",",
"'__len__'",
")",
":",
"request",
"=",
"','",
".",
"join",
"(",
"ticker",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'ticker should be either string or list/array of strings'",
")",
"if",
"fields",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"fields",
",",
"basestring",
")",
":",
"request",
"+=",
"'~='",
"+",
"fields",
"elif",
"isinstance",
"(",
"fields",
",",
"list",
")",
"and",
"len",
"(",
"fields",
")",
">",
"0",
":",
"request",
"+=",
"'~='",
"+",
"','",
".",
"join",
"(",
"fields",
")",
"if",
"date",
"is",
"not",
"None",
":",
"request",
"+=",
"'~@'",
"+",
"pd",
".",
"to_datetime",
"(",
"date",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"else",
":",
"if",
"date_from",
"is",
"not",
"None",
":",
"request",
"+=",
"'~'",
"+",
"pd",
".",
"to_datetime",
"(",
"date_from",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"if",
"date_to",
"is",
"not",
"None",
":",
"request",
"+=",
"'~:'",
"+",
"pd",
".",
"to_datetime",
"(",
"date_to",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"if",
"freq",
"is",
"not",
"None",
":",
"request",
"+=",
"'~'",
"+",
"freq",
"return",
"request"
] |
Construct a request string for querying TR DWE.
tickers - ticker or symbol
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
Use here 'REP' for static requests
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
|
[
"Construct",
"a",
"request",
"string",
"for",
"querying",
"TR",
"DWE",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L413-L462
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.fetch
|
def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None,
freq='D', only_data=True, static=False):
"""Fetch data from TR DWE.
tickers - ticker or list of tickers
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
only_data - if True then metadata will not be returned
static - if True "static" request is created (i.e. not a series).
In this case 'date_from', 'date_to' and 'freq' are ignored
In case list of tickers is requested, a MultiIndex-dataframe is returned.
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if static:
query = self.construct_request(tickers, fields, date, freq='REP')
else:
query = self.construct_request(tickers, fields, date, date_from, date_to, freq)
raw = self.request(query)
if static:
data, metadata = self.parse_record_static(raw)
elif isinstance(tickers, basestring) or len(tickers) == 1:
data, metadata = self.parse_record(raw)
elif hasattr(tickers, '__len__'):
metadata = pd.DataFrame()
data = {}
for indx in range(len(tickers)):
dat, meta = self.parse_record(raw, indx)
data[tickers[indx]] = dat
metadata = metadata.append(meta, ignore_index=False)
data = pd.concat(data)
else:
raise DatastreamException(('First argument should be either ticker or '
'list of tickers'))
if only_data:
return data
else:
return data, metadata
|
python
|
def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None,
freq='D', only_data=True, static=False):
"""Fetch data from TR DWE.
tickers - ticker or list of tickers
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
only_data - if True then metadata will not be returned
static - if True "static" request is created (i.e. not a series).
In this case 'date_from', 'date_to' and 'freq' are ignored
In case list of tickers is requested, a MultiIndex-dataframe is returned.
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if static:
query = self.construct_request(tickers, fields, date, freq='REP')
else:
query = self.construct_request(tickers, fields, date, date_from, date_to, freq)
raw = self.request(query)
if static:
data, metadata = self.parse_record_static(raw)
elif isinstance(tickers, basestring) or len(tickers) == 1:
data, metadata = self.parse_record(raw)
elif hasattr(tickers, '__len__'):
metadata = pd.DataFrame()
data = {}
for indx in range(len(tickers)):
dat, meta = self.parse_record(raw, indx)
data[tickers[indx]] = dat
metadata = metadata.append(meta, ignore_index=False)
data = pd.concat(data)
else:
raise DatastreamException(('First argument should be either ticker or '
'list of tickers'))
if only_data:
return data
else:
return data, metadata
|
[
"def",
"fetch",
"(",
"self",
",",
"tickers",
",",
"fields",
"=",
"None",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
",",
"freq",
"=",
"'D'",
",",
"only_data",
"=",
"True",
",",
"static",
"=",
"False",
")",
":",
"if",
"static",
":",
"query",
"=",
"self",
".",
"construct_request",
"(",
"tickers",
",",
"fields",
",",
"date",
",",
"freq",
"=",
"'REP'",
")",
"else",
":",
"query",
"=",
"self",
".",
"construct_request",
"(",
"tickers",
",",
"fields",
",",
"date",
",",
"date_from",
",",
"date_to",
",",
"freq",
")",
"raw",
"=",
"self",
".",
"request",
"(",
"query",
")",
"if",
"static",
":",
"data",
",",
"metadata",
"=",
"self",
".",
"parse_record_static",
"(",
"raw",
")",
"elif",
"isinstance",
"(",
"tickers",
",",
"basestring",
")",
"or",
"len",
"(",
"tickers",
")",
"==",
"1",
":",
"data",
",",
"metadata",
"=",
"self",
".",
"parse_record",
"(",
"raw",
")",
"elif",
"hasattr",
"(",
"tickers",
",",
"'__len__'",
")",
":",
"metadata",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"data",
"=",
"{",
"}",
"for",
"indx",
"in",
"range",
"(",
"len",
"(",
"tickers",
")",
")",
":",
"dat",
",",
"meta",
"=",
"self",
".",
"parse_record",
"(",
"raw",
",",
"indx",
")",
"data",
"[",
"tickers",
"[",
"indx",
"]",
"]",
"=",
"dat",
"metadata",
"=",
"metadata",
".",
"append",
"(",
"meta",
",",
"ignore_index",
"=",
"False",
")",
"data",
"=",
"pd",
".",
"concat",
"(",
"data",
")",
"else",
":",
"raise",
"DatastreamException",
"(",
"(",
"'First argument should be either ticker or '",
"'list of tickers'",
")",
")",
"if",
"only_data",
":",
"return",
"data",
"else",
":",
"return",
"data",
",",
"metadata"
] |
Fetch data from TR DWE.
tickers - ticker or list of tickers
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
only_data - if True then metadata will not be returned
static - if True "static" request is created (i.e. not a series).
In this case 'date_from', 'date_to' and 'freq' are ignored
In case list of tickers is requested, a MultiIndex-dataframe is returned.
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
|
[
"Fetch",
"data",
"from",
"TR",
"DWE",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L465-L525
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.get_OHLCV
|
def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
"""Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is printed as
a warning.
"""
data, meta = self.fetch(ticker + "~OHLCV", None, date,
date_from, date_to, 'D', only_data=False)
return data
|
python
|
def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
"""Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is printed as
a warning.
"""
data, meta = self.fetch(ticker + "~OHLCV", None, date,
date_from, date_to, 'D', only_data=False)
return data
|
[
"def",
"get_OHLCV",
"(",
"self",
",",
"ticker",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
")",
":",
"data",
",",
"meta",
"=",
"self",
".",
"fetch",
"(",
"ticker",
"+",
"\"~OHLCV\"",
",",
"None",
",",
"date",
",",
"date_from",
",",
"date_to",
",",
"'D'",
",",
"only_data",
"=",
"False",
")",
"return",
"data"
] |
Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is printed as
a warning.
|
[
"Get",
"Open",
"High",
"Low",
"Close",
"prices",
"and",
"daily",
"Volume",
"for",
"a",
"given",
"ticker",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L528-L540
|
train
|
vfilimonov/pydatastream
|
pydatastream/pydatastream.py
|
Datastream.get_constituents
|
def get_constituents(self, index_ticker, date=None, only_list=False):
""" Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
for large indices like Russel-3000. If only_list=True,
then only the list of symbols and names are retrieved.
"""
if date is not None:
str_date = pd.to_datetime(date).strftime('%m%y')
else:
str_date = ''
# Note: ~XREF is equal to the following large request
# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,
# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE
fields = '~REP~=NAME' if only_list else '~XREF'
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
res, metadata = self.parse_record_static(raw)
return res
|
python
|
def get_constituents(self, index_ticker, date=None, only_list=False):
""" Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
for large indices like Russel-3000. If only_list=True,
then only the list of symbols and names are retrieved.
"""
if date is not None:
str_date = pd.to_datetime(date).strftime('%m%y')
else:
str_date = ''
# Note: ~XREF is equal to the following large request
# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,
# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE
fields = '~REP~=NAME' if only_list else '~XREF'
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
res, metadata = self.parse_record_static(raw)
return res
|
[
"def",
"get_constituents",
"(",
"self",
",",
"index_ticker",
",",
"date",
"=",
"None",
",",
"only_list",
"=",
"False",
")",
":",
"if",
"date",
"is",
"not",
"None",
":",
"str_date",
"=",
"pd",
".",
"to_datetime",
"(",
"date",
")",
".",
"strftime",
"(",
"'%m%y'",
")",
"else",
":",
"str_date",
"=",
"''",
"# Note: ~XREF is equal to the following large request",
"# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,",
"# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE",
"fields",
"=",
"'~REP~=NAME'",
"if",
"only_list",
"else",
"'~XREF'",
"query",
"=",
"'L'",
"+",
"index_ticker",
"+",
"str_date",
"+",
"fields",
"raw",
"=",
"self",
".",
"request",
"(",
"query",
")",
"res",
",",
"metadata",
"=",
"self",
".",
"parse_record_static",
"(",
"raw",
")",
"return",
"res"
] |
Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
for large indices like Russel-3000. If only_list=True,
then only the list of symbols and names are retrieved.
|
[
"Get",
"a",
"list",
"of",
"all",
"constituents",
"of",
"a",
"given",
"index",
"."
] |
15d2adac1c83501715db1542373fa8428542816e
|
https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L571-L595
|
train
|
crs4/hl7apy
|
hl7apy/__init__.py
|
check_encoding_chars
|
def check_encoding_chars(encoding_chars):
"""
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
"""
if not isinstance(encoding_chars, collections.MutableMapping):
raise InvalidEncodingChars
required = {'FIELD', 'COMPONENT', 'SUBCOMPONENT', 'REPETITION', 'ESCAPE'}
missing = required - set(encoding_chars.keys())
if missing:
raise InvalidEncodingChars('Missing required encoding chars')
values = [v for k, v in encoding_chars.items() if k in required]
if len(values) > len(set(values)):
raise InvalidEncodingChars('Found duplicate encoding chars')
|
python
|
def check_encoding_chars(encoding_chars):
"""
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
"""
if not isinstance(encoding_chars, collections.MutableMapping):
raise InvalidEncodingChars
required = {'FIELD', 'COMPONENT', 'SUBCOMPONENT', 'REPETITION', 'ESCAPE'}
missing = required - set(encoding_chars.keys())
if missing:
raise InvalidEncodingChars('Missing required encoding chars')
values = [v for k, v in encoding_chars.items() if k in required]
if len(values) > len(set(values)):
raise InvalidEncodingChars('Found duplicate encoding chars')
|
[
"def",
"check_encoding_chars",
"(",
"encoding_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"encoding_chars",
",",
"collections",
".",
"MutableMapping",
")",
":",
"raise",
"InvalidEncodingChars",
"required",
"=",
"{",
"'FIELD'",
",",
"'COMPONENT'",
",",
"'SUBCOMPONENT'",
",",
"'REPETITION'",
",",
"'ESCAPE'",
"}",
"missing",
"=",
"required",
"-",
"set",
"(",
"encoding_chars",
".",
"keys",
"(",
")",
")",
"if",
"missing",
":",
"raise",
"InvalidEncodingChars",
"(",
"'Missing required encoding chars'",
")",
"values",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"encoding_chars",
".",
"items",
"(",
")",
"if",
"k",
"in",
"required",
"]",
"if",
"len",
"(",
"values",
")",
">",
"len",
"(",
"set",
"(",
"values",
")",
")",
":",
"raise",
"InvalidEncodingChars",
"(",
"'Found duplicate encoding chars'",
")"
] |
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
|
[
"Validate",
"the",
"given",
"encoding",
"chars"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L46-L63
|
train
|
crs4/hl7apy
|
hl7apy/__init__.py
|
check_validation_level
|
def check_validation_level(validation_level):
"""
Validate the given validation level
:type validation_level: ``int``
:param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)
:raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported
"""
if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):
raise UnknownValidationLevel
|
python
|
def check_validation_level(validation_level):
"""
Validate the given validation level
:type validation_level: ``int``
:param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)
:raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported
"""
if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):
raise UnknownValidationLevel
|
[
"def",
"check_validation_level",
"(",
"validation_level",
")",
":",
"if",
"validation_level",
"not",
"in",
"(",
"VALIDATION_LEVEL",
".",
"QUIET",
",",
"VALIDATION_LEVEL",
".",
"STRICT",
",",
"VALIDATION_LEVEL",
".",
"TOLERANT",
")",
":",
"raise",
"UnknownValidationLevel"
] |
Validate the given validation level
:type validation_level: ``int``
:param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)
:raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported
|
[
"Validate",
"the",
"given",
"validation",
"level"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L66-L75
|
train
|
crs4/hl7apy
|
hl7apy/__init__.py
|
load_library
|
def load_library(version):
"""
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
"""
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib
|
python
|
def load_library(version):
"""
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
"""
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib
|
[
"def",
"load_library",
"(",
"version",
")",
":",
"check_version",
"(",
"version",
")",
"module_name",
"=",
"SUPPORTED_LIBRARIES",
"[",
"version",
"]",
"lib",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"module_name",
")",
"if",
"lib",
"is",
"None",
":",
"lib",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"return",
"lib"
] |
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
|
[
"Load",
"the",
"correct",
"module",
"according",
"to",
"the",
"version"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L223-L236
|
train
|
crs4/hl7apy
|
hl7apy/__init__.py
|
load_reference
|
def load_reference(name, element_type, version):
"""
Look for an element of the given type, name and version and return its reference structure
:type element_type: ``str``
:param element_type: the element type to look for (e.g. 'Segment')
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: ``KeyError`` if the element has not been found
The returned dictionary will contain the following keys:
+--------------+--------------------------------------------+
|Key |Value |
+==============+============================================+
|cls |an :class:`hl7apy.core.Element` subclass |
+--------------+--------------------------------------------+
|name |the Element name (e.g. PID) |
+--------------+--------------------------------------------+
|ref |a tuple of one of the following format: |
| | |
| |('leaf', <datatype>, <longName>, <table>) |
| |('sequence', (<child>, (<min>, <max>), ...))|
+--------------+--------------------------------------------+
>>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> r = load_reference('ADT_A01', 'Message', '2.5')
>>> print(r[0])
sequence
>>> r = load_reference('MSH_3', 'Field', '2.5')
>>> print(r[0])
sequence
"""
lib = load_library(version)
ref = lib.get(name, element_type)
return ref
|
python
|
def load_reference(name, element_type, version):
"""
Look for an element of the given type, name and version and return its reference structure
:type element_type: ``str``
:param element_type: the element type to look for (e.g. 'Segment')
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: ``KeyError`` if the element has not been found
The returned dictionary will contain the following keys:
+--------------+--------------------------------------------+
|Key |Value |
+==============+============================================+
|cls |an :class:`hl7apy.core.Element` subclass |
+--------------+--------------------------------------------+
|name |the Element name (e.g. PID) |
+--------------+--------------------------------------------+
|ref |a tuple of one of the following format: |
| | |
| |('leaf', <datatype>, <longName>, <table>) |
| |('sequence', (<child>, (<min>, <max>), ...))|
+--------------+--------------------------------------------+
>>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> r = load_reference('ADT_A01', 'Message', '2.5')
>>> print(r[0])
sequence
>>> r = load_reference('MSH_3', 'Field', '2.5')
>>> print(r[0])
sequence
"""
lib = load_library(version)
ref = lib.get(name, element_type)
return ref
|
[
"def",
"load_reference",
"(",
"name",
",",
"element_type",
",",
"version",
")",
":",
"lib",
"=",
"load_library",
"(",
"version",
")",
"ref",
"=",
"lib",
".",
"get",
"(",
"name",
",",
"element_type",
")",
"return",
"ref"
] |
Look for an element of the given type, name and version and return its reference structure
:type element_type: ``str``
:param element_type: the element type to look for (e.g. 'Segment')
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: ``KeyError`` if the element has not been found
The returned dictionary will contain the following keys:
+--------------+--------------------------------------------+
|Key |Value |
+==============+============================================+
|cls |an :class:`hl7apy.core.Element` subclass |
+--------------+--------------------------------------------+
|name |the Element name (e.g. PID) |
+--------------+--------------------------------------------+
|ref |a tuple of one of the following format: |
| | |
| |('leaf', <datatype>, <longName>, <table>) |
| |('sequence', (<child>, (<min>, <max>), ...))|
+--------------+--------------------------------------------+
>>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> r = load_reference('ADT_A01', 'Message', '2.5')
>>> print(r[0])
sequence
>>> r = load_reference('MSH_3', 'Field', '2.5')
>>> print(r[0])
sequence
|
[
"Look",
"for",
"an",
"element",
"of",
"the",
"given",
"type",
"name",
"and",
"version",
"and",
"return",
"its",
"reference",
"structure"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L239-L281
|
train
|
crs4/hl7apy
|
hl7apy/__init__.py
|
find_reference
|
def find_reference(name, element_types, version):
"""
Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found
>>> from hl7apy.core import Message, Segment
>>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named ADT_A01
>>> r = find_reference('ADT_A01', (Message,), '2.5')
>>> print('%s %s' % (r['name'], r['cls']))
ADT_A01 <class 'hl7apy.core.Message'>
"""
lib = load_library(version)
ref = lib.find(name, element_types)
return ref
|
python
|
def find_reference(name, element_types, version):
"""
Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found
>>> from hl7apy.core import Message, Segment
>>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named ADT_A01
>>> r = find_reference('ADT_A01', (Message,), '2.5')
>>> print('%s %s' % (r['name'], r['cls']))
ADT_A01 <class 'hl7apy.core.Message'>
"""
lib = load_library(version)
ref = lib.find(name, element_types)
return ref
|
[
"def",
"find_reference",
"(",
"name",
",",
"element_types",
",",
"version",
")",
":",
"lib",
"=",
"load_library",
"(",
"version",
")",
"ref",
"=",
"lib",
".",
"find",
"(",
"name",
",",
"element_types",
")",
"return",
"ref"
] |
Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found
>>> from hl7apy.core import Message, Segment
>>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named ADT_A01
>>> r = find_reference('ADT_A01', (Message,), '2.5')
>>> print('%s %s' % (r['name'], r['cls']))
ADT_A01 <class 'hl7apy.core.Message'>
|
[
"Look",
"for",
"an",
"element",
"of",
"the",
"given",
"name",
"and",
"version",
"into",
"the",
"given",
"types",
"and",
"return",
"its",
"reference",
"structure"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L284-L313
|
train
|
crs4/hl7apy
|
hl7apy/utils.py
|
get_date_info
|
def get_date_info(value):
"""
Returns the datetime object and the format of the date in input
:type value: `str`
"""
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt
|
python
|
def get_date_info(value):
"""
Returns the datetime object and the format of the date in input
:type value: `str`
"""
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt
|
[
"def",
"get_date_info",
"(",
"value",
")",
":",
"fmt",
"=",
"_get_date_format",
"(",
"value",
")",
"dt_value",
"=",
"_datetime_obj_factory",
"(",
"value",
",",
"fmt",
")",
"return",
"dt_value",
",",
"fmt"
] |
Returns the datetime object and the format of the date in input
:type value: `str`
|
[
"Returns",
"the",
"datetime",
"object",
"and",
"the",
"format",
"of",
"the",
"date",
"in",
"input"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L70-L78
|
train
|
crs4/hl7apy
|
hl7apy/utils.py
|
get_timestamp_info
|
def get_timestamp_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the timestamp in input
:type value: `str`
"""
value, offset = _split_offset(value)
fmt, microsec = _get_timestamp_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt, offset, microsec
|
python
|
def get_timestamp_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the timestamp in input
:type value: `str`
"""
value, offset = _split_offset(value)
fmt, microsec = _get_timestamp_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt, offset, microsec
|
[
"def",
"get_timestamp_info",
"(",
"value",
")",
":",
"value",
",",
"offset",
"=",
"_split_offset",
"(",
"value",
")",
"fmt",
",",
"microsec",
"=",
"_get_timestamp_format",
"(",
"value",
")",
"dt_value",
"=",
"_datetime_obj_factory",
"(",
"value",
",",
"fmt",
")",
"return",
"dt_value",
",",
"fmt",
",",
"offset",
",",
"microsec"
] |
Returns the datetime object, the format, the offset and the microsecond of the timestamp in input
:type value: `str`
|
[
"Returns",
"the",
"datetime",
"object",
"the",
"format",
"the",
"offset",
"and",
"the",
"microsecond",
"of",
"the",
"timestamp",
"in",
"input"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L81-L90
|
train
|
crs4/hl7apy
|
hl7apy/utils.py
|
get_datetime_info
|
def get_datetime_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the datetime in input
:type value: `str`
"""
date_value, offset = _split_offset(value)
date_format = _get_date_format(date_value[:8])
try:
timestamp_form, microsec = _get_timestamp_format(date_value[8:])
except ValueError:
if not date_value[8:]: # if it's empty
timestamp_form, microsec = '', 4
else:
raise ValueError('{0} is not an HL7 valid date value'.format(value))
fmt = '{0}{1}'.format(date_format, timestamp_form)
dt_value = _datetime_obj_factory(date_value, fmt)
return dt_value, fmt, offset, microsec
|
python
|
def get_datetime_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the datetime in input
:type value: `str`
"""
date_value, offset = _split_offset(value)
date_format = _get_date_format(date_value[:8])
try:
timestamp_form, microsec = _get_timestamp_format(date_value[8:])
except ValueError:
if not date_value[8:]: # if it's empty
timestamp_form, microsec = '', 4
else:
raise ValueError('{0} is not an HL7 valid date value'.format(value))
fmt = '{0}{1}'.format(date_format, timestamp_form)
dt_value = _datetime_obj_factory(date_value, fmt)
return dt_value, fmt, offset, microsec
|
[
"def",
"get_datetime_info",
"(",
"value",
")",
":",
"date_value",
",",
"offset",
"=",
"_split_offset",
"(",
"value",
")",
"date_format",
"=",
"_get_date_format",
"(",
"date_value",
"[",
":",
"8",
"]",
")",
"try",
":",
"timestamp_form",
",",
"microsec",
"=",
"_get_timestamp_format",
"(",
"date_value",
"[",
"8",
":",
"]",
")",
"except",
"ValueError",
":",
"if",
"not",
"date_value",
"[",
"8",
":",
"]",
":",
"# if it's empty",
"timestamp_form",
",",
"microsec",
"=",
"''",
",",
"4",
"else",
":",
"raise",
"ValueError",
"(",
"'{0} is not an HL7 valid date value'",
".",
"format",
"(",
"value",
")",
")",
"fmt",
"=",
"'{0}{1}'",
".",
"format",
"(",
"date_format",
",",
"timestamp_form",
")",
"dt_value",
"=",
"_datetime_obj_factory",
"(",
"date_value",
",",
"fmt",
")",
"return",
"dt_value",
",",
"fmt",
",",
"offset",
",",
"microsec"
] |
Returns the datetime object, the format, the offset and the microsecond of the datetime in input
:type value: `str`
|
[
"Returns",
"the",
"datetime",
"object",
"the",
"format",
"the",
"offset",
"and",
"the",
"microsecond",
"of",
"the",
"datetime",
"in",
"input"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L93-L112
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
is_base_datatype
|
def is_base_datatype(datatype, version=None):
"""
Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')
True
>>> is_base_datatype('CE')
False
"""
if version is None:
version = get_default_version()
lib = load_library(version)
return lib.is_base_datatype(datatype)
|
python
|
def is_base_datatype(datatype, version=None):
"""
Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')
True
>>> is_base_datatype('CE')
False
"""
if version is None:
version = get_default_version()
lib = load_library(version)
return lib.is_base_datatype(datatype)
|
[
"def",
"is_base_datatype",
"(",
"datatype",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"get_default_version",
"(",
")",
"lib",
"=",
"load_library",
"(",
"version",
")",
"return",
"lib",
".",
"is_base_datatype",
"(",
"datatype",
")"
] |
Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')
True
>>> is_base_datatype('CE')
False
|
[
"Check",
"if",
"the",
"given",
"datatype",
"is",
"a",
"base",
"datatype",
"of",
"the",
"specified",
"version"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L59-L79
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.get_ordered_children
|
def get_ordered_children(self):
"""
Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>`
"""
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children
|
python
|
def get_ordered_children(self):
"""
Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>`
"""
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children
|
[
"def",
"get_ordered_children",
"(",
"self",
")",
":",
"ordered_keys",
"=",
"self",
".",
"element",
".",
"ordered_children",
"if",
"self",
".",
"element",
".",
"ordered_children",
"is",
"not",
"None",
"else",
"[",
"]",
"children",
"=",
"[",
"self",
".",
"indexes",
".",
"get",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"ordered_keys",
"]",
"return",
"children"
] |
Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>`
|
[
"Return",
"the",
"list",
"of",
"children",
"ordered",
"according",
"to",
"the",
"element",
"structure"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L210-L218
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.insert
|
def insert(self, index, child, by_name_index=-1):
"""
Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
try:
if by_name_index == -1:
self.indexes[child.name].append(child)
else:
self.indexes[child.name].insert(by_name_index, child)
except KeyError:
self.indexes[child.name] = [child]
self.list.insert(index, child)
|
python
|
def insert(self, index, child, by_name_index=-1):
"""
Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
try:
if by_name_index == -1:
self.indexes[child.name].append(child)
else:
self.indexes[child.name].insert(by_name_index, child)
except KeyError:
self.indexes[child.name] = [child]
self.list.insert(index, child)
|
[
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"by_name_index",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"try",
":",
"if",
"by_name_index",
"==",
"-",
"1",
":",
"self",
".",
"indexes",
"[",
"child",
".",
"name",
"]",
".",
"append",
"(",
"child",
")",
"else",
":",
"self",
".",
"indexes",
"[",
"child",
".",
"name",
"]",
".",
"insert",
"(",
"by_name_index",
",",
"child",
")",
"except",
"KeyError",
":",
"self",
".",
"indexes",
"[",
"child",
".",
"name",
"]",
"=",
"[",
"child",
"]",
"self",
".",
"list",
".",
"insert",
"(",
"index",
",",
"child",
")"
] |
Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
|
[
"Add",
"the",
"child",
"at",
"the",
"given",
"index"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L228-L246
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.append
|
def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_traversal_index(child)
self.list.append(child)
try:
self.indexes[child.name].append(child)
except KeyError:
self.indexes[child.name] = [child]
elif self.element == child.traversal_parent:
try:
self.traversal_indexes[child.name].append(child)
except KeyError:
self.traversal_indexes[child.name] = [child]
|
python
|
def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_traversal_index(child)
self.list.append(child)
try:
self.indexes[child.name].append(child)
except KeyError:
self.indexes[child.name] = [child]
elif self.element == child.traversal_parent:
try:
self.traversal_indexes[child.name].append(child)
except KeyError:
self.traversal_indexes[child.name] = [child]
|
[
"def",
"append",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"if",
"self",
".",
"element",
"==",
"child",
".",
"parent",
":",
"self",
".",
"_remove_from_traversal_index",
"(",
"child",
")",
"self",
".",
"list",
".",
"append",
"(",
"child",
")",
"try",
":",
"self",
".",
"indexes",
"[",
"child",
".",
"name",
"]",
".",
"append",
"(",
"child",
")",
"except",
"KeyError",
":",
"self",
".",
"indexes",
"[",
"child",
".",
"name",
"]",
"=",
"[",
"child",
"]",
"elif",
"self",
".",
"element",
"==",
"child",
".",
"traversal_parent",
":",
"try",
":",
"self",
".",
"traversal_indexes",
"[",
"child",
".",
"name",
"]",
".",
"append",
"(",
"child",
")",
"except",
"KeyError",
":",
"self",
".",
"traversal_indexes",
"[",
"child",
".",
"name",
"]",
"=",
"[",
"child",
"]"
] |
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
|
[
"Append",
"the",
"given",
"child"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L248-L267
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.set
|
def set(self, name, value, index=-1):
"""
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementProxy>`
:param value: the child value
:type index: ``int``
:param index: the child position (e.g. 1)
"""
# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)
if isinstance(value, ElementProxy):
value = value[0].to_er7()
name = name.upper()
reference = None if name is None else self.element.find_child_reference(name)
child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name'])
if isinstance(value, basestring): # if the value is a basestring, parse it
child = self.element.parse_child(value, child_name=child_name, reference=child_ref)
elif isinstance(value, Element): # it is already an instance of Element
child = value
elif isinstance(value, BaseDataType):
child = self.create_element(name, False, reference)
child.value = value
else:
raise ChildNotValid(value, child_name)
if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden
raise ChildNotValid(value, child_name)
child_to_remove = self.child_at_index(child_name, index)
if child_to_remove is None:
self.append(child)
else:
self.replace_child(child_to_remove, child)
# a set has been called, change the temporary parent to be the actual one
self.element.set_parent_to_traversal()
|
python
|
def set(self, name, value, index=-1):
"""
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementProxy>`
:param value: the child value
:type index: ``int``
:param index: the child position (e.g. 1)
"""
# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)
if isinstance(value, ElementProxy):
value = value[0].to_er7()
name = name.upper()
reference = None if name is None else self.element.find_child_reference(name)
child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name'])
if isinstance(value, basestring): # if the value is a basestring, parse it
child = self.element.parse_child(value, child_name=child_name, reference=child_ref)
elif isinstance(value, Element): # it is already an instance of Element
child = value
elif isinstance(value, BaseDataType):
child = self.create_element(name, False, reference)
child.value = value
else:
raise ChildNotValid(value, child_name)
if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden
raise ChildNotValid(value, child_name)
child_to_remove = self.child_at_index(child_name, index)
if child_to_remove is None:
self.append(child)
else:
self.replace_child(child_to_remove, child)
# a set has been called, change the temporary parent to be the actual one
self.element.set_parent_to_traversal()
|
[
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"index",
"=",
"-",
"1",
")",
":",
"# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)",
"if",
"isinstance",
"(",
"value",
",",
"ElementProxy",
")",
":",
"value",
"=",
"value",
"[",
"0",
"]",
".",
"to_er7",
"(",
")",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"reference",
"=",
"None",
"if",
"name",
"is",
"None",
"else",
"self",
".",
"element",
".",
"find_child_reference",
"(",
"name",
")",
"child_ref",
",",
"child_name",
"=",
"(",
"None",
",",
"None",
")",
"if",
"reference",
"is",
"None",
"else",
"(",
"reference",
"[",
"'ref'",
"]",
",",
"reference",
"[",
"'name'",
"]",
")",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"# if the value is a basestring, parse it",
"child",
"=",
"self",
".",
"element",
".",
"parse_child",
"(",
"value",
",",
"child_name",
"=",
"child_name",
",",
"reference",
"=",
"child_ref",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Element",
")",
":",
"# it is already an instance of Element",
"child",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"BaseDataType",
")",
":",
"child",
"=",
"self",
".",
"create_element",
"(",
"name",
",",
"False",
",",
"reference",
")",
"child",
".",
"value",
"=",
"value",
"else",
":",
"raise",
"ChildNotValid",
"(",
"value",
",",
"child_name",
")",
"if",
"child",
".",
"name",
"!=",
"child_name",
":",
"# e.g. message.pid = Segment('SPM') is forbidden",
"raise",
"ChildNotValid",
"(",
"value",
",",
"child_name",
")",
"child_to_remove",
"=",
"self",
".",
"child_at_index",
"(",
"child_name",
",",
"index",
")",
"if",
"child_to_remove",
"is",
"None",
":",
"self",
".",
"append",
"(",
"child",
")",
"else",
":",
"self",
".",
"replace_child",
"(",
"child_to_remove",
",",
"child",
")",
"# a set has been called, change the temporary parent to be the actual one",
"self",
".",
"element",
".",
"set_parent_to_traversal",
"(",
")"
] |
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementProxy>`
:param value: the child value
:type index: ``int``
:param index: the child position (e.g. 1)
|
[
"Assign",
"the",
"value",
"to",
"the",
"child",
"having",
"the",
"given",
"name",
"at",
"the",
"index",
"position"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L285-L329
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.remove
|
def remove(self, child):
"""
Remove the given child from both child list and child indexes
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
try:
if self.element == child.traversal_parent:
self._remove_from_traversal_index(child)
else:
self._remove_from_index(child)
self.list.remove(child)
except:
raise
|
python
|
def remove(self, child):
"""
Remove the given child from both child list and child indexes
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
try:
if self.element == child.traversal_parent:
self._remove_from_traversal_index(child)
else:
self._remove_from_index(child)
self.list.remove(child)
except:
raise
|
[
"def",
"remove",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"if",
"self",
".",
"element",
"==",
"child",
".",
"traversal_parent",
":",
"self",
".",
"_remove_from_traversal_index",
"(",
"child",
")",
"else",
":",
"self",
".",
"_remove_from_index",
"(",
"child",
")",
"self",
".",
"list",
".",
"remove",
"(",
"child",
")",
"except",
":",
"raise"
] |
Remove the given child from both child list and child indexes
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of :class:`Element <hl7apy.core.Element>` subclass
|
[
"Remove",
"the",
"given",
"child",
"from",
"both",
"child",
"list",
"and",
"child",
"indexes"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L331-L345
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.remove_by_name
|
def remove_by_name(self, name, index=0):
"""
Remove the child having the given name at the given position
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
child = self.child_at_index(name, index)
self.remove(child)
return child
|
python
|
def remove_by_name(self, name, index=0):
"""
Remove the child having the given name at the given position
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
child = self.child_at_index(name, index)
self.remove(child)
return child
|
[
"def",
"remove_by_name",
"(",
"self",
",",
"name",
",",
"index",
"=",
"0",
")",
":",
"child",
"=",
"self",
".",
"child_at_index",
"(",
"name",
",",
"index",
")",
"self",
".",
"remove",
"(",
"child",
")",
"return",
"child"
] |
Remove the child having the given name at the given position
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
|
[
"Remove",
"the",
"child",
"having",
"the",
"given",
"name",
"at",
"the",
"given",
"position"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L347-L361
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.child_at_index
|
def child_at_index(self, name, index):
"""
Return the child named `name` at the given index
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
def _finder(n, i):
try:
return self.indexes[n][i]
except (KeyError, IndexError):
try:
return self.traversal_indexes[n][i]
except (KeyError, IndexError):
return None
child = _finder(name, index)
child_name = None if name is None else self._find_name(name)
if child_name != name:
child = _finder(child_name, index)
return child
|
python
|
def child_at_index(self, name, index):
"""
Return the child named `name` at the given index
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
def _finder(n, i):
try:
return self.indexes[n][i]
except (KeyError, IndexError):
try:
return self.traversal_indexes[n][i]
except (KeyError, IndexError):
return None
child = _finder(name, index)
child_name = None if name is None else self._find_name(name)
if child_name != name:
child = _finder(child_name, index)
return child
|
[
"def",
"child_at_index",
"(",
"self",
",",
"name",
",",
"index",
")",
":",
"def",
"_finder",
"(",
"n",
",",
"i",
")",
":",
"try",
":",
"return",
"self",
".",
"indexes",
"[",
"n",
"]",
"[",
"i",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"try",
":",
"return",
"self",
".",
"traversal_indexes",
"[",
"n",
"]",
"[",
"i",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
"None",
"child",
"=",
"_finder",
"(",
"name",
",",
"index",
")",
"child_name",
"=",
"None",
"if",
"name",
"is",
"None",
"else",
"self",
".",
"_find_name",
"(",
"name",
")",
"if",
"child_name",
"!=",
"name",
":",
"child",
"=",
"_finder",
"(",
"child_name",
",",
"index",
")",
"return",
"child"
] |
Return the child named `name` at the given index
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
|
[
"Return",
"the",
"child",
"named",
"name",
"at",
"the",
"given",
"index"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L363-L389
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList.create_element
|
def create_element(self, name, traversal_parent=False, reference=None):
"""
Create an element having the given name
:type name: ``str``
:param name: the name of the element to be created (e.g. PID)
:type traversal_parent: ``bool``
:param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes
:param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)
:return: an instance of an :class:`hl7apy.core.Element` subclass
:raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist
"""
if reference is None:
reference = self.element.find_child_reference(name)
if reference is not None:
cls = reference['cls']
element_name = reference['name']
kwargs = {'reference': reference['ref'],
'validation_level': self.element.validation_level,
'version': self.element.version}
if not traversal_parent:
kwargs['parent'] = self.element
else:
kwargs['traversal_parent'] = self.element
return cls(element_name, **kwargs)
else:
raise ChildNotFound(name)
|
python
|
def create_element(self, name, traversal_parent=False, reference=None):
"""
Create an element having the given name
:type name: ``str``
:param name: the name of the element to be created (e.g. PID)
:type traversal_parent: ``bool``
:param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes
:param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)
:return: an instance of an :class:`hl7apy.core.Element` subclass
:raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist
"""
if reference is None:
reference = self.element.find_child_reference(name)
if reference is not None:
cls = reference['cls']
element_name = reference['name']
kwargs = {'reference': reference['ref'],
'validation_level': self.element.validation_level,
'version': self.element.version}
if not traversal_parent:
kwargs['parent'] = self.element
else:
kwargs['traversal_parent'] = self.element
return cls(element_name, **kwargs)
else:
raise ChildNotFound(name)
|
[
"def",
"create_element",
"(",
"self",
",",
"name",
",",
"traversal_parent",
"=",
"False",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"reference",
"=",
"self",
".",
"element",
".",
"find_child_reference",
"(",
"name",
")",
"if",
"reference",
"is",
"not",
"None",
":",
"cls",
"=",
"reference",
"[",
"'cls'",
"]",
"element_name",
"=",
"reference",
"[",
"'name'",
"]",
"kwargs",
"=",
"{",
"'reference'",
":",
"reference",
"[",
"'ref'",
"]",
",",
"'validation_level'",
":",
"self",
".",
"element",
".",
"validation_level",
",",
"'version'",
":",
"self",
".",
"element",
".",
"version",
"}",
"if",
"not",
"traversal_parent",
":",
"kwargs",
"[",
"'parent'",
"]",
"=",
"self",
".",
"element",
"else",
":",
"kwargs",
"[",
"'traversal_parent'",
"]",
"=",
"self",
".",
"element",
"return",
"cls",
"(",
"element_name",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"ChildNotFound",
"(",
"name",
")"
] |
Create an element having the given name
:type name: ``str``
:param name: the name of the element to be created (e.g. PID)
:type traversal_parent: ``bool``
:param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes
:param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)
:return: an instance of an :class:`hl7apy.core.Element` subclass
:raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist
|
[
"Create",
"an",
"element",
"having",
"the",
"given",
"name"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L403-L433
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementList._find_name
|
def _find_name(self, name):
"""
Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been found
"""
name = name.upper()
element = self.element.find_child_reference(name)
return element['name'] if element is not None else None
|
python
|
def _find_name(self, name):
"""
Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been found
"""
name = name.upper()
element = self.element.find_child_reference(name)
return element['name'] if element is not None else None
|
[
"def",
"_find_name",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"element",
"=",
"self",
".",
"element",
".",
"find_child_reference",
"(",
"name",
")",
"return",
"element",
"[",
"'name'",
"]",
"if",
"element",
"is",
"not",
"None",
"else",
"None"
] |
Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been found
|
[
"Find",
"the",
"reference",
"of",
"a",
"child",
"having",
"the",
"given",
"name"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L435-L447
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementFinder.get_structure
|
def get_structure(element, reference=None):
"""
Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
if reference is None:
try:
reference = load_reference(element.name, element.classname, element.version)
except (ChildNotFound, KeyError):
raise InvalidName(element.classname, element.name)
if not isinstance(reference, collections.Sequence):
raise Exception
return ElementFinder._parse_structure(element, reference)
|
python
|
def get_structure(element, reference=None):
"""
Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
if reference is None:
try:
reference = load_reference(element.name, element.classname, element.version)
except (ChildNotFound, KeyError):
raise InvalidName(element.classname, element.name)
if not isinstance(reference, collections.Sequence):
raise Exception
return ElementFinder._parse_structure(element, reference)
|
[
"def",
"get_structure",
"(",
"element",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"try",
":",
"reference",
"=",
"load_reference",
"(",
"element",
".",
"name",
",",
"element",
".",
"classname",
",",
"element",
".",
"version",
")",
"except",
"(",
"ChildNotFound",
",",
"KeyError",
")",
":",
"raise",
"InvalidName",
"(",
"element",
".",
"classname",
",",
"element",
".",
"name",
")",
"if",
"not",
"isinstance",
"(",
"reference",
",",
"collections",
".",
"Sequence",
")",
":",
"raise",
"Exception",
"return",
"ElementFinder",
".",
"_parse_structure",
"(",
"element",
",",
"reference",
")"
] |
Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
|
[
"Get",
"the",
"element",
"structure"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L532-L551
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
ElementFinder._parse_structure
|
def _parse_structure(element, reference):
"""
Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
data = {
'reference': reference
}
content_type = reference[0] # content type can be sequence, choice or leaf
if content_type in ('sequence', 'choice'):
children = reference[1]
ordered_children = []
structure = {}
structure_by_longname = {}
repetitions = {}
counters = collections.defaultdict(int)
for c in children:
child_name, child_ref, cardinality, cls = c
k = child_name if child_name not in structure \
else '{0}_{1}'.format(child_name, counters[child_name])
structure[k] = {"ref": child_ref, "name": k, "cls": element.child_classes[cls]}
try:
structure_by_longname[child_ref[3]] = structure[k]
except IndexError:
pass
counters[child_name] += 1
repetitions[k] = cardinality
ordered_children.append(k)
data['repetitions'] = repetitions
data['ordered_children'] = ordered_children
data['structure_by_name'] = structure
data['structure_by_longname'] = structure_by_longname
if len(reference) > 5:
datatype, long_name, table, max_length = reference[2:]
data['datatype'] = datatype
data['table'] = table
data['long_name'] = long_name
return data
|
python
|
def _parse_structure(element, reference):
"""
Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
data = {
'reference': reference
}
content_type = reference[0] # content type can be sequence, choice or leaf
if content_type in ('sequence', 'choice'):
children = reference[1]
ordered_children = []
structure = {}
structure_by_longname = {}
repetitions = {}
counters = collections.defaultdict(int)
for c in children:
child_name, child_ref, cardinality, cls = c
k = child_name if child_name not in structure \
else '{0}_{1}'.format(child_name, counters[child_name])
structure[k] = {"ref": child_ref, "name": k, "cls": element.child_classes[cls]}
try:
structure_by_longname[child_ref[3]] = structure[k]
except IndexError:
pass
counters[child_name] += 1
repetitions[k] = cardinality
ordered_children.append(k)
data['repetitions'] = repetitions
data['ordered_children'] = ordered_children
data['structure_by_name'] = structure
data['structure_by_longname'] = structure_by_longname
if len(reference) > 5:
datatype, long_name, table, max_length = reference[2:]
data['datatype'] = datatype
data['table'] = table
data['long_name'] = long_name
return data
|
[
"def",
"_parse_structure",
"(",
"element",
",",
"reference",
")",
":",
"data",
"=",
"{",
"'reference'",
":",
"reference",
"}",
"content_type",
"=",
"reference",
"[",
"0",
"]",
"# content type can be sequence, choice or leaf",
"if",
"content_type",
"in",
"(",
"'sequence'",
",",
"'choice'",
")",
":",
"children",
"=",
"reference",
"[",
"1",
"]",
"ordered_children",
"=",
"[",
"]",
"structure",
"=",
"{",
"}",
"structure_by_longname",
"=",
"{",
"}",
"repetitions",
"=",
"{",
"}",
"counters",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"c",
"in",
"children",
":",
"child_name",
",",
"child_ref",
",",
"cardinality",
",",
"cls",
"=",
"c",
"k",
"=",
"child_name",
"if",
"child_name",
"not",
"in",
"structure",
"else",
"'{0}_{1}'",
".",
"format",
"(",
"child_name",
",",
"counters",
"[",
"child_name",
"]",
")",
"structure",
"[",
"k",
"]",
"=",
"{",
"\"ref\"",
":",
"child_ref",
",",
"\"name\"",
":",
"k",
",",
"\"cls\"",
":",
"element",
".",
"child_classes",
"[",
"cls",
"]",
"}",
"try",
":",
"structure_by_longname",
"[",
"child_ref",
"[",
"3",
"]",
"]",
"=",
"structure",
"[",
"k",
"]",
"except",
"IndexError",
":",
"pass",
"counters",
"[",
"child_name",
"]",
"+=",
"1",
"repetitions",
"[",
"k",
"]",
"=",
"cardinality",
"ordered_children",
".",
"append",
"(",
"k",
")",
"data",
"[",
"'repetitions'",
"]",
"=",
"repetitions",
"data",
"[",
"'ordered_children'",
"]",
"=",
"ordered_children",
"data",
"[",
"'structure_by_name'",
"]",
"=",
"structure",
"data",
"[",
"'structure_by_longname'",
"]",
"=",
"structure_by_longname",
"if",
"len",
"(",
"reference",
")",
">",
"5",
":",
"datatype",
",",
"long_name",
",",
"table",
",",
"max_length",
"=",
"reference",
"[",
"2",
":",
"]",
"data",
"[",
"'datatype'",
"]",
"=",
"datatype",
"data",
"[",
"'table'",
"]",
"=",
"table",
"data",
"[",
"'long_name'",
"]",
"=",
"long_name",
"return",
"data"
] |
Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
|
[
"Parse",
"the",
"given",
"reference"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L554-L600
|
train
|
crs4/hl7apy
|
hl7apy/core.py
|
Message.to_mllp
|
def to_mllp(self, encoding_chars=None, trailing_children=False):
"""
Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)
:type trailing_children: ``bool``
:param trailing_children: if ``True``, trailing children will be added even if their value is ``None``
:return: the ER7-encoded string wrapped with the mllp encoding characters
"""
if encoding_chars is None:
encoding_chars = self.encoding_chars
return "{0}{1}{2}{3}{2}".format(MLLP_ENCODING_CHARS.SB,
self.to_er7(encoding_chars, trailing_children),
MLLP_ENCODING_CHARS.CR,
MLLP_ENCODING_CHARS.EB)
|
python
|
def to_mllp(self, encoding_chars=None, trailing_children=False):
"""
Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)
:type trailing_children: ``bool``
:param trailing_children: if ``True``, trailing children will be added even if their value is ``None``
:return: the ER7-encoded string wrapped with the mllp encoding characters
"""
if encoding_chars is None:
encoding_chars = self.encoding_chars
return "{0}{1}{2}{3}{2}".format(MLLP_ENCODING_CHARS.SB,
self.to_er7(encoding_chars, trailing_children),
MLLP_ENCODING_CHARS.CR,
MLLP_ENCODING_CHARS.EB)
|
[
"def",
"to_mllp",
"(",
"self",
",",
"encoding_chars",
"=",
"None",
",",
"trailing_children",
"=",
"False",
")",
":",
"if",
"encoding_chars",
"is",
"None",
":",
"encoding_chars",
"=",
"self",
".",
"encoding_chars",
"return",
"\"{0}{1}{2}{3}{2}\"",
".",
"format",
"(",
"MLLP_ENCODING_CHARS",
".",
"SB",
",",
"self",
".",
"to_er7",
"(",
"encoding_chars",
",",
"trailing_children",
")",
",",
"MLLP_ENCODING_CHARS",
".",
"CR",
",",
"MLLP_ENCODING_CHARS",
".",
"EB",
")"
] |
Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)
:type trailing_children: ``bool``
:param trailing_children: if ``True``, trailing children will be added even if their value is ``None``
:return: the ER7-encoded string wrapped with the mllp encoding characters
|
[
"Returns",
"the",
"er7",
"representation",
"of",
"the",
"message",
"wrapped",
"with",
"mllp",
"encoding",
"characters"
] |
91be488e9274f6ec975519a1d9c17045bc91bf74
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L1969-L1988
|
train
|
playpauseandstop/Flask-And-Redis
|
flask_redis.py
|
Redis.get_app
|
def get_app(self):
"""Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin.
"""
# First see to connection stack
ctx = connection_stack.top
if ctx is not None:
return ctx.app
# Next return app from instance cache
if self.app is not None:
return self.app
# Something went wrong, in most cases app just not instantiated yet
# and we cannot locate it
raise RuntimeError(
'Flask application not registered on Redis instance '
'and no applcation bound to current context')
|
python
|
def get_app(self):
"""Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin.
"""
# First see to connection stack
ctx = connection_stack.top
if ctx is not None:
return ctx.app
# Next return app from instance cache
if self.app is not None:
return self.app
# Something went wrong, in most cases app just not instantiated yet
# and we cannot locate it
raise RuntimeError(
'Flask application not registered on Redis instance '
'and no applcation bound to current context')
|
[
"def",
"get_app",
"(",
"self",
")",
":",
"# First see to connection stack",
"ctx",
"=",
"connection_stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"return",
"ctx",
".",
"app",
"# Next return app from instance cache",
"if",
"self",
".",
"app",
"is",
"not",
"None",
":",
"return",
"self",
".",
"app",
"# Something went wrong, in most cases app just not instantiated yet",
"# and we cannot locate it",
"raise",
"RuntimeError",
"(",
"'Flask application not registered on Redis instance '",
"'and no applcation bound to current context'",
")"
] |
Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin.
|
[
"Get",
"current",
"app",
"from",
"Flast",
"stack",
"to",
"use",
"."
] |
878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5
|
https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L79-L98
|
train
|
playpauseandstop/Flask-And-Redis
|
flask_redis.py
|
Redis.init_app
|
def init_app(self, app, config_prefix=None):
"""
Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_prefix: Config prefix to use. By default: ``REDIS``
"""
# Put redis to application extensions
if 'redis' not in app.extensions:
app.extensions['redis'] = {}
# Which config prefix to use, custom or default one?
self.config_prefix = config_prefix = config_prefix or 'REDIS'
# No way to do registration two times
if config_prefix in app.extensions['redis']:
raise ValueError('Already registered config prefix {0!r}.'.
format(config_prefix))
# Start reading configuration, define converters to use and key func
# to prepend config prefix to key value
converters = {'port': int}
convert = lambda arg, value: (converters[arg](value)
if arg in converters
else value)
key = lambda param: '{0}_{1}'.format(config_prefix, param)
# Which redis connection class to use?
klass = app.config.get(key('CLASS'), RedisClass)
# Import connection class if it stil path notation
if isinstance(klass, string_types):
klass = import_string(klass)
# Should we use URL configuration
url = app.config.get(key('URL'))
# If should, parse URL and store values to application config to later
# reuse if necessary
if url:
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(url)
# URL could contains host, port, user, password and db values
app.config[key('HOST')] = url.hostname
app.config[key('PORT')] = url.port or 6379
app.config[key('USER')] = url.username
app.config[key('PASSWORD')] = url.password
db = url.path.replace('/', '')
app.config[key('DB')] = db if db.isdigit() else None
# Host is not a mandatory key if you want to use connection pool. But
# when present and starts with file:// or / use it as unix socket path
host = app.config.get(key('HOST'))
if host and (host.startswith('file://') or host.startswith('/')):
app.config.pop(key('HOST'))
app.config[key('UNIX_SOCKET_PATH')] = host
args = self._build_connection_args(klass)
kwargs = dict([(arg, convert(arg, app.config[key(arg.upper())]))
for arg in args
if key(arg.upper()) in app.config])
# Initialize connection and store it to extensions
connection = klass(**kwargs)
app.extensions['redis'][config_prefix] = connection
# Include public methods to current instance
self._include_public_methods(connection)
|
python
|
def init_app(self, app, config_prefix=None):
"""
Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_prefix: Config prefix to use. By default: ``REDIS``
"""
# Put redis to application extensions
if 'redis' not in app.extensions:
app.extensions['redis'] = {}
# Which config prefix to use, custom or default one?
self.config_prefix = config_prefix = config_prefix or 'REDIS'
# No way to do registration two times
if config_prefix in app.extensions['redis']:
raise ValueError('Already registered config prefix {0!r}.'.
format(config_prefix))
# Start reading configuration, define converters to use and key func
# to prepend config prefix to key value
converters = {'port': int}
convert = lambda arg, value: (converters[arg](value)
if arg in converters
else value)
key = lambda param: '{0}_{1}'.format(config_prefix, param)
# Which redis connection class to use?
klass = app.config.get(key('CLASS'), RedisClass)
# Import connection class if it stil path notation
if isinstance(klass, string_types):
klass = import_string(klass)
# Should we use URL configuration
url = app.config.get(key('URL'))
# If should, parse URL and store values to application config to later
# reuse if necessary
if url:
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(url)
# URL could contains host, port, user, password and db values
app.config[key('HOST')] = url.hostname
app.config[key('PORT')] = url.port or 6379
app.config[key('USER')] = url.username
app.config[key('PASSWORD')] = url.password
db = url.path.replace('/', '')
app.config[key('DB')] = db if db.isdigit() else None
# Host is not a mandatory key if you want to use connection pool. But
# when present and starts with file:// or / use it as unix socket path
host = app.config.get(key('HOST'))
if host and (host.startswith('file://') or host.startswith('/')):
app.config.pop(key('HOST'))
app.config[key('UNIX_SOCKET_PATH')] = host
args = self._build_connection_args(klass)
kwargs = dict([(arg, convert(arg, app.config[key(arg.upper())]))
for arg in args
if key(arg.upper()) in app.config])
# Initialize connection and store it to extensions
connection = klass(**kwargs)
app.extensions['redis'][config_prefix] = connection
# Include public methods to current instance
self._include_public_methods(connection)
|
[
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"config_prefix",
"=",
"None",
")",
":",
"# Put redis to application extensions",
"if",
"'redis'",
"not",
"in",
"app",
".",
"extensions",
":",
"app",
".",
"extensions",
"[",
"'redis'",
"]",
"=",
"{",
"}",
"# Which config prefix to use, custom or default one?",
"self",
".",
"config_prefix",
"=",
"config_prefix",
"=",
"config_prefix",
"or",
"'REDIS'",
"# No way to do registration two times",
"if",
"config_prefix",
"in",
"app",
".",
"extensions",
"[",
"'redis'",
"]",
":",
"raise",
"ValueError",
"(",
"'Already registered config prefix {0!r}.'",
".",
"format",
"(",
"config_prefix",
")",
")",
"# Start reading configuration, define converters to use and key func",
"# to prepend config prefix to key value",
"converters",
"=",
"{",
"'port'",
":",
"int",
"}",
"convert",
"=",
"lambda",
"arg",
",",
"value",
":",
"(",
"converters",
"[",
"arg",
"]",
"(",
"value",
")",
"if",
"arg",
"in",
"converters",
"else",
"value",
")",
"key",
"=",
"lambda",
"param",
":",
"'{0}_{1}'",
".",
"format",
"(",
"config_prefix",
",",
"param",
")",
"# Which redis connection class to use?",
"klass",
"=",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'CLASS'",
")",
",",
"RedisClass",
")",
"# Import connection class if it stil path notation",
"if",
"isinstance",
"(",
"klass",
",",
"string_types",
")",
":",
"klass",
"=",
"import_string",
"(",
"klass",
")",
"# Should we use URL configuration",
"url",
"=",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'URL'",
")",
")",
"# If should, parse URL and store values to application config to later",
"# reuse if necessary",
"if",
"url",
":",
"urlparse",
".",
"uses_netloc",
".",
"append",
"(",
"'redis'",
")",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"# URL could contains host, port, user, password and db values",
"app",
".",
"config",
"[",
"key",
"(",
"'HOST'",
")",
"]",
"=",
"url",
".",
"hostname",
"app",
".",
"config",
"[",
"key",
"(",
"'PORT'",
")",
"]",
"=",
"url",
".",
"port",
"or",
"6379",
"app",
".",
"config",
"[",
"key",
"(",
"'USER'",
")",
"]",
"=",
"url",
".",
"username",
"app",
".",
"config",
"[",
"key",
"(",
"'PASSWORD'",
")",
"]",
"=",
"url",
".",
"password",
"db",
"=",
"url",
".",
"path",
".",
"replace",
"(",
"'/'",
",",
"''",
")",
"app",
".",
"config",
"[",
"key",
"(",
"'DB'",
")",
"]",
"=",
"db",
"if",
"db",
".",
"isdigit",
"(",
")",
"else",
"None",
"# Host is not a mandatory key if you want to use connection pool. But",
"# when present and starts with file:// or / use it as unix socket path",
"host",
"=",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'HOST'",
")",
")",
"if",
"host",
"and",
"(",
"host",
".",
"startswith",
"(",
"'file://'",
")",
"or",
"host",
".",
"startswith",
"(",
"'/'",
")",
")",
":",
"app",
".",
"config",
".",
"pop",
"(",
"key",
"(",
"'HOST'",
")",
")",
"app",
".",
"config",
"[",
"key",
"(",
"'UNIX_SOCKET_PATH'",
")",
"]",
"=",
"host",
"args",
"=",
"self",
".",
"_build_connection_args",
"(",
"klass",
")",
"kwargs",
"=",
"dict",
"(",
"[",
"(",
"arg",
",",
"convert",
"(",
"arg",
",",
"app",
".",
"config",
"[",
"key",
"(",
"arg",
".",
"upper",
"(",
")",
")",
"]",
")",
")",
"for",
"arg",
"in",
"args",
"if",
"key",
"(",
"arg",
".",
"upper",
"(",
")",
")",
"in",
"app",
".",
"config",
"]",
")",
"# Initialize connection and store it to extensions",
"connection",
"=",
"klass",
"(",
"*",
"*",
"kwargs",
")",
"app",
".",
"extensions",
"[",
"'redis'",
"]",
"[",
"config_prefix",
"]",
"=",
"connection",
"# Include public methods to current instance",
"self",
".",
"_include_public_methods",
"(",
"connection",
")"
] |
Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_prefix: Config prefix to use. By default: ``REDIS``
|
[
"Actual",
"method",
"to",
"read",
"redis",
"settings",
"from",
"app",
"configuration",
"initialize",
"Redis",
"connection",
"and",
"copy",
"all",
"public",
"connection",
"methods",
"to",
"current",
"instance",
"."
] |
878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5
|
https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L100-L170
|
train
|
playpauseandstop/Flask-And-Redis
|
flask_redis.py
|
Redis._build_connection_args
|
def _build_connection_args(self, klass):
"""Read connection args spec, exclude self from list of possible
:param klass: Redis connection class.
"""
bases = [base for base in klass.__bases__ if base is not object]
all_args = []
for cls in [klass] + bases:
try:
args = inspect.getfullargspec(cls.__init__).args
except AttributeError:
args = inspect.getargspec(cls.__init__).args
for arg in args:
if arg in all_args:
continue
all_args.append(arg)
all_args.remove('self')
return all_args
|
python
|
def _build_connection_args(self, klass):
"""Read connection args spec, exclude self from list of possible
:param klass: Redis connection class.
"""
bases = [base for base in klass.__bases__ if base is not object]
all_args = []
for cls in [klass] + bases:
try:
args = inspect.getfullargspec(cls.__init__).args
except AttributeError:
args = inspect.getargspec(cls.__init__).args
for arg in args:
if arg in all_args:
continue
all_args.append(arg)
all_args.remove('self')
return all_args
|
[
"def",
"_build_connection_args",
"(",
"self",
",",
"klass",
")",
":",
"bases",
"=",
"[",
"base",
"for",
"base",
"in",
"klass",
".",
"__bases__",
"if",
"base",
"is",
"not",
"object",
"]",
"all_args",
"=",
"[",
"]",
"for",
"cls",
"in",
"[",
"klass",
"]",
"+",
"bases",
":",
"try",
":",
"args",
"=",
"inspect",
".",
"getfullargspec",
"(",
"cls",
".",
"__init__",
")",
".",
"args",
"except",
"AttributeError",
":",
"args",
"=",
"inspect",
".",
"getargspec",
"(",
"cls",
".",
"__init__",
")",
".",
"args",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"in",
"all_args",
":",
"continue",
"all_args",
".",
"append",
"(",
"arg",
")",
"all_args",
".",
"remove",
"(",
"'self'",
")",
"return",
"all_args"
] |
Read connection args spec, exclude self from list of possible
:param klass: Redis connection class.
|
[
"Read",
"connection",
"args",
"spec",
"exclude",
"self",
"from",
"list",
"of",
"possible"
] |
878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5
|
https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L172-L189
|
train
|
playpauseandstop/Flask-And-Redis
|
flask_redis.py
|
Redis._include_public_methods
|
def _include_public_methods(self, connection):
"""Include public methods from Redis connection to current instance.
:param connection: Redis connection instance.
"""
for attr in dir(connection):
value = getattr(connection, attr)
if attr.startswith('_') or not callable(value):
continue
self.__dict__[attr] = self._wrap_public_method(attr)
|
python
|
def _include_public_methods(self, connection):
"""Include public methods from Redis connection to current instance.
:param connection: Redis connection instance.
"""
for attr in dir(connection):
value = getattr(connection, attr)
if attr.startswith('_') or not callable(value):
continue
self.__dict__[attr] = self._wrap_public_method(attr)
|
[
"def",
"_include_public_methods",
"(",
"self",
",",
"connection",
")",
":",
"for",
"attr",
"in",
"dir",
"(",
"connection",
")",
":",
"value",
"=",
"getattr",
"(",
"connection",
",",
"attr",
")",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"or",
"not",
"callable",
"(",
"value",
")",
":",
"continue",
"self",
".",
"__dict__",
"[",
"attr",
"]",
"=",
"self",
".",
"_wrap_public_method",
"(",
"attr",
")"
] |
Include public methods from Redis connection to current instance.
:param connection: Redis connection instance.
|
[
"Include",
"public",
"methods",
"from",
"Redis",
"connection",
"to",
"current",
"instance",
"."
] |
878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5
|
https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L191-L200
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.prepare
|
def prepare(self):
'''Prepare to run the docker command'''
self.__make_scubadir()
if self.is_remote_docker:
'''
Docker is running remotely (e.g. boot2docker on OSX).
We don't need to do any user setup whatsoever.
TODO: For now, remote instances won't have any .scubainit
See:
https://github.com/JonathonReinhart/scuba/issues/17
'''
raise ScubaError('Remote docker not supported (DOCKER_HOST is set)')
# Docker is running natively
self.__setup_native_run()
# Apply environment vars from .scuba.yml
self.env_vars.update(self.context.environment)
|
python
|
def prepare(self):
'''Prepare to run the docker command'''
self.__make_scubadir()
if self.is_remote_docker:
'''
Docker is running remotely (e.g. boot2docker on OSX).
We don't need to do any user setup whatsoever.
TODO: For now, remote instances won't have any .scubainit
See:
https://github.com/JonathonReinhart/scuba/issues/17
'''
raise ScubaError('Remote docker not supported (DOCKER_HOST is set)')
# Docker is running natively
self.__setup_native_run()
# Apply environment vars from .scuba.yml
self.env_vars.update(self.context.environment)
|
[
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"__make_scubadir",
"(",
")",
"if",
"self",
".",
"is_remote_docker",
":",
"'''\n Docker is running remotely (e.g. boot2docker on OSX).\n We don't need to do any user setup whatsoever.\n\n TODO: For now, remote instances won't have any .scubainit\n\n See:\n https://github.com/JonathonReinhart/scuba/issues/17\n '''",
"raise",
"ScubaError",
"(",
"'Remote docker not supported (DOCKER_HOST is set)'",
")",
"# Docker is running natively",
"self",
".",
"__setup_native_run",
"(",
")",
"# Apply environment vars from .scuba.yml",
"self",
".",
"env_vars",
".",
"update",
"(",
"self",
".",
"context",
".",
"environment",
")"
] |
Prepare to run the docker command
|
[
"Prepare",
"to",
"run",
"the",
"docker",
"command"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L119-L139
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.add_env
|
def add_env(self, name, val):
'''Add an environment variable to the docker run invocation
'''
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val
|
python
|
def add_env(self, name, val):
'''Add an environment variable to the docker run invocation
'''
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val
|
[
"def",
"add_env",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"if",
"name",
"in",
"self",
".",
"env_vars",
":",
"raise",
"KeyError",
"(",
"name",
")",
"self",
".",
"env_vars",
"[",
"name",
"]",
"=",
"val"
] |
Add an environment variable to the docker run invocation
|
[
"Add",
"an",
"environment",
"variable",
"to",
"the",
"docker",
"run",
"invocation"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L176-L181
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.__locate_scubainit
|
def __locate_scubainit(self):
'''Determine path to scubainit binary
'''
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, 'scubainit')
if not os.path.isfile(self.scubainit_path):
raise ScubaError('scubainit not found at "{}"'.format(self.scubainit_path))
|
python
|
def __locate_scubainit(self):
'''Determine path to scubainit binary
'''
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, 'scubainit')
if not os.path.isfile(self.scubainit_path):
raise ScubaError('scubainit not found at "{}"'.format(self.scubainit_path))
|
[
"def",
"__locate_scubainit",
"(",
"self",
")",
":",
"pkg_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"self",
".",
"scubainit_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_path",
",",
"'scubainit'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"scubainit_path",
")",
":",
"raise",
"ScubaError",
"(",
"'scubainit not found at \"{}\"'",
".",
"format",
"(",
"self",
".",
"scubainit_path",
")",
")"
] |
Determine path to scubainit binary
|
[
"Determine",
"path",
"to",
"scubainit",
"binary"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L198-L205
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.__load_config
|
def __load_config(self):
'''Find and load .scuba.yml
'''
# top_path is where .scuba.yml is found, and becomes the top of our bind mount.
# top_rel is the relative path from top_path to the current working directory,
# and is where we'll set the working directory in the container (relative to
# the bind mount point).
try:
top_path, top_rel = find_config()
self.config = load_config(os.path.join(top_path, SCUBA_YML))
except ConfigNotFoundError as cfgerr:
# SCUBA_YML can be missing if --image was given.
# In this case, we assume a default config
if not self.image_override:
raise ScubaError(str(cfgerr))
top_path, top_rel = os.getcwd(), ''
self.config = ScubaConfig(image=None)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
# Mount scuba root directory at the same path in the container...
self.add_volume(top_path, top_path)
# ...and set the working dir relative to it
self.set_workdir(os.path.join(top_path, top_rel))
self.add_env('SCUBA_ROOT', top_path)
|
python
|
def __load_config(self):
'''Find and load .scuba.yml
'''
# top_path is where .scuba.yml is found, and becomes the top of our bind mount.
# top_rel is the relative path from top_path to the current working directory,
# and is where we'll set the working directory in the container (relative to
# the bind mount point).
try:
top_path, top_rel = find_config()
self.config = load_config(os.path.join(top_path, SCUBA_YML))
except ConfigNotFoundError as cfgerr:
# SCUBA_YML can be missing if --image was given.
# In this case, we assume a default config
if not self.image_override:
raise ScubaError(str(cfgerr))
top_path, top_rel = os.getcwd(), ''
self.config = ScubaConfig(image=None)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
# Mount scuba root directory at the same path in the container...
self.add_volume(top_path, top_path)
# ...and set the working dir relative to it
self.set_workdir(os.path.join(top_path, top_rel))
self.add_env('SCUBA_ROOT', top_path)
|
[
"def",
"__load_config",
"(",
"self",
")",
":",
"# top_path is where .scuba.yml is found, and becomes the top of our bind mount.",
"# top_rel is the relative path from top_path to the current working directory,",
"# and is where we'll set the working directory in the container (relative to",
"# the bind mount point).",
"try",
":",
"top_path",
",",
"top_rel",
"=",
"find_config",
"(",
")",
"self",
".",
"config",
"=",
"load_config",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top_path",
",",
"SCUBA_YML",
")",
")",
"except",
"ConfigNotFoundError",
"as",
"cfgerr",
":",
"# SCUBA_YML can be missing if --image was given.",
"# In this case, we assume a default config",
"if",
"not",
"self",
".",
"image_override",
":",
"raise",
"ScubaError",
"(",
"str",
"(",
"cfgerr",
")",
")",
"top_path",
",",
"top_rel",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"''",
"self",
".",
"config",
"=",
"ScubaConfig",
"(",
"image",
"=",
"None",
")",
"except",
"ConfigError",
"as",
"cfgerr",
":",
"raise",
"ScubaError",
"(",
"str",
"(",
"cfgerr",
")",
")",
"# Mount scuba root directory at the same path in the container...",
"self",
".",
"add_volume",
"(",
"top_path",
",",
"top_path",
")",
"# ...and set the working dir relative to it",
"self",
".",
"set_workdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top_path",
",",
"top_rel",
")",
")",
"self",
".",
"add_env",
"(",
"'SCUBA_ROOT'",
",",
"top_path",
")"
] |
Find and load .scuba.yml
|
[
"Find",
"and",
"load",
".",
"scuba",
".",
"yml"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L208-L235
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.__make_scubadir
|
def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath)
|
python
|
def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath)
|
[
"def",
"__make_scubadir",
"(",
"self",
")",
":",
"self",
".",
"__scubadir_hostpath",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'scubadir'",
")",
"self",
".",
"__scubadir_contpath",
"=",
"'/.scuba'",
"self",
".",
"add_volume",
"(",
"self",
".",
"__scubadir_hostpath",
",",
"self",
".",
"__scubadir_contpath",
")"
] |
Make temp directory where all ancillary files are bind-mounted
|
[
"Make",
"temp",
"directory",
"where",
"all",
"ancillary",
"files",
"are",
"bind",
"-",
"mounted"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L237-L242
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.__setup_native_run
|
def __setup_native_run(self):
# These options are appended to mounted volume arguments
# NOTE: This tells Docker to re-label the directory for compatibility
# with SELinux. See `man docker-run` for more information.
self.vol_opts = ['z']
# Pass variables to scubainit
self.add_env('SCUBAINIT_UMASK', '{:04o}'.format(get_umask()))
if not self.as_root:
self.add_env('SCUBAINIT_UID', os.getuid())
self.add_env('SCUBAINIT_GID', os.getgid())
if self.verbose:
self.add_env('SCUBAINIT_VERBOSE', 1)
# Copy scubainit into the container
# We make a copy because Docker 1.13 gets pissed if we try to re-label
# /usr, and Fedora 28 gives an AVC denial.
scubainit_cpath = self.copy_scubadir_file('scubainit', self.scubainit_path)
# Hooks
for name in ('root', 'user', ):
self.__generate_hook_script(name)
# allocate TTY if scuba's output is going to a terminal
# and stdin is not redirected
if sys.stdout.isatty() and sys.stdin.isatty():
self.add_option('--tty')
# Process any aliases
try:
context = self.config.process_command(self.user_command)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
if self.image_override:
context.image = self.image_override
'''
Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself.
'''
if not context.script:
# No user-provided command; we want to run the image's default command
verbose_msg('No user command; getting command from image')
default_cmd = get_image_command(context.image)
if not default_cmd:
raise ScubaError('No command given and no image-specified command')
verbose_msg('{} Cmd: "{}"'.format(context.image, default_cmd))
context.script = [shell_quote_cmd(default_cmd)]
# Make scubainit the real entrypoint, and use the defined entrypoint as
# the docker command (if it exists)
self.add_option('--entrypoint={}'.format(scubainit_cpath))
self.docker_cmd = []
if self.entrypoint_override is not None:
# --entrypoint takes precedence
if self.entrypoint_override != '':
self.docker_cmd = [self.entrypoint_override]
elif context.entrypoint is not None:
# then .scuba.yml
if context.entrypoint != '':
self.docker_cmd = [context.entrypoint]
else:
ep = get_image_entrypoint(context.image)
if ep:
self.docker_cmd = ep
# The user command is executed via a generated shell script
with self.open_scubadir_file('command.sh', 'wt') as f:
self.docker_cmd += ['/bin/sh', f.container_path]
writeln(f, '#!/bin/sh')
writeln(f, '# Auto-generated from scuba')
writeln(f, 'set -e')
for cmd in context.script:
writeln(f, cmd)
self.context = context
|
python
|
def __setup_native_run(self):
# These options are appended to mounted volume arguments
# NOTE: This tells Docker to re-label the directory for compatibility
# with SELinux. See `man docker-run` for more information.
self.vol_opts = ['z']
# Pass variables to scubainit
self.add_env('SCUBAINIT_UMASK', '{:04o}'.format(get_umask()))
if not self.as_root:
self.add_env('SCUBAINIT_UID', os.getuid())
self.add_env('SCUBAINIT_GID', os.getgid())
if self.verbose:
self.add_env('SCUBAINIT_VERBOSE', 1)
# Copy scubainit into the container
# We make a copy because Docker 1.13 gets pissed if we try to re-label
# /usr, and Fedora 28 gives an AVC denial.
scubainit_cpath = self.copy_scubadir_file('scubainit', self.scubainit_path)
# Hooks
for name in ('root', 'user', ):
self.__generate_hook_script(name)
# allocate TTY if scuba's output is going to a terminal
# and stdin is not redirected
if sys.stdout.isatty() and sys.stdin.isatty():
self.add_option('--tty')
# Process any aliases
try:
context = self.config.process_command(self.user_command)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
if self.image_override:
context.image = self.image_override
'''
Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself.
'''
if not context.script:
# No user-provided command; we want to run the image's default command
verbose_msg('No user command; getting command from image')
default_cmd = get_image_command(context.image)
if not default_cmd:
raise ScubaError('No command given and no image-specified command')
verbose_msg('{} Cmd: "{}"'.format(context.image, default_cmd))
context.script = [shell_quote_cmd(default_cmd)]
# Make scubainit the real entrypoint, and use the defined entrypoint as
# the docker command (if it exists)
self.add_option('--entrypoint={}'.format(scubainit_cpath))
self.docker_cmd = []
if self.entrypoint_override is not None:
# --entrypoint takes precedence
if self.entrypoint_override != '':
self.docker_cmd = [self.entrypoint_override]
elif context.entrypoint is not None:
# then .scuba.yml
if context.entrypoint != '':
self.docker_cmd = [context.entrypoint]
else:
ep = get_image_entrypoint(context.image)
if ep:
self.docker_cmd = ep
# The user command is executed via a generated shell script
with self.open_scubadir_file('command.sh', 'wt') as f:
self.docker_cmd += ['/bin/sh', f.container_path]
writeln(f, '#!/bin/sh')
writeln(f, '# Auto-generated from scuba')
writeln(f, 'set -e')
for cmd in context.script:
writeln(f, cmd)
self.context = context
|
[
"def",
"__setup_native_run",
"(",
"self",
")",
":",
"# These options are appended to mounted volume arguments",
"# NOTE: This tells Docker to re-label the directory for compatibility",
"# with SELinux. See `man docker-run` for more information.",
"self",
".",
"vol_opts",
"=",
"[",
"'z'",
"]",
"# Pass variables to scubainit",
"self",
".",
"add_env",
"(",
"'SCUBAINIT_UMASK'",
",",
"'{:04o}'",
".",
"format",
"(",
"get_umask",
"(",
")",
")",
")",
"if",
"not",
"self",
".",
"as_root",
":",
"self",
".",
"add_env",
"(",
"'SCUBAINIT_UID'",
",",
"os",
".",
"getuid",
"(",
")",
")",
"self",
".",
"add_env",
"(",
"'SCUBAINIT_GID'",
",",
"os",
".",
"getgid",
"(",
")",
")",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"add_env",
"(",
"'SCUBAINIT_VERBOSE'",
",",
"1",
")",
"# Copy scubainit into the container",
"# We make a copy because Docker 1.13 gets pissed if we try to re-label",
"# /usr, and Fedora 28 gives an AVC denial.",
"scubainit_cpath",
"=",
"self",
".",
"copy_scubadir_file",
"(",
"'scubainit'",
",",
"self",
".",
"scubainit_path",
")",
"# Hooks",
"for",
"name",
"in",
"(",
"'root'",
",",
"'user'",
",",
")",
":",
"self",
".",
"__generate_hook_script",
"(",
"name",
")",
"# allocate TTY if scuba's output is going to a terminal",
"# and stdin is not redirected",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"and",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
":",
"self",
".",
"add_option",
"(",
"'--tty'",
")",
"# Process any aliases",
"try",
":",
"context",
"=",
"self",
".",
"config",
".",
"process_command",
"(",
"self",
".",
"user_command",
")",
"except",
"ConfigError",
"as",
"cfgerr",
":",
"raise",
"ScubaError",
"(",
"str",
"(",
"cfgerr",
")",
")",
"if",
"self",
".",
"image_override",
":",
"context",
".",
"image",
"=",
"self",
".",
"image_override",
"if",
"not",
"context",
".",
"script",
":",
"# No user-provided command; we want to run the image's default command",
"verbose_msg",
"(",
"'No user command; getting command from image'",
")",
"default_cmd",
"=",
"get_image_command",
"(",
"context",
".",
"image",
")",
"if",
"not",
"default_cmd",
":",
"raise",
"ScubaError",
"(",
"'No command given and no image-specified command'",
")",
"verbose_msg",
"(",
"'{} Cmd: \"{}\"'",
".",
"format",
"(",
"context",
".",
"image",
",",
"default_cmd",
")",
")",
"context",
".",
"script",
"=",
"[",
"shell_quote_cmd",
"(",
"default_cmd",
")",
"]",
"# Make scubainit the real entrypoint, and use the defined entrypoint as",
"# the docker command (if it exists)",
"self",
".",
"add_option",
"(",
"'--entrypoint={}'",
".",
"format",
"(",
"scubainit_cpath",
")",
")",
"self",
".",
"docker_cmd",
"=",
"[",
"]",
"if",
"self",
".",
"entrypoint_override",
"is",
"not",
"None",
":",
"# --entrypoint takes precedence",
"if",
"self",
".",
"entrypoint_override",
"!=",
"''",
":",
"self",
".",
"docker_cmd",
"=",
"[",
"self",
".",
"entrypoint_override",
"]",
"elif",
"context",
".",
"entrypoint",
"is",
"not",
"None",
":",
"# then .scuba.yml",
"if",
"context",
".",
"entrypoint",
"!=",
"''",
":",
"self",
".",
"docker_cmd",
"=",
"[",
"context",
".",
"entrypoint",
"]",
"else",
":",
"ep",
"=",
"get_image_entrypoint",
"(",
"context",
".",
"image",
")",
"if",
"ep",
":",
"self",
".",
"docker_cmd",
"=",
"ep",
"# The user command is executed via a generated shell script",
"with",
"self",
".",
"open_scubadir_file",
"(",
"'command.sh'",
",",
"'wt'",
")",
"as",
"f",
":",
"self",
".",
"docker_cmd",
"+=",
"[",
"'/bin/sh'",
",",
"f",
".",
"container_path",
"]",
"writeln",
"(",
"f",
",",
"'#!/bin/sh'",
")",
"writeln",
"(",
"f",
",",
"'# Auto-generated from scuba'",
")",
"writeln",
"(",
"f",
",",
"'set -e'",
")",
"for",
"cmd",
"in",
"context",
".",
"script",
":",
"writeln",
"(",
"f",
",",
"cmd",
")",
"self",
".",
"context",
"=",
"context"
] |
Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself.
|
[
"Normally",
"if",
"the",
"user",
"provides",
"no",
"command",
"to",
"docker",
"run",
"the",
"image",
"s",
"default",
"CMD",
"is",
"run",
".",
"Because",
"we",
"set",
"the",
"entrypiont",
"scuba",
"must",
"emulate",
"the",
"default",
"behavior",
"itself",
"."
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L244-L326
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.open_scubadir_file
|
def open_scubadir_file(self, name, mode):
'''Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
'''
path = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(path)
# Make any directories required
mkdir_p(os.path.dirname(path))
f = File(path, mode)
f.container_path = os.path.join(self.__scubadir_contpath, name)
return f
|
python
|
def open_scubadir_file(self, name, mode):
'''Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
'''
path = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(path)
# Make any directories required
mkdir_p(os.path.dirname(path))
f = File(path, mode)
f.container_path = os.path.join(self.__scubadir_contpath, name)
return f
|
[
"def",
"open_scubadir_file",
"(",
"self",
",",
"name",
",",
"mode",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_hostpath",
",",
"name",
")",
"assert",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"# Make any directories required",
"mkdir_p",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"f",
"=",
"File",
"(",
"path",
",",
"mode",
")",
"f",
".",
"container_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_contpath",
",",
"name",
")",
"return",
"f"
] |
Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
|
[
"Opens",
"a",
"file",
"in",
"the",
"scubadir"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L330-L344
|
train
|
JonathonReinhart/scuba
|
scuba/__main__.py
|
ScubaDive.copy_scubadir_file
|
def copy_scubadir_file(self, name, source):
'''Copies source into the scubadir
Returns the container-path of the copied file
'''
dest = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(dest)
shutil.copy2(source, dest)
return os.path.join(self.__scubadir_contpath, name)
|
python
|
def copy_scubadir_file(self, name, source):
'''Copies source into the scubadir
Returns the container-path of the copied file
'''
dest = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(dest)
shutil.copy2(source, dest)
return os.path.join(self.__scubadir_contpath, name)
|
[
"def",
"copy_scubadir_file",
"(",
"self",
",",
"name",
",",
"source",
")",
":",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_hostpath",
",",
"name",
")",
"assert",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
"shutil",
".",
"copy2",
"(",
"source",
",",
"dest",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_contpath",
",",
"name",
")"
] |
Copies source into the scubadir
Returns the container-path of the copied file
|
[
"Copies",
"source",
"into",
"the",
"scubadir"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L347-L356
|
train
|
JonathonReinhart/scuba
|
scuba/utils.py
|
format_cmdline
|
def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines())
|
python
|
def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines())
|
[
"def",
"format_cmdline",
"(",
"args",
",",
"maxwidth",
"=",
"80",
")",
":",
"# Leave room for the space and backslash at the end of each line",
"maxwidth",
"-=",
"2",
"def",
"lines",
"(",
")",
":",
"line",
"=",
"''",
"for",
"a",
"in",
"(",
"shell_quote",
"(",
"a",
")",
"for",
"a",
"in",
"args",
")",
":",
"# If adding this argument will make the line too long,",
"# yield the current line, and start a new one.",
"if",
"len",
"(",
"line",
")",
"+",
"len",
"(",
"a",
")",
"+",
"1",
">",
"maxwidth",
":",
"yield",
"line",
"line",
"=",
"''",
"# Append this argument to the current line, separating",
"# it by a space from the existing arguments.",
"if",
"line",
":",
"line",
"+=",
"' '",
"+",
"a",
"else",
":",
"line",
"=",
"a",
"yield",
"line",
"return",
"' \\\\\\n'",
".",
"join",
"(",
"lines",
"(",
")",
")"
] |
Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
|
[
"Format",
"args",
"into",
"a",
"shell",
"-",
"quoted",
"command",
"line",
"."
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/utils.py#L13-L41
|
train
|
JonathonReinhart/scuba
|
scuba/utils.py
|
parse_env_var
|
def parse_env_var(s):
"""Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environment
"""
parts = s.split('=', 1)
if len(parts) == 2:
k, v = parts
return (k, v)
k = parts[0]
return (k, os.getenv(k, ''))
|
python
|
def parse_env_var(s):
"""Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environment
"""
parts = s.split('=', 1)
if len(parts) == 2:
k, v = parts
return (k, v)
k = parts[0]
return (k, os.getenv(k, ''))
|
[
"def",
"parse_env_var",
"(",
"s",
")",
":",
"parts",
"=",
"s",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"k",
",",
"v",
"=",
"parts",
"return",
"(",
"k",
",",
"v",
")",
"k",
"=",
"parts",
"[",
"0",
"]",
"return",
"(",
"k",
",",
"os",
".",
"getenv",
"(",
"k",
",",
"''",
")",
")"
] |
Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environment
|
[
"Parse",
"an",
"environment",
"variable",
"string"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/utils.py#L53-L69
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
__wrap_docker_exec
|
def __wrap_docker_exec(func):
'''Wrap a function to raise DockerExecuteError on ENOENT'''
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is it installed?')
raise
return call
|
python
|
def __wrap_docker_exec(func):
'''Wrap a function to raise DockerExecuteError on ENOENT'''
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is it installed?')
raise
return call
|
[
"def",
"__wrap_docker_exec",
"(",
"func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"raise",
"DockerExecuteError",
"(",
"'Failed to execute docker. Is it installed?'",
")",
"raise",
"return",
"call"
] |
Wrap a function to raise DockerExecuteError on ENOENT
|
[
"Wrap",
"a",
"function",
"to",
"raise",
"DockerExecuteError",
"on",
"ENOENT"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L19-L28
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
docker_inspect
|
def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if not p.returncode == 0:
if 'no such image' in stderr.lower():
raise NoSuchImageError(image)
raise DockerError('Failed to inspect image: {}'.format(stderr.strip()))
return json.loads(stdout)[0]
|
python
|
def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if not p.returncode == 0:
if 'no such image' in stderr.lower():
raise NoSuchImageError(image)
raise DockerError('Failed to inspect image: {}'.format(stderr.strip()))
return json.loads(stdout)[0]
|
[
"def",
"docker_inspect",
"(",
"image",
")",
":",
"args",
"=",
"[",
"'docker'",
",",
"'inspect'",
",",
"'--type'",
",",
"'image'",
",",
"image",
"]",
"p",
"=",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
"stderr",
"=",
"stderr",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"not",
"p",
".",
"returncode",
"==",
"0",
":",
"if",
"'no such image'",
"in",
"stderr",
".",
"lower",
"(",
")",
":",
"raise",
"NoSuchImageError",
"(",
"image",
")",
"raise",
"DockerError",
"(",
"'Failed to inspect image: {}'",
".",
"format",
"(",
"stderr",
".",
"strip",
"(",
")",
")",
")",
"return",
"json",
".",
"loads",
"(",
"stdout",
")",
"[",
"0",
"]"
] |
Inspects a docker image
Returns: Parsed JSON data
|
[
"Inspects",
"a",
"docker",
"image"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L34-L51
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
docker_pull
|
def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image))
|
python
|
def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image))
|
[
"def",
"docker_pull",
"(",
"image",
")",
":",
"args",
"=",
"[",
"'docker'",
",",
"'pull'",
",",
"image",
"]",
"# If this fails, the default docker stdout/stderr looks good to the user.",
"ret",
"=",
"call",
"(",
"args",
")",
"if",
"ret",
"!=",
"0",
":",
"raise",
"DockerError",
"(",
"'Failed to pull image \"{}\"'",
".",
"format",
"(",
"image",
")",
")"
] |
Pulls an image
|
[
"Pulls",
"an",
"image"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L53-L60
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
get_image_command
|
def get_image_command(image):
'''Gets the default command for an image'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Cmd']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))
|
python
|
def get_image_command(image):
'''Gets the default command for an image'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Cmd']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))
|
[
"def",
"get_image_command",
"(",
"image",
")",
":",
"info",
"=",
"docker_inspect_or_pull",
"(",
"image",
")",
"try",
":",
"return",
"info",
"[",
"'Config'",
"]",
"[",
"'Cmd'",
"]",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"DockerError",
"(",
"'Failed to inspect image: JSON result missing key {}'",
".",
"format",
"(",
"ke",
")",
")"
] |
Gets the default command for an image
|
[
"Gets",
"the",
"default",
"command",
"for",
"an",
"image"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L71-L77
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
get_image_entrypoint
|
def get_image_entrypoint(image):
'''Gets the image entrypoint'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Entrypoint']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))
|
python
|
def get_image_entrypoint(image):
'''Gets the image entrypoint'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Entrypoint']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))
|
[
"def",
"get_image_entrypoint",
"(",
"image",
")",
":",
"info",
"=",
"docker_inspect_or_pull",
"(",
"image",
")",
"try",
":",
"return",
"info",
"[",
"'Config'",
"]",
"[",
"'Entrypoint'",
"]",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"DockerError",
"(",
"'Failed to inspect image: JSON result missing key {}'",
".",
"format",
"(",
"ke",
")",
")"
] |
Gets the image entrypoint
|
[
"Gets",
"the",
"image",
"entrypoint"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L79-L85
|
train
|
JonathonReinhart/scuba
|
scuba/dockerutil.py
|
make_vol_opt
|
def make_vol_opt(hostdir, contdir, options=None):
'''Generate a docker volume option'''
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol
|
python
|
def make_vol_opt(hostdir, contdir, options=None):
'''Generate a docker volume option'''
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol
|
[
"def",
"make_vol_opt",
"(",
"hostdir",
",",
"contdir",
",",
"options",
"=",
"None",
")",
":",
"vol",
"=",
"'--volume={}:{}'",
".",
"format",
"(",
"hostdir",
",",
"contdir",
")",
"if",
"options",
"!=",
"None",
":",
"if",
"isinstance",
"(",
"options",
",",
"str",
")",
":",
"options",
"=",
"(",
"options",
",",
")",
"vol",
"+=",
"':'",
"+",
"','",
".",
"join",
"(",
"options",
")",
"return",
"vol"
] |
Generate a docker volume option
|
[
"Generate",
"a",
"docker",
"volume",
"option"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L88-L95
|
train
|
JonathonReinhart/scuba
|
scuba/config.py
|
find_config
|
def find_config():
'''Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory
'''
cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os.environ
path = os.getcwd()
rel = ''
while True:
if os.path.exists(os.path.join(path, SCUBA_YML)):
return path, rel
if not cross_fs and os.path.ismount(path):
msg = '{} not found here or any parent up to mount point {}'.format(SCUBA_YML, path) \
+ '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).'
raise ConfigNotFoundError(msg)
# Traverse up directory hierarchy
path, rest = os.path.split(path)
if not rest:
raise ConfigNotFoundError('{} not found here or any parent directories'.format(SCUBA_YML))
# Accumulate the relative path back to where we started
rel = os.path.join(rest, rel)
|
python
|
def find_config():
'''Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory
'''
cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os.environ
path = os.getcwd()
rel = ''
while True:
if os.path.exists(os.path.join(path, SCUBA_YML)):
return path, rel
if not cross_fs and os.path.ismount(path):
msg = '{} not found here or any parent up to mount point {}'.format(SCUBA_YML, path) \
+ '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).'
raise ConfigNotFoundError(msg)
# Traverse up directory hierarchy
path, rest = os.path.split(path)
if not rest:
raise ConfigNotFoundError('{} not found here or any parent directories'.format(SCUBA_YML))
# Accumulate the relative path back to where we started
rel = os.path.join(rest, rel)
|
[
"def",
"find_config",
"(",
")",
":",
"cross_fs",
"=",
"'SCUBA_DISCOVERY_ACROSS_FILESYSTEM'",
"in",
"os",
".",
"environ",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"rel",
"=",
"''",
"while",
"True",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"SCUBA_YML",
")",
")",
":",
"return",
"path",
",",
"rel",
"if",
"not",
"cross_fs",
"and",
"os",
".",
"path",
".",
"ismount",
"(",
"path",
")",
":",
"msg",
"=",
"'{} not found here or any parent up to mount point {}'",
".",
"format",
"(",
"SCUBA_YML",
",",
"path",
")",
"+",
"'\\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).'",
"raise",
"ConfigNotFoundError",
"(",
"msg",
")",
"# Traverse up directory hierarchy",
"path",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"not",
"rest",
":",
"raise",
"ConfigNotFoundError",
"(",
"'{} not found here or any parent directories'",
".",
"format",
"(",
"SCUBA_YML",
")",
")",
"# Accumulate the relative path back to where we started",
"rel",
"=",
"os",
".",
"path",
".",
"join",
"(",
"rest",
",",
"rel",
")"
] |
Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory
|
[
"Search",
"up",
"the",
"diretcory",
"hierarchy",
"for",
".",
"scuba",
".",
"yml"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L74-L101
|
train
|
JonathonReinhart/scuba
|
scuba/config.py
|
_process_script_node
|
def _process_script_node(node, name):
'''Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
'''
if isinstance(node, basestring):
# The script is just the text itself
return [node]
if isinstance(node, dict):
# There must be a "script" key, which must be a list of strings
script = node.get('script')
if not script:
raise ConfigError("{}: must have a 'script' subkey".format(name))
if isinstance(script, list):
return script
if isinstance(script, basestring):
return [script]
raise ConfigError("{}.script: must be a string or list".format(name))
raise ConfigError("{}: must be string or dict".format(name))
|
python
|
def _process_script_node(node, name):
'''Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
'''
if isinstance(node, basestring):
# The script is just the text itself
return [node]
if isinstance(node, dict):
# There must be a "script" key, which must be a list of strings
script = node.get('script')
if not script:
raise ConfigError("{}: must have a 'script' subkey".format(name))
if isinstance(script, list):
return script
if isinstance(script, basestring):
return [script]
raise ConfigError("{}.script: must be a string or list".format(name))
raise ConfigError("{}: must be string or dict".format(name))
|
[
"def",
"_process_script_node",
"(",
"node",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"basestring",
")",
":",
"# The script is just the text itself",
"return",
"[",
"node",
"]",
"if",
"isinstance",
"(",
"node",
",",
"dict",
")",
":",
"# There must be a \"script\" key, which must be a list of strings",
"script",
"=",
"node",
".",
"get",
"(",
"'script'",
")",
"if",
"not",
"script",
":",
"raise",
"ConfigError",
"(",
"\"{}: must have a 'script' subkey\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"isinstance",
"(",
"script",
",",
"list",
")",
":",
"return",
"script",
"if",
"isinstance",
"(",
"script",
",",
"basestring",
")",
":",
"return",
"[",
"script",
"]",
"raise",
"ConfigError",
"(",
"\"{}.script: must be a string or list\"",
".",
"format",
"(",
"name",
")",
")",
"raise",
"ConfigError",
"(",
"\"{}: must be string or dict\"",
".",
"format",
"(",
"name",
")",
")"
] |
Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
|
[
"Process",
"a",
"script",
"-",
"type",
"node"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L104-L129
|
train
|
JonathonReinhart/scuba
|
scuba/config.py
|
ScubaConfig.process_command
|
def process_command(self, command):
'''Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use
'''
result = ScubaContext()
result.script = None
result.image = self.image
result.entrypoint = self.entrypoint
result.environment = self.environment.copy()
if command:
alias = self.aliases.get(command[0])
if not alias:
# Command is not an alias; use it as-is.
result.script = [shell_quote_cmd(command)]
else:
# Using an alias
# Does this alias override the image and/or entrypoint?
if alias.image:
result.image = alias.image
if alias.entrypoint is not None:
result.entrypoint = alias.entrypoint
# Merge/override the environment
if alias.environment:
result.environment.update(alias.environment)
if len(alias.script) > 1:
# Alias is a multiline script; no additional
# arguments are allowed in the scuba invocation.
if len(command) > 1:
raise ConfigError('Additional arguments not allowed with multi-line aliases')
result.script = alias.script
else:
# Alias is a single-line script; perform substituion
# and add user arguments.
command.pop(0)
result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
result.script = flatten_list(result.script)
return result
|
python
|
def process_command(self, command):
'''Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use
'''
result = ScubaContext()
result.script = None
result.image = self.image
result.entrypoint = self.entrypoint
result.environment = self.environment.copy()
if command:
alias = self.aliases.get(command[0])
if not alias:
# Command is not an alias; use it as-is.
result.script = [shell_quote_cmd(command)]
else:
# Using an alias
# Does this alias override the image and/or entrypoint?
if alias.image:
result.image = alias.image
if alias.entrypoint is not None:
result.entrypoint = alias.entrypoint
# Merge/override the environment
if alias.environment:
result.environment.update(alias.environment)
if len(alias.script) > 1:
# Alias is a multiline script; no additional
# arguments are allowed in the scuba invocation.
if len(command) > 1:
raise ConfigError('Additional arguments not allowed with multi-line aliases')
result.script = alias.script
else:
# Alias is a single-line script; perform substituion
# and add user arguments.
command.pop(0)
result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
result.script = flatten_list(result.script)
return result
|
[
"def",
"process_command",
"(",
"self",
",",
"command",
")",
":",
"result",
"=",
"ScubaContext",
"(",
")",
"result",
".",
"script",
"=",
"None",
"result",
".",
"image",
"=",
"self",
".",
"image",
"result",
".",
"entrypoint",
"=",
"self",
".",
"entrypoint",
"result",
".",
"environment",
"=",
"self",
".",
"environment",
".",
"copy",
"(",
")",
"if",
"command",
":",
"alias",
"=",
"self",
".",
"aliases",
".",
"get",
"(",
"command",
"[",
"0",
"]",
")",
"if",
"not",
"alias",
":",
"# Command is not an alias; use it as-is.",
"result",
".",
"script",
"=",
"[",
"shell_quote_cmd",
"(",
"command",
")",
"]",
"else",
":",
"# Using an alias",
"# Does this alias override the image and/or entrypoint?",
"if",
"alias",
".",
"image",
":",
"result",
".",
"image",
"=",
"alias",
".",
"image",
"if",
"alias",
".",
"entrypoint",
"is",
"not",
"None",
":",
"result",
".",
"entrypoint",
"=",
"alias",
".",
"entrypoint",
"# Merge/override the environment",
"if",
"alias",
".",
"environment",
":",
"result",
".",
"environment",
".",
"update",
"(",
"alias",
".",
"environment",
")",
"if",
"len",
"(",
"alias",
".",
"script",
")",
">",
"1",
":",
"# Alias is a multiline script; no additional",
"# arguments are allowed in the scuba invocation.",
"if",
"len",
"(",
"command",
")",
">",
"1",
":",
"raise",
"ConfigError",
"(",
"'Additional arguments not allowed with multi-line aliases'",
")",
"result",
".",
"script",
"=",
"alias",
".",
"script",
"else",
":",
"# Alias is a single-line script; perform substituion",
"# and add user arguments.",
"command",
".",
"pop",
"(",
"0",
")",
"result",
".",
"script",
"=",
"[",
"alias",
".",
"script",
"[",
"0",
"]",
"+",
"' '",
"+",
"shell_quote_cmd",
"(",
"command",
")",
"]",
"result",
".",
"script",
"=",
"flatten_list",
"(",
"result",
".",
"script",
")",
"return",
"result"
] |
Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use
|
[
"Processes",
"a",
"user",
"command",
"using",
"aliases"
] |
0244c81ec482d3c60202028bc075621447bc3ad1
|
https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L276-L324
|
train
|
chrislim2888/IP2Location-Python
|
IP2Location.py
|
IP2Location.open
|
def open(self, filename):
''' Opens a database file '''
# Ensure old file is closed before opening a new one
self.close()
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
self._dbyear = struct.unpack('B', self._f.read(1))[0]
self._dbmonth = struct.unpack('B', self._f.read(1))[0]
self._dbday = struct.unpack('B', self._f.read(1))[0]
self._ipv4dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv4dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv4indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
|
python
|
def open(self, filename):
''' Opens a database file '''
# Ensure old file is closed before opening a new one
self.close()
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
self._dbyear = struct.unpack('B', self._f.read(1))[0]
self._dbmonth = struct.unpack('B', self._f.read(1))[0]
self._dbday = struct.unpack('B', self._f.read(1))[0]
self._ipv4dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv4dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv4indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
|
[
"def",
"open",
"(",
"self",
",",
"filename",
")",
":",
"# Ensure old file is closed before opening a new one",
"self",
".",
"close",
"(",
")",
"self",
".",
"_f",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"self",
".",
"_dbtype",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"self",
".",
"_dbcolumn",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"self",
".",
"_dbyear",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"self",
".",
"_dbmonth",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"self",
".",
"_dbday",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv4dbcount",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv4dbaddr",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv6dbcount",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv6dbaddr",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv4indexbaseaddr",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"self",
".",
"_ipv6indexbaseaddr",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"self",
".",
"_f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]"
] |
Opens a database file
|
[
"Opens",
"a",
"database",
"file"
] |
6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621
|
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L105-L121
|
train
|
chrislim2888/IP2Location-Python
|
IP2Location.py
|
IP2Location._parse_addr
|
def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
except:
ipv = 6
else:
ipv = 6
except:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
return ipv
|
python
|
def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
except:
ipv = 6
else:
ipv = 6
except:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
return ipv
|
[
"def",
"_parse_addr",
"(",
"self",
",",
"addr",
")",
":",
"ipv",
"=",
"0",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"addr",
")",
"# Convert ::FFFF:x.y.z.y to IPv4",
"if",
"addr",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'::ffff:'",
")",
":",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET",
",",
"addr",
")",
"ipv",
"=",
"4",
"except",
":",
"ipv",
"=",
"6",
"else",
":",
"ipv",
"=",
"6",
"except",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET",
",",
"addr",
")",
"ipv",
"=",
"4",
"return",
"ipv"
] |
Parses address and returns IP version. Raises exception on invalid argument
|
[
"Parses",
"address",
"and",
"returns",
"IP",
"version",
".",
"Raises",
"exception",
"on",
"invalid",
"argument"
] |
6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621
|
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L342-L359
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.rates_for_location
|
def rates_for_location(self, postal_code, location_deets=None):
"""Shows the sales tax rates for a given location."""
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request)
|
python
|
def rates_for_location(self, postal_code, location_deets=None):
"""Shows the sales tax rates for a given location."""
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request)
|
[
"def",
"rates_for_location",
"(",
"self",
",",
"postal_code",
",",
"location_deets",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"\"rates/\"",
"+",
"postal_code",
",",
"location_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Shows the sales tax rates for a given location.
|
[
"Shows",
"the",
"sales",
"tax",
"rates",
"for",
"a",
"given",
"location",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L31-L34
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.tax_for_order
|
def tax_for_order(self, order_deets):
"""Shows the sales tax that should be collected for a given order."""
request = self._post('taxes', order_deets)
return self.responder(request)
|
python
|
def tax_for_order(self, order_deets):
"""Shows the sales tax that should be collected for a given order."""
request = self._post('taxes', order_deets)
return self.responder(request)
|
[
"def",
"tax_for_order",
"(",
"self",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'taxes'",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Shows the sales tax that should be collected for a given order.
|
[
"Shows",
"the",
"sales",
"tax",
"that",
"should",
"be",
"collected",
"for",
"a",
"given",
"order",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L36-L39
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.list_orders
|
def list_orders(self, params=None):
"""Lists existing order transactions."""
request = self._get('transactions/orders', params)
return self.responder(request)
|
python
|
def list_orders(self, params=None):
"""Lists existing order transactions."""
request = self._get('transactions/orders', params)
return self.responder(request)
|
[
"def",
"list_orders",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/orders'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Lists existing order transactions.
|
[
"Lists",
"existing",
"order",
"transactions",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L41-L44
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.show_order
|
def show_order(self, order_id):
"""Shows an existing order transaction."""
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request)
|
python
|
def show_order(self, order_id):
"""Shows an existing order transaction."""
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request)
|
[
"def",
"show_order",
"(",
"self",
",",
"order_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/orders/'",
"+",
"str",
"(",
"order_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Shows an existing order transaction.
|
[
"Shows",
"an",
"existing",
"order",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L46-L49
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.create_order
|
def create_order(self, order_deets):
"""Creates a new order transaction."""
request = self._post('transactions/orders', order_deets)
return self.responder(request)
|
python
|
def create_order(self, order_deets):
"""Creates a new order transaction."""
request = self._post('transactions/orders', order_deets)
return self.responder(request)
|
[
"def",
"create_order",
"(",
"self",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'transactions/orders'",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Creates a new order transaction.
|
[
"Creates",
"a",
"new",
"order",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L51-L54
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.update_order
|
def update_order(self, order_id, order_deets):
"""Updates an existing order transaction."""
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request)
|
python
|
def update_order(self, order_id, order_deets):
"""Updates an existing order transaction."""
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request)
|
[
"def",
"update_order",
"(",
"self",
",",
"order_id",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"\"transactions/orders/\"",
"+",
"str",
"(",
"order_id",
")",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Updates an existing order transaction.
|
[
"Updates",
"an",
"existing",
"order",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L56-L59
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.delete_order
|
def delete_order(self, order_id):
"""Deletes an existing order transaction."""
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request)
|
python
|
def delete_order(self, order_id):
"""Deletes an existing order transaction."""
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request)
|
[
"def",
"delete_order",
"(",
"self",
",",
"order_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"\"transactions/orders/\"",
"+",
"str",
"(",
"order_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Deletes an existing order transaction.
|
[
"Deletes",
"an",
"existing",
"order",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L61-L64
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.list_refunds
|
def list_refunds(self, params=None):
"""Lists existing refund transactions."""
request = self._get('transactions/refunds', params)
return self.responder(request)
|
python
|
def list_refunds(self, params=None):
"""Lists existing refund transactions."""
request = self._get('transactions/refunds', params)
return self.responder(request)
|
[
"def",
"list_refunds",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/refunds'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Lists existing refund transactions.
|
[
"Lists",
"existing",
"refund",
"transactions",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L66-L69
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.show_refund
|
def show_refund(self, refund_id):
"""Shows an existing refund transaction."""
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request)
|
python
|
def show_refund(self, refund_id):
"""Shows an existing refund transaction."""
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request)
|
[
"def",
"show_refund",
"(",
"self",
",",
"refund_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Shows an existing refund transaction.
|
[
"Shows",
"an",
"existing",
"refund",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L71-L74
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.create_refund
|
def create_refund(self, refund_deets):
"""Creates a new refund transaction."""
request = self._post('transactions/refunds', refund_deets)
return self.responder(request)
|
python
|
def create_refund(self, refund_deets):
"""Creates a new refund transaction."""
request = self._post('transactions/refunds', refund_deets)
return self.responder(request)
|
[
"def",
"create_refund",
"(",
"self",
",",
"refund_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'transactions/refunds'",
",",
"refund_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Creates a new refund transaction.
|
[
"Creates",
"a",
"new",
"refund",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L76-L79
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.update_refund
|
def update_refund(self, refund_id, refund_deets):
"""Updates an existing refund transaction."""
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request)
|
python
|
def update_refund(self, refund_id, refund_deets):
"""Updates an existing refund transaction."""
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request)
|
[
"def",
"update_refund",
"(",
"self",
",",
"refund_id",
",",
"refund_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
",",
"refund_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Updates an existing refund transaction.
|
[
"Updates",
"an",
"existing",
"refund",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L81-L84
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.delete_refund
|
def delete_refund(self, refund_id):
"""Deletes an existing refund transaction."""
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request)
|
python
|
def delete_refund(self, refund_id):
"""Deletes an existing refund transaction."""
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request)
|
[
"def",
"delete_refund",
"(",
"self",
",",
"refund_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Deletes an existing refund transaction.
|
[
"Deletes",
"an",
"existing",
"refund",
"transaction",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L86-L89
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.list_customers
|
def list_customers(self, params=None):
"""Lists existing customers."""
request = self._get('customers', params)
return self.responder(request)
|
python
|
def list_customers(self, params=None):
"""Lists existing customers."""
request = self._get('customers', params)
return self.responder(request)
|
[
"def",
"list_customers",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'customers'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Lists existing customers.
|
[
"Lists",
"existing",
"customers",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L91-L94
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.show_customer
|
def show_customer(self, customer_id):
"""Shows an existing customer."""
request = self._get('customers/' + str(customer_id))
return self.responder(request)
|
python
|
def show_customer(self, customer_id):
"""Shows an existing customer."""
request = self._get('customers/' + str(customer_id))
return self.responder(request)
|
[
"def",
"show_customer",
"(",
"self",
",",
"customer_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'customers/'",
"+",
"str",
"(",
"customer_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Shows an existing customer.
|
[
"Shows",
"an",
"existing",
"customer",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L96-L99
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.create_customer
|
def create_customer(self, customer_deets):
"""Creates a new customer."""
request = self._post('customers', customer_deets)
return self.responder(request)
|
python
|
def create_customer(self, customer_deets):
"""Creates a new customer."""
request = self._post('customers', customer_deets)
return self.responder(request)
|
[
"def",
"create_customer",
"(",
"self",
",",
"customer_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'customers'",
",",
"customer_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Creates a new customer.
|
[
"Creates",
"a",
"new",
"customer",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L101-L104
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.update_customer
|
def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request)
|
python
|
def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request)
|
[
"def",
"update_customer",
"(",
"self",
",",
"customer_id",
",",
"customer_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"\"customers/\"",
"+",
"str",
"(",
"customer_id",
")",
",",
"customer_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Updates an existing customer.
|
[
"Updates",
"an",
"existing",
"customer",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L106-L109
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.delete_customer
|
def delete_customer(self, customer_id):
"""Deletes an existing customer."""
request = self._delete("customers/" + str(customer_id))
return self.responder(request)
|
python
|
def delete_customer(self, customer_id):
"""Deletes an existing customer."""
request = self._delete("customers/" + str(customer_id))
return self.responder(request)
|
[
"def",
"delete_customer",
"(",
"self",
",",
"customer_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"\"customers/\"",
"+",
"str",
"(",
"customer_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Deletes an existing customer.
|
[
"Deletes",
"an",
"existing",
"customer",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L111-L114
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.validate_address
|
def validate_address(self, address_deets):
"""Validates a customer address and returns back a collection of address matches."""
request = self._post('addresses/validate', address_deets)
return self.responder(request)
|
python
|
def validate_address(self, address_deets):
"""Validates a customer address and returns back a collection of address matches."""
request = self._post('addresses/validate', address_deets)
return self.responder(request)
|
[
"def",
"validate_address",
"(",
"self",
",",
"address_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'addresses/validate'",
",",
"address_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Validates a customer address and returns back a collection of address matches.
|
[
"Validates",
"a",
"customer",
"address",
"and",
"returns",
"back",
"a",
"collection",
"of",
"address",
"matches",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L121-L124
|
train
|
taxjar/taxjar-python
|
taxjar/client.py
|
Client.validate
|
def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request)
|
python
|
def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request)
|
[
"def",
"validate",
"(",
"self",
",",
"vat_deets",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'validation'",
",",
"vat_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] |
Validates an existing VAT identification number against VIES.
|
[
"Validates",
"an",
"existing",
"VAT",
"identification",
"number",
"against",
"VIES",
"."
] |
be9b30d7dc968d24e066c7c133849fee180f8d95
|
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L126-L129
|
train
|
last-partizan/pytils
|
pytils/templatetags/pytils_numeral.py
|
choose_plural
|
def choose_plural(amount, variants):
"""
Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"пример,примера,примеров" }}
"""
try:
if isinstance(variants, six.string_types):
uvariants = smart_text(variants, encoding)
else:
uvariants = [smart_text(v, encoding) for v in variants]
res = numeral.choose_plural(amount, uvariants)
except Exception as err:
# because filter must die silently
try:
default_variant = variants
except Exception:
default_variant = ""
res = default_value % {'error': err, 'value': default_variant}
return res
|
python
|
def choose_plural(amount, variants):
"""
Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"пример,примера,примеров" }}
"""
try:
if isinstance(variants, six.string_types):
uvariants = smart_text(variants, encoding)
else:
uvariants = [smart_text(v, encoding) for v in variants]
res = numeral.choose_plural(amount, uvariants)
except Exception as err:
# because filter must die silently
try:
default_variant = variants
except Exception:
default_variant = ""
res = default_value % {'error': err, 'value': default_variant}
return res
|
[
"def",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"variants",
",",
"six",
".",
"string_types",
")",
":",
"uvariants",
"=",
"smart_text",
"(",
"variants",
",",
"encoding",
")",
"else",
":",
"uvariants",
"=",
"[",
"smart_text",
"(",
"v",
",",
"encoding",
")",
"for",
"v",
"in",
"variants",
"]",
"res",
"=",
"numeral",
".",
"choose_plural",
"(",
"amount",
",",
"uvariants",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"try",
":",
"default_variant",
"=",
"variants",
"except",
"Exception",
":",
"default_variant",
"=",
"\"\"",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err",
",",
"'value'",
":",
"default_variant",
"}",
"return",
"res"
] |
Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"пример,примера,примеров" }}
|
[
"Choose",
"proper",
"form",
"for",
"plural",
"."
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L29-L54
|
train
|
last-partizan/pytils
|
pytils/templatetags/pytils_numeral.py
|
in_words
|
def in_words(amount, gender=None):
"""
In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }}
"""
try:
res = numeral.in_words(amount, getattr(numeral, str(gender), None))
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res
|
python
|
def in_words(amount, gender=None):
"""
In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }}
"""
try:
res = numeral.in_words(amount, getattr(numeral, str(gender), None))
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res
|
[
"def",
"in_words",
"(",
"amount",
",",
"gender",
"=",
"None",
")",
":",
"try",
":",
"res",
"=",
"numeral",
".",
"in_words",
"(",
"amount",
",",
"getattr",
"(",
"numeral",
",",
"str",
"(",
"gender",
")",
",",
"None",
")",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err",
",",
"'value'",
":",
"str",
"(",
"amount",
")",
"}",
"return",
"res"
] |
In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }}
|
[
"In",
"-",
"words",
"representation",
"of",
"amount",
"."
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L92-L107
|
train
|
last-partizan/pytils
|
pytils/templatetags/pytils_numeral.py
|
sum_string
|
def sum_string(amount, gender, items):
"""
in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
Examples::
{% sum_string some_int MALE "пример,примера,примеров" %}
{% sum_string some_other_int FEMALE "задача,задачи,задач" %}
"""
try:
if isinstance(items, six.string_types):
uitems = smart_text(items, encoding, default_uvalue)
else:
uitems = [smart_text(i, encoding) for i in items]
res = numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems)
except Exception as err:
# because tag's renderer must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res
|
python
|
def sum_string(amount, gender, items):
"""
in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
Examples::
{% sum_string some_int MALE "пример,примера,примеров" %}
{% sum_string some_other_int FEMALE "задача,задачи,задач" %}
"""
try:
if isinstance(items, six.string_types):
uitems = smart_text(items, encoding, default_uvalue)
else:
uitems = [smart_text(i, encoding) for i in items]
res = numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems)
except Exception as err:
# because tag's renderer must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res
|
[
"def",
"sum_string",
"(",
"amount",
",",
"gender",
",",
"items",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"items",
",",
"six",
".",
"string_types",
")",
":",
"uitems",
"=",
"smart_text",
"(",
"items",
",",
"encoding",
",",
"default_uvalue",
")",
"else",
":",
"uitems",
"=",
"[",
"smart_text",
"(",
"i",
",",
"encoding",
")",
"for",
"i",
"in",
"items",
"]",
"res",
"=",
"numeral",
".",
"sum_string",
"(",
"amount",
",",
"getattr",
"(",
"numeral",
",",
"str",
"(",
"gender",
")",
",",
"None",
")",
",",
"uitems",
")",
"except",
"Exception",
"as",
"err",
":",
"# because tag's renderer must die silently",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err",
",",
"'value'",
":",
"str",
"(",
"amount",
")",
"}",
"return",
"res"
] |
in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
Examples::
{% sum_string some_int MALE "пример,примера,примеров" %}
{% sum_string some_other_int FEMALE "задача,задачи,задач" %}
|
[
"in_words",
"and",
"choose_plural",
"in",
"a",
"one",
"flask",
"Makes",
"in",
"-",
"words",
"representation",
"of",
"value",
"with",
"choosing",
"correct",
"form",
"of",
"noun",
"."
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L118-L141
|
train
|
last-partizan/pytils
|
pytils/typo.py
|
rl_cleanspaces
|
def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака препинания, если только за ним нет другого
(r'([\.,?!\)]+)([^\.!,?\)]+)', r'\1 \2'),
# убираем пробел после открывающей скобки
(r'(\S+)\s*(\()\s*(\S+)', r'\1 (\3'),
)
# удаляем двойные, начальные и конечные пробелы
return os.linesep.join(
' '.join(part for part in line.split(' ') if part)
for line in _sub_patterns(patterns, x).split(os.linesep)
)
|
python
|
def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака препинания, если только за ним нет другого
(r'([\.,?!\)]+)([^\.!,?\)]+)', r'\1 \2'),
# убираем пробел после открывающей скобки
(r'(\S+)\s*(\()\s*(\S+)', r'\1 (\3'),
)
# удаляем двойные, начальные и конечные пробелы
return os.linesep.join(
' '.join(part for part in line.split(' ') if part)
for line in _sub_patterns(patterns, x).split(os.linesep)
)
|
[
"def",
"rl_cleanspaces",
"(",
"x",
")",
":",
"patterns",
"=",
"(",
"# arguments for re.sub: pattern and repl",
"# удаляем пробел перед знаками препинания",
"(",
"r' +([\\.,?!\\)]+)'",
",",
"r'\\1'",
")",
",",
"# добавляем пробел после знака препинания, если только за ним нет другого",
"(",
"r'([\\.,?!\\)]+)([^\\.!,?\\)]+)'",
",",
"r'\\1 \\2'",
")",
",",
"# убираем пробел после открывающей скобки",
"(",
"r'(\\S+)\\s*(\\()\\s*(\\S+)'",
",",
"r'\\1 (\\3'",
")",
",",
")",
"# удаляем двойные, начальные и конечные пробелы",
"return",
"os",
".",
"linesep",
".",
"join",
"(",
"' '",
".",
"join",
"(",
"part",
"for",
"part",
"in",
"line",
".",
"split",
"(",
"' '",
")",
"if",
"part",
")",
"for",
"line",
"in",
"_sub_patterns",
"(",
"patterns",
",",
"x",
")",
".",
"split",
"(",
"os",
".",
"linesep",
")",
")"
] |
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
|
[
"Clean",
"double",
"spaces",
"trailing",
"spaces",
"heading",
"spaces",
"spaces",
"before",
"punctuations"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L26-L44
|
train
|
last-partizan/pytils
|
pytils/typo.py
|
rl_quotes
|
def rl_quotes(x):
"""
Replace quotes by typographic quotes
"""
patterns = (
# открывающие кавычки ставятся обычно вплотную к слову слева
# а закрывающие -- вплотную справа
# открывающие русские кавычки-ёлочки
(re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab\\3'),
# закрывающие русские кавычки-ёлочки
(re.compile(r'(\S)(")((?u))', re.UNICODE), u'\\1\xbb\\3'),
# открывающие кавычки-лапки, вместо одинарных кавычек
(re.compile(r'((?:^|\s))(\')((?u))', re.UNICODE), u'\\1\u201c\\3'),
# закрывающие кавычки-лапки
(re.compile(r'(\S)(\')((?u))', re.UNICODE), u'\\1\u201d\\3'),
)
return _sub_patterns(patterns, x)
|
python
|
def rl_quotes(x):
"""
Replace quotes by typographic quotes
"""
patterns = (
# открывающие кавычки ставятся обычно вплотную к слову слева
# а закрывающие -- вплотную справа
# открывающие русские кавычки-ёлочки
(re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab\\3'),
# закрывающие русские кавычки-ёлочки
(re.compile(r'(\S)(")((?u))', re.UNICODE), u'\\1\xbb\\3'),
# открывающие кавычки-лапки, вместо одинарных кавычек
(re.compile(r'((?:^|\s))(\')((?u))', re.UNICODE), u'\\1\u201c\\3'),
# закрывающие кавычки-лапки
(re.compile(r'(\S)(\')((?u))', re.UNICODE), u'\\1\u201d\\3'),
)
return _sub_patterns(patterns, x)
|
[
"def",
"rl_quotes",
"(",
"x",
")",
":",
"patterns",
"=",
"(",
"# открывающие кавычки ставятся обычно вплотную к слову слева",
"# а закрывающие -- вплотную справа",
"# открывающие русские кавычки-ёлочки",
"(",
"re",
".",
"compile",
"(",
"r'((?:^|\\s))(\")((?u))'",
",",
"re",
".",
"UNICODE",
")",
",",
"u'\\\\1\\xab\\\\3'",
")",
",",
"# закрывающие русские кавычки-ёлочки",
"(",
"re",
".",
"compile",
"(",
"r'(\\S)(\")((?u))'",
",",
"re",
".",
"UNICODE",
")",
",",
"u'\\\\1\\xbb\\\\3'",
")",
",",
"# открывающие кавычки-лапки, вместо одинарных кавычек",
"(",
"re",
".",
"compile",
"(",
"r'((?:^|\\s))(\\')((?u))'",
",",
"re",
".",
"UNICODE",
")",
",",
"u'\\\\1\\u201c\\\\3'",
")",
",",
"# закрывающие кавычки-лапки",
"(",
"re",
".",
"compile",
"(",
"r'(\\S)(\\')((?u))'",
",",
"re",
".",
"UNICODE",
")",
",",
"u'\\\\1\\u201d\\\\3'",
")",
",",
")",
"return",
"_sub_patterns",
"(",
"patterns",
",",
"x",
")"
] |
Replace quotes by typographic quotes
|
[
"Replace",
"quotes",
"by",
"typographic",
"quotes"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L134-L151
|
train
|
last-partizan/pytils
|
pytils/templatetags/pytils_dt.py
|
distance_of_time
|
def distance_of_time(from_time, accuracy=1):
"""
Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_of_time }}
{{ some_dtime|distance_of_time:2 }}
"""
try:
to_time = None
if conf.settings.USE_TZ:
to_time=utils.timezone.now()
res = dt.distance_of_time_in_words(from_time, accuracy, to_time)
except Exception as err:
# because filter must die silently
try:
default_distance = "%s seconds" % str(int(time.time() - from_time))
except Exception:
default_distance = ""
res = default_value % {'error': err, 'value': default_distance}
return res
|
python
|
def distance_of_time(from_time, accuracy=1):
"""
Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_of_time }}
{{ some_dtime|distance_of_time:2 }}
"""
try:
to_time = None
if conf.settings.USE_TZ:
to_time=utils.timezone.now()
res = dt.distance_of_time_in_words(from_time, accuracy, to_time)
except Exception as err:
# because filter must die silently
try:
default_distance = "%s seconds" % str(int(time.time() - from_time))
except Exception:
default_distance = ""
res = default_value % {'error': err, 'value': default_distance}
return res
|
[
"def",
"distance_of_time",
"(",
"from_time",
",",
"accuracy",
"=",
"1",
")",
":",
"try",
":",
"to_time",
"=",
"None",
"if",
"conf",
".",
"settings",
".",
"USE_TZ",
":",
"to_time",
"=",
"utils",
".",
"timezone",
".",
"now",
"(",
")",
"res",
"=",
"dt",
".",
"distance_of_time_in_words",
"(",
"from_time",
",",
"accuracy",
",",
"to_time",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"try",
":",
"default_distance",
"=",
"\"%s seconds\"",
"%",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"from_time",
")",
")",
"except",
"Exception",
":",
"default_distance",
"=",
"\"\"",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err",
",",
"'value'",
":",
"default_distance",
"}",
"return",
"res"
] |
Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_of_time }}
{{ some_dtime|distance_of_time:2 }}
|
[
"Display",
"distance",
"of",
"time",
"from",
"current",
"time",
"."
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L20-L45
|
train
|
last-partizan/pytils
|
pytils/templatetags/pytils_dt.py
|
ru_strftime
|
def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False):
"""
Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strftime:
http://docs.python.org/lib/module-time.html
Examples::
{{ some_date|ru_strftime:"%d %B %Y, %A" }}
"""
try:
res = dt.ru_strftime(format,
date,
inflected=True,
inflected_day=inflected_day,
preposition=preposition)
except Exception as err:
# because filter must die silently
try:
default_date = date.strftime(format)
except Exception:
default_date = str(date)
res = default_value % {'error': err, 'value': default_date}
return res
|
python
|
def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False):
"""
Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strftime:
http://docs.python.org/lib/module-time.html
Examples::
{{ some_date|ru_strftime:"%d %B %Y, %A" }}
"""
try:
res = dt.ru_strftime(format,
date,
inflected=True,
inflected_day=inflected_day,
preposition=preposition)
except Exception as err:
# because filter must die silently
try:
default_date = date.strftime(format)
except Exception:
default_date = str(date)
res = default_value % {'error': err, 'value': default_date}
return res
|
[
"def",
"ru_strftime",
"(",
"date",
",",
"format",
"=",
"\"%d.%m.%Y\"",
",",
"inflected_day",
"=",
"False",
",",
"preposition",
"=",
"False",
")",
":",
"try",
":",
"res",
"=",
"dt",
".",
"ru_strftime",
"(",
"format",
",",
"date",
",",
"inflected",
"=",
"True",
",",
"inflected_day",
"=",
"inflected_day",
",",
"preposition",
"=",
"preposition",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"try",
":",
"default_date",
"=",
"date",
".",
"strftime",
"(",
"format",
")",
"except",
"Exception",
":",
"default_date",
"=",
"str",
"(",
"date",
")",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err",
",",
"'value'",
":",
"default_date",
"}",
"return",
"res"
] |
Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strftime:
http://docs.python.org/lib/module-time.html
Examples::
{{ some_date|ru_strftime:"%d %B %Y, %A" }}
|
[
"Russian",
"strftime",
"formats",
"date",
"with",
"given",
"format",
"."
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L47-L72
|
train
|
last-partizan/pytils
|
pytils/dt.py
|
ru_strftime
|
def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime.date} or C{datetime.datetime}
@param inflected: is month inflected, default False
@type inflected: C{bool}
@param inflected_day: is day inflected, default False
@type inflected: C{bool}
@param preposition: is preposition used, default False
preposition=True automatically implies inflected_day=True
@type preposition: C{bool}
@return: strftime string
@rtype: unicode
"""
if date is None:
date = datetime.datetime.today()
weekday = date.weekday()
prepos = preposition and DAY_NAMES[weekday][3] or u""
month_idx = inflected and 2 or 1
day_idx = (inflected_day or preposition) and 2 or 1
# for russian typography standard,
# 1 April 2007, but 01.04.2007
if u'%b' in format or u'%B' in format:
format = format.replace(u'%d', six.text_type(date.day))
format = format.replace(u'%a', prepos+DAY_NAMES[weekday][0])
format = format.replace(u'%A', prepos+DAY_NAMES[weekday][day_idx])
format = format.replace(u'%b', MONTH_NAMES[date.month-1][0])
format = format.replace(u'%B', MONTH_NAMES[date.month-1][month_idx])
# Python 2: strftime's argument must be str
# Python 3: strftime's argument str, not a bitestring
if six.PY2:
# strftime must be str, so encode it to utf8:
s_format = format.encode("utf-8")
s_res = date.strftime(s_format)
# and back to unicode
u_res = s_res.decode("utf-8")
else:
u_res = date.strftime(format)
return u_res
|
python
|
def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime.date} or C{datetime.datetime}
@param inflected: is month inflected, default False
@type inflected: C{bool}
@param inflected_day: is day inflected, default False
@type inflected: C{bool}
@param preposition: is preposition used, default False
preposition=True automatically implies inflected_day=True
@type preposition: C{bool}
@return: strftime string
@rtype: unicode
"""
if date is None:
date = datetime.datetime.today()
weekday = date.weekday()
prepos = preposition and DAY_NAMES[weekday][3] or u""
month_idx = inflected and 2 or 1
day_idx = (inflected_day or preposition) and 2 or 1
# for russian typography standard,
# 1 April 2007, but 01.04.2007
if u'%b' in format or u'%B' in format:
format = format.replace(u'%d', six.text_type(date.day))
format = format.replace(u'%a', prepos+DAY_NAMES[weekday][0])
format = format.replace(u'%A', prepos+DAY_NAMES[weekday][day_idx])
format = format.replace(u'%b', MONTH_NAMES[date.month-1][0])
format = format.replace(u'%B', MONTH_NAMES[date.month-1][month_idx])
# Python 2: strftime's argument must be str
# Python 3: strftime's argument str, not a bitestring
if six.PY2:
# strftime must be str, so encode it to utf8:
s_format = format.encode("utf-8")
s_res = date.strftime(s_format)
# and back to unicode
u_res = s_res.decode("utf-8")
else:
u_res = date.strftime(format)
return u_res
|
[
"def",
"ru_strftime",
"(",
"format",
"=",
"u\"%d.%m.%Y\"",
",",
"date",
"=",
"None",
",",
"inflected",
"=",
"False",
",",
"inflected_day",
"=",
"False",
",",
"preposition",
"=",
"False",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"weekday",
"=",
"date",
".",
"weekday",
"(",
")",
"prepos",
"=",
"preposition",
"and",
"DAY_NAMES",
"[",
"weekday",
"]",
"[",
"3",
"]",
"or",
"u\"\"",
"month_idx",
"=",
"inflected",
"and",
"2",
"or",
"1",
"day_idx",
"=",
"(",
"inflected_day",
"or",
"preposition",
")",
"and",
"2",
"or",
"1",
"# for russian typography standard,",
"# 1 April 2007, but 01.04.2007",
"if",
"u'%b'",
"in",
"format",
"or",
"u'%B'",
"in",
"format",
":",
"format",
"=",
"format",
".",
"replace",
"(",
"u'%d'",
",",
"six",
".",
"text_type",
"(",
"date",
".",
"day",
")",
")",
"format",
"=",
"format",
".",
"replace",
"(",
"u'%a'",
",",
"prepos",
"+",
"DAY_NAMES",
"[",
"weekday",
"]",
"[",
"0",
"]",
")",
"format",
"=",
"format",
".",
"replace",
"(",
"u'%A'",
",",
"prepos",
"+",
"DAY_NAMES",
"[",
"weekday",
"]",
"[",
"day_idx",
"]",
")",
"format",
"=",
"format",
".",
"replace",
"(",
"u'%b'",
",",
"MONTH_NAMES",
"[",
"date",
".",
"month",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"format",
"=",
"format",
".",
"replace",
"(",
"u'%B'",
",",
"MONTH_NAMES",
"[",
"date",
".",
"month",
"-",
"1",
"]",
"[",
"month_idx",
"]",
")",
"# Python 2: strftime's argument must be str",
"# Python 3: strftime's argument str, not a bitestring",
"if",
"six",
".",
"PY2",
":",
"# strftime must be str, so encode it to utf8:",
"s_format",
"=",
"format",
".",
"encode",
"(",
"\"utf-8\"",
")",
"s_res",
"=",
"date",
".",
"strftime",
"(",
"s_format",
")",
"# and back to unicode",
"u_res",
"=",
"s_res",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"u_res",
"=",
"date",
".",
"strftime",
"(",
"format",
")",
"return",
"u_res"
] |
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime.date} or C{datetime.datetime}
@param inflected: is month inflected, default False
@type inflected: C{bool}
@param inflected_day: is day inflected, default False
@type inflected: C{bool}
@param preposition: is preposition used, default False
preposition=True automatically implies inflected_day=True
@type preposition: C{bool}
@return: strftime string
@rtype: unicode
|
[
"Russian",
"strftime",
"without",
"locale"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/dt.py#L179-L233
|
train
|
last-partizan/pytils
|
pytils/numeral.py
|
_get_float_remainder
|
def _get_float_remainder(fvalue, signs=9):
"""
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: signs overflow
"""
check_positive(fvalue)
if isinstance(fvalue, six.integer_types):
return "0"
if isinstance(fvalue, Decimal) and fvalue.as_tuple()[2] == 0:
# Decimal.as_tuple() -> (sign, digit_tuple, exponent)
# если экспонента "0" -- значит дробной части нет
return "0"
signs = min(signs, len(FRACTIONS))
# нужно remainder в строке, потому что дробные X.0Y
# будут "ломаться" до X.Y
remainder = str(fvalue).split('.')[1]
iremainder = int(remainder)
orig_remainder = remainder
factor = len(str(remainder)) - signs
if factor > 0:
# после запятой цифр больше чем signs, округляем
iremainder = int(round(iremainder / (10.0**factor)))
format = "%%0%dd" % min(len(remainder), signs)
remainder = format % iremainder
if len(remainder) > signs:
# при округлении цифр вида 0.998 ругаться
raise ValueError("Signs overflow: I can't round only fractional part \
of %s to fit %s in %d signs" % \
(str(fvalue), orig_remainder, signs))
return remainder
|
python
|
def _get_float_remainder(fvalue, signs=9):
"""
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: signs overflow
"""
check_positive(fvalue)
if isinstance(fvalue, six.integer_types):
return "0"
if isinstance(fvalue, Decimal) and fvalue.as_tuple()[2] == 0:
# Decimal.as_tuple() -> (sign, digit_tuple, exponent)
# если экспонента "0" -- значит дробной части нет
return "0"
signs = min(signs, len(FRACTIONS))
# нужно remainder в строке, потому что дробные X.0Y
# будут "ломаться" до X.Y
remainder = str(fvalue).split('.')[1]
iremainder = int(remainder)
orig_remainder = remainder
factor = len(str(remainder)) - signs
if factor > 0:
# после запятой цифр больше чем signs, округляем
iremainder = int(round(iremainder / (10.0**factor)))
format = "%%0%dd" % min(len(remainder), signs)
remainder = format % iremainder
if len(remainder) > signs:
# при округлении цифр вида 0.998 ругаться
raise ValueError("Signs overflow: I can't round only fractional part \
of %s to fit %s in %d signs" % \
(str(fvalue), orig_remainder, signs))
return remainder
|
[
"def",
"_get_float_remainder",
"(",
"fvalue",
",",
"signs",
"=",
"9",
")",
":",
"check_positive",
"(",
"fvalue",
")",
"if",
"isinstance",
"(",
"fvalue",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"\"0\"",
"if",
"isinstance",
"(",
"fvalue",
",",
"Decimal",
")",
"and",
"fvalue",
".",
"as_tuple",
"(",
")",
"[",
"2",
"]",
"==",
"0",
":",
"# Decimal.as_tuple() -> (sign, digit_tuple, exponent)",
"# если экспонента \"0\" -- значит дробной части нет",
"return",
"\"0\"",
"signs",
"=",
"min",
"(",
"signs",
",",
"len",
"(",
"FRACTIONS",
")",
")",
"# нужно remainder в строке, потому что дробные X.0Y",
"# будут \"ломаться\" до X.Y",
"remainder",
"=",
"str",
"(",
"fvalue",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"iremainder",
"=",
"int",
"(",
"remainder",
")",
"orig_remainder",
"=",
"remainder",
"factor",
"=",
"len",
"(",
"str",
"(",
"remainder",
")",
")",
"-",
"signs",
"if",
"factor",
">",
"0",
":",
"# после запятой цифр больше чем signs, округляем",
"iremainder",
"=",
"int",
"(",
"round",
"(",
"iremainder",
"/",
"(",
"10.0",
"**",
"factor",
")",
")",
")",
"format",
"=",
"\"%%0%dd\"",
"%",
"min",
"(",
"len",
"(",
"remainder",
")",
",",
"signs",
")",
"remainder",
"=",
"format",
"%",
"iremainder",
"if",
"len",
"(",
"remainder",
")",
">",
"signs",
":",
"# при округлении цифр вида 0.998 ругаться",
"raise",
"ValueError",
"(",
"\"Signs overflow: I can't round only fractional part \\\n of %s to fit %s in %d signs\"",
"%",
"(",
"str",
"(",
"fvalue",
")",
",",
"orig_remainder",
",",
"signs",
")",
")",
"return",
"remainder"
] |
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: signs overflow
|
[
"Get",
"remainder",
"of",
"float",
"i",
".",
"e",
".",
"2",
".",
"05",
"-",
">",
"05"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L77-L123
|
train
|
last-partizan/pytils
|
pytils/numeral.py
|
choose_plural
|
def choose_plural(amount, variants):
"""
Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@return: proper variant
@rtype: C{unicode}
@raise ValueError: variants' length lesser than 3
"""
if isinstance(variants, six.text_type):
variants = split_values(variants)
check_length(variants, 3)
amount = abs(amount)
if amount % 10 == 1 and amount % 100 != 11:
variant = 0
elif amount % 10 >= 2 and amount % 10 <= 4 and \
(amount % 100 < 10 or amount % 100 >= 20):
variant = 1
else:
variant = 2
return variants[variant]
|
python
|
def choose_plural(amount, variants):
"""
Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@return: proper variant
@rtype: C{unicode}
@raise ValueError: variants' length lesser than 3
"""
if isinstance(variants, six.text_type):
variants = split_values(variants)
check_length(variants, 3)
amount = abs(amount)
if amount % 10 == 1 and amount % 100 != 11:
variant = 0
elif amount % 10 >= 2 and amount % 10 <= 4 and \
(amount % 100 < 10 or amount % 100 >= 20):
variant = 1
else:
variant = 2
return variants[variant]
|
[
"def",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
":",
"if",
"isinstance",
"(",
"variants",
",",
"six",
".",
"text_type",
")",
":",
"variants",
"=",
"split_values",
"(",
"variants",
")",
"check_length",
"(",
"variants",
",",
"3",
")",
"amount",
"=",
"abs",
"(",
"amount",
")",
"if",
"amount",
"%",
"10",
"==",
"1",
"and",
"amount",
"%",
"100",
"!=",
"11",
":",
"variant",
"=",
"0",
"elif",
"amount",
"%",
"10",
">=",
"2",
"and",
"amount",
"%",
"10",
"<=",
"4",
"and",
"(",
"amount",
"%",
"100",
"<",
"10",
"or",
"amount",
"%",
"100",
">=",
"20",
")",
":",
"variant",
"=",
"1",
"else",
":",
"variant",
"=",
"2",
"return",
"variants",
"[",
"variant",
"]"
] |
Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@return: proper variant
@rtype: C{unicode}
@raise ValueError: variants' length lesser than 3
|
[
"Choose",
"proper",
"case",
"depending",
"on",
"amount"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L126-L157
|
train
|
last-partizan/pytils
|
pytils/numeral.py
|
get_plural
|
def get_plural(amount, variants, absence=None):
"""
Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@param absence: if amount is zero will return it
@type absence: C{unicode}
@return: amount with proper variant
@rtype: C{unicode}
"""
if amount or absence is None:
return u"%d %s" % (amount, choose_plural(amount, variants))
else:
return absence
|
python
|
def get_plural(amount, variants, absence=None):
"""
Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@param absence: if amount is zero will return it
@type absence: C{unicode}
@return: amount with proper variant
@rtype: C{unicode}
"""
if amount or absence is None:
return u"%d %s" % (amount, choose_plural(amount, variants))
else:
return absence
|
[
"def",
"get_plural",
"(",
"amount",
",",
"variants",
",",
"absence",
"=",
"None",
")",
":",
"if",
"amount",
"or",
"absence",
"is",
"None",
":",
"return",
"u\"%d %s\"",
"%",
"(",
"amount",
",",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
")",
"else",
":",
"return",
"absence"
] |
Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@param absence: if amount is zero will return it
@type absence: C{unicode}
@return: amount with proper variant
@rtype: C{unicode}
|
[
"Get",
"proper",
"case",
"with",
"value"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L160-L181
|
train
|
last-partizan/pytils
|
pytils/numeral.py
|
in_words
|
def in_words(amount, gender=None):
"""
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError: when amount is negative
"""
check_positive(amount)
if isinstance(amount, Decimal) and amount.as_tuple()[2] == 0:
# если целое,
# т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0
# то как целое
amount = int(amount)
if gender is None:
args = (amount,)
else:
args = (amount, gender)
# если целое
if isinstance(amount, six.integer_types):
return in_words_int(*args)
# если дробное
elif isinstance(amount, (float, Decimal)):
return in_words_float(*args)
# ни float, ни int, ни Decimal
else:
# до сюда не должно дойти
raise TypeError(
"amount should be number type (int, long, float, Decimal), got %s"
% type(amount))
|
python
|
def in_words(amount, gender=None):
"""
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError: when amount is negative
"""
check_positive(amount)
if isinstance(amount, Decimal) and amount.as_tuple()[2] == 0:
# если целое,
# т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0
# то как целое
amount = int(amount)
if gender is None:
args = (amount,)
else:
args = (amount, gender)
# если целое
if isinstance(amount, six.integer_types):
return in_words_int(*args)
# если дробное
elif isinstance(amount, (float, Decimal)):
return in_words_float(*args)
# ни float, ни int, ни Decimal
else:
# до сюда не должно дойти
raise TypeError(
"amount should be number type (int, long, float, Decimal), got %s"
% type(amount))
|
[
"def",
"in_words",
"(",
"amount",
",",
"gender",
"=",
"None",
")",
":",
"check_positive",
"(",
"amount",
")",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
"and",
"amount",
".",
"as_tuple",
"(",
")",
"[",
"2",
"]",
"==",
"0",
":",
"# если целое,",
"# т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0",
"# то как целое",
"amount",
"=",
"int",
"(",
"amount",
")",
"if",
"gender",
"is",
"None",
":",
"args",
"=",
"(",
"amount",
",",
")",
"else",
":",
"args",
"=",
"(",
"amount",
",",
"gender",
")",
"# если целое",
"if",
"isinstance",
"(",
"amount",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"in_words_int",
"(",
"*",
"args",
")",
"# если дробное",
"elif",
"isinstance",
"(",
"amount",
",",
"(",
"float",
",",
"Decimal",
")",
")",
":",
"return",
"in_words_float",
"(",
"*",
"args",
")",
"# ни float, ни int, ни Decimal",
"else",
":",
"# до сюда не должно дойти",
"raise",
"TypeError",
"(",
"\"amount should be number type (int, long, float, Decimal), got %s\"",
"%",
"type",
"(",
"amount",
")",
")"
] |
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError: when amount is negative
|
[
"Numeral",
"in",
"words"
] |
1c570a32b15e564bc68587b8207e32d464e61d08
|
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L289-L325
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.