partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
Collection.add_device
|
Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint.
:param device_id: ID of the Device being added to Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/collections.py
|
def add_device(self, device_id):
""" Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint.
:param device_id: ID of the Device being added to Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
path = self.subpath('/devices/{device_id}'.format(device_id=device_id))
return self.api.put(path)
|
def add_device(self, device_id):
""" Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint.
:param device_id: ID of the Device being added to Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
path = self.subpath('/devices/{device_id}'.format(device_id=device_id))
return self.api.put(path)
|
[
"Method",
"for",
"Add",
"device",
"to",
"collection",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"collections#Add",
"-",
"device",
"-",
"to",
"-",
"collection",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/collections.py#L28-L37
|
[
"def",
"add_device",
"(",
"self",
",",
"device_id",
")",
":",
"path",
"=",
"self",
".",
"subpath",
"(",
"'/devices/{device_id}'",
".",
"format",
"(",
"device_id",
"=",
"device_id",
")",
")",
"return",
"self",
".",
"api",
".",
"put",
"(",
"path",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Collection.remove_device
|
Method for `Remove device from collection <https://m2x.att.com/developer/documentation/v2/collections#Remove-device-from-collection>`_ endpoint.
:param device_id: ID of the Device being removed from Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/collections.py
|
def remove_device(self, device_id):
""" Method for `Remove device from collection <https://m2x.att.com/developer/documentation/v2/collections#Remove-device-from-collection>`_ endpoint.
:param device_id: ID of the Device being removed from Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
path = self.subpath('/devices/{device_id}'.format(device_id=device_id))
return self.api.delete(path)
|
def remove_device(self, device_id):
""" Method for `Remove device from collection <https://m2x.att.com/developer/documentation/v2/collections#Remove-device-from-collection>`_ endpoint.
:param device_id: ID of the Device being removed from Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
path = self.subpath('/devices/{device_id}'.format(device_id=device_id))
return self.api.delete(path)
|
[
"Method",
"for",
"Remove",
"device",
"from",
"collection",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"collections#Remove",
"-",
"device",
"-",
"from",
"-",
"collection",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/collections.py#L39-L48
|
[
"def",
"remove_device",
"(",
"self",
",",
"device_id",
")",
":",
"path",
"=",
"self",
".",
"subpath",
"(",
"'/devices/{device_id}'",
".",
"format",
"(",
"device_id",
"=",
"device_id",
")",
")",
"return",
"self",
".",
"api",
".",
"delete",
"(",
"path",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.create_stream
|
Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be created
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Stream
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def create_stream(self, name, **params):
""" Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be created
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Stream
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Stream.create(self.api, self, name, **params)
|
def create_stream(self, name, **params):
""" Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be created
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Stream
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Stream.create(self.api, self, name, **params)
|
[
"Method",
"for",
"Create",
"/",
"Update",
"Data",
"Stream",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Create",
"-",
"Update",
"-",
"Data",
"-",
"Stream",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L37-L48
|
[
"def",
"create_stream",
"(",
"self",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"return",
"Stream",
".",
"create",
"(",
"self",
".",
"api",
",",
"self",
",",
"name",
",",
"*",
"*",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.update_stream
|
Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be updated
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def update_stream(self, name, **params):
""" Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be updated
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Stream.item_update(self.api, self, name, **params)
|
def update_stream(self, name, **params):
""" Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param name: Name of the stream to be updated
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Stream.item_update(self.api, self, name, **params)
|
[
"Method",
"for",
"Create",
"/",
"Update",
"Data",
"Stream",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Create",
"-",
"Update",
"-",
"Data",
"-",
"Stream",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L50-L61
|
[
"def",
"update_stream",
"(",
"self",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"return",
"Stream",
".",
"item_update",
"(",
"self",
".",
"api",
",",
"self",
",",
"name",
",",
"*",
"*",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.create_key
|
Create an API Key for this Device via the `Create Key <https://m2x.att.com/developer/documentation/v2/keys#Create-Key>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Key
:rtype: Key
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def create_key(self, **params):
""" Create an API Key for this Device via the `Create Key <https://m2x.att.com/developer/documentation/v2/keys#Create-Key>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Key
:rtype: Key
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Key.create(self.api, device=self.id, **params)
|
def create_key(self, **params):
""" Create an API Key for this Device via the `Create Key <https://m2x.att.com/developer/documentation/v2/keys#Create-Key>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The newly created Key
:rtype: Key
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return Key.create(self.api, device=self.id, **params)
|
[
"Create",
"an",
"API",
"Key",
"for",
"this",
"Device",
"via",
"the",
"Create",
"Key",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"keys#Create",
"-",
"Key",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L74-L84
|
[
"def",
"create_key",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"Key",
".",
"create",
"(",
"self",
".",
"api",
",",
"device",
"=",
"self",
".",
"id",
",",
"*",
"*",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.location
|
Method for `Read Device Location <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location>`_ endpoint.
:return: Most recently logged location of the Device, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def location(self):
""" Method for `Read Device Location <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location>`_ endpoint.
:return: Most recently logged location of the Device, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.data.get('location') or \
self.api.get(self.subpath('/location')) or {}
|
def location(self):
""" Method for `Read Device Location <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location>`_ endpoint.
:return: Most recently logged location of the Device, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.data.get('location') or \
self.api.get(self.subpath('/location')) or {}
|
[
"Method",
"for",
"Read",
"Device",
"Location",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Read",
"-",
"Device",
"-",
"Location",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L86-L95
|
[
"def",
"location",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'location'",
")",
"or",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/location'",
")",
")",
"or",
"{",
"}"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.location_history
|
Method for `Read Device Location History <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location-History>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: Location history of the Device
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def location_history(self, **params):
""" Method for `Read Device Location History <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location-History>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: Location history of the Device
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/location/waypoints'), params=params)
|
def location_history(self, **params):
""" Method for `Read Device Location History <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location-History>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: Location history of the Device
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/location/waypoints'), params=params)
|
[
"Method",
"for",
"Read",
"Device",
"Location",
"History",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Read",
"-",
"Device",
"-",
"Location",
"-",
"History",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L97-L107
|
[
"def",
"location_history",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/location/waypoints'",
")",
",",
"params",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.update_location
|
Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def update_location(self, **params):
""" Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.subpath('/location'), data=params)
|
def update_location(self, **params):
""" Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.subpath('/location'), data=params)
|
[
"Method",
"for",
"Update",
"Device",
"Location",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Update",
"-",
"Device",
"-",
"Location",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L109-L119
|
[
"def",
"update_location",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"put",
"(",
"self",
".",
"subpath",
"(",
"'/location'",
")",
",",
"data",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.post_updates
|
Method for `Post Device Updates (Multiple Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Updates--Multiple-Values-to-Multiple-Streams->`_ endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def post_updates(self, **values):
""" Method for `Post Device Updates (Multiple Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Updates--Multiple-Values-to-Multiple-Streams->`_ endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/updates'), data=values)
|
def post_updates(self, **values):
""" Method for `Post Device Updates (Multiple Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Updates--Multiple-Values-to-Multiple-Streams->`_ endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/updates'), data=values)
|
[
"Method",
"for",
"Post",
"Device",
"Updates",
"(",
"Multiple",
"Values",
"to",
"Multiple",
"Streams",
")",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Post",
"-",
"Device",
"-",
"Updates",
"--",
"Multiple",
"-",
"Values",
"-",
"to",
"-",
"Multiple",
"-",
"Streams",
"-",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L143-L154
|
[
"def",
"post_updates",
"(",
"self",
",",
"*",
"*",
"values",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/updates'",
")",
",",
"data",
"=",
"values",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.post_update
|
Method for `Post Device Update (Single Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Update--Single-Values-to-Multiple-Streams->` endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def post_update(self, **values):
""" Method for `Post Device Update (Single Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Update--Single-Values-to-Multiple-Streams->` endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/update'), data=values)
|
def post_update(self, **values):
""" Method for `Post Device Update (Single Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Update--Single-Values-to-Multiple-Streams->` endpoint.
:param values: The values being posted, formatted according to the API docs
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/update'), data=values)
|
[
"Method",
"for",
"Post",
"Device",
"Update",
"(",
"Single",
"Values",
"to",
"Multiple",
"Streams",
")",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Post",
"-",
"Device",
"-",
"Update",
"--",
"Single",
"-",
"Values",
"-",
"to",
"-",
"Multiple",
"-",
"Streams",
"-",
">",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L156-L167
|
[
"def",
"post_update",
"(",
"self",
",",
"*",
"*",
"values",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/update'",
")",
",",
"data",
"=",
"values",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.values
|
Method for `List Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#List-Data-Stream-Values>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def values(self, **params):
""" Method for `List Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#List-Data-Stream-Values>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/values'), params=params)
|
def values(self, **params):
""" Method for `List Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#List-Data-Stream-Values>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/values'), params=params)
|
[
"Method",
"for",
"List",
"Data",
"Stream",
"Values",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#List",
"-",
"Data",
"-",
"Stream",
"-",
"Values",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L169-L179
|
[
"def",
"values",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/values'",
")",
",",
"params",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.values_export
|
Method for `Export Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Export-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def values_export(self, **params):
""" Method for `Export Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Export-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.api.get(self.subpath('/values/export.csv'), params=params)
return self.api.last_response
|
def values_export(self, **params):
""" Method for `Export Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Export-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.api.get(self.subpath('/values/export.csv'), params=params)
return self.api.last_response
|
[
"Method",
"for",
"Export",
"Values",
"from",
"all",
"Data",
"Streams",
"of",
"a",
"Device",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Export",
"-",
"Values",
"-",
"from",
"-",
"all",
"-",
"Data",
"-",
"Streams",
"-",
"of",
"-",
"a",
"-",
"Device",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L181-L192
|
[
"def",
"values_export",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/values/export.csv'",
")",
",",
"params",
"=",
"params",
")",
"return",
"self",
".",
"api",
".",
"last_response"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.values_search
|
Method for `Search Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Search-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def values_search(self, **params):
""" Method for `Search Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Search-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/values/search'), data=params)
|
def values_search(self, **params):
""" Method for `Search Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Search-Values-from-all-Data-Streams-of-a-Device>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/values/search'), data=params)
|
[
"Method",
"for",
"Search",
"Values",
"from",
"all",
"Data",
"Streams",
"of",
"a",
"Device",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Search",
"-",
"Values",
"-",
"from",
"-",
"all",
"-",
"Data",
"-",
"Streams",
"-",
"of",
"-",
"a",
"-",
"Device",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L194-L204
|
[
"def",
"values_search",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/values/search'",
")",
",",
"data",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.commands
|
Method for `Device's List of Received Commands <https://m2x.att.com/developer/documentation/v2/commands#Device-s-List-of-Received-Commands>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def commands(self, **params):
""" Method for `Device's List of Received Commands <https://m2x.att.com/developer/documentation/v2/commands#Device-s-List-of-Received-Commands>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/commands'), params=params)
|
def commands(self, **params):
""" Method for `Device's List of Received Commands <https://m2x.att.com/developer/documentation/v2/commands#Device-s-List-of-Received-Commands>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/commands'), params=params)
|
[
"Method",
"for",
"Device",
"s",
"List",
"of",
"Received",
"Commands",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"commands#Device",
"-",
"s",
"-",
"List",
"-",
"of",
"-",
"Received",
"-",
"Commands",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L206-L216
|
[
"def",
"commands",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/commands'",
")",
",",
"params",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.process_command
|
Method for `Device Marks a Command as Processed <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Processed>`_ endpoint.
:param id: ID of the Command being marked as processed
:param params: Optional data to be associated with the processed command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def process_command(self, id, **params):
""" Method for `Device Marks a Command as Processed <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Processed>`_ endpoint.
:param id: ID of the Command being marked as processed
:param params: Optional data to be associated with the processed command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/commands/%s/process' % id), data=params)
|
def process_command(self, id, **params):
""" Method for `Device Marks a Command as Processed <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Processed>`_ endpoint.
:param id: ID of the Command being marked as processed
:param params: Optional data to be associated with the processed command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/commands/%s/process' % id), data=params)
|
[
"Method",
"for",
"Device",
"Marks",
"a",
"Command",
"as",
"Processed",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"commands#Device",
"-",
"Marks",
"-",
"a",
"-",
"Command",
"-",
"as",
"-",
"Processed",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L230-L241
|
[
"def",
"process_command",
"(",
"self",
",",
"id",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/commands/%s/process'",
"%",
"id",
")",
",",
"data",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Device.reject_command
|
Method for `Device Marks a Command as Rejected <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Rejected>`_ endpoint.
:param id: ID of the Command being marked as rejected
:param params: Optional data to be associated with the rejected command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/devices.py
|
def reject_command(self, id, **params):
""" Method for `Device Marks a Command as Rejected <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Rejected>`_ endpoint.
:param id: ID of the Command being marked as rejected
:param params: Optional data to be associated with the rejected command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/commands/%s/reject' % id), data=params)
|
def reject_command(self, id, **params):
""" Method for `Device Marks a Command as Rejected <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Rejected>`_ endpoint.
:param id: ID of the Command being marked as rejected
:param params: Optional data to be associated with the rejected command, see API docs for details
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/commands/%s/reject' % id), data=params)
|
[
"Method",
"for",
"Device",
"Marks",
"a",
"Command",
"as",
"Rejected",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"commands#Device",
"-",
"Marks",
"-",
"a",
"-",
"Command",
"-",
"as",
"-",
"Rejected",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L243-L254
|
[
"def",
"reject_command",
"(",
"self",
",",
"id",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/commands/%s/reject'",
"%",
"id",
")",
",",
"data",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Metadata.update_metadata
|
Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>`_
* `Update Collection Metadata <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata>`_
:param params: The metadata being updated
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/metadata.py
|
def update_metadata(self, params):
""" Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>`_
* `Update Collection Metadata <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata>`_
:param params: The metadata being updated
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.metadata_path(), data=params)
|
def update_metadata(self, params):
""" Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>`_
* `Update Collection Metadata <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata>`_
:param params: The metadata being updated
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.metadata_path(), data=params)
|
[
"Generic",
"method",
"for",
"a",
"resource",
"s",
"Update",
"Metadata",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/metadata.py#L39-L55
|
[
"def",
"update_metadata",
"(",
"self",
",",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"put",
"(",
"self",
".",
"metadata_path",
"(",
")",
",",
"data",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Metadata.update_metadata_field
|
Generic method for a resource's Update Metadata Field endpoint.
Example endpoints:
* `Update Device Metadata Field <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata-Field>`_
* `Update Distribution Metadata Field <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata-Field>`_
* `Update Collection Metadata Field <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata-Field>`_
:param field: The metadata field to be updated
:param value: The value to update
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/metadata.py
|
def update_metadata_field(self, field, value):
""" Generic method for a resource's Update Metadata Field endpoint.
Example endpoints:
* `Update Device Metadata Field <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata-Field>`_
* `Update Distribution Metadata Field <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata-Field>`_
* `Update Collection Metadata Field <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata-Field>`_
:param field: The metadata field to be updated
:param value: The value to update
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.metadata_field_path(field), data={ "value": value })
|
def update_metadata_field(self, field, value):
""" Generic method for a resource's Update Metadata Field endpoint.
Example endpoints:
* `Update Device Metadata Field <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata-Field>`_
* `Update Distribution Metadata Field <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata-Field>`_
* `Update Collection Metadata Field <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata-Field>`_
:param field: The metadata field to be updated
:param value: The value to update
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.put(self.metadata_field_path(field), data={ "value": value })
|
[
"Generic",
"method",
"for",
"a",
"resource",
"s",
"Update",
"Metadata",
"Field",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/metadata.py#L57-L74
|
[
"def",
"update_metadata_field",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"return",
"self",
".",
"api",
".",
"put",
"(",
"self",
".",
"metadata_field_path",
"(",
"field",
")",
",",
"data",
"=",
"{",
"\"value\"",
":",
"value",
"}",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Resource.update
|
Generic method for a resource's Update endpoint.
Example endpoints:
* `Update Device Details <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Details>`_
* `Update Distribution Details <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Details>`_
* `Update Collection Details <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Details>`_
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/resource.py
|
def update(self, **attrs):
""" Generic method for a resource's Update endpoint.
Example endpoints:
* `Update Device Details <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Details>`_
* `Update Distribution Details <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Details>`_
* `Update Collection Details <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Details>`_
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.data.update(self.item_update(self.api, self.id, **attrs))
return self.data
|
def update(self, **attrs):
""" Generic method for a resource's Update endpoint.
Example endpoints:
* `Update Device Details <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Details>`_
* `Update Distribution Details <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Details>`_
* `Update Collection Details <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Details>`_
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.data.update(self.item_update(self.api, self.id, **attrs))
return self.data
|
[
"Generic",
"method",
"for",
"a",
"resource",
"s",
"Update",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/resource.py#L17-L34
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"self",
".",
"data",
".",
"update",
"(",
"self",
".",
"item_update",
"(",
"self",
".",
"api",
",",
"self",
".",
"id",
",",
"*",
"*",
"attrs",
")",
")",
"return",
"self",
".",
"data"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.update
|
Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def update(self, **attrs):
""" Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.data.update(self.item_update(self.api, self.device, self.name, **attrs))
return self.data
|
def update(self, **attrs):
""" Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being updated
:rtype: Stream
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
self.data.update(self.item_update(self.api, self.device, self.name, **attrs))
return self.data
|
[
"Method",
"for",
"Update",
"Data",
"Stream",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Create",
"-",
"Update",
"-",
"Data",
"-",
"Stream",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L15-L26
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"self",
".",
"data",
".",
"update",
"(",
"self",
".",
"item_update",
"(",
"self",
".",
"api",
",",
"self",
".",
"device",
",",
"self",
".",
"name",
",",
"*",
"*",
"attrs",
")",
")",
"return",
"self",
".",
"data"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.sampling
|
Method for `Data Stream Sampling <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Sampling>`_ endpoint.
:param interval: the sampling interval, see API docs for supported interval types
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def sampling(self, interval, **params):
""" Method for `Data Stream Sampling <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Sampling>`_ endpoint.
:param interval: the sampling interval, see API docs for supported interval types
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
params['interval'] = interval
return self.api.get(self.subpath('/sampling'), params=params)
|
def sampling(self, interval, **params):
""" Method for `Data Stream Sampling <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Sampling>`_ endpoint.
:param interval: the sampling interval, see API docs for supported interval types
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
params['interval'] = interval
return self.api.get(self.subpath('/sampling'), params=params)
|
[
"Method",
"for",
"Data",
"Stream",
"Sampling",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Data",
"-",
"Stream",
"-",
"Sampling",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L50-L62
|
[
"def",
"sampling",
"(",
"self",
",",
"interval",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'interval'",
"]",
"=",
"interval",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/sampling'",
")",
",",
"params",
"=",
"params",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.stats
|
Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def stats(self, **attrs):
""" Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/stats'), data=attrs)
|
def stats(self, **attrs):
""" Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.get(self.subpath('/stats'), data=attrs)
|
[
"Method",
"for",
"Data",
"Stream",
"Stats",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Data",
"-",
"Stream",
"-",
"Stats",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L64-L74
|
[
"def",
"stats",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/stats'",
")",
",",
"data",
"=",
"attrs",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.add_value
|
Method for `Update Data Stream Value <https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value>`_ endpoint.
:param value: The updated stream value
:param timestamp: The (optional) timestamp for the upadted value
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def add_value(self, value, timestamp=None):
""" Method for `Update Data Stream Value <https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value>`_ endpoint.
:param value: The updated stream value
:param timestamp: The (optional) timestamp for the upadted value
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
data = {'value': value}
if timestamp:
data['timestamp'] = timestamp
return self.api.put(self.subpath('/value'), data=data)
|
def add_value(self, value, timestamp=None):
""" Method for `Update Data Stream Value <https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value>`_ endpoint.
:param value: The updated stream value
:param timestamp: The (optional) timestamp for the upadted value
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
data = {'value': value}
if timestamp:
data['timestamp'] = timestamp
return self.api.put(self.subpath('/value'), data=data)
|
[
"Method",
"for",
"Update",
"Data",
"Stream",
"Value",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Update",
"-",
"Data",
"-",
"Stream",
"-",
"Value",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L76-L90
|
[
"def",
"add_value",
"(",
"self",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'value'",
":",
"value",
"}",
"if",
"timestamp",
":",
"data",
"[",
"'timestamp'",
"]",
"=",
"timestamp",
"return",
"self",
".",
"api",
".",
"put",
"(",
"self",
".",
"subpath",
"(",
"'/value'",
")",
",",
"data",
"=",
"data",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.post_values
|
Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint.
:param values: Values to post, see M2X API docs for details
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def post_values(self, values):
""" Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint.
:param values: Values to post, see M2X API docs for details
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/values'), data={
'values': values
})
|
def post_values(self, values):
""" Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint.
:param values: Values to post, see M2X API docs for details
:type values: dict
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.post(self.subpath('/values'), data={
'values': values
})
|
[
"Method",
"for",
"Post",
"Data",
"Stream",
"Values",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Post",
"-",
"Data",
"-",
"Stream",
"-",
"Values",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L94-L107
|
[
"def",
"post_values",
"(",
"self",
",",
"values",
")",
":",
"return",
"self",
".",
"api",
".",
"post",
"(",
"self",
".",
"subpath",
"(",
"'/values'",
")",
",",
"data",
"=",
"{",
"'values'",
":",
"values",
"}",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
Stream.delete_values
|
Method for `Delete Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Delete-Data-Stream-Values>`_ endpoint.
:param start: ISO8601 timestamp for starting timerange for values to be deleted
:param stop: ISO8601 timestamp for ending timerange for values to be deleted
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
|
m2x/v2/streams.py
|
def delete_values(self, start, stop):
""" Method for `Delete Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Delete-Data-Stream-Values>`_ endpoint.
:param start: ISO8601 timestamp for starting timerange for values to be deleted
:param stop: ISO8601 timestamp for ending timerange for values to be deleted
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.delete(self.subpath('/values'), data=self.to_server({
'from': start,
'end': stop
}))
|
def delete_values(self, start, stop):
""" Method for `Delete Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Delete-Data-Stream-Values>`_ endpoint.
:param start: ISO8601 timestamp for starting timerange for values to be deleted
:param stop: ISO8601 timestamp for ending timerange for values to be deleted
:return: The API response, see M2X API docs for details
:rtype: dict
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
"""
return self.api.delete(self.subpath('/values'), data=self.to_server({
'from': start,
'end': stop
}))
|
[
"Method",
"for",
"Delete",
"Data",
"Stream",
"Values",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"device#Delete",
"-",
"Data",
"-",
"Stream",
"-",
"Values",
">",
"_",
"endpoint",
"."
] |
attm2x/m2x-python
|
python
|
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/streams.py#L109-L123
|
[
"def",
"delete_values",
"(",
"self",
",",
"start",
",",
"stop",
")",
":",
"return",
"self",
".",
"api",
".",
"delete",
"(",
"self",
".",
"subpath",
"(",
"'/values'",
")",
",",
"data",
"=",
"self",
".",
"to_server",
"(",
"{",
"'from'",
":",
"start",
",",
"'end'",
":",
"stop",
"}",
")",
")"
] |
df83f590114692b1f96577148b7ba260065905bb
|
test
|
loads
|
Load a list of trees from a Newick formatted string.
:param s: Newick formatted string.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
|
src/newick.py
|
def loads(s, strip_comments=False, **kw):
"""
Load a list of trees from a Newick formatted string.
:param s: Newick formatted string.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
return [parse_node(ss.strip(), **kw) for ss in s.split(';') if ss.strip()]
|
def loads(s, strip_comments=False, **kw):
"""
Load a list of trees from a Newick formatted string.
:param s: Newick formatted string.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
return [parse_node(ss.strip(), **kw) for ss in s.split(';') if ss.strip()]
|
[
"Load",
"a",
"list",
"of",
"trees",
"from",
"a",
"Newick",
"formatted",
"string",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L360-L371
|
[
"def",
"loads",
"(",
"s",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'strip_comments'",
"]",
"=",
"strip_comments",
"return",
"[",
"parse_node",
"(",
"ss",
".",
"strip",
"(",
")",
",",
"*",
"*",
"kw",
")",
"for",
"ss",
"in",
"s",
".",
"split",
"(",
"';'",
")",
"if",
"ss",
".",
"strip",
"(",
")",
"]"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
dumps
|
Serialize a list of trees in Newick format.
:param trees: List of Node objects or a single Node object.
:return: Newick formatted string.
|
src/newick.py
|
def dumps(trees):
"""
Serialize a list of trees in Newick format.
:param trees: List of Node objects or a single Node object.
:return: Newick formatted string.
"""
if isinstance(trees, Node):
trees = [trees]
return ';\n'.join([tree.newick for tree in trees]) + ';'
|
def dumps(trees):
"""
Serialize a list of trees in Newick format.
:param trees: List of Node objects or a single Node object.
:return: Newick formatted string.
"""
if isinstance(trees, Node):
trees = [trees]
return ';\n'.join([tree.newick for tree in trees]) + ';'
|
[
"Serialize",
"a",
"list",
"of",
"trees",
"in",
"Newick",
"format",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L374-L383
|
[
"def",
"dumps",
"(",
"trees",
")",
":",
"if",
"isinstance",
"(",
"trees",
",",
"Node",
")",
":",
"trees",
"=",
"[",
"trees",
"]",
"return",
"';\\n'",
".",
"join",
"(",
"[",
"tree",
".",
"newick",
"for",
"tree",
"in",
"trees",
"]",
")",
"+",
"';'"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
load
|
Load a list of trees from an open Newick formatted file.
:param fp: open file handle.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
|
src/newick.py
|
def load(fp, strip_comments=False, **kw):
"""
Load a list of trees from an open Newick formatted file.
:param fp: open file handle.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
return loads(fp.read(), **kw)
|
def load(fp, strip_comments=False, **kw):
"""
Load a list of trees from an open Newick formatted file.
:param fp: open file handle.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
return loads(fp.read(), **kw)
|
[
"Load",
"a",
"list",
"of",
"trees",
"from",
"an",
"open",
"Newick",
"formatted",
"file",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L386-L397
|
[
"def",
"load",
"(",
"fp",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'strip_comments'",
"]",
"=",
"strip_comments",
"return",
"loads",
"(",
"fp",
".",
"read",
"(",
")",
",",
"*",
"*",
"kw",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
read
|
Load a list of trees from a Newick formatted file.
:param fname: file path.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
|
src/newick.py
|
def read(fname, encoding='utf8', strip_comments=False, **kw):
"""
Load a list of trees from a Newick formatted file.
:param fname: file path.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
with io.open(fname, encoding=encoding) as fp:
return load(fp, **kw)
|
def read(fname, encoding='utf8', strip_comments=False, **kw):
"""
Load a list of trees from a Newick formatted file.
:param fname: file path.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
with io.open(fname, encoding=encoding) as fp:
return load(fp, **kw)
|
[
"Load",
"a",
"list",
"of",
"trees",
"from",
"a",
"Newick",
"formatted",
"file",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L404-L416
|
[
"def",
"read",
"(",
"fname",
",",
"encoding",
"=",
"'utf8'",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'strip_comments'",
"]",
"=",
"strip_comments",
"with",
"io",
".",
"open",
"(",
"fname",
",",
"encoding",
"=",
"encoding",
")",
"as",
"fp",
":",
"return",
"load",
"(",
"fp",
",",
"*",
"*",
"kw",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
_parse_siblings
|
http://stackoverflow.com/a/26809037
|
src/newick.py
|
def _parse_siblings(s, **kw):
"""
http://stackoverflow.com/a/26809037
"""
bracket_level = 0
current = []
# trick to remove special-case of trailing chars
for c in (s + ","):
if c == "," and bracket_level == 0:
yield parse_node("".join(current), **kw)
current = []
else:
if c == "(":
bracket_level += 1
elif c == ")":
bracket_level -= 1
current.append(c)
|
def _parse_siblings(s, **kw):
"""
http://stackoverflow.com/a/26809037
"""
bracket_level = 0
current = []
# trick to remove special-case of trailing chars
for c in (s + ","):
if c == "," and bracket_level == 0:
yield parse_node("".join(current), **kw)
current = []
else:
if c == "(":
bracket_level += 1
elif c == ")":
bracket_level -= 1
current.append(c)
|
[
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"26809037"
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L431-L448
|
[
"def",
"_parse_siblings",
"(",
"s",
",",
"*",
"*",
"kw",
")",
":",
"bracket_level",
"=",
"0",
"current",
"=",
"[",
"]",
"# trick to remove special-case of trailing chars",
"for",
"c",
"in",
"(",
"s",
"+",
"\",\"",
")",
":",
"if",
"c",
"==",
"\",\"",
"and",
"bracket_level",
"==",
"0",
":",
"yield",
"parse_node",
"(",
"\"\"",
".",
"join",
"(",
"current",
")",
",",
"*",
"*",
"kw",
")",
"current",
"=",
"[",
"]",
"else",
":",
"if",
"c",
"==",
"\"(\"",
":",
"bracket_level",
"+=",
"1",
"elif",
"c",
"==",
"\")\"",
":",
"bracket_level",
"-=",
"1",
"current",
".",
"append",
"(",
"c",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
parse_node
|
Parse a Newick formatted string into a `Node` object.
:param s: Newick formatted string to parse.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: `Node` instance.
|
src/newick.py
|
def parse_node(s, strip_comments=False, **kw):
"""
Parse a Newick formatted string into a `Node` object.
:param s: Newick formatted string to parse.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: `Node` instance.
"""
if strip_comments:
s = COMMENT.sub('', s)
s = s.strip()
parts = s.split(')')
if len(parts) == 1:
descendants, label = [], s
else:
if not parts[0].startswith('('):
raise ValueError('unmatched braces %s' % parts[0][:100])
descendants = list(_parse_siblings(')'.join(parts[:-1])[1:], **kw))
label = parts[-1]
name, length = _parse_name_and_length(label)
return Node.create(name=name, length=length, descendants=descendants, **kw)
|
def parse_node(s, strip_comments=False, **kw):
"""
Parse a Newick formatted string into a `Node` object.
:param s: Newick formatted string to parse.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: `Node` instance.
"""
if strip_comments:
s = COMMENT.sub('', s)
s = s.strip()
parts = s.split(')')
if len(parts) == 1:
descendants, label = [], s
else:
if not parts[0].startswith('('):
raise ValueError('unmatched braces %s' % parts[0][:100])
descendants = list(_parse_siblings(')'.join(parts[:-1])[1:], **kw))
label = parts[-1]
name, length = _parse_name_and_length(label)
return Node.create(name=name, length=length, descendants=descendants, **kw)
|
[
"Parse",
"a",
"Newick",
"formatted",
"string",
"into",
"a",
"Node",
"object",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L451-L473
|
[
"def",
"parse_node",
"(",
"s",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"if",
"strip_comments",
":",
"s",
"=",
"COMMENT",
".",
"sub",
"(",
"''",
",",
"s",
")",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"parts",
"=",
"s",
".",
"split",
"(",
"')'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"descendants",
",",
"label",
"=",
"[",
"]",
",",
"s",
"else",
":",
"if",
"not",
"parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'('",
")",
":",
"raise",
"ValueError",
"(",
"'unmatched braces %s'",
"%",
"parts",
"[",
"0",
"]",
"[",
":",
"100",
"]",
")",
"descendants",
"=",
"list",
"(",
"_parse_siblings",
"(",
"')'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"[",
"1",
":",
"]",
",",
"*",
"*",
"kw",
")",
")",
"label",
"=",
"parts",
"[",
"-",
"1",
"]",
"name",
",",
"length",
"=",
"_parse_name_and_length",
"(",
"label",
")",
"return",
"Node",
".",
"create",
"(",
"name",
"=",
"name",
",",
"length",
"=",
"length",
",",
"descendants",
"=",
"descendants",
",",
"*",
"*",
"kw",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.create
|
Create a new `Node` object.
:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.
|
src/newick.py
|
def create(cls, name=None, length=None, descendants=None, **kw):
"""
Create a new `Node` object.
:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.
"""
node = cls(name=name, length=length, **kw)
for descendant in descendants or []:
node.add_descendant(descendant)
return node
|
def create(cls, name=None, length=None, descendants=None, **kw):
"""
Create a new `Node` object.
:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.
"""
node = cls(name=name, length=length, **kw)
for descendant in descendants or []:
node.add_descendant(descendant)
return node
|
[
"Create",
"a",
"new",
"Node",
"object",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L68-L81
|
[
"def",
"create",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"length",
"=",
"None",
",",
"descendants",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"node",
"=",
"cls",
"(",
"name",
"=",
"name",
",",
"length",
"=",
"length",
",",
"*",
"*",
"kw",
")",
"for",
"descendant",
"in",
"descendants",
"or",
"[",
"]",
":",
"node",
".",
"add_descendant",
"(",
"descendant",
")",
"return",
"node"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.newick
|
The representation of the Node in Newick format.
|
src/newick.py
|
def newick(self):
"""The representation of the Node in Newick format."""
label = self.name or ''
if self._length:
label += ':' + self._length
descendants = ','.join([n.newick for n in self.descendants])
if descendants:
descendants = '(' + descendants + ')'
return descendants + label
|
def newick(self):
"""The representation of the Node in Newick format."""
label = self.name or ''
if self._length:
label += ':' + self._length
descendants = ','.join([n.newick for n in self.descendants])
if descendants:
descendants = '(' + descendants + ')'
return descendants + label
|
[
"The",
"representation",
"of",
"the",
"Node",
"in",
"Newick",
"format",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L88-L96
|
[
"def",
"newick",
"(",
"self",
")",
":",
"label",
"=",
"self",
".",
"name",
"or",
"''",
"if",
"self",
".",
"_length",
":",
"label",
"+=",
"':'",
"+",
"self",
".",
"_length",
"descendants",
"=",
"','",
".",
"join",
"(",
"[",
"n",
".",
"newick",
"for",
"n",
"in",
"self",
".",
"descendants",
"]",
")",
"if",
"descendants",
":",
"descendants",
"=",
"'('",
"+",
"descendants",
"+",
"')'",
"return",
"descendants",
"+",
"label"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.ascii_art
|
Return a unicode string representing a tree in ASCII art fashion.
:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string
>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
/-A
/---|
| \-B
----| /-D
| /---|
| | \-E
\---|
|-G
\-H
|
src/newick.py
|
def ascii_art(self, strict=False, show_internal=True):
"""
Return a unicode string representing a tree in ASCII art fashion.
:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string
>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
/-A
/---|
| \-B
----| /-D
| /---|
| | \-E
\---|
|-G
\-H
"""
cmap = {
'\u2500': '-',
'\u2502': '|',
'\u250c': '/',
'\u2514': '\\',
'\u251c': '|',
'\u2524': '|',
'\u253c': '+',
}
def normalize(line):
m = re.compile('(?<=\u2502)(?P<s>\s+)(?=[\u250c\u2514\u2502])')
line = m.sub(lambda m: m.group('s')[1:], line)
line = re.sub('\u2500\u2502', '\u2500\u2524', line) # -|
line = re.sub('\u2502\u2500', '\u251c', line) # |-
line = re.sub('\u2524\u2500', '\u253c', line) # -|-
if strict:
for u, a in cmap.items():
line = line.replace(u, a)
return line
return '\n'.join(
normalize(l) for l in self._ascii_art(show_internal=show_internal)[0]
if set(l) != {' ', '\u2502'})
|
def ascii_art(self, strict=False, show_internal=True):
"""
Return a unicode string representing a tree in ASCII art fashion.
:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string
>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
/-A
/---|
| \-B
----| /-D
| /---|
| | \-E
\---|
|-G
\-H
"""
cmap = {
'\u2500': '-',
'\u2502': '|',
'\u250c': '/',
'\u2514': '\\',
'\u251c': '|',
'\u2524': '|',
'\u253c': '+',
}
def normalize(line):
m = re.compile('(?<=\u2502)(?P<s>\s+)(?=[\u250c\u2514\u2502])')
line = m.sub(lambda m: m.group('s')[1:], line)
line = re.sub('\u2500\u2502', '\u2500\u2524', line) # -|
line = re.sub('\u2502\u2500', '\u251c', line) # |-
line = re.sub('\u2524\u2500', '\u253c', line) # -|-
if strict:
for u, a in cmap.items():
line = line.replace(u, a)
return line
return '\n'.join(
normalize(l) for l in self._ascii_art(show_internal=show_internal)[0]
if set(l) != {' ', '\u2502'})
|
[
"Return",
"a",
"unicode",
"string",
"representing",
"a",
"tree",
"in",
"ASCII",
"art",
"fashion",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L137-L179
|
[
"def",
"ascii_art",
"(",
"self",
",",
"strict",
"=",
"False",
",",
"show_internal",
"=",
"True",
")",
":",
"cmap",
"=",
"{",
"'\\u2500'",
":",
"'-'",
",",
"'\\u2502'",
":",
"'|'",
",",
"'\\u250c'",
":",
"'/'",
",",
"'\\u2514'",
":",
"'\\\\'",
",",
"'\\u251c'",
":",
"'|'",
",",
"'\\u2524'",
":",
"'|'",
",",
"'\\u253c'",
":",
"'+'",
",",
"}",
"def",
"normalize",
"(",
"line",
")",
":",
"m",
"=",
"re",
".",
"compile",
"(",
"'(?<=\\u2502)(?P<s>\\s+)(?=[\\u250c\\u2514\\u2502])'",
")",
"line",
"=",
"m",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"'s'",
")",
"[",
"1",
":",
"]",
",",
"line",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"'\\u2500\\u2502'",
",",
"'\\u2500\\u2524'",
",",
"line",
")",
"# -|",
"line",
"=",
"re",
".",
"sub",
"(",
"'\\u2502\\u2500'",
",",
"'\\u251c'",
",",
"line",
")",
"# |-",
"line",
"=",
"re",
".",
"sub",
"(",
"'\\u2524\\u2500'",
",",
"'\\u253c'",
",",
"line",
")",
"# -|-",
"if",
"strict",
":",
"for",
"u",
",",
"a",
"in",
"cmap",
".",
"items",
"(",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"u",
",",
"a",
")",
"return",
"line",
"return",
"'\\n'",
".",
"join",
"(",
"normalize",
"(",
"l",
")",
"for",
"l",
"in",
"self",
".",
"_ascii_art",
"(",
"show_internal",
"=",
"show_internal",
")",
"[",
"0",
"]",
"if",
"set",
"(",
"l",
")",
"!=",
"{",
"' '",
",",
"'\\u2502'",
"}",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.walk
|
Traverses the (sub)tree rooted at self, yielding each visited Node.
.. seealso:: https://en.wikipedia.org/wiki/Tree_traversal
:param mode: Specifies the algorithm to use when traversing the subtree rooted \
at self. `None` for breadth-first, `'postorder'` for post-order depth-first \
search.
:return: Generator of the visited Nodes.
|
src/newick.py
|
def walk(self, mode=None):
"""
Traverses the (sub)tree rooted at self, yielding each visited Node.
.. seealso:: https://en.wikipedia.org/wiki/Tree_traversal
:param mode: Specifies the algorithm to use when traversing the subtree rooted \
at self. `None` for breadth-first, `'postorder'` for post-order depth-first \
search.
:return: Generator of the visited Nodes.
"""
if mode == 'postorder':
for n in self._postorder():
yield n
else: # default to a breadth-first search
yield self
for node in self.descendants:
for n in node.walk():
yield n
|
def walk(self, mode=None):
"""
Traverses the (sub)tree rooted at self, yielding each visited Node.
.. seealso:: https://en.wikipedia.org/wiki/Tree_traversal
:param mode: Specifies the algorithm to use when traversing the subtree rooted \
at self. `None` for breadth-first, `'postorder'` for post-order depth-first \
search.
:return: Generator of the visited Nodes.
"""
if mode == 'postorder':
for n in self._postorder():
yield n
else: # default to a breadth-first search
yield self
for node in self.descendants:
for n in node.walk():
yield n
|
[
"Traverses",
"the",
"(",
"sub",
")",
"tree",
"rooted",
"at",
"self",
"yielding",
"each",
"visited",
"Node",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L189-L207
|
[
"def",
"walk",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"==",
"'postorder'",
":",
"for",
"n",
"in",
"self",
".",
"_postorder",
"(",
")",
":",
"yield",
"n",
"else",
":",
"# default to a breadth-first search",
"yield",
"self",
"for",
"node",
"in",
"self",
".",
"descendants",
":",
"for",
"n",
"in",
"node",
".",
"walk",
"(",
")",
":",
"yield",
"n"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.visit
|
Apply a function to matching nodes in the (sub)tree rooted at self.
:param visitor: A callable accepting a Node object as single argument..
:param predicate: A callable accepting a Node object as single argument and \
returning a boolean signaling whether Node matches; if `None` all nodes match.
:param kw: Addtional keyword arguments are passed through to self.walk.
|
src/newick.py
|
def visit(self, visitor, predicate=None, **kw):
"""
Apply a function to matching nodes in the (sub)tree rooted at self.
:param visitor: A callable accepting a Node object as single argument..
:param predicate: A callable accepting a Node object as single argument and \
returning a boolean signaling whether Node matches; if `None` all nodes match.
:param kw: Addtional keyword arguments are passed through to self.walk.
"""
predicate = predicate or bool
for n in self.walk(**kw):
if predicate(n):
visitor(n)
|
def visit(self, visitor, predicate=None, **kw):
"""
Apply a function to matching nodes in the (sub)tree rooted at self.
:param visitor: A callable accepting a Node object as single argument..
:param predicate: A callable accepting a Node object as single argument and \
returning a boolean signaling whether Node matches; if `None` all nodes match.
:param kw: Addtional keyword arguments are passed through to self.walk.
"""
predicate = predicate or bool
for n in self.walk(**kw):
if predicate(n):
visitor(n)
|
[
"Apply",
"a",
"function",
"to",
"matching",
"nodes",
"in",
"the",
"(",
"sub",
")",
"tree",
"rooted",
"at",
"self",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L209-L222
|
[
"def",
"visit",
"(",
"self",
",",
"visitor",
",",
"predicate",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"predicate",
"=",
"predicate",
"or",
"bool",
"for",
"n",
"in",
"self",
".",
"walk",
"(",
"*",
"*",
"kw",
")",
":",
"if",
"predicate",
"(",
"n",
")",
":",
"visitor",
"(",
"n",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.get_node
|
Gets the specified node by name.
:return: Node or None if name does not exist in tree
|
src/newick.py
|
def get_node(self, label):
"""
Gets the specified node by name.
:return: Node or None if name does not exist in tree
"""
for n in self.walk():
if n.name == label:
return n
|
def get_node(self, label):
"""
Gets the specified node by name.
:return: Node or None if name does not exist in tree
"""
for n in self.walk():
if n.name == label:
return n
|
[
"Gets",
"the",
"specified",
"node",
"by",
"name",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L249-L257
|
[
"def",
"get_node",
"(",
"self",
",",
"label",
")",
":",
"for",
"n",
"in",
"self",
".",
"walk",
"(",
")",
":",
"if",
"n",
".",
"name",
"==",
"label",
":",
"return",
"n"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.prune
|
Remove all those nodes in the specified list, or if inverse=True,
remove all those nodes not in the specified list. The specified nodes
must be leaves and distinct from the root node.
:param nodes: A list of Node objects
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
|
src/newick.py
|
def prune(self, leaves, inverse=False):
"""
Remove all those nodes in the specified list, or if inverse=True,
remove all those nodes not in the specified list. The specified nodes
must be leaves and distinct from the root node.
:param nodes: A list of Node objects
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.visit(
lambda n: n.ancestor.descendants.remove(n),
# We won't prune the root node, even if it is a leave and requested to
# be pruned!
lambda n: ((not inverse and n in leaves) or
(inverse and n.is_leaf and n not in leaves)) and n.ancestor,
mode="postorder")
|
def prune(self, leaves, inverse=False):
"""
Remove all those nodes in the specified list, or if inverse=True,
remove all those nodes not in the specified list. The specified nodes
must be leaves and distinct from the root node.
:param nodes: A list of Node objects
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.visit(
lambda n: n.ancestor.descendants.remove(n),
# We won't prune the root node, even if it is a leave and requested to
# be pruned!
lambda n: ((not inverse and n in leaves) or
(inverse and n.is_leaf and n not in leaves)) and n.ancestor,
mode="postorder")
|
[
"Remove",
"all",
"those",
"nodes",
"in",
"the",
"specified",
"list",
"or",
"if",
"inverse",
"=",
"True",
"remove",
"all",
"those",
"nodes",
"not",
"in",
"the",
"specified",
"list",
".",
"The",
"specified",
"nodes",
"must",
"be",
"leaves",
"and",
"distinct",
"from",
"the",
"root",
"node",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L268-L284
|
[
"def",
"prune",
"(",
"self",
",",
"leaves",
",",
"inverse",
"=",
"False",
")",
":",
"self",
".",
"visit",
"(",
"lambda",
"n",
":",
"n",
".",
"ancestor",
".",
"descendants",
".",
"remove",
"(",
"n",
")",
",",
"# We won't prune the root node, even if it is a leave and requested to",
"# be pruned!",
"lambda",
"n",
":",
"(",
"(",
"not",
"inverse",
"and",
"n",
"in",
"leaves",
")",
"or",
"(",
"inverse",
"and",
"n",
".",
"is_leaf",
"and",
"n",
"not",
"in",
"leaves",
")",
")",
"and",
"n",
".",
"ancestor",
",",
"mode",
"=",
"\"postorder\"",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.prune_by_names
|
Perform an (inverse) prune, with leaves specified by name.
:param node_names: A list of leaaf Node names (strings)
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
|
src/newick.py
|
def prune_by_names(self, leaf_names, inverse=False):
"""
Perform an (inverse) prune, with leaves specified by name.
:param node_names: A list of leaaf Node names (strings)
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.prune([l for l in self.walk() if l.name in leaf_names], inverse)
|
def prune_by_names(self, leaf_names, inverse=False):
"""
Perform an (inverse) prune, with leaves specified by name.
:param node_names: A list of leaaf Node names (strings)
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.prune([l for l in self.walk() if l.name in leaf_names], inverse)
|
[
"Perform",
"an",
"(",
"inverse",
")",
"prune",
"with",
"leaves",
"specified",
"by",
"name",
".",
":",
"param",
"node_names",
":",
"A",
"list",
"of",
"leaaf",
"Node",
"names",
"(",
"strings",
")",
":",
"param",
"inverse",
":",
"Specifies",
"whether",
"to",
"remove",
"nodes",
"in",
"the",
"list",
"or",
"not",
"\\",
"in",
"the",
"list",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L286-L293
|
[
"def",
"prune_by_names",
"(",
"self",
",",
"leaf_names",
",",
"inverse",
"=",
"False",
")",
":",
"self",
".",
"prune",
"(",
"[",
"l",
"for",
"l",
"in",
"self",
".",
"walk",
"(",
")",
"if",
"l",
".",
"name",
"in",
"leaf_names",
"]",
",",
"inverse",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.remove_redundant_nodes
|
Remove all nodes which have only a single child, and attach their
grandchildren to their parent. The resulting tree has the minimum
number of internal nodes required for the number of leaves.
:param preserve_lengths: If true, branch lengths of removed nodes are \
added to those of their children.
|
src/newick.py
|
def remove_redundant_nodes(self, preserve_lengths=True):
"""
Remove all nodes which have only a single child, and attach their
grandchildren to their parent. The resulting tree has the minimum
number of internal nodes required for the number of leaves.
:param preserve_lengths: If true, branch lengths of removed nodes are \
added to those of their children.
"""
for n in self.walk(mode='postorder'):
while n.ancestor and len(n.ancestor.descendants) == 1:
grandfather = n.ancestor.ancestor
father = n.ancestor
if preserve_lengths:
n.length += father.length
if grandfather:
for i, child in enumerate(grandfather.descendants):
if child is father:
del grandfather.descendants[i]
grandfather.add_descendant(n)
father.ancestor = None
else:
self.descendants = n.descendants
if preserve_lengths:
self.length = n.length
|
def remove_redundant_nodes(self, preserve_lengths=True):
"""
Remove all nodes which have only a single child, and attach their
grandchildren to their parent. The resulting tree has the minimum
number of internal nodes required for the number of leaves.
:param preserve_lengths: If true, branch lengths of removed nodes are \
added to those of their children.
"""
for n in self.walk(mode='postorder'):
while n.ancestor and len(n.ancestor.descendants) == 1:
grandfather = n.ancestor.ancestor
father = n.ancestor
if preserve_lengths:
n.length += father.length
if grandfather:
for i, child in enumerate(grandfather.descendants):
if child is father:
del grandfather.descendants[i]
grandfather.add_descendant(n)
father.ancestor = None
else:
self.descendants = n.descendants
if preserve_lengths:
self.length = n.length
|
[
"Remove",
"all",
"nodes",
"which",
"have",
"only",
"a",
"single",
"child",
"and",
"attach",
"their",
"grandchildren",
"to",
"their",
"parent",
".",
"The",
"resulting",
"tree",
"has",
"the",
"minimum",
"number",
"of",
"internal",
"nodes",
"required",
"for",
"the",
"number",
"of",
"leaves",
".",
":",
"param",
"preserve_lengths",
":",
"If",
"true",
"branch",
"lengths",
"of",
"removed",
"nodes",
"are",
"\\",
"added",
"to",
"those",
"of",
"their",
"children",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L295-L319
|
[
"def",
"remove_redundant_nodes",
"(",
"self",
",",
"preserve_lengths",
"=",
"True",
")",
":",
"for",
"n",
"in",
"self",
".",
"walk",
"(",
"mode",
"=",
"'postorder'",
")",
":",
"while",
"n",
".",
"ancestor",
"and",
"len",
"(",
"n",
".",
"ancestor",
".",
"descendants",
")",
"==",
"1",
":",
"grandfather",
"=",
"n",
".",
"ancestor",
".",
"ancestor",
"father",
"=",
"n",
".",
"ancestor",
"if",
"preserve_lengths",
":",
"n",
".",
"length",
"+=",
"father",
".",
"length",
"if",
"grandfather",
":",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"grandfather",
".",
"descendants",
")",
":",
"if",
"child",
"is",
"father",
":",
"del",
"grandfather",
".",
"descendants",
"[",
"i",
"]",
"grandfather",
".",
"add_descendant",
"(",
"n",
")",
"father",
".",
"ancestor",
"=",
"None",
"else",
":",
"self",
".",
"descendants",
"=",
"n",
".",
"descendants",
"if",
"preserve_lengths",
":",
"self",
".",
"length",
"=",
"n",
".",
"length"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.resolve_polytomies
|
Insert additional nodes with length=0 into the subtree in such a way
that all non-leaf nodes have only 2 descendants, i.e. the tree becomes
a fully resolved binary tree.
|
src/newick.py
|
def resolve_polytomies(self):
"""
Insert additional nodes with length=0 into the subtree in such a way
that all non-leaf nodes have only 2 descendants, i.e. the tree becomes
a fully resolved binary tree.
"""
def _resolve_polytomies(n):
new = Node(length=self._length_formatter(self._length_parser('0')))
while len(n.descendants) > 1:
new.add_descendant(n.descendants.pop())
n.descendants.append(new)
self.visit(_resolve_polytomies, lambda n: len(n.descendants) > 2)
|
def resolve_polytomies(self):
"""
Insert additional nodes with length=0 into the subtree in such a way
that all non-leaf nodes have only 2 descendants, i.e. the tree becomes
a fully resolved binary tree.
"""
def _resolve_polytomies(n):
new = Node(length=self._length_formatter(self._length_parser('0')))
while len(n.descendants) > 1:
new.add_descendant(n.descendants.pop())
n.descendants.append(new)
self.visit(_resolve_polytomies, lambda n: len(n.descendants) > 2)
|
[
"Insert",
"additional",
"nodes",
"with",
"length",
"=",
"0",
"into",
"the",
"subtree",
"in",
"such",
"a",
"way",
"that",
"all",
"non",
"-",
"leaf",
"nodes",
"have",
"only",
"2",
"descendants",
"i",
".",
"e",
".",
"the",
"tree",
"becomes",
"a",
"fully",
"resolved",
"binary",
"tree",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L321-L333
|
[
"def",
"resolve_polytomies",
"(",
"self",
")",
":",
"def",
"_resolve_polytomies",
"(",
"n",
")",
":",
"new",
"=",
"Node",
"(",
"length",
"=",
"self",
".",
"_length_formatter",
"(",
"self",
".",
"_length_parser",
"(",
"'0'",
")",
")",
")",
"while",
"len",
"(",
"n",
".",
"descendants",
")",
">",
"1",
":",
"new",
".",
"add_descendant",
"(",
"n",
".",
"descendants",
".",
"pop",
"(",
")",
")",
"n",
".",
"descendants",
".",
"append",
"(",
"new",
")",
"self",
".",
"visit",
"(",
"_resolve_polytomies",
",",
"lambda",
"n",
":",
"len",
"(",
"n",
".",
"descendants",
")",
">",
"2",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.remove_internal_names
|
Set the name of all non-leaf nodes in the subtree to None.
|
src/newick.py
|
def remove_internal_names(self):
"""
Set the name of all non-leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf)
|
def remove_internal_names(self):
"""
Set the name of all non-leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf)
|
[
"Set",
"the",
"name",
"of",
"all",
"non",
"-",
"leaf",
"nodes",
"in",
"the",
"subtree",
"to",
"None",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L341-L345
|
[
"def",
"remove_internal_names",
"(",
"self",
")",
":",
"self",
".",
"visit",
"(",
"lambda",
"n",
":",
"setattr",
"(",
"n",
",",
"'name'",
",",
"None",
")",
",",
"lambda",
"n",
":",
"not",
"n",
".",
"is_leaf",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
Node.remove_leaf_names
|
Set the name of all leaf nodes in the subtree to None.
|
src/newick.py
|
def remove_leaf_names(self):
"""
Set the name of all leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: n.is_leaf)
|
def remove_leaf_names(self):
"""
Set the name of all leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: n.is_leaf)
|
[
"Set",
"the",
"name",
"of",
"all",
"leaf",
"nodes",
"in",
"the",
"subtree",
"to",
"None",
"."
] |
glottobank/python-newick
|
python
|
https://github.com/glottobank/python-newick/blob/e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702/src/newick.py#L347-L351
|
[
"def",
"remove_leaf_names",
"(",
"self",
")",
":",
"self",
".",
"visit",
"(",
"lambda",
"n",
":",
"setattr",
"(",
"n",
",",
"'name'",
",",
"None",
")",
",",
"lambda",
"n",
":",
"n",
".",
"is_leaf",
")"
] |
e8d4d1e4610f271d0f0e5cb86c0e0360b43bd702
|
test
|
auth_required
|
Decorator that protect methods with HTTP authentication.
|
tornado_http_auth.py
|
def auth_required(realm, auth_func):
'''Decorator that protect methods with HTTP authentication.'''
def auth_decorator(func):
def inner(self, *args, **kw):
if self.get_authenticated_user(auth_func, realm):
return func(self, *args, **kw)
return inner
return auth_decorator
|
def auth_required(realm, auth_func):
'''Decorator that protect methods with HTTP authentication.'''
def auth_decorator(func):
def inner(self, *args, **kw):
if self.get_authenticated_user(auth_func, realm):
return func(self, *args, **kw)
return inner
return auth_decorator
|
[
"Decorator",
"that",
"protect",
"methods",
"with",
"HTTP",
"authentication",
"."
] |
gvalkov/tornado-http-auth
|
python
|
https://github.com/gvalkov/tornado-http-auth/blob/9eb225c1740fad1e53320b55d8d4fc6ab4ba58b6/tornado_http_auth.py#L227-L234
|
[
"def",
"auth_required",
"(",
"realm",
",",
"auth_func",
")",
":",
"def",
"auth_decorator",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"get_authenticated_user",
"(",
"auth_func",
",",
"realm",
")",
":",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"inner",
"return",
"auth_decorator"
] |
9eb225c1740fad1e53320b55d8d4fc6ab4ba58b6
|
test
|
dispose
|
Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode)
|
jstyleson.py
|
def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode)
"""
result_str = list(json_str)
escaped = False
normal = True
sl_comment = False
ml_comment = False
quoted = False
a_step_from_comment = False
a_step_from_comment_away = False
former_index = None
for index, char in enumerate(json_str):
if escaped: # We have just met a '\'
escaped = False
continue
if a_step_from_comment: # We have just met a '/'
if char != '/' and char != '*':
a_step_from_comment = False
normal = True
continue
if a_step_from_comment_away: # We have just met a '*'
if char != '/':
a_step_from_comment_away = False
if char == '"':
if normal and not escaped:
# We are now in a string
quoted = True
normal = False
elif quoted and not escaped:
# We are now out of a string
quoted = False
normal = True
elif char == '\\':
# '\' should not take effect in comment
if normal or quoted:
escaped = True
elif char == '/':
if a_step_from_comment:
# Now we are in single line comment
a_step_from_comment = False
sl_comment = True
normal = False
former_index = index - 1
elif a_step_from_comment_away:
# Now we are out of comment
a_step_from_comment_away = False
normal = True
ml_comment = False
for i in range(former_index, index + 1):
result_str[i] = ""
elif normal:
# Now we are just one step away from comment
a_step_from_comment = True
normal = False
elif char == '*':
if a_step_from_comment:
# We are now in multi-line comment
a_step_from_comment = False
ml_comment = True
normal = False
former_index = index - 1
elif ml_comment:
a_step_from_comment_away = True
elif char == '\n':
if sl_comment:
sl_comment = False
normal = True
for i in range(former_index, index + 1):
result_str[i] = ""
elif char == ']' or char == '}':
if normal:
_remove_last_comma(result_str, index)
# Show respect to original input if we are in python2
return ("" if isinstance(json_str, str) else u"").join(result_str)
|
def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode)
"""
result_str = list(json_str)
escaped = False
normal = True
sl_comment = False
ml_comment = False
quoted = False
a_step_from_comment = False
a_step_from_comment_away = False
former_index = None
for index, char in enumerate(json_str):
if escaped: # We have just met a '\'
escaped = False
continue
if a_step_from_comment: # We have just met a '/'
if char != '/' and char != '*':
a_step_from_comment = False
normal = True
continue
if a_step_from_comment_away: # We have just met a '*'
if char != '/':
a_step_from_comment_away = False
if char == '"':
if normal and not escaped:
# We are now in a string
quoted = True
normal = False
elif quoted and not escaped:
# We are now out of a string
quoted = False
normal = True
elif char == '\\':
# '\' should not take effect in comment
if normal or quoted:
escaped = True
elif char == '/':
if a_step_from_comment:
# Now we are in single line comment
a_step_from_comment = False
sl_comment = True
normal = False
former_index = index - 1
elif a_step_from_comment_away:
# Now we are out of comment
a_step_from_comment_away = False
normal = True
ml_comment = False
for i in range(former_index, index + 1):
result_str[i] = ""
elif normal:
# Now we are just one step away from comment
a_step_from_comment = True
normal = False
elif char == '*':
if a_step_from_comment:
# We are now in multi-line comment
a_step_from_comment = False
ml_comment = True
normal = False
former_index = index - 1
elif ml_comment:
a_step_from_comment_away = True
elif char == '\n':
if sl_comment:
sl_comment = False
normal = True
for i in range(former_index, index + 1):
result_str[i] = ""
elif char == ']' or char == '}':
if normal:
_remove_last_comma(result_str, index)
# Show respect to original input if we are in python2
return ("" if isinstance(json_str, str) else u"").join(result_str)
|
[
"Clear",
"all",
"comments",
"in",
"json_str",
"."
] |
linjackson78/jstyleson
|
python
|
https://github.com/linjackson78/jstyleson/blob/a5aff96642684118a9a5efcb69e366f8b840346b/jstyleson.py#L4-L99
|
[
"def",
"dispose",
"(",
"json_str",
")",
":",
"result_str",
"=",
"list",
"(",
"json_str",
")",
"escaped",
"=",
"False",
"normal",
"=",
"True",
"sl_comment",
"=",
"False",
"ml_comment",
"=",
"False",
"quoted",
"=",
"False",
"a_step_from_comment",
"=",
"False",
"a_step_from_comment_away",
"=",
"False",
"former_index",
"=",
"None",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"json_str",
")",
":",
"if",
"escaped",
":",
"# We have just met a '\\'",
"escaped",
"=",
"False",
"continue",
"if",
"a_step_from_comment",
":",
"# We have just met a '/'",
"if",
"char",
"!=",
"'/'",
"and",
"char",
"!=",
"'*'",
":",
"a_step_from_comment",
"=",
"False",
"normal",
"=",
"True",
"continue",
"if",
"a_step_from_comment_away",
":",
"# We have just met a '*'",
"if",
"char",
"!=",
"'/'",
":",
"a_step_from_comment_away",
"=",
"False",
"if",
"char",
"==",
"'\"'",
":",
"if",
"normal",
"and",
"not",
"escaped",
":",
"# We are now in a string",
"quoted",
"=",
"True",
"normal",
"=",
"False",
"elif",
"quoted",
"and",
"not",
"escaped",
":",
"# We are now out of a string",
"quoted",
"=",
"False",
"normal",
"=",
"True",
"elif",
"char",
"==",
"'\\\\'",
":",
"# '\\' should not take effect in comment",
"if",
"normal",
"or",
"quoted",
":",
"escaped",
"=",
"True",
"elif",
"char",
"==",
"'/'",
":",
"if",
"a_step_from_comment",
":",
"# Now we are in single line comment",
"a_step_from_comment",
"=",
"False",
"sl_comment",
"=",
"True",
"normal",
"=",
"False",
"former_index",
"=",
"index",
"-",
"1",
"elif",
"a_step_from_comment_away",
":",
"# Now we are out of comment",
"a_step_from_comment_away",
"=",
"False",
"normal",
"=",
"True",
"ml_comment",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"former_index",
",",
"index",
"+",
"1",
")",
":",
"result_str",
"[",
"i",
"]",
"=",
"\"\"",
"elif",
"normal",
":",
"# Now we are just one step away from comment",
"a_step_from_comment",
"=",
"True",
"normal",
"=",
"False",
"elif",
"char",
"==",
"'*'",
":",
"if",
"a_step_from_comment",
":",
"# We are now in multi-line comment",
"a_step_from_comment",
"=",
"False",
"ml_comment",
"=",
"True",
"normal",
"=",
"False",
"former_index",
"=",
"index",
"-",
"1",
"elif",
"ml_comment",
":",
"a_step_from_comment_away",
"=",
"True",
"elif",
"char",
"==",
"'\\n'",
":",
"if",
"sl_comment",
":",
"sl_comment",
"=",
"False",
"normal",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"former_index",
",",
"index",
"+",
"1",
")",
":",
"result_str",
"[",
"i",
"]",
"=",
"\"\"",
"elif",
"char",
"==",
"']'",
"or",
"char",
"==",
"'}'",
":",
"if",
"normal",
":",
"_remove_last_comma",
"(",
"result_str",
",",
"index",
")",
"# Show respect to original input if we are in python2",
"return",
"(",
"\"\"",
"if",
"isinstance",
"(",
"json_str",
",",
"str",
")",
"else",
"u\"\"",
")",
".",
"join",
"(",
"result_str",
")"
] |
a5aff96642684118a9a5efcb69e366f8b840346b
|
test
|
GenericAuth.require_setting
|
Raises an exception if the given app setting is not defined.
|
bottle_auth/core/auth.py
|
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if name not in self.settings:
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
|
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if name not in self.settings:
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
|
[
"Raises",
"an",
"exception",
"if",
"the",
"given",
"app",
"setting",
"is",
"not",
"defined",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L142-L146
|
[
"def",
"require_setting",
"(",
"self",
",",
"name",
",",
"feature",
"=",
"\"this feature\"",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"settings",
":",
"raise",
"Exception",
"(",
"\"You must define the '%s' setting in your \"",
"\"application to use %s\"",
"%",
"(",
"name",
",",
"feature",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.get_argument
|
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 400 exception if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
|
bottle_auth/core/auth.py
|
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 400 exception if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
args = self.get_arguments(name, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise HTTPError(400, "Missing argument %s" % name)
return default
return args[-1]
|
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 400 exception if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
args = self.get_arguments(name, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise HTTPError(400, "Missing argument %s" % name)
return default
return args[-1]
|
[
"Returns",
"the",
"value",
"of",
"the",
"argument",
"with",
"the",
"given",
"name",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L150-L166
|
[
"def",
"get_argument",
"(",
"self",
",",
"name",
",",
"default",
"=",
"_ARG_DEFAULT",
",",
"strip",
"=",
"True",
")",
":",
"args",
"=",
"self",
".",
"get_arguments",
"(",
"name",
",",
"strip",
"=",
"strip",
")",
"if",
"not",
"args",
":",
"if",
"default",
"is",
"self",
".",
"_ARG_DEFAULT",
":",
"raise",
"HTTPError",
"(",
"400",
",",
"\"Missing argument %s\"",
"%",
"name",
")",
"return",
"default",
"return",
"args",
"[",
"-",
"1",
"]"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.get_arguments
|
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
|
bottle_auth/core/auth.py
|
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = []
for v in self.request.params.getall(name):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v)
if strip:
v = v.strip()
values.append(v)
return values
|
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = []
for v in self.request.params.getall(name):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v)
if strip:
v = v.strip()
values.append(v)
return values
|
[
"Returns",
"a",
"list",
"of",
"the",
"arguments",
"with",
"the",
"given",
"name",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L168-L185
|
[
"def",
"get_arguments",
"(",
"self",
",",
"name",
",",
"strip",
"=",
"True",
")",
":",
"values",
"=",
"[",
"]",
"for",
"v",
"in",
"self",
".",
"request",
".",
"params",
".",
"getall",
"(",
"name",
")",
":",
"v",
"=",
"self",
".",
"decode_argument",
"(",
"v",
",",
"name",
"=",
"name",
")",
"if",
"isinstance",
"(",
"v",
",",
"unicode",
")",
":",
"# Get rid of any weird control chars (unless decoding gave",
"# us bytes, in which case leave it alone)",
"v",
"=",
"re",
".",
"sub",
"(",
"r\"[\\x00-\\x08\\x0e-\\x1f]\"",
",",
"\" \"",
",",
"v",
")",
"if",
"strip",
":",
"v",
"=",
"v",
".",
"strip",
"(",
")",
"values",
".",
"append",
"(",
"v",
")",
"return",
"values"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.async_callback
|
Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.
|
bottle_auth/core/auth.py
|
def async_callback(self, callback, *args, **kwargs):
"""Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.
"""
if callback is None:
return None
if args or kwargs:
callback = functools.partial(callback, *args, **kwargs)
#FIXME what about the exception wrapper?
return callback
|
def async_callback(self, callback, *args, **kwargs):
"""Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.
"""
if callback is None:
return None
if args or kwargs:
callback = functools.partial(callback, *args, **kwargs)
#FIXME what about the exception wrapper?
return callback
|
[
"Obsolete",
"-",
"catches",
"exceptions",
"from",
"the",
"wrapped",
"function",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L202-L214
|
[
"def",
"async_callback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callback",
"is",
"None",
":",
"return",
"None",
"if",
"args",
"or",
"kwargs",
":",
"callback",
"=",
"functools",
".",
"partial",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"#FIXME what about the exception wrapper?",
"return",
"callback"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.get_cookie
|
Gets the value of the cookie with the given name, else default.
|
bottle_auth/core/auth.py
|
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
assert self.cookie_monster, 'Cookie Monster not set'
return self.cookie_monster.get_cookie(name, default)
|
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
assert self.cookie_monster, 'Cookie Monster not set'
return self.cookie_monster.get_cookie(name, default)
|
[
"Gets",
"the",
"value",
"of",
"the",
"cookie",
"with",
"the",
"given",
"name",
"else",
"default",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L216-L219
|
[
"def",
"get_cookie",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"assert",
"self",
".",
"cookie_monster",
",",
"'Cookie Monster not set'",
"return",
"self",
".",
"cookie_monster",
".",
"get_cookie",
"(",
"name",
",",
"default",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.set_cookie
|
Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
|
bottle_auth/core/auth.py
|
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
assert self.cookie_monster, 'Cookie Monster not set'
#, domain=domain, path=path)
self.cookie_monster.set_cookie(name, value)
|
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
assert self.cookie_monster, 'Cookie Monster not set'
#, domain=domain, path=path)
self.cookie_monster.set_cookie(name, value)
|
[
"Sets",
"the",
"given",
"cookie",
"name",
"/",
"value",
"with",
"the",
"given",
"options",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L221-L232
|
[
"def",
"set_cookie",
"(",
"self",
",",
"name",
",",
"value",
",",
"domain",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"path",
"=",
"\"/\"",
",",
"expires_days",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"cookie_monster",
",",
"'Cookie Monster not set'",
"#, domain=domain, path=path)",
"self",
".",
"cookie_monster",
".",
"set_cookie",
"(",
"name",
",",
"value",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GenericAuth.clear_cookie
|
Deletes the cookie with the given name.
|
bottle_auth/core/auth.py
|
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
assert self.cookie_monster, 'Cookie Monster not set'
#, path=path, domain=domain)
self.cookie_monster.delete_cookie(name)
|
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
assert self.cookie_monster, 'Cookie Monster not set'
#, path=path, domain=domain)
self.cookie_monster.delete_cookie(name)
|
[
"Deletes",
"the",
"cookie",
"with",
"the",
"given",
"name",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L234-L238
|
[
"def",
"clear_cookie",
"(",
"self",
",",
"name",
",",
"path",
"=",
"\"/\"",
",",
"domain",
"=",
"None",
")",
":",
"assert",
"self",
".",
"cookie_monster",
",",
"'Cookie Monster not set'",
"#, path=path, domain=domain)",
"self",
".",
"cookie_monster",
".",
"delete_cookie",
"(",
"name",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OpenIdMixin.authenticate_redirect
|
Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the ax_attrs keyword argument.
|
bottle_auth/core/auth.py
|
def authenticate_redirect(
self, callback_uri=None, ax_attrs=["name", "email", "language",
"username"]):
"""Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the ax_attrs keyword argument.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
def authenticate_redirect(
self, callback_uri=None, ax_attrs=["name", "email", "language",
"username"]):
"""Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the ax_attrs keyword argument.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
[
"Returns",
"the",
"authentication",
"URL",
"for",
"this",
"service",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L246-L262
|
[
"def",
"authenticate_redirect",
"(",
"self",
",",
"callback_uri",
"=",
"None",
",",
"ax_attrs",
"=",
"[",
"\"name\"",
",",
"\"email\"",
",",
"\"language\"",
",",
"\"username\"",
"]",
")",
":",
"callback_uri",
"=",
"callback_uri",
"or",
"self",
".",
"request",
".",
"uri",
"args",
"=",
"self",
".",
"_openid_args",
"(",
"callback_uri",
",",
"ax_attrs",
"=",
"ax_attrs",
")",
"self",
".",
"redirect",
"(",
"self",
".",
"_OPENID_ENDPOINT",
"+",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OpenIdMixin.get_authenticated_user
|
Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
|
bottle_auth/core/auth.py
|
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
"""
# Verify the OpenID response via direct request to the OP
# Recommendation @hmarrao, ref #3
args = dict((k, unicode(v[-1]).encode('utf-8')) for k, v in self.request.arguments.iteritems())
args["openid.mode"] = u"check_authentication"
url = self._OPENID_ENDPOINT
http = httpclient.AsyncHTTPClient()
log.debug("OpenID requesting {0} at uri {1}".format(args, url))
http.fetch(url, self.async_callback(
self._on_authentication_verified, callback),
method="POST", body=urllib.urlencode(args))
|
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
"""
# Verify the OpenID response via direct request to the OP
# Recommendation @hmarrao, ref #3
args = dict((k, unicode(v[-1]).encode('utf-8')) for k, v in self.request.arguments.iteritems())
args["openid.mode"] = u"check_authentication"
url = self._OPENID_ENDPOINT
http = httpclient.AsyncHTTPClient()
log.debug("OpenID requesting {0} at uri {1}".format(args, url))
http.fetch(url, self.async_callback(
self._on_authentication_verified, callback),
method="POST", body=urllib.urlencode(args))
|
[
"Fetches",
"the",
"authenticated",
"user",
"data",
"upon",
"redirect",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L264-L280
|
[
"def",
"get_authenticated_user",
"(",
"self",
",",
"callback",
")",
":",
"# Verify the OpenID response via direct request to the OP",
"# Recommendation @hmarrao, ref #3",
"args",
"=",
"dict",
"(",
"(",
"k",
",",
"unicode",
"(",
"v",
"[",
"-",
"1",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"request",
".",
"arguments",
".",
"iteritems",
"(",
")",
")",
"args",
"[",
"\"openid.mode\"",
"]",
"=",
"u\"check_authentication\"",
"url",
"=",
"self",
".",
"_OPENID_ENDPOINT",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"log",
".",
"debug",
"(",
"\"OpenID requesting {0} at uri {1}\"",
".",
"format",
"(",
"args",
",",
"url",
")",
")",
"http",
".",
"fetch",
"(",
"url",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_authentication_verified",
",",
"callback",
")",
",",
"method",
"=",
"\"POST\"",
",",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"args",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OAuthMixin.authorize_redirect
|
Redirects the user to obtain OAuth authorization for this service.
Twitter and FriendFeed both require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
This method sets a cookie called _oauth_request_token which is
subsequently used (and cleared) in get_authenticated_user for
security purposes.
|
bottle_auth/core/auth.py
|
def authorize_redirect(self, callback_uri=None, extra_params=None):
"""Redirects the user to obtain OAuth authorization for this service.
Twitter and FriendFeed both require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
This method sets a cookie called _oauth_request_token which is
subsequently used (and cleared) in get_authenticated_user for
security purposes.
"""
if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False):
raise Exception("This service does not support oauth_callback")
http = httpclient.AsyncHTTPClient()
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
http.fetch(self._oauth_request_token_url(callback_uri=callback_uri,
extra_params=extra_params),
self.async_callback(
self._on_request_token,
self._OAUTH_AUTHORIZE_URL,
callback_uri))
else:
http.fetch(self._oauth_request_token_url(), self.async_callback(
self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri))
|
def authorize_redirect(self, callback_uri=None, extra_params=None):
"""Redirects the user to obtain OAuth authorization for this service.
Twitter and FriendFeed both require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
This method sets a cookie called _oauth_request_token which is
subsequently used (and cleared) in get_authenticated_user for
security purposes.
"""
if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False):
raise Exception("This service does not support oauth_callback")
http = httpclient.AsyncHTTPClient()
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
http.fetch(self._oauth_request_token_url(callback_uri=callback_uri,
extra_params=extra_params),
self.async_callback(
self._on_request_token,
self._OAUTH_AUTHORIZE_URL,
callback_uri))
else:
http.fetch(self._oauth_request_token_url(), self.async_callback(
self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri))
|
[
"Redirects",
"the",
"user",
"to",
"obtain",
"OAuth",
"authorization",
"for",
"this",
"service",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L398-L423
|
[
"def",
"authorize_redirect",
"(",
"self",
",",
"callback_uri",
"=",
"None",
",",
"extra_params",
"=",
"None",
")",
":",
"if",
"callback_uri",
"and",
"getattr",
"(",
"self",
",",
"\"_OAUTH_NO_CALLBACKS\"",
",",
"False",
")",
":",
"raise",
"Exception",
"(",
"\"This service does not support oauth_callback\"",
")",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"if",
"getattr",
"(",
"self",
",",
"\"_OAUTH_VERSION\"",
",",
"\"1.0a\"",
")",
"==",
"\"1.0a\"",
":",
"http",
".",
"fetch",
"(",
"self",
".",
"_oauth_request_token_url",
"(",
"callback_uri",
"=",
"callback_uri",
",",
"extra_params",
"=",
"extra_params",
")",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_request_token",
",",
"self",
".",
"_OAUTH_AUTHORIZE_URL",
",",
"callback_uri",
")",
")",
"else",
":",
"http",
".",
"fetch",
"(",
"self",
".",
"_oauth_request_token_url",
"(",
")",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_request_token",
",",
"self",
".",
"_OAUTH_AUTHORIZE_URL",
",",
"callback_uri",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OAuthMixin.get_authenticated_user
|
Gets the OAuth authorized user and access token on callback.
This method should be called from the handler for your registered
OAuth Callback URL to complete the registration process. We call
callback with the authenticated user, which in addition to standard
attributes like 'name' includes the 'access_key' attribute, which
contains the OAuth access you can use to make authorized requests
to this service on behalf of the user.
|
bottle_auth/core/auth.py
|
def get_authenticated_user(self, callback):
"""Gets the OAuth authorized user and access token on callback.
This method should be called from the handler for your registered
OAuth Callback URL to complete the registration process. We call
callback with the authenticated user, which in addition to standard
attributes like 'name' includes the 'access_key' attribute, which
contains the OAuth access you can use to make authorized requests
to this service on behalf of the user.
"""
request_key = self.get_argument("oauth_token")
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
log.warning("Missing OAuth request token cookie")
callback(None)
return
self.clear_cookie("_oauth_request_token")
cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("|")]
if cookie_key != request_key:
log.warning("Request token does not match cookie")
callback(None)
return
token = dict(key=cookie_key, secret=cookie_secret)
if oauth_verifier:
token["verifier"] = oauth_verifier
http = httpclient.AsyncHTTPClient()
http.fetch(self._oauth_access_token_url(token), self.async_callback(
self._on_access_token, callback))
|
def get_authenticated_user(self, callback):
"""Gets the OAuth authorized user and access token on callback.
This method should be called from the handler for your registered
OAuth Callback URL to complete the registration process. We call
callback with the authenticated user, which in addition to standard
attributes like 'name' includes the 'access_key' attribute, which
contains the OAuth access you can use to make authorized requests
to this service on behalf of the user.
"""
request_key = self.get_argument("oauth_token")
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
log.warning("Missing OAuth request token cookie")
callback(None)
return
self.clear_cookie("_oauth_request_token")
cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("|")]
if cookie_key != request_key:
log.warning("Request token does not match cookie")
callback(None)
return
token = dict(key=cookie_key, secret=cookie_secret)
if oauth_verifier:
token["verifier"] = oauth_verifier
http = httpclient.AsyncHTTPClient()
http.fetch(self._oauth_access_token_url(token), self.async_callback(
self._on_access_token, callback))
|
[
"Gets",
"the",
"OAuth",
"authorized",
"user",
"and",
"access",
"token",
"on",
"callback",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L426-L455
|
[
"def",
"get_authenticated_user",
"(",
"self",
",",
"callback",
")",
":",
"request_key",
"=",
"self",
".",
"get_argument",
"(",
"\"oauth_token\"",
")",
"oauth_verifier",
"=",
"self",
".",
"get_argument",
"(",
"\"oauth_verifier\"",
",",
"None",
")",
"request_cookie",
"=",
"self",
".",
"get_cookie",
"(",
"\"_oauth_request_token\"",
")",
"if",
"not",
"request_cookie",
":",
"log",
".",
"warning",
"(",
"\"Missing OAuth request token cookie\"",
")",
"callback",
"(",
"None",
")",
"return",
"self",
".",
"clear_cookie",
"(",
"\"_oauth_request_token\"",
")",
"cookie_key",
",",
"cookie_secret",
"=",
"[",
"base64",
".",
"b64decode",
"(",
"i",
")",
"for",
"i",
"in",
"request_cookie",
".",
"split",
"(",
"\"|\"",
")",
"]",
"if",
"cookie_key",
"!=",
"request_key",
":",
"log",
".",
"warning",
"(",
"\"Request token does not match cookie\"",
")",
"callback",
"(",
"None",
")",
"return",
"token",
"=",
"dict",
"(",
"key",
"=",
"cookie_key",
",",
"secret",
"=",
"cookie_secret",
")",
"if",
"oauth_verifier",
":",
"token",
"[",
"\"verifier\"",
"]",
"=",
"oauth_verifier",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"http",
".",
"fetch",
"(",
"self",
".",
"_oauth_access_token_url",
"(",
"token",
")",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_access_token",
",",
"callback",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OAuthMixin._oauth_request_parameters
|
Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
|
bottle_auth/core/auth.py
|
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
"""
consumer_token = self._oauth_consumer_token()
base_args = dict(
oauth_consumer_key=consumer_token["key"],
oauth_token=access_token["key"],
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
)
args = {}
args.update(base_args)
args.update(parameters)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
signature = _oauth10a_signature(consumer_token, method, url, args,
access_token)
else:
signature = _oauth_signature(consumer_token, method, url, args,
access_token)
base_args["oauth_signature"] = signature
return base_args
|
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
"""
consumer_token = self._oauth_consumer_token()
base_args = dict(
oauth_consumer_key=consumer_token["key"],
oauth_token=access_token["key"],
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
)
args = {}
args.update(base_args)
args.update(parameters)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
signature = _oauth10a_signature(consumer_token, method, url, args,
access_token)
else:
signature = _oauth_signature(consumer_token, method, url, args,
access_token)
base_args["oauth_signature"] = signature
return base_args
|
[
"Returns",
"the",
"OAuth",
"parameters",
"as",
"a",
"dict",
"for",
"the",
"given",
"request",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L536-L562
|
[
"def",
"_oauth_request_parameters",
"(",
"self",
",",
"url",
",",
"access_token",
",",
"parameters",
"=",
"{",
"}",
",",
"method",
"=",
"\"GET\"",
")",
":",
"consumer_token",
"=",
"self",
".",
"_oauth_consumer_token",
"(",
")",
"base_args",
"=",
"dict",
"(",
"oauth_consumer_key",
"=",
"consumer_token",
"[",
"\"key\"",
"]",
",",
"oauth_token",
"=",
"access_token",
"[",
"\"key\"",
"]",
",",
"oauth_signature_method",
"=",
"\"HMAC-SHA1\"",
",",
"oauth_timestamp",
"=",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
",",
"oauth_nonce",
"=",
"binascii",
".",
"b2a_hex",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
",",
"oauth_version",
"=",
"getattr",
"(",
"self",
",",
"\"_OAUTH_VERSION\"",
",",
"\"1.0a\"",
")",
",",
")",
"args",
"=",
"{",
"}",
"args",
".",
"update",
"(",
"base_args",
")",
"args",
".",
"update",
"(",
"parameters",
")",
"if",
"getattr",
"(",
"self",
",",
"\"_OAUTH_VERSION\"",
",",
"\"1.0a\"",
")",
"==",
"\"1.0a\"",
":",
"signature",
"=",
"_oauth10a_signature",
"(",
"consumer_token",
",",
"method",
",",
"url",
",",
"args",
",",
"access_token",
")",
"else",
":",
"signature",
"=",
"_oauth_signature",
"(",
"consumer_token",
",",
"method",
",",
"url",
",",
"args",
",",
"access_token",
")",
"base_args",
"[",
"\"oauth_signature\"",
"]",
"=",
"signature",
"return",
"base_args"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
OAuth2Mixin.authorize_redirect
|
Redirects the user to obtain OAuth authorization for this service.
Some providers require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
|
bottle_auth/core/auth.py
|
def authorize_redirect(self, redirect_uri=None, client_id=None,
client_secret=None, extra_params=None ):
"""Redirects the user to obtain OAuth authorization for this service.
Some providers require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
"""
args = {
"redirect_uri": redirect_uri,
"client_id": client_id
}
if extra_params: args.update(extra_params)
self.redirect(
url_concat(self._OAUTH_AUTHORIZE_URL, args))
|
def authorize_redirect(self, redirect_uri=None, client_id=None,
client_secret=None, extra_params=None ):
"""Redirects the user to obtain OAuth authorization for this service.
Some providers require that you register a Callback
URL with your application. You should call this method to log the
user in, and then call get_authenticated_user() in the handler
you registered as your Callback URL to complete the authorization
process.
"""
args = {
"redirect_uri": redirect_uri,
"client_id": client_id
}
if extra_params: args.update(extra_params)
self.redirect(
url_concat(self._OAUTH_AUTHORIZE_URL, args))
|
[
"Redirects",
"the",
"user",
"to",
"obtain",
"OAuth",
"authorization",
"for",
"this",
"service",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L567-L583
|
[
"def",
"authorize_redirect",
"(",
"self",
",",
"redirect_uri",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"extra_params",
"=",
"None",
")",
":",
"args",
"=",
"{",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"\"client_id\"",
":",
"client_id",
"}",
"if",
"extra_params",
":",
"args",
".",
"update",
"(",
"extra_params",
")",
"self",
".",
"redirect",
"(",
"url_concat",
"(",
"self",
".",
"_OAUTH_AUTHORIZE_URL",
",",
"args",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
FriendFeedMixin.friendfeed_request
|
Fetches the given relative API path, e.g., "/bret/friends"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
All the FriendFeed methods are documented at
http://friendfeed.com/api/documentation.
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FriendFeedMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.friendfeed_request(
"/entry",
post_args={"body": "Testing Tornado Web Server"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
|
bottle_auth/core/auth.py
|
def friendfeed_request(self, path, callback, access_token=None,
post_args=None, **args):
"""Fetches the given relative API path, e.g., "/bret/friends"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
All the FriendFeed methods are documented at
http://friendfeed.com/api/documentation.
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FriendFeedMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.friendfeed_request(
"/entry",
post_args={"body": "Testing Tornado Web Server"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
"""
# Add the OAuth resource request signature if we have credentials
url = "http://friendfeed-api.com/v2" + path
if access_token:
all_args = {}
all_args.update(args)
all_args.update(post_args or {})
consumer_token = self._oauth_consumer_token()
method = "POST" if post_args is not None else "GET"
oauth = self._oauth_request_parameters(
url, access_token, all_args, method=method)
args.update(oauth)
if args: url += "?" + urllib.urlencode(args)
callback = self.async_callback(self._on_friendfeed_request, callback)
http = httpclient.AsyncHTTPClient()
if post_args is not None:
http.fetch(url, method="POST", body=urllib.urlencode(post_args),
callback=callback)
else:
http.fetch(url, callback=callback)
|
def friendfeed_request(self, path, callback, access_token=None,
post_args=None, **args):
"""Fetches the given relative API path, e.g., "/bret/friends"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
All the FriendFeed methods are documented at
http://friendfeed.com/api/documentation.
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FriendFeedMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.friendfeed_request(
"/entry",
post_args={"body": "Testing Tornado Web Server"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
"""
# Add the OAuth resource request signature if we have credentials
url = "http://friendfeed-api.com/v2" + path
if access_token:
all_args = {}
all_args.update(args)
all_args.update(post_args or {})
consumer_token = self._oauth_consumer_token()
method = "POST" if post_args is not None else "GET"
oauth = self._oauth_request_parameters(
url, access_token, all_args, method=method)
args.update(oauth)
if args: url += "?" + urllib.urlencode(args)
callback = self.async_callback(self._on_friendfeed_request, callback)
http = httpclient.AsyncHTTPClient()
if post_args is not None:
http.fetch(url, method="POST", body=urllib.urlencode(post_args),
callback=callback)
else:
http.fetch(url, callback=callback)
|
[
"Fetches",
"the",
"given",
"relative",
"API",
"path",
"e",
".",
"g",
".",
"/",
"bret",
"/",
"friends"
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L775-L828
|
[
"def",
"friendfeed_request",
"(",
"self",
",",
"path",
",",
"callback",
",",
"access_token",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"# Add the OAuth resource request signature if we have credentials",
"url",
"=",
"\"http://friendfeed-api.com/v2\"",
"+",
"path",
"if",
"access_token",
":",
"all_args",
"=",
"{",
"}",
"all_args",
".",
"update",
"(",
"args",
")",
"all_args",
".",
"update",
"(",
"post_args",
"or",
"{",
"}",
")",
"consumer_token",
"=",
"self",
".",
"_oauth_consumer_token",
"(",
")",
"method",
"=",
"\"POST\"",
"if",
"post_args",
"is",
"not",
"None",
"else",
"\"GET\"",
"oauth",
"=",
"self",
".",
"_oauth_request_parameters",
"(",
"url",
",",
"access_token",
",",
"all_args",
",",
"method",
"=",
"method",
")",
"args",
".",
"update",
"(",
"oauth",
")",
"if",
"args",
":",
"url",
"+=",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
"callback",
"=",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_friendfeed_request",
",",
"callback",
")",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"if",
"post_args",
"is",
"not",
"None",
":",
"http",
".",
"fetch",
"(",
"url",
",",
"method",
"=",
"\"POST\"",
",",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"post_args",
")",
",",
"callback",
"=",
"callback",
")",
"else",
":",
"http",
".",
"fetch",
"(",
"url",
",",
"callback",
"=",
"callback",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GoogleMixin.authorize_redirect
|
Authenticates and authorizes for the given Google resource.
Some of the available resources are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar - http://www.google.com/calendar/feeds/
* Finance - http://finance.google.com/finance/feeds/
You can authorize multiple resources by separating the resource
URLs with a space.
|
bottle_auth/core/auth.py
|
def authorize_redirect(self, oauth_scope, callback_uri=None,
ax_attrs=["name","email","language","username"]):
"""Authenticates and authorizes for the given Google resource.
Some of the available resources are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar - http://www.google.com/calendar/feeds/
* Finance - http://finance.google.com/finance/feeds/
You can authorize multiple resources by separating the resource
URLs with a space.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs,
oauth_scope=oauth_scope)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
def authorize_redirect(self, oauth_scope, callback_uri=None,
ax_attrs=["name","email","language","username"]):
"""Authenticates and authorizes for the given Google resource.
Some of the available resources are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar - http://www.google.com/calendar/feeds/
* Finance - http://finance.google.com/finance/feeds/
You can authorize multiple resources by separating the resource
URLs with a space.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs,
oauth_scope=oauth_scope)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
[
"Authenticates",
"and",
"authorizes",
"for",
"the",
"given",
"Google",
"resource",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L885-L901
|
[
"def",
"authorize_redirect",
"(",
"self",
",",
"oauth_scope",
",",
"callback_uri",
"=",
"None",
",",
"ax_attrs",
"=",
"[",
"\"name\"",
",",
"\"email\"",
",",
"\"language\"",
",",
"\"username\"",
"]",
")",
":",
"callback_uri",
"=",
"callback_uri",
"or",
"self",
".",
"request",
".",
"uri",
"args",
"=",
"self",
".",
"_openid_args",
"(",
"callback_uri",
",",
"ax_attrs",
"=",
"ax_attrs",
",",
"oauth_scope",
"=",
"oauth_scope",
")",
"self",
".",
"redirect",
"(",
"self",
".",
"_OPENID_ENDPOINT",
"+",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
GoogleMixin.get_authenticated_user
|
Fetches the authenticated user data upon redirect.
|
bottle_auth/core/auth.py
|
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect."""
# Look to see if we are doing combined OpenID/OAuth
oauth_ns = ""
for name, values in self.request.arguments.iteritems():
if name.startswith("openid.ns.") and \
values[-1] == u"http://specs.openid.net/extensions/oauth/1.0":
oauth_ns = name[10:]
break
token = self.get_argument("openid." + oauth_ns + ".request_token", "")
if token:
http = httpclient.AsyncHTTPClient()
token = dict(key=token, secret="")
http.fetch(self._oauth_access_token_url(token),
self.async_callback(self._on_access_token, callback))
else:
OpenIdMixin.get_authenticated_user(self, callback)
|
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect."""
# Look to see if we are doing combined OpenID/OAuth
oauth_ns = ""
for name, values in self.request.arguments.iteritems():
if name.startswith("openid.ns.") and \
values[-1] == u"http://specs.openid.net/extensions/oauth/1.0":
oauth_ns = name[10:]
break
token = self.get_argument("openid." + oauth_ns + ".request_token", "")
if token:
http = httpclient.AsyncHTTPClient()
token = dict(key=token, secret="")
http.fetch(self._oauth_access_token_url(token),
self.async_callback(self._on_access_token, callback))
else:
OpenIdMixin.get_authenticated_user(self, callback)
|
[
"Fetches",
"the",
"authenticated",
"user",
"data",
"upon",
"redirect",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L903-L919
|
[
"def",
"get_authenticated_user",
"(",
"self",
",",
"callback",
")",
":",
"# Look to see if we are doing combined OpenID/OAuth",
"oauth_ns",
"=",
"\"\"",
"for",
"name",
",",
"values",
"in",
"self",
".",
"request",
".",
"arguments",
".",
"iteritems",
"(",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"\"openid.ns.\"",
")",
"and",
"values",
"[",
"-",
"1",
"]",
"==",
"u\"http://specs.openid.net/extensions/oauth/1.0\"",
":",
"oauth_ns",
"=",
"name",
"[",
"10",
":",
"]",
"break",
"token",
"=",
"self",
".",
"get_argument",
"(",
"\"openid.\"",
"+",
"oauth_ns",
"+",
"\".request_token\"",
",",
"\"\"",
")",
"if",
"token",
":",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"token",
"=",
"dict",
"(",
"key",
"=",
"token",
",",
"secret",
"=",
"\"\"",
")",
"http",
".",
"fetch",
"(",
"self",
".",
"_oauth_access_token_url",
"(",
"token",
")",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_access_token",
",",
"callback",
")",
")",
"else",
":",
"OpenIdMixin",
".",
"get_authenticated_user",
"(",
"self",
",",
"callback",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
FacebookMixin.facebook_request
|
Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include 'session_key' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is an example for the stream.get() method::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
method="stream.get",
callback=self.async_callback(self._on_stream),
session_key=self.current_user["session_key"])
def _on_stream(self, stream):
if stream is None:
# Not authorized to read the stream yet?
self.redirect(self.authorize_redirect("read_stream"))
return
self.render("stream.html", stream=stream)
|
bottle_auth/core/auth.py
|
def facebook_request(self, method, callback, **args):
"""Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include 'session_key' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is an example for the stream.get() method::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
method="stream.get",
callback=self.async_callback(self._on_stream),
session_key=self.current_user["session_key"])
def _on_stream(self, stream):
if stream is None:
# Not authorized to read the stream yet?
self.redirect(self.authorize_redirect("read_stream"))
return
self.render("stream.html", stream=stream)
"""
self.require_setting("facebook_api_key", "Facebook Connect")
self.require_setting("facebook_secret", "Facebook Connect")
if not method.startswith("facebook."):
method = "facebook." + method
args["api_key"] = self.settings["facebook_api_key"]
args["v"] = "1.0"
args["method"] = method
args["call_id"] = str(long(time.time() * 1e6))
args["format"] = "json"
args["sig"] = self._signature(args)
url = "http://api.facebook.com/restserver.php?" + \
urllib.urlencode(args)
http = httpclient.AsyncHTTPClient()
http.fetch(url, callback=self.async_callback(
self._parse_response, callback))
|
def facebook_request(self, method, callback, **args):
"""Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include 'session_key' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is an example for the stream.get() method::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
method="stream.get",
callback=self.async_callback(self._on_stream),
session_key=self.current_user["session_key"])
def _on_stream(self, stream):
if stream is None:
# Not authorized to read the stream yet?
self.redirect(self.authorize_redirect("read_stream"))
return
self.render("stream.html", stream=stream)
"""
self.require_setting("facebook_api_key", "Facebook Connect")
self.require_setting("facebook_secret", "Facebook Connect")
if not method.startswith("facebook."):
method = "facebook." + method
args["api_key"] = self.settings["facebook_api_key"]
args["v"] = "1.0"
args["method"] = method
args["call_id"] = str(long(time.time() * 1e6))
args["format"] = "json"
args["sig"] = self._signature(args)
url = "http://api.facebook.com/restserver.php?" + \
urllib.urlencode(args)
http = httpclient.AsyncHTTPClient()
http.fetch(url, callback=self.async_callback(
self._parse_response, callback))
|
[
"Makes",
"a",
"Facebook",
"API",
"REST",
"request",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L1027-L1071
|
[
"def",
"facebook_request",
"(",
"self",
",",
"method",
",",
"callback",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"require_setting",
"(",
"\"facebook_api_key\"",
",",
"\"Facebook Connect\"",
")",
"self",
".",
"require_setting",
"(",
"\"facebook_secret\"",
",",
"\"Facebook Connect\"",
")",
"if",
"not",
"method",
".",
"startswith",
"(",
"\"facebook.\"",
")",
":",
"method",
"=",
"\"facebook.\"",
"+",
"method",
"args",
"[",
"\"api_key\"",
"]",
"=",
"self",
".",
"settings",
"[",
"\"facebook_api_key\"",
"]",
"args",
"[",
"\"v\"",
"]",
"=",
"\"1.0\"",
"args",
"[",
"\"method\"",
"]",
"=",
"method",
"args",
"[",
"\"call_id\"",
"]",
"=",
"str",
"(",
"long",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
")",
"args",
"[",
"\"format\"",
"]",
"=",
"\"json\"",
"args",
"[",
"\"sig\"",
"]",
"=",
"self",
".",
"_signature",
"(",
"args",
")",
"url",
"=",
"\"http://api.facebook.com/restserver.php?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"http",
".",
"fetch",
"(",
"url",
",",
"callback",
"=",
"self",
".",
"async_callback",
"(",
"self",
".",
"_parse_response",
",",
"callback",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
FacebookGraphMixin.get_authenticated_user
|
Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("code", False):
self.get_authenticated_user(
redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"),
callback=self.async_callback(
self._on_login))
return
self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
extra_params={"scope": "read_stream,offline_access"})
def _on_login(self, user):
log.error(user)
self.finish()
|
bottle_auth/core/auth.py
|
def get_authenticated_user(self, redirect_uri, client_id, client_secret,
code, callback, fields=None):
"""Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("code", False):
self.get_authenticated_user(
redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"),
callback=self.async_callback(
self._on_login))
return
self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
extra_params={"scope": "read_stream,offline_access"})
def _on_login(self, user):
log.error(user)
self.finish()
"""
http = httpclient.AsyncHTTPClient()
args = {
"redirect_uri": redirect_uri,
"code": code,
"client_id": client_id,
"client_secret": client_secret,
}
#fields = set(['id', 'name', 'first_name', 'last_name',
# 'locale', 'picture', 'link'])
#if extra_fields: fields.update(extra_fields)
if fields:
fields = fields.split(',')
http.fetch(self._oauth_request_token_url(**args),
self.async_callback(self._on_access_token, redirect_uri, client_id,
client_secret, callback, fields))
|
def get_authenticated_user(self, redirect_uri, client_id, client_secret,
code, callback, fields=None):
"""Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("code", False):
self.get_authenticated_user(
redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"),
callback=self.async_callback(
self._on_login))
return
self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
extra_params={"scope": "read_stream,offline_access"})
def _on_login(self, user):
log.error(user)
self.finish()
"""
http = httpclient.AsyncHTTPClient()
args = {
"redirect_uri": redirect_uri,
"code": code,
"client_id": client_id,
"client_secret": client_secret,
}
#fields = set(['id', 'name', 'first_name', 'last_name',
# 'locale', 'picture', 'link'])
#if extra_fields: fields.update(extra_fields)
if fields:
fields = fields.split(',')
http.fetch(self._oauth_request_token_url(**args),
self.async_callback(self._on_access_token, redirect_uri, client_id,
client_secret, callback, fields))
|
[
"Handles",
"the",
"login",
"for",
"the",
"Facebook",
"user",
"returning",
"a",
"user",
"object",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L1120-L1163
|
[
"def",
"get_authenticated_user",
"(",
"self",
",",
"redirect_uri",
",",
"client_id",
",",
"client_secret",
",",
"code",
",",
"callback",
",",
"fields",
"=",
"None",
")",
":",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"args",
"=",
"{",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"\"code\"",
":",
"code",
",",
"\"client_id\"",
":",
"client_id",
",",
"\"client_secret\"",
":",
"client_secret",
",",
"}",
"#fields = set(['id', 'name', 'first_name', 'last_name',",
"# 'locale', 'picture', 'link'])",
"#if extra_fields: fields.update(extra_fields)",
"if",
"fields",
":",
"fields",
"=",
"fields",
".",
"split",
"(",
"','",
")",
"http",
".",
"fetch",
"(",
"self",
".",
"_oauth_request_token_url",
"(",
"*",
"*",
"args",
")",
",",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_access_token",
",",
"redirect_uri",
",",
"client_id",
",",
"client_secret",
",",
"callback",
",",
"fields",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
FacebookGraphMixin.facebook_request
|
Fetches the given relative API path, e.g., "/btaylor/picture"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
An introduction to the Facebook Graph API can be found at
http://developers.facebook.com/docs/api
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookGraphMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
"/me/feed",
post_args={"message": "I am posting from my Tornado application!"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
|
bottle_auth/core/auth.py
|
def facebook_request(self, path, callback, access_token=None,
post_args=None, **args):
"""Fetches the given relative API path, e.g., "/btaylor/picture"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
An introduction to the Facebook Graph API can be found at
http://developers.facebook.com/docs/api
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookGraphMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
"/me/feed",
post_args={"message": "I am posting from my Tornado application!"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
"""
url = "https://graph.facebook.com" + path
all_args = {}
if access_token:
all_args["access_token"] = access_token
all_args.update(args)
all_args.update(post_args or {})
if all_args: url += "?" + urllib.urlencode(all_args)
callback = self.async_callback(self._on_facebook_request, callback)
http = httpclient.AsyncHTTPClient()
if post_args is not None:
http.fetch(url, method="POST", body=urllib.urlencode(post_args),
callback=callback)
else:
http.fetch(url, callback=callback)
|
def facebook_request(self, path, callback, access_token=None,
post_args=None, **args):
"""Fetches the given relative API path, e.g., "/btaylor/picture"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.
An introduction to the Facebook Graph API can be found at
http://developers.facebook.com/docs/api
Many methods require an OAuth access token which you can obtain
through authorize_redirect() and get_authenticated_user(). The
user returned through that process includes an 'access_token'
attribute that can be used to make authenticated requests via
this method. Example usage::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookGraphMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
"/me/feed",
post_args={"message": "I am posting from my Tornado application!"},
access_token=self.current_user["access_token"],
callback=self.async_callback(self._on_post))
def _on_post(self, new_entry):
if not new_entry:
# Call failed; perhaps missing permission?
self.authorize_redirect()
return
self.finish("Posted a message!")
"""
url = "https://graph.facebook.com" + path
all_args = {}
if access_token:
all_args["access_token"] = access_token
all_args.update(args)
all_args.update(post_args or {})
if all_args: url += "?" + urllib.urlencode(all_args)
callback = self.async_callback(self._on_facebook_request, callback)
http = httpclient.AsyncHTTPClient()
if post_args is not None:
http.fetch(url, method="POST", body=urllib.urlencode(post_args),
callback=callback)
else:
http.fetch(url, callback=callback)
|
[
"Fetches",
"the",
"given",
"relative",
"API",
"path",
"e",
".",
"g",
".",
"/",
"btaylor",
"/",
"picture"
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L1209-L1257
|
[
"def",
"facebook_request",
"(",
"self",
",",
"path",
",",
"callback",
",",
"access_token",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"url",
"=",
"\"https://graph.facebook.com\"",
"+",
"path",
"all_args",
"=",
"{",
"}",
"if",
"access_token",
":",
"all_args",
"[",
"\"access_token\"",
"]",
"=",
"access_token",
"all_args",
".",
"update",
"(",
"args",
")",
"all_args",
".",
"update",
"(",
"post_args",
"or",
"{",
"}",
")",
"if",
"all_args",
":",
"url",
"+=",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"all_args",
")",
"callback",
"=",
"self",
".",
"async_callback",
"(",
"self",
".",
"_on_facebook_request",
",",
"callback",
")",
"http",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"if",
"post_args",
"is",
"not",
"None",
":",
"http",
".",
"fetch",
"(",
"url",
",",
"method",
"=",
"\"POST\"",
",",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"post_args",
")",
",",
"callback",
"=",
"callback",
")",
"else",
":",
"http",
".",
"fetch",
"(",
"url",
",",
"callback",
"=",
"callback",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
url_concat
|
Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
|
bottle_auth/core/httputil.py
|
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args: return url
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urllib.urlencode(args)
|
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args: return url
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urllib.urlencode(args)
|
[
"Concatenate",
"url",
"and",
"argument",
"dictionary",
"regardless",
"of",
"whether",
"url",
"has",
"existing",
"query",
"parameters",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L179-L189
|
[
"def",
"url_concat",
"(",
"url",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"url",
"if",
"url",
"[",
"-",
"1",
"]",
"not",
"in",
"(",
"'?'",
",",
"'&'",
")",
":",
"url",
"+=",
"'&'",
"if",
"(",
"'?'",
"in",
"url",
")",
"else",
"'?'",
"return",
"url",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
parse_multipart_form_data
|
Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
|
bottle_auth/core/httputil.py
|
def parse_multipart_form_data(boundary, data, arguments, files):
"""Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
"""
# The standard allows for the boundary to be quoted in the header,
# although it's rare (it happens at least for google app engine
# xmpp). I think we're also supposed to handle backslash-escapes
# here but I'll save that until we see a client that uses them
# in the wild.
if boundary.startswith(b('"')) and boundary.endswith(b('"')):
boundary = boundary[1:-1]
if data.endswith(b("\r\n")):
footer_length = len(boundary) + 6
else:
footer_length = len(boundary) + 4
parts = data[:-footer_length].split(b("--") + boundary + b("\r\n"))
for part in parts:
if not part: continue
eoh = part.find(b("\r\n\r\n"))
if eoh == -1:
logging.warning("multipart/form-data missing headers")
continue
headers = HTTPHeaders.parse(part[:eoh].decode("utf-8"))
disp_header = headers.get("Content-Disposition", "")
disposition, disp_params = _parse_header(disp_header)
if disposition != "form-data" or not part.endswith(b("\r\n")):
logging.warning("Invalid multipart/form-data")
continue
value = part[eoh + 4:-2]
if not disp_params.get("name"):
logging.warning("multipart/form-data value missing name")
continue
name = disp_params["name"]
if disp_params.get("filename"):
ctype = headers.get("Content-Type", "application/unknown")
files.setdefault(name, []).append(dict(
filename=disp_params["filename"], body=value,
content_type=ctype))
else:
arguments.setdefault(name, []).append(value)
|
def parse_multipart_form_data(boundary, data, arguments, files):
"""Parses a multipart/form-data body.
The boundary and data parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
"""
# The standard allows for the boundary to be quoted in the header,
# although it's rare (it happens at least for google app engine
# xmpp). I think we're also supposed to handle backslash-escapes
# here but I'll save that until we see a client that uses them
# in the wild.
if boundary.startswith(b('"')) and boundary.endswith(b('"')):
boundary = boundary[1:-1]
if data.endswith(b("\r\n")):
footer_length = len(boundary) + 6
else:
footer_length = len(boundary) + 4
parts = data[:-footer_length].split(b("--") + boundary + b("\r\n"))
for part in parts:
if not part: continue
eoh = part.find(b("\r\n\r\n"))
if eoh == -1:
logging.warning("multipart/form-data missing headers")
continue
headers = HTTPHeaders.parse(part[:eoh].decode("utf-8"))
disp_header = headers.get("Content-Disposition", "")
disposition, disp_params = _parse_header(disp_header)
if disposition != "form-data" or not part.endswith(b("\r\n")):
logging.warning("Invalid multipart/form-data")
continue
value = part[eoh + 4:-2]
if not disp_params.get("name"):
logging.warning("multipart/form-data value missing name")
continue
name = disp_params["name"]
if disp_params.get("filename"):
ctype = headers.get("Content-Type", "application/unknown")
files.setdefault(name, []).append(dict(
filename=disp_params["filename"], body=value,
content_type=ctype))
else:
arguments.setdefault(name, []).append(value)
|
[
"Parses",
"a",
"multipart",
"/",
"form",
"-",
"data",
"body",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L191-L233
|
[
"def",
"parse_multipart_form_data",
"(",
"boundary",
",",
"data",
",",
"arguments",
",",
"files",
")",
":",
"# The standard allows for the boundary to be quoted in the header,",
"# although it's rare (it happens at least for google app engine",
"# xmpp). I think we're also supposed to handle backslash-escapes",
"# here but I'll save that until we see a client that uses them",
"# in the wild.",
"if",
"boundary",
".",
"startswith",
"(",
"b",
"(",
"'\"'",
")",
")",
"and",
"boundary",
".",
"endswith",
"(",
"b",
"(",
"'\"'",
")",
")",
":",
"boundary",
"=",
"boundary",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"data",
".",
"endswith",
"(",
"b",
"(",
"\"\\r\\n\"",
")",
")",
":",
"footer_length",
"=",
"len",
"(",
"boundary",
")",
"+",
"6",
"else",
":",
"footer_length",
"=",
"len",
"(",
"boundary",
")",
"+",
"4",
"parts",
"=",
"data",
"[",
":",
"-",
"footer_length",
"]",
".",
"split",
"(",
"b",
"(",
"\"--\"",
")",
"+",
"boundary",
"+",
"b",
"(",
"\"\\r\\n\"",
")",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"not",
"part",
":",
"continue",
"eoh",
"=",
"part",
".",
"find",
"(",
"b",
"(",
"\"\\r\\n\\r\\n\"",
")",
")",
"if",
"eoh",
"==",
"-",
"1",
":",
"logging",
".",
"warning",
"(",
"\"multipart/form-data missing headers\"",
")",
"continue",
"headers",
"=",
"HTTPHeaders",
".",
"parse",
"(",
"part",
"[",
":",
"eoh",
"]",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"disp_header",
"=",
"headers",
".",
"get",
"(",
"\"Content-Disposition\"",
",",
"\"\"",
")",
"disposition",
",",
"disp_params",
"=",
"_parse_header",
"(",
"disp_header",
")",
"if",
"disposition",
"!=",
"\"form-data\"",
"or",
"not",
"part",
".",
"endswith",
"(",
"b",
"(",
"\"\\r\\n\"",
")",
")",
":",
"logging",
".",
"warning",
"(",
"\"Invalid multipart/form-data\"",
")",
"continue",
"value",
"=",
"part",
"[",
"eoh",
"+",
"4",
":",
"-",
"2",
"]",
"if",
"not",
"disp_params",
".",
"get",
"(",
"\"name\"",
")",
":",
"logging",
".",
"warning",
"(",
"\"multipart/form-data value missing name\"",
")",
"continue",
"name",
"=",
"disp_params",
"[",
"\"name\"",
"]",
"if",
"disp_params",
".",
"get",
"(",
"\"filename\"",
")",
":",
"ctype",
"=",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"application/unknown\"",
")",
"files",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"dict",
"(",
"filename",
"=",
"disp_params",
"[",
"\"filename\"",
"]",
",",
"body",
"=",
"value",
",",
"content_type",
"=",
"ctype",
")",
")",
"else",
":",
"arguments",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"value",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
_parse_header
|
Parse a Content-type like header.
Return the main content-type and a dictionary of options.
|
bottle_auth/core/httputil.py
|
def _parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
pdict[name] = value
return key, pdict
|
def _parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
pdict[name] = value
return key, pdict
|
[
"Parse",
"a",
"Content",
"-",
"type",
"like",
"header",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L251-L269
|
[
"def",
"_parse_header",
"(",
"line",
")",
":",
"parts",
"=",
"_parseparam",
"(",
"';'",
"+",
"line",
")",
"key",
"=",
"parts",
".",
"next",
"(",
")",
"pdict",
"=",
"{",
"}",
"for",
"p",
"in",
"parts",
":",
"i",
"=",
"p",
".",
"find",
"(",
"'='",
")",
"if",
"i",
">=",
"0",
":",
"name",
"=",
"p",
"[",
":",
"i",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"value",
"=",
"p",
"[",
"i",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"value",
")",
">=",
"2",
"and",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
"value",
"=",
"value",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"'\\\\'",
")",
".",
"replace",
"(",
"'\\\\\"'",
",",
"'\"'",
")",
"pdict",
"[",
"name",
"]",
"=",
"value",
"return",
"key",
",",
"pdict"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders.add
|
Adds a new value for the given key.
|
bottle_auth/core/httputil.py
|
def add(self, name, value):
"""Adds a new value for the given key."""
norm_name = HTTPHeaders._normalize_name(name)
self._last_key = norm_name
if norm_name in self:
# bypass our override of __setitem__ since it modifies _as_list
dict.__setitem__(self, norm_name, self[norm_name] + ',' + value)
self._as_list[norm_name].append(value)
else:
self[norm_name] = value
|
def add(self, name, value):
"""Adds a new value for the given key."""
norm_name = HTTPHeaders._normalize_name(name)
self._last_key = norm_name
if norm_name in self:
# bypass our override of __setitem__ since it modifies _as_list
dict.__setitem__(self, norm_name, self[norm_name] + ',' + value)
self._as_list[norm_name].append(value)
else:
self[norm_name] = value
|
[
"Adds",
"a",
"new",
"value",
"for",
"the",
"given",
"key",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L77-L86
|
[
"def",
"add",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"norm_name",
"=",
"HTTPHeaders",
".",
"_normalize_name",
"(",
"name",
")",
"self",
".",
"_last_key",
"=",
"norm_name",
"if",
"norm_name",
"in",
"self",
":",
"# bypass our override of __setitem__ since it modifies _as_list",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"norm_name",
",",
"self",
"[",
"norm_name",
"]",
"+",
"','",
"+",
"value",
")",
"self",
".",
"_as_list",
"[",
"norm_name",
"]",
".",
"append",
"(",
"value",
")",
"else",
":",
"self",
"[",
"norm_name",
"]",
"=",
"value"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders.get_list
|
Returns all values for the given header as a list.
|
bottle_auth/core/httputil.py
|
def get_list(self, name):
"""Returns all values for the given header as a list."""
norm_name = HTTPHeaders._normalize_name(name)
return self._as_list.get(norm_name, [])
|
def get_list(self, name):
"""Returns all values for the given header as a list."""
norm_name = HTTPHeaders._normalize_name(name)
return self._as_list.get(norm_name, [])
|
[
"Returns",
"all",
"values",
"for",
"the",
"given",
"header",
"as",
"a",
"list",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L88-L91
|
[
"def",
"get_list",
"(",
"self",
",",
"name",
")",
":",
"norm_name",
"=",
"HTTPHeaders",
".",
"_normalize_name",
"(",
"name",
")",
"return",
"self",
".",
"_as_list",
".",
"get",
"(",
"norm_name",
",",
"[",
"]",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders.get_all
|
Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
|
bottle_auth/core/httputil.py
|
def get_all(self):
"""Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
"""
for name, list in self._as_list.iteritems():
for value in list:
yield (name, value)
|
def get_all(self):
"""Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
"""
for name, list in self._as_list.iteritems():
for value in list:
yield (name, value)
|
[
"Returns",
"an",
"iterable",
"of",
"all",
"(",
"name",
"value",
")",
"pairs",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L93-L101
|
[
"def",
"get_all",
"(",
"self",
")",
":",
"for",
"name",
",",
"list",
"in",
"self",
".",
"_as_list",
".",
"iteritems",
"(",
")",
":",
"for",
"value",
"in",
"list",
":",
"yield",
"(",
"name",
",",
"value",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders.parse_line
|
Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
|
bottle_auth/core/httputil.py
|
def parse_line(self, line):
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
# continuation of a multi-line header
new_part = ' ' + line.lstrip()
self._as_list[self._last_key][-1] += new_part
dict.__setitem__(self, self._last_key,
self[self._last_key] + new_part)
else:
name, value = line.split(":", 1)
self.add(name, value.strip())
|
def parse_line(self, line):
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
# continuation of a multi-line header
new_part = ' ' + line.lstrip()
self._as_list[self._last_key][-1] += new_part
dict.__setitem__(self, self._last_key,
self[self._last_key] + new_part)
else:
name, value = line.split(":", 1)
self.add(name, value.strip())
|
[
"Updates",
"the",
"dictionary",
"with",
"a",
"single",
"header",
"line",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L103-L119
|
[
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"[",
"0",
"]",
".",
"isspace",
"(",
")",
":",
"# continuation of a multi-line header",
"new_part",
"=",
"' '",
"+",
"line",
".",
"lstrip",
"(",
")",
"self",
".",
"_as_list",
"[",
"self",
".",
"_last_key",
"]",
"[",
"-",
"1",
"]",
"+=",
"new_part",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"self",
".",
"_last_key",
",",
"self",
"[",
"self",
".",
"_last_key",
"]",
"+",
"new_part",
")",
"else",
":",
"name",
",",
"value",
"=",
"line",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"self",
".",
"add",
"(",
"name",
",",
"value",
".",
"strip",
"(",
")",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders.parse
|
Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
|
bottle_auth/core/httputil.py
|
def parse(cls, headers):
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
"""
h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h
|
def parse(cls, headers):
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
"""
h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h
|
[
"Returns",
"a",
"dictionary",
"from",
"HTTP",
"header",
"text",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L122-L133
|
[
"def",
"parse",
"(",
"cls",
",",
"headers",
")",
":",
"h",
"=",
"cls",
"(",
")",
"for",
"line",
"in",
"headers",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
":",
"h",
".",
"parse_line",
"(",
"line",
")",
"return",
"h"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
HTTPHeaders._normalize_name
|
Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
|
bottle_auth/core/httputil.py
|
def _normalize_name(name):
"""Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
"""
try:
return HTTPHeaders._normalized_headers[name]
except KeyError:
if HTTPHeaders._NORMALIZED_HEADER_RE.match(name):
normalized = name
else:
normalized = "-".join([w.capitalize() for w in name.split("-")])
HTTPHeaders._normalized_headers[name] = normalized
return normalized
|
def _normalize_name(name):
"""Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
"""
try:
return HTTPHeaders._normalized_headers[name]
except KeyError:
if HTTPHeaders._NORMALIZED_HEADER_RE.match(name):
normalized = name
else:
normalized = "-".join([w.capitalize() for w in name.split("-")])
HTTPHeaders._normalized_headers[name] = normalized
return normalized
|
[
"Converts",
"a",
"name",
"to",
"Http",
"-",
"Header",
"-",
"Case",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L162-L176
|
[
"def",
"_normalize_name",
"(",
"name",
")",
":",
"try",
":",
"return",
"HTTPHeaders",
".",
"_normalized_headers",
"[",
"name",
"]",
"except",
"KeyError",
":",
"if",
"HTTPHeaders",
".",
"_NORMALIZED_HEADER_RE",
".",
"match",
"(",
"name",
")",
":",
"normalized",
"=",
"name",
"else",
":",
"normalized",
"=",
"\"-\"",
".",
"join",
"(",
"[",
"w",
".",
"capitalize",
"(",
")",
"for",
"w",
"in",
"name",
".",
"split",
"(",
"\"-\"",
")",
"]",
")",
"HTTPHeaders",
".",
"_normalized_headers",
"[",
"name",
"]",
"=",
"normalized",
"return",
"normalized"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
utf8
|
Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
|
bottle_auth/core/escape.py
|
def utf8(value):
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):
return value
assert isinstance(value, unicode)
return value.encode("utf-8")
|
def utf8(value):
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):
return value
assert isinstance(value, unicode)
return value.encode("utf-8")
|
[
"Converts",
"a",
"string",
"argument",
"to",
"a",
"byte",
"string",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/escape.py#L153-L162
|
[
"def",
"utf8",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_UTF8_TYPES",
")",
":",
"return",
"value",
"assert",
"isinstance",
"(",
"value",
",",
"unicode",
")",
"return",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
to_unicode
|
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
|
bottle_auth/core/escape.py
|
def to_unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
def to_unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
[
"Converts",
"a",
"string",
"argument",
"to",
"a",
"unicode",
"string",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/escape.py#L165-L174
|
[
"def",
"to_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_TO_UNICODE_TYPES",
")",
":",
"return",
"value",
"assert",
"isinstance",
"(",
"value",
",",
"bytes",
")",
"return",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
to_basestring
|
Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode.
|
bottle_auth/core/escape.py
|
def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode.
"""
if isinstance(value, _BASESTRING_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode.
"""
if isinstance(value, _BASESTRING_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
[
"Converts",
"a",
"string",
"argument",
"to",
"a",
"subclass",
"of",
"basestring",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/escape.py#L188-L200
|
[
"def",
"to_basestring",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_BASESTRING_TYPES",
")",
":",
"return",
"value",
"assert",
"isinstance",
"(",
"value",
",",
"bytes",
")",
"return",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
recursive_unicode
|
Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
|
bottle_auth/core/escape.py
|
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.iteritems())
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)
elif isinstance(obj, tuple):
return tuple(recursive_unicode(i) for i in obj)
elif isinstance(obj, bytes):
return to_unicode(obj)
else:
return obj
|
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.iteritems())
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)
elif isinstance(obj, tuple):
return tuple(recursive_unicode(i) for i in obj)
elif isinstance(obj, bytes):
return to_unicode(obj)
else:
return obj
|
[
"Walks",
"a",
"simple",
"data",
"structure",
"converting",
"byte",
"strings",
"to",
"unicode",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/escape.py#L202-L216
|
[
"def",
"recursive_unicode",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"recursive_unicode",
"(",
"k",
")",
",",
"recursive_unicode",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"obj",
".",
"iteritems",
"(",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"list",
"(",
"recursive_unicode",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"recursive_unicode",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"return",
"to_unicode",
"(",
"obj",
")",
"else",
":",
"return",
"obj"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
AuthPlugin.setup
|
Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available.
|
bottle_auth/__init__.py
|
def setup(self, app):
""" Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available."""
for other in app.plugins:
if not isinstance(other, AuthPlugin):
continue
if other.keyword == self.keyword:
raise bottle.PluginError("Found another auth plugin "
"with conflicting settings ("
"non-unique keyword).")
|
def setup(self, app):
""" Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available."""
for other in app.plugins:
if not isinstance(other, AuthPlugin):
continue
if other.keyword == self.keyword:
raise bottle.PluginError("Found another auth plugin "
"with conflicting settings ("
"non-unique keyword).")
|
[
"Make",
"sure",
"that",
"other",
"installed",
"plugins",
"don",
"t",
"affect",
"the",
"same",
"keyword",
"argument",
"and",
"check",
"if",
"metadata",
"is",
"available",
"."
] |
avelino/bottle-auth
|
python
|
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/__init__.py#L18-L27
|
[
"def",
"setup",
"(",
"self",
",",
"app",
")",
":",
"for",
"other",
"in",
"app",
".",
"plugins",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"AuthPlugin",
")",
":",
"continue",
"if",
"other",
".",
"keyword",
"==",
"self",
".",
"keyword",
":",
"raise",
"bottle",
".",
"PluginError",
"(",
"\"Found another auth plugin \"",
"\"with conflicting settings (\"",
"\"non-unique keyword).\"",
")"
] |
db07e526864aeac05ee68444b47e5db29540ce18
|
test
|
iter_subclasses
|
Generator over all subclasses of a given class, in depth-first order.
>>> bool in list(iter_subclasses(int))
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in iter_subclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> res = [cls.__name__ for cls in iter_subclasses(object)]
>>> 'type' in res
True
>>> 'tuple' in res
True
>>> len(res) > 100
True
|
jaraco/classes/ancestry.py
|
def iter_subclasses(cls, _seen=None):
"""
Generator over all subclasses of a given class, in depth-first order.
>>> bool in list(iter_subclasses(int))
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in iter_subclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> res = [cls.__name__ for cls in iter_subclasses(object)]
>>> 'type' in res
True
>>> 'tuple' in res
True
>>> len(res) > 100
True
"""
if not isinstance(cls, type):
raise TypeError(
'iter_subclasses must be called with '
'new-style classes, not %.100r' % cls
)
if _seen is None:
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError: # fails only when cls is type
subs = cls.__subclasses__(cls)
for sub in subs:
if sub in _seen:
continue
_seen.add(sub)
yield sub
for sub in iter_subclasses(sub, _seen):
yield sub
|
def iter_subclasses(cls, _seen=None):
"""
Generator over all subclasses of a given class, in depth-first order.
>>> bool in list(iter_subclasses(int))
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in iter_subclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> res = [cls.__name__ for cls in iter_subclasses(object)]
>>> 'type' in res
True
>>> 'tuple' in res
True
>>> len(res) > 100
True
"""
if not isinstance(cls, type):
raise TypeError(
'iter_subclasses must be called with '
'new-style classes, not %.100r' % cls
)
if _seen is None:
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError: # fails only when cls is type
subs = cls.__subclasses__(cls)
for sub in subs:
if sub in _seen:
continue
_seen.add(sub)
yield sub
for sub in iter_subclasses(sub, _seen):
yield sub
|
[
"Generator",
"over",
"all",
"subclasses",
"of",
"a",
"given",
"class",
"in",
"depth",
"-",
"first",
"order",
"."
] |
jaraco/jaraco.classes
|
python
|
https://github.com/jaraco/jaraco.classes/blob/6347957478d589101a0774464d8d282520c2c990/jaraco/classes/ancestry.py#L30-L75
|
[
"def",
"iter_subclasses",
"(",
"cls",
",",
"_seen",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
",",
"type",
")",
":",
"raise",
"TypeError",
"(",
"'iter_subclasses must be called with '",
"'new-style classes, not %.100r'",
"%",
"cls",
")",
"if",
"_seen",
"is",
"None",
":",
"_seen",
"=",
"set",
"(",
")",
"try",
":",
"subs",
"=",
"cls",
".",
"__subclasses__",
"(",
")",
"except",
"TypeError",
":",
"# fails only when cls is type",
"subs",
"=",
"cls",
".",
"__subclasses__",
"(",
"cls",
")",
"for",
"sub",
"in",
"subs",
":",
"if",
"sub",
"in",
"_seen",
":",
"continue",
"_seen",
".",
"add",
"(",
"sub",
")",
"yield",
"sub",
"for",
"sub",
"in",
"iter_subclasses",
"(",
"sub",
",",
"_seen",
")",
":",
"yield",
"sub"
] |
6347957478d589101a0774464d8d282520c2c990
|
test
|
CORS.selectPolicy
|
Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned.
|
wsgicors.py
|
def selectPolicy(self, origin, request_method=None):
"Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned."
ret_origin = None
policyname = None
if self.matchstrategy in ("firstmatch", "verbmatch"):
for pol in self.activepolicies:
policy=self.policies[pol]
ret_origin = None
policyname = policy.name
if policyname == "deny":
break
if self.matchstrategy == "verbmatch":
if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True):
continue
if origin and policy.match:
if CORS.matchlist(origin, policy.match):
ret_origin = origin
elif policy.origin == "copy":
ret_origin = origin
elif policy.origin:
ret_origin = policy.origin
if ret_origin:
break
return policyname, ret_origin
|
def selectPolicy(self, origin, request_method=None):
"Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned."
ret_origin = None
policyname = None
if self.matchstrategy in ("firstmatch", "verbmatch"):
for pol in self.activepolicies:
policy=self.policies[pol]
ret_origin = None
policyname = policy.name
if policyname == "deny":
break
if self.matchstrategy == "verbmatch":
if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True):
continue
if origin and policy.match:
if CORS.matchlist(origin, policy.match):
ret_origin = origin
elif policy.origin == "copy":
ret_origin = origin
elif policy.origin:
ret_origin = policy.origin
if ret_origin:
break
return policyname, ret_origin
|
[
"Based",
"on",
"the",
"matching",
"strategy",
"and",
"the",
"origin",
"and",
"optionally",
"the",
"requested",
"method",
"a",
"tuple",
"of",
"policyname",
"and",
"origin",
"to",
"pass",
"back",
"is",
"returned",
"."
] |
may-day/wsgicors
|
python
|
https://github.com/may-day/wsgicors/blob/619867a811b10c788c40c4af5204142ffabe0f1f/wsgicors.py#L104-L127
|
[
"def",
"selectPolicy",
"(",
"self",
",",
"origin",
",",
"request_method",
"=",
"None",
")",
":",
"ret_origin",
"=",
"None",
"policyname",
"=",
"None",
"if",
"self",
".",
"matchstrategy",
"in",
"(",
"\"firstmatch\"",
",",
"\"verbmatch\"",
")",
":",
"for",
"pol",
"in",
"self",
".",
"activepolicies",
":",
"policy",
"=",
"self",
".",
"policies",
"[",
"pol",
"]",
"ret_origin",
"=",
"None",
"policyname",
"=",
"policy",
".",
"name",
"if",
"policyname",
"==",
"\"deny\"",
":",
"break",
"if",
"self",
".",
"matchstrategy",
"==",
"\"verbmatch\"",
":",
"if",
"policy",
".",
"methods",
"!=",
"\"*\"",
"and",
"not",
"CORS",
".",
"matchlist",
"(",
"request_method",
",",
"policy",
".",
"methods",
",",
"case_sensitive",
"=",
"True",
")",
":",
"continue",
"if",
"origin",
"and",
"policy",
".",
"match",
":",
"if",
"CORS",
".",
"matchlist",
"(",
"origin",
",",
"policy",
".",
"match",
")",
":",
"ret_origin",
"=",
"origin",
"elif",
"policy",
".",
"origin",
"==",
"\"copy\"",
":",
"ret_origin",
"=",
"origin",
"elif",
"policy",
".",
"origin",
":",
"ret_origin",
"=",
"policy",
".",
"origin",
"if",
"ret_origin",
":",
"break",
"return",
"policyname",
",",
"ret_origin"
] |
619867a811b10c788c40c4af5204142ffabe0f1f
|
test
|
loads
|
Loads Appinfo content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with Appinfo data.
|
steamfiles/appinfo.py
|
def loads(data, wrapper=dict):
"""
Loads Appinfo content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with Appinfo data.
"""
if not isinstance(data, (bytes, bytearray)):
raise TypeError('can only load a bytes-like object as an Appinfo but got ' + type(data).__name__)
return AppinfoDecoder(data, wrapper=wrapper).decode()
|
def loads(data, wrapper=dict):
"""
Loads Appinfo content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with Appinfo data.
"""
if not isinstance(data, (bytes, bytearray)):
raise TypeError('can only load a bytes-like object as an Appinfo but got ' + type(data).__name__)
return AppinfoDecoder(data, wrapper=wrapper).decode()
|
[
"Loads",
"Appinfo",
"content",
"into",
"a",
"Python",
"object",
".",
":",
"param",
"data",
":",
"A",
"byte",
"-",
"like",
"object",
"with",
"the",
"contents",
"of",
"an",
"Appinfo",
"file",
".",
":",
"param",
"wrapper",
":",
"A",
"wrapping",
"object",
"for",
"key",
"-",
"value",
"pairs",
".",
":",
"return",
":",
"An",
"Ordered",
"Dictionary",
"with",
"Appinfo",
"data",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/appinfo.py#L32-L42
|
[
"def",
"loads",
"(",
"data",
",",
"wrapper",
"=",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'can only load a bytes-like object as an Appinfo but got '",
"+",
"type",
"(",
"data",
")",
".",
"__name__",
")",
"return",
"AppinfoDecoder",
"(",
"data",
",",
"wrapper",
"=",
"wrapper",
")",
".",
"decode",
"(",
")"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
dumps
|
Serializes a dictionary into Appinfo data.
:param obj: A dictionary to serialize.
:return:
|
steamfiles/appinfo.py
|
def dumps(obj):
"""
Serializes a dictionary into Appinfo data.
:param obj: A dictionary to serialize.
:return:
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as an Appinfo but got ' + type(obj).__name__)
return b''.join(AppinfoEncoder(obj).iter_encode())
|
def dumps(obj):
"""
Serializes a dictionary into Appinfo data.
:param obj: A dictionary to serialize.
:return:
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as an Appinfo but got ' + type(obj).__name__)
return b''.join(AppinfoEncoder(obj).iter_encode())
|
[
"Serializes",
"a",
"dictionary",
"into",
"Appinfo",
"data",
".",
":",
"param",
"obj",
":",
"A",
"dictionary",
"to",
"serialize",
".",
":",
"return",
":"
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/appinfo.py#L54-L63
|
[
"def",
"dumps",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'can only dump a dictionary as an Appinfo but got '",
"+",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"return",
"b''",
".",
"join",
"(",
"AppinfoEncoder",
"(",
"obj",
")",
".",
"iter_encode",
"(",
")",
")"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
loads
|
Loads Manifest content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: A dictionary with Manifest data.
|
steamfiles/manifest.py
|
def loads(data, wrapper=dict):
"""
Loads Manifest content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: A dictionary with Manifest data.
"""
if not isinstance(data, (bytes, bytearray)):
raise TypeError('can only load a bytes-like object as a Manifest but got ' + type(data).__name__)
offset = 0
parsed = wrapper()
int32 = struct.Struct('<I')
while True:
msg_id, = int32.unpack_from(data, offset)
offset += int32.size
if msg_id == MSG_EOF:
break
msg_size, = int32.unpack_from(data, offset)
offset += int32.size
msg_data = data[offset:offset + msg_size]
offset += msg_size
message = MessageClass[msg_id]()
message.ParseFromString(msg_data)
parsed[MSG_NAMES[msg_id]] = wrapper(protobuf_to_dict(message))
return parsed
|
def loads(data, wrapper=dict):
"""
Loads Manifest content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: A dictionary with Manifest data.
"""
if not isinstance(data, (bytes, bytearray)):
raise TypeError('can only load a bytes-like object as a Manifest but got ' + type(data).__name__)
offset = 0
parsed = wrapper()
int32 = struct.Struct('<I')
while True:
msg_id, = int32.unpack_from(data, offset)
offset += int32.size
if msg_id == MSG_EOF:
break
msg_size, = int32.unpack_from(data, offset)
offset += int32.size
msg_data = data[offset:offset + msg_size]
offset += msg_size
message = MessageClass[msg_id]()
message.ParseFromString(msg_data)
parsed[MSG_NAMES[msg_id]] = wrapper(protobuf_to_dict(message))
return parsed
|
[
"Loads",
"Manifest",
"content",
"into",
"a",
"Python",
"object",
".",
":",
"param",
"data",
":",
"A",
"byte",
"-",
"like",
"object",
"with",
"the",
"contents",
"of",
"an",
"Appinfo",
"file",
".",
":",
"param",
"wrapper",
":",
"A",
"wrapping",
"object",
"for",
"key",
"-",
"value",
"pairs",
".",
":",
"return",
":",
"A",
"dictionary",
"with",
"Manifest",
"data",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/manifest.py#L46-L78
|
[
"def",
"loads",
"(",
"data",
",",
"wrapper",
"=",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'can only load a bytes-like object as a Manifest but got '",
"+",
"type",
"(",
"data",
")",
".",
"__name__",
")",
"offset",
"=",
"0",
"parsed",
"=",
"wrapper",
"(",
")",
"int32",
"=",
"struct",
".",
"Struct",
"(",
"'<I'",
")",
"while",
"True",
":",
"msg_id",
",",
"=",
"int32",
".",
"unpack_from",
"(",
"data",
",",
"offset",
")",
"offset",
"+=",
"int32",
".",
"size",
"if",
"msg_id",
"==",
"MSG_EOF",
":",
"break",
"msg_size",
",",
"=",
"int32",
".",
"unpack_from",
"(",
"data",
",",
"offset",
")",
"offset",
"+=",
"int32",
".",
"size",
"msg_data",
"=",
"data",
"[",
"offset",
":",
"offset",
"+",
"msg_size",
"]",
"offset",
"+=",
"msg_size",
"message",
"=",
"MessageClass",
"[",
"msg_id",
"]",
"(",
")",
"message",
".",
"ParseFromString",
"(",
"msg_data",
")",
"parsed",
"[",
"MSG_NAMES",
"[",
"msg_id",
"]",
"]",
"=",
"wrapper",
"(",
"protobuf_to_dict",
"(",
"message",
")",
")",
"return",
"parsed"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
dumps
|
Serializes a dictionary into Manifest data.
:param obj: A dictionary to serialize.
:return: A file object.
|
steamfiles/manifest.py
|
def dumps(obj):
"""
Serializes a dictionary into Manifest data.
:param obj: A dictionary to serialize.
:return: A file object.
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as a Manifest but got ' + type(obj).__name__)
data = []
int32 = struct.Struct('<I')
for message_name in ('payload', 'metadata', 'signature'):
message_data = obj[message_name]
message_id = MSG_IDS[message_name]
message_class = MessageClass[message_id]
message = dict_to_protobuf(message_class, message_data)
message_bytes = message.SerializeToString()
message_size = len(message_bytes)
data.append(int32.pack(message_id))
data.append(int32.pack(message_size))
data.append(message_bytes)
# MSG_EOF marks the end of messages.
data.append(int32.pack(MSG_EOF))
return b''.join(data)
|
def dumps(obj):
"""
Serializes a dictionary into Manifest data.
:param obj: A dictionary to serialize.
:return: A file object.
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as a Manifest but got ' + type(obj).__name__)
data = []
int32 = struct.Struct('<I')
for message_name in ('payload', 'metadata', 'signature'):
message_data = obj[message_name]
message_id = MSG_IDS[message_name]
message_class = MessageClass[message_id]
message = dict_to_protobuf(message_class, message_data)
message_bytes = message.SerializeToString()
message_size = len(message_bytes)
data.append(int32.pack(message_id))
data.append(int32.pack(message_size))
data.append(message_bytes)
# MSG_EOF marks the end of messages.
data.append(int32.pack(MSG_EOF))
return b''.join(data)
|
[
"Serializes",
"a",
"dictionary",
"into",
"Manifest",
"data",
".",
":",
"param",
"obj",
":",
"A",
"dictionary",
"to",
"serialize",
".",
":",
"return",
":",
"A",
"file",
"object",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/manifest.py#L90-L116
|
[
"def",
"dumps",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'can only dump a dictionary as a Manifest but got '",
"+",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"data",
"=",
"[",
"]",
"int32",
"=",
"struct",
".",
"Struct",
"(",
"'<I'",
")",
"for",
"message_name",
"in",
"(",
"'payload'",
",",
"'metadata'",
",",
"'signature'",
")",
":",
"message_data",
"=",
"obj",
"[",
"message_name",
"]",
"message_id",
"=",
"MSG_IDS",
"[",
"message_name",
"]",
"message_class",
"=",
"MessageClass",
"[",
"message_id",
"]",
"message",
"=",
"dict_to_protobuf",
"(",
"message_class",
",",
"message_data",
")",
"message_bytes",
"=",
"message",
".",
"SerializeToString",
"(",
")",
"message_size",
"=",
"len",
"(",
"message_bytes",
")",
"data",
".",
"append",
"(",
"int32",
".",
"pack",
"(",
"message_id",
")",
")",
"data",
".",
"append",
"(",
"int32",
".",
"pack",
"(",
"message_size",
")",
")",
"data",
".",
"append",
"(",
"message_bytes",
")",
"# MSG_EOF marks the end of messages.",
"data",
".",
"append",
"(",
"int32",
".",
"pack",
"(",
"MSG_EOF",
")",
")",
"return",
"b''",
".",
"join",
"(",
"data",
")"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
loads
|
Loads ACF content into a Python object.
:param data: An UTF-8 encoded content of an ACF file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with ACF data.
|
steamfiles/acf.py
|
def loads(data, wrapper=dict):
"""
Loads ACF content into a Python object.
:param data: An UTF-8 encoded content of an ACF file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with ACF data.
"""
if not isinstance(data, str):
raise TypeError('can only load a str as an ACF but got ' + type(data).__name__)
parsed = wrapper()
current_section = parsed
sections = []
lines = (line.strip() for line in data.splitlines())
for line in lines:
try:
key, value = line.split(None, 1)
key = key.replace('"', '').lstrip()
value = value.replace('"', '').rstrip()
except ValueError:
if line == SECTION_START:
# Initialize the last added section.
current_section = _prepare_subsection(parsed, sections, wrapper)
elif line == SECTION_END:
# Remove the last section from the queue.
sections.pop()
else:
# Add a new section to the queue.
sections.append(line.replace('"', ''))
continue
current_section[key] = value
return parsed
|
def loads(data, wrapper=dict):
"""
Loads ACF content into a Python object.
:param data: An UTF-8 encoded content of an ACF file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with ACF data.
"""
if not isinstance(data, str):
raise TypeError('can only load a str as an ACF but got ' + type(data).__name__)
parsed = wrapper()
current_section = parsed
sections = []
lines = (line.strip() for line in data.splitlines())
for line in lines:
try:
key, value = line.split(None, 1)
key = key.replace('"', '').lstrip()
value = value.replace('"', '').rstrip()
except ValueError:
if line == SECTION_START:
# Initialize the last added section.
current_section = _prepare_subsection(parsed, sections, wrapper)
elif line == SECTION_END:
# Remove the last section from the queue.
sections.pop()
else:
# Add a new section to the queue.
sections.append(line.replace('"', ''))
continue
current_section[key] = value
return parsed
|
[
"Loads",
"ACF",
"content",
"into",
"a",
"Python",
"object",
".",
":",
"param",
"data",
":",
"An",
"UTF",
"-",
"8",
"encoded",
"content",
"of",
"an",
"ACF",
"file",
".",
":",
"param",
"wrapper",
":",
"A",
"wrapping",
"object",
"for",
"key",
"-",
"value",
"pairs",
".",
":",
"return",
":",
"An",
"Ordered",
"Dictionary",
"with",
"ACF",
"data",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/acf.py#L7-L42
|
[
"def",
"loads",
"(",
"data",
",",
"wrapper",
"=",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'can only load a str as an ACF but got '",
"+",
"type",
"(",
"data",
")",
".",
"__name__",
")",
"parsed",
"=",
"wrapper",
"(",
")",
"current_section",
"=",
"parsed",
"sections",
"=",
"[",
"]",
"lines",
"=",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
")",
"for",
"line",
"in",
"lines",
":",
"try",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"None",
",",
"1",
")",
"key",
"=",
"key",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
".",
"lstrip",
"(",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
".",
"rstrip",
"(",
")",
"except",
"ValueError",
":",
"if",
"line",
"==",
"SECTION_START",
":",
"# Initialize the last added section.",
"current_section",
"=",
"_prepare_subsection",
"(",
"parsed",
",",
"sections",
",",
"wrapper",
")",
"elif",
"line",
"==",
"SECTION_END",
":",
"# Remove the last section from the queue.",
"sections",
".",
"pop",
"(",
")",
"else",
":",
"# Add a new section to the queue.",
"sections",
".",
"append",
"(",
"line",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
")",
"continue",
"current_section",
"[",
"key",
"]",
"=",
"value",
"return",
"parsed"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
dumps
|
Serializes a dictionary into ACF data.
:param obj: A dictionary to serialize.
:return: ACF data.
|
steamfiles/acf.py
|
def dumps(obj):
"""
Serializes a dictionary into ACF data.
:param obj: A dictionary to serialize.
:return: ACF data.
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as an ACF but got ' + type(obj).__name__)
return '\n'.join(_dumps(obj, level=0)) + '\n'
|
def dumps(obj):
"""
Serializes a dictionary into ACF data.
:param obj: A dictionary to serialize.
:return: ACF data.
"""
if not isinstance(obj, dict):
raise TypeError('can only dump a dictionary as an ACF but got ' + type(obj).__name__)
return '\n'.join(_dumps(obj, level=0)) + '\n'
|
[
"Serializes",
"a",
"dictionary",
"into",
"ACF",
"data",
".",
":",
"param",
"obj",
":",
"A",
"dictionary",
"to",
"serialize",
".",
":",
"return",
":",
"ACF",
"data",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/acf.py#L55-L64
|
[
"def",
"dumps",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'can only dump a dictionary as an ACF but got '",
"+",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"return",
"'\\n'",
".",
"join",
"(",
"_dumps",
"(",
"obj",
",",
"level",
"=",
"0",
")",
")",
"+",
"'\\n'"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
_dumps
|
Does the actual serializing of data into an ACF format.
:param obj: A dictionary to serialize.
:param level: Nesting level.
:return: A List of strings.
|
steamfiles/acf.py
|
def _dumps(obj, level):
"""
Does the actual serializing of data into an ACF format.
:param obj: A dictionary to serialize.
:param level: Nesting level.
:return: A List of strings.
"""
lines = []
indent = '\t' * level
for key, value in obj.items():
if isinstance(value, dict):
# [INDENT]"KEY"
# [INDENT]{
line = indent + '"{}"\n'.format(key) + indent + '{'
lines.append(line)
# Increase intendation of the nested dict
lines.extend(_dumps(value, level+1))
# [INDENT]}
lines.append(indent + '}')
else:
# [INDENT]"KEY"[TAB][TAB]"VALUE"
lines.append(indent + '"{}"'.format(key) + '\t\t' + '"{}"'.format(value))
return lines
|
def _dumps(obj, level):
"""
Does the actual serializing of data into an ACF format.
:param obj: A dictionary to serialize.
:param level: Nesting level.
:return: A List of strings.
"""
lines = []
indent = '\t' * level
for key, value in obj.items():
if isinstance(value, dict):
# [INDENT]"KEY"
# [INDENT]{
line = indent + '"{}"\n'.format(key) + indent + '{'
lines.append(line)
# Increase intendation of the nested dict
lines.extend(_dumps(value, level+1))
# [INDENT]}
lines.append(indent + '}')
else:
# [INDENT]"KEY"[TAB][TAB]"VALUE"
lines.append(indent + '"{}"'.format(key) + '\t\t' + '"{}"'.format(value))
return lines
|
[
"Does",
"the",
"actual",
"serializing",
"of",
"data",
"into",
"an",
"ACF",
"format",
".",
":",
"param",
"obj",
":",
"A",
"dictionary",
"to",
"serialize",
".",
":",
"param",
"level",
":",
"Nesting",
"level",
".",
":",
"return",
":",
"A",
"List",
"of",
"strings",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/acf.py#L76-L100
|
[
"def",
"_dumps",
"(",
"obj",
",",
"level",
")",
":",
"lines",
"=",
"[",
"]",
"indent",
"=",
"'\\t'",
"*",
"level",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"# [INDENT]\"KEY\"",
"# [INDENT]{",
"line",
"=",
"indent",
"+",
"'\"{}\"\\n'",
".",
"format",
"(",
"key",
")",
"+",
"indent",
"+",
"'{'",
"lines",
".",
"append",
"(",
"line",
")",
"# Increase intendation of the nested dict",
"lines",
".",
"extend",
"(",
"_dumps",
"(",
"value",
",",
"level",
"+",
"1",
")",
")",
"# [INDENT]}",
"lines",
".",
"append",
"(",
"indent",
"+",
"'}'",
")",
"else",
":",
"# [INDENT]\"KEY\"[TAB][TAB]\"VALUE\"",
"lines",
".",
"append",
"(",
"indent",
"+",
"'\"{}\"'",
".",
"format",
"(",
"key",
")",
"+",
"'\\t\\t'",
"+",
"'\"{}\"'",
".",
"format",
"(",
"value",
")",
")",
"return",
"lines"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
_prepare_subsection
|
Creates a subsection ready to be filled.
:param data: Semi-parsed dictionary.
:param sections: A list of sections.
:param wrapper: A wrapping object for key-value pairs.
:return: A newly created subsection.
|
steamfiles/acf.py
|
def _prepare_subsection(data, sections, wrapper):
"""
Creates a subsection ready to be filled.
:param data: Semi-parsed dictionary.
:param sections: A list of sections.
:param wrapper: A wrapping object for key-value pairs.
:return: A newly created subsection.
"""
current = data
for i in sections[:-1]:
current = current[i]
current[sections[-1]] = wrapper()
return current[sections[-1]]
|
def _prepare_subsection(data, sections, wrapper):
"""
Creates a subsection ready to be filled.
:param data: Semi-parsed dictionary.
:param sections: A list of sections.
:param wrapper: A wrapping object for key-value pairs.
:return: A newly created subsection.
"""
current = data
for i in sections[:-1]:
current = current[i]
current[sections[-1]] = wrapper()
return current[sections[-1]]
|
[
"Creates",
"a",
"subsection",
"ready",
"to",
"be",
"filled",
".",
":",
"param",
"data",
":",
"Semi",
"-",
"parsed",
"dictionary",
".",
":",
"param",
"sections",
":",
"A",
"list",
"of",
"sections",
".",
":",
"param",
"wrapper",
":",
"A",
"wrapping",
"object",
"for",
"key",
"-",
"value",
"pairs",
".",
":",
"return",
":",
"A",
"newly",
"created",
"subsection",
"."
] |
leovp/steamfiles
|
python
|
https://github.com/leovp/steamfiles/blob/e2264d09d128aecb838c4d310d7ea11e28c6597e/steamfiles/acf.py#L103-L116
|
[
"def",
"_prepare_subsection",
"(",
"data",
",",
"sections",
",",
"wrapper",
")",
":",
"current",
"=",
"data",
"for",
"i",
"in",
"sections",
"[",
":",
"-",
"1",
"]",
":",
"current",
"=",
"current",
"[",
"i",
"]",
"current",
"[",
"sections",
"[",
"-",
"1",
"]",
"]",
"=",
"wrapper",
"(",
")",
"return",
"current",
"[",
"sections",
"[",
"-",
"1",
"]",
"]"
] |
e2264d09d128aecb838c4d310d7ea11e28c6597e
|
test
|
occupancy
|
Return a vector with the occupancy of each grid point for
given array of points
|
insane/structure.py
|
def occupancy(grid, points, spacing=0.01):
"""Return a vector with the occupancy of each grid point for
given array of points"""
distances = ((grid[:,None,:] - points[None,:,:])**2).sum(axis=2)
occupied = (distances < spacing).sum(axis=1)
return occupied
|
def occupancy(grid, points, spacing=0.01):
"""Return a vector with the occupancy of each grid point for
given array of points"""
distances = ((grid[:,None,:] - points[None,:,:])**2).sum(axis=2)
occupied = (distances < spacing).sum(axis=1)
return occupied
|
[
"Return",
"a",
"vector",
"with",
"the",
"occupancy",
"of",
"each",
"grid",
"point",
"for",
"given",
"array",
"of",
"points"
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/structure.py#L10-L15
|
[
"def",
"occupancy",
"(",
"grid",
",",
"points",
",",
"spacing",
"=",
"0.01",
")",
":",
"distances",
"=",
"(",
"(",
"grid",
"[",
":",
",",
"None",
",",
":",
"]",
"-",
"points",
"[",
"None",
",",
":",
",",
":",
"]",
")",
"**",
"2",
")",
".",
"sum",
"(",
"axis",
"=",
"2",
")",
"occupied",
"=",
"(",
"distances",
"<",
"spacing",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"return",
"occupied"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
write_gro
|
Write a GRO file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
|
insane/structure.py
|
def write_gro(outfile, title, atoms, box):
"""
Write a GRO file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print(title, file=outfile)
# Print the number of atoms
print("{:5d}".format(len(atoms)), file=outfile)
# Print the atoms
atom_template = "{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}"
for idx, atname, resname, resid, x, y, z in atoms:
print(atom_template
.format(int(resid % 1e5), resname, atname, int(idx % 1e5),
x, y, z),
file=outfile)
# Print the box
grobox = (box[0][0], box[1][1], box[2][2],
box[0][1], box[0][2], box[1][0],
box[1][2], box[2][0], box[2][1])
box_template = '{:10.5f}' * 9
print(box_template.format(*grobox), file=outfile)
|
def write_gro(outfile, title, atoms, box):
"""
Write a GRO file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print(title, file=outfile)
# Print the number of atoms
print("{:5d}".format(len(atoms)), file=outfile)
# Print the atoms
atom_template = "{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}"
for idx, atname, resname, resid, x, y, z in atoms:
print(atom_template
.format(int(resid % 1e5), resname, atname, int(idx % 1e5),
x, y, z),
file=outfile)
# Print the box
grobox = (box[0][0], box[1][1], box[2][2],
box[0][1], box[0][2], box[1][0],
box[1][2], box[2][0], box[2][1])
box_template = '{:10.5f}' * 9
print(box_template.format(*grobox), file=outfile)
|
[
"Write",
"a",
"GRO",
"file",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/structure.py#L332-L366
|
[
"def",
"write_gro",
"(",
"outfile",
",",
"title",
",",
"atoms",
",",
"box",
")",
":",
"# Print the title",
"print",
"(",
"title",
",",
"file",
"=",
"outfile",
")",
"# Print the number of atoms",
"print",
"(",
"\"{:5d}\"",
".",
"format",
"(",
"len",
"(",
"atoms",
")",
")",
",",
"file",
"=",
"outfile",
")",
"# Print the atoms",
"atom_template",
"=",
"\"{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}\"",
"for",
"idx",
",",
"atname",
",",
"resname",
",",
"resid",
",",
"x",
",",
"y",
",",
"z",
"in",
"atoms",
":",
"print",
"(",
"atom_template",
".",
"format",
"(",
"int",
"(",
"resid",
"%",
"1e5",
")",
",",
"resname",
",",
"atname",
",",
"int",
"(",
"idx",
"%",
"1e5",
")",
",",
"x",
",",
"y",
",",
"z",
")",
",",
"file",
"=",
"outfile",
")",
"# Print the box",
"grobox",
"=",
"(",
"box",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"box",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"box",
"[",
"2",
"]",
"[",
"2",
"]",
",",
"box",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"box",
"[",
"0",
"]",
"[",
"2",
"]",
",",
"box",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"box",
"[",
"1",
"]",
"[",
"2",
"]",
",",
"box",
"[",
"2",
"]",
"[",
"0",
"]",
",",
"box",
"[",
"2",
"]",
"[",
"1",
"]",
")",
"box_template",
"=",
"'{:10.5f}'",
"*",
"9",
"print",
"(",
"box_template",
".",
"format",
"(",
"*",
"grobox",
")",
",",
"file",
"=",
"outfile",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
write_pdb
|
Write a PDB file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
|
insane/structure.py
|
def write_pdb(outfile, title, atoms, box):
"""
Write a PDB file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print('TITLE ' + title, file=outfile)
# Print the box
print(pdbBoxString(box), file=outfile)
# Print the atoms
for idx, atname, resname, resid, x, y, z in atoms:
print(pdbline % (idx % 1e5, atname[:4], resname[:3], "",
resid % 1e4, '', 10*x, 10*y, 10*z, 0, 0, ''),
file=outfile)
|
def write_pdb(outfile, title, atoms, box):
"""
Write a PDB file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print('TITLE ' + title, file=outfile)
# Print the box
print(pdbBoxString(box), file=outfile)
# Print the atoms
for idx, atname, resname, resid, x, y, z in atoms:
print(pdbline % (idx % 1e5, atname[:4], resname[:3], "",
resid % 1e4, '', 10*x, 10*y, 10*z, 0, 0, ''),
file=outfile)
|
[
"Write",
"a",
"PDB",
"file",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/structure.py#L369-L394
|
[
"def",
"write_pdb",
"(",
"outfile",
",",
"title",
",",
"atoms",
",",
"box",
")",
":",
"# Print the title",
"print",
"(",
"'TITLE '",
"+",
"title",
",",
"file",
"=",
"outfile",
")",
"# Print the box",
"print",
"(",
"pdbBoxString",
"(",
"box",
")",
",",
"file",
"=",
"outfile",
")",
"# Print the atoms",
"for",
"idx",
",",
"atname",
",",
"resname",
",",
"resid",
",",
"x",
",",
"y",
",",
"z",
"in",
"atoms",
":",
"print",
"(",
"pdbline",
"%",
"(",
"idx",
"%",
"1e5",
",",
"atname",
"[",
":",
"4",
"]",
",",
"resname",
"[",
":",
"3",
"]",
",",
"\"\"",
",",
"resid",
"%",
"1e4",
",",
"''",
",",
"10",
"*",
"x",
",",
"10",
"*",
"y",
",",
"10",
"*",
"z",
",",
"0",
",",
"0",
",",
"''",
")",
",",
"file",
"=",
"outfile",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
determine_molecule_numbers
|
Determine molecule numbers for given total,
absolute and relative numbers
|
insane/core.py
|
def determine_molecule_numbers(total, molecules, absolute, relative):
"""Determine molecule numbers for given total,
absolute and relative numbers"""
weight = sum(relative)
if not any(absolute):
# Only relative numbers
numbers = [int(total*i/weight) for i in relative]
elif any(relative):
# Absolute numbers and fill the rest with relative numbers
rest = total - sum(absolute)
numbers = [int(rest*i/weight) if i else j
for i,j in zip(relative, absolute)]
else:
# Only absolute numbers
numbers = absolute
return list(zip(molecules, numbers))
|
def determine_molecule_numbers(total, molecules, absolute, relative):
"""Determine molecule numbers for given total,
absolute and relative numbers"""
weight = sum(relative)
if not any(absolute):
# Only relative numbers
numbers = [int(total*i/weight) for i in relative]
elif any(relative):
# Absolute numbers and fill the rest with relative numbers
rest = total - sum(absolute)
numbers = [int(rest*i/weight) if i else j
for i,j in zip(relative, absolute)]
else:
# Only absolute numbers
numbers = absolute
return list(zip(molecules, numbers))
|
[
"Determine",
"molecule",
"numbers",
"for",
"given",
"total",
"absolute",
"and",
"relative",
"numbers"
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/core.py#L69-L84
|
[
"def",
"determine_molecule_numbers",
"(",
"total",
",",
"molecules",
",",
"absolute",
",",
"relative",
")",
":",
"weight",
"=",
"sum",
"(",
"relative",
")",
"if",
"not",
"any",
"(",
"absolute",
")",
":",
"# Only relative numbers",
"numbers",
"=",
"[",
"int",
"(",
"total",
"*",
"i",
"/",
"weight",
")",
"for",
"i",
"in",
"relative",
"]",
"elif",
"any",
"(",
"relative",
")",
":",
"# Absolute numbers and fill the rest with relative numbers",
"rest",
"=",
"total",
"-",
"sum",
"(",
"absolute",
")",
"numbers",
"=",
"[",
"int",
"(",
"rest",
"*",
"i",
"/",
"weight",
")",
"if",
"i",
"else",
"j",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"relative",
",",
"absolute",
")",
"]",
"else",
":",
"# Only absolute numbers",
"numbers",
"=",
"absolute",
"return",
"list",
"(",
"zip",
"(",
"molecules",
",",
"numbers",
")",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
resize_pbc_for_lipids
|
Adapt the size of the box to accomodate the lipids.
The PBC is changed **in place**.
|
insane/core.py
|
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU,
uparea, area, hole, proteins):
"""
Adapt the size of the box to accomodate the lipids.
The PBC is changed **in place**.
"""
if any(relL) and any(relU):
# Determine box from size
# If one leaflet is defined with an absolute number of lipids
# then the other leaflet (with relative numbers) will follow
# from that.
# box/d/x/y/z needed to define unit cell
# box is set up already...
# yet it may be set to 0, then there is nothing we can do.
if 0 in (pbc.x, pbc.y, pbc.z):
raise PBCException('Not enough information to set the box size.')
elif any(absL) or any(absU):
# All numbers are absolute.. determine size from number of lipids
# Box x/y will be set, d/dz/z is needed to set third box vector.
# The area is needed to determine the size of the x/y plane OR
# the area will be SET if a box is given.
if pbc.z == 0:
raise PBCException('Not enough information to set the box size.')
if 0 in (pbc.x, pbc.y):
# We do not know what size the box should be.
# Let X and Y be the same.
#T This does not agree with the default pbc being hexagonal...
pbc.x = pbc.y = 1
# A scaling factor is needed for the box
# This is the area for the given number of lipids
upsize = sum(absU) * uparea
losize = sum(absL) * area
# This is the size of the hole, going through both leaflets
holesize = np.pi * hole ** 2
# This is the area of the PBC xy plane
xysize = pbc.x * pbc.y
# This is the total area of the proteins per leaflet (IMPLEMENT!)
psize_up = sum([p.areaxy(0, 2.4) for p in proteins])
psize_lo = sum([p.areaxy(-2.4, 0) for p in proteins])
# So this is unavailable:
unavail_up = holesize + psize_up
unavail_lo = holesize + psize_lo
# This is the current area marked for lipids
# xysize_up = xysize - unavail_up
# xysize_lo = xysize - unavail_lo
# This is how much the unit cell xy needs to be scaled
# to accomodate the fixed amount of lipids with given area.
upscale = (upsize + unavail_up)/xysize
loscale = (losize + unavail_lo)/xysize
area_scale = max(upscale, loscale)
aspect_ratio = pbc.x / pbc.y
scale_x = np.sqrt(area_scale / aspect_ratio)
scale_y = np.sqrt(area_scale / aspect_ratio)
pbc.box[:2,:] *= math.sqrt(area_scale)
|
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU,
uparea, area, hole, proteins):
"""
Adapt the size of the box to accomodate the lipids.
The PBC is changed **in place**.
"""
if any(relL) and any(relU):
# Determine box from size
# If one leaflet is defined with an absolute number of lipids
# then the other leaflet (with relative numbers) will follow
# from that.
# box/d/x/y/z needed to define unit cell
# box is set up already...
# yet it may be set to 0, then there is nothing we can do.
if 0 in (pbc.x, pbc.y, pbc.z):
raise PBCException('Not enough information to set the box size.')
elif any(absL) or any(absU):
# All numbers are absolute.. determine size from number of lipids
# Box x/y will be set, d/dz/z is needed to set third box vector.
# The area is needed to determine the size of the x/y plane OR
# the area will be SET if a box is given.
if pbc.z == 0:
raise PBCException('Not enough information to set the box size.')
if 0 in (pbc.x, pbc.y):
# We do not know what size the box should be.
# Let X and Y be the same.
#T This does not agree with the default pbc being hexagonal...
pbc.x = pbc.y = 1
# A scaling factor is needed for the box
# This is the area for the given number of lipids
upsize = sum(absU) * uparea
losize = sum(absL) * area
# This is the size of the hole, going through both leaflets
holesize = np.pi * hole ** 2
# This is the area of the PBC xy plane
xysize = pbc.x * pbc.y
# This is the total area of the proteins per leaflet (IMPLEMENT!)
psize_up = sum([p.areaxy(0, 2.4) for p in proteins])
psize_lo = sum([p.areaxy(-2.4, 0) for p in proteins])
# So this is unavailable:
unavail_up = holesize + psize_up
unavail_lo = holesize + psize_lo
# This is the current area marked for lipids
# xysize_up = xysize - unavail_up
# xysize_lo = xysize - unavail_lo
# This is how much the unit cell xy needs to be scaled
# to accomodate the fixed amount of lipids with given area.
upscale = (upsize + unavail_up)/xysize
loscale = (losize + unavail_lo)/xysize
area_scale = max(upscale, loscale)
aspect_ratio = pbc.x / pbc.y
scale_x = np.sqrt(area_scale / aspect_ratio)
scale_y = np.sqrt(area_scale / aspect_ratio)
pbc.box[:2,:] *= math.sqrt(area_scale)
|
[
"Adapt",
"the",
"size",
"of",
"the",
"box",
"to",
"accomodate",
"the",
"lipids",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/core.py#L87-L144
|
[
"def",
"resize_pbc_for_lipids",
"(",
"pbc",
",",
"relL",
",",
"relU",
",",
"absL",
",",
"absU",
",",
"uparea",
",",
"area",
",",
"hole",
",",
"proteins",
")",
":",
"if",
"any",
"(",
"relL",
")",
"and",
"any",
"(",
"relU",
")",
":",
"# Determine box from size",
"# If one leaflet is defined with an absolute number of lipids",
"# then the other leaflet (with relative numbers) will follow",
"# from that.",
"# box/d/x/y/z needed to define unit cell",
"# box is set up already...",
"# yet it may be set to 0, then there is nothing we can do.",
"if",
"0",
"in",
"(",
"pbc",
".",
"x",
",",
"pbc",
".",
"y",
",",
"pbc",
".",
"z",
")",
":",
"raise",
"PBCException",
"(",
"'Not enough information to set the box size.'",
")",
"elif",
"any",
"(",
"absL",
")",
"or",
"any",
"(",
"absU",
")",
":",
"# All numbers are absolute.. determine size from number of lipids",
"# Box x/y will be set, d/dz/z is needed to set third box vector.",
"# The area is needed to determine the size of the x/y plane OR",
"# the area will be SET if a box is given.",
"if",
"pbc",
".",
"z",
"==",
"0",
":",
"raise",
"PBCException",
"(",
"'Not enough information to set the box size.'",
")",
"if",
"0",
"in",
"(",
"pbc",
".",
"x",
",",
"pbc",
".",
"y",
")",
":",
"# We do not know what size the box should be. ",
"# Let X and Y be the same.",
"#T This does not agree with the default pbc being hexagonal...",
"pbc",
".",
"x",
"=",
"pbc",
".",
"y",
"=",
"1",
"# A scaling factor is needed for the box",
"# This is the area for the given number of lipids",
"upsize",
"=",
"sum",
"(",
"absU",
")",
"*",
"uparea",
"losize",
"=",
"sum",
"(",
"absL",
")",
"*",
"area",
"# This is the size of the hole, going through both leaflets",
"holesize",
"=",
"np",
".",
"pi",
"*",
"hole",
"**",
"2",
"# This is the area of the PBC xy plane",
"xysize",
"=",
"pbc",
".",
"x",
"*",
"pbc",
".",
"y",
"# This is the total area of the proteins per leaflet (IMPLEMENT!)",
"psize_up",
"=",
"sum",
"(",
"[",
"p",
".",
"areaxy",
"(",
"0",
",",
"2.4",
")",
"for",
"p",
"in",
"proteins",
"]",
")",
"psize_lo",
"=",
"sum",
"(",
"[",
"p",
".",
"areaxy",
"(",
"-",
"2.4",
",",
"0",
")",
"for",
"p",
"in",
"proteins",
"]",
")",
"# So this is unavailable:",
"unavail_up",
"=",
"holesize",
"+",
"psize_up",
"unavail_lo",
"=",
"holesize",
"+",
"psize_lo",
"# This is the current area marked for lipids",
"# xysize_up = xysize - unavail_up",
"# xysize_lo = xysize - unavail_lo",
"# This is how much the unit cell xy needs to be scaled",
"# to accomodate the fixed amount of lipids with given area.",
"upscale",
"=",
"(",
"upsize",
"+",
"unavail_up",
")",
"/",
"xysize",
"loscale",
"=",
"(",
"losize",
"+",
"unavail_lo",
")",
"/",
"xysize",
"area_scale",
"=",
"max",
"(",
"upscale",
",",
"loscale",
")",
"aspect_ratio",
"=",
"pbc",
".",
"x",
"/",
"pbc",
".",
"y",
"scale_x",
"=",
"np",
".",
"sqrt",
"(",
"area_scale",
"/",
"aspect_ratio",
")",
"scale_y",
"=",
"np",
".",
"sqrt",
"(",
"area_scale",
"/",
"aspect_ratio",
")",
"pbc",
".",
"box",
"[",
":",
"2",
",",
":",
"]",
"*=",
"math",
".",
"sqrt",
"(",
"area_scale",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
write_top
|
Write a basic TOP file.
The topology is written in *outpath*. If *outpath* is en empty string, or
anything for which ``bool(outpath) == False``, the topology is written on
the standard error, and the header is omitted, and only what has been buit
by Insane id displayed (e.g. Proteins are excluded).
Parameters
----------
outpath
The path to the file to write. If empty, a simplify topology is
written on stderr.
molecules
List of molecules with the number of them.
title
Title of the system.
|
insane/core.py
|
def write_top(outpath, molecules, title):
"""
Write a basic TOP file.
The topology is written in *outpath*. If *outpath* is en empty string, or
anything for which ``bool(outpath) == False``, the topology is written on
the standard error, and the header is omitted, and only what has been buit
by Insane id displayed (e.g. Proteins are excluded).
Parameters
----------
outpath
The path to the file to write. If empty, a simplify topology is
written on stderr.
molecules
List of molecules with the number of them.
title
Title of the system.
"""
topmolecules = []
for i in molecules:
if i[0].endswith('.o'):
topmolecules.append(tuple([i[0][:-2]]+list(i[1:])))
else:
topmolecules.append(i)
if outpath:
# Write a rudimentary topology file
with open(outpath, "w") as top:
print('#include "martini.itp"\n', file=top)
print('[ system ]', file=top)
print('; name', file=top)
print(title, file=top)
print('\n', file=top)
print('[ molecules ]', file=top)
print('; name number', file=top)
print("\n".join("%-10s %7d"%i for i in topmolecules), file=top)
else:
# Here we only include molecules that have beed added by insane.
# This is usually concatenated at the end of an existint top file.
# As the existing file usually contain the proteins already, we do not
# include them here.
added_molecules = (molecule for molecule in topmolecules
if molecule[0] != 'Protein')
print("\n".join("%-10s %7d"%i for i in added_molecules), file=sys.stderr)
|
def write_top(outpath, molecules, title):
"""
Write a basic TOP file.
The topology is written in *outpath*. If *outpath* is en empty string, or
anything for which ``bool(outpath) == False``, the topology is written on
the standard error, and the header is omitted, and only what has been buit
by Insane id displayed (e.g. Proteins are excluded).
Parameters
----------
outpath
The path to the file to write. If empty, a simplify topology is
written on stderr.
molecules
List of molecules with the number of them.
title
Title of the system.
"""
topmolecules = []
for i in molecules:
if i[0].endswith('.o'):
topmolecules.append(tuple([i[0][:-2]]+list(i[1:])))
else:
topmolecules.append(i)
if outpath:
# Write a rudimentary topology file
with open(outpath, "w") as top:
print('#include "martini.itp"\n', file=top)
print('[ system ]', file=top)
print('; name', file=top)
print(title, file=top)
print('\n', file=top)
print('[ molecules ]', file=top)
print('; name number', file=top)
print("\n".join("%-10s %7d"%i for i in topmolecules), file=top)
else:
# Here we only include molecules that have beed added by insane.
# This is usually concatenated at the end of an existint top file.
# As the existing file usually contain the proteins already, we do not
# include them here.
added_molecules = (molecule for molecule in topmolecules
if molecule[0] != 'Protein')
print("\n".join("%-10s %7d"%i for i in added_molecules), file=sys.stderr)
|
[
"Write",
"a",
"basic",
"TOP",
"file",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/core.py#L773-L817
|
[
"def",
"write_top",
"(",
"outpath",
",",
"molecules",
",",
"title",
")",
":",
"topmolecules",
"=",
"[",
"]",
"for",
"i",
"in",
"molecules",
":",
"if",
"i",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.o'",
")",
":",
"topmolecules",
".",
"append",
"(",
"tuple",
"(",
"[",
"i",
"[",
"0",
"]",
"[",
":",
"-",
"2",
"]",
"]",
"+",
"list",
"(",
"i",
"[",
"1",
":",
"]",
")",
")",
")",
"else",
":",
"topmolecules",
".",
"append",
"(",
"i",
")",
"if",
"outpath",
":",
"# Write a rudimentary topology file",
"with",
"open",
"(",
"outpath",
",",
"\"w\"",
")",
"as",
"top",
":",
"print",
"(",
"'#include \"martini.itp\"\\n'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"'[ system ]'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"'; name'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"title",
",",
"file",
"=",
"top",
")",
"print",
"(",
"'\\n'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"'[ molecules ]'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"'; name number'",
",",
"file",
"=",
"top",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"\"%-10s %7d\"",
"%",
"i",
"for",
"i",
"in",
"topmolecules",
")",
",",
"file",
"=",
"top",
")",
"else",
":",
"# Here we only include molecules that have beed added by insane.",
"# This is usually concatenated at the end of an existint top file.",
"# As the existing file usually contain the proteins already, we do not",
"# include them here.",
"added_molecules",
"=",
"(",
"molecule",
"for",
"molecule",
"in",
"topmolecules",
"if",
"molecule",
"[",
"0",
"]",
"!=",
"'Protein'",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"\"%-10s %7d\"",
"%",
"i",
"for",
"i",
"in",
"added_molecules",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
iter_resource
|
Return a stream for a given resource file in the module.
The resource file has to be part of the module and its filenane given
relative to the module.
|
insane/utils.py
|
def iter_resource(filename):
"""
Return a stream for a given resource file in the module.
The resource file has to be part of the module and its filenane given
relative to the module.
"""
with pkg_resources.resource_stream(__name__, filename) as resource:
for line in resource:
yield line.decode('utf-8')
|
def iter_resource(filename):
"""
Return a stream for a given resource file in the module.
The resource file has to be part of the module and its filenane given
relative to the module.
"""
with pkg_resources.resource_stream(__name__, filename) as resource:
for line in resource:
yield line.decode('utf-8')
|
[
"Return",
"a",
"stream",
"for",
"a",
"given",
"resource",
"file",
"in",
"the",
"module",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/utils.py#L25-L34
|
[
"def",
"iter_resource",
"(",
"filename",
")",
":",
"with",
"pkg_resources",
".",
"resource_stream",
"(",
"__name__",
",",
"filename",
")",
"as",
"resource",
":",
"for",
"line",
"in",
"resource",
":",
"yield",
"line",
".",
"decode",
"(",
"'utf-8'",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
Lipid.parse
|
Parse lipid definition from string:
alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0
|
insane/lipids.py
|
def parse(self, string):
"""
Parse lipid definition from string:
alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0
"""
fields = [i.split("=") for i in string.split(', ')]
for what, val in fields:
what = what.strip()
val = val.split()
if what.endswith("head"):
self.head = val
elif what.endswith("link"):
self.link = val
elif what.endswith("tail"):
self.tail = val
elif what == "charge":
self.charge = float(val[0])
elif what.endswith("name") and not self.name:
self.name = val[0]
if self.charge is None:
# Infer charge from head groups
self.charge = sum([headgroup_charges[bead] for bead in self.head])
|
def parse(self, string):
"""
Parse lipid definition from string:
alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0
"""
fields = [i.split("=") for i in string.split(', ')]
for what, val in fields:
what = what.strip()
val = val.split()
if what.endswith("head"):
self.head = val
elif what.endswith("link"):
self.link = val
elif what.endswith("tail"):
self.tail = val
elif what == "charge":
self.charge = float(val[0])
elif what.endswith("name") and not self.name:
self.name = val[0]
if self.charge is None:
# Infer charge from head groups
self.charge = sum([headgroup_charges[bead] for bead in self.head])
|
[
"Parse",
"lipid",
"definition",
"from",
"string",
":"
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/lipids.py#L66-L88
|
[
"def",
"parse",
"(",
"self",
",",
"string",
")",
":",
"fields",
"=",
"[",
"i",
".",
"split",
"(",
"\"=\"",
")",
"for",
"i",
"in",
"string",
".",
"split",
"(",
"', '",
")",
"]",
"for",
"what",
",",
"val",
"in",
"fields",
":",
"what",
"=",
"what",
".",
"strip",
"(",
")",
"val",
"=",
"val",
".",
"split",
"(",
")",
"if",
"what",
".",
"endswith",
"(",
"\"head\"",
")",
":",
"self",
".",
"head",
"=",
"val",
"elif",
"what",
".",
"endswith",
"(",
"\"link\"",
")",
":",
"self",
".",
"link",
"=",
"val",
"elif",
"what",
".",
"endswith",
"(",
"\"tail\"",
")",
":",
"self",
".",
"tail",
"=",
"val",
"elif",
"what",
"==",
"\"charge\"",
":",
"self",
".",
"charge",
"=",
"float",
"(",
"val",
"[",
"0",
"]",
")",
"elif",
"what",
".",
"endswith",
"(",
"\"name\"",
")",
"and",
"not",
"self",
".",
"name",
":",
"self",
".",
"name",
"=",
"val",
"[",
"0",
"]",
"if",
"self",
".",
"charge",
"is",
"None",
":",
"# Infer charge from head groups",
"self",
".",
"charge",
"=",
"sum",
"(",
"[",
"headgroup_charges",
"[",
"bead",
"]",
"for",
"bead",
"in",
"self",
".",
"head",
"]",
")"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
Lipid.build
|
Build/return a list of [(bead, x, y, z), ...]
|
insane/lipids.py
|
def build(self, **kwargs):
"""Build/return a list of [(bead, x, y, z), ...]"""
if not self.coords:
if self.beads and self.template:
stuff = zip(self.beads, self.template)
self.coords = [[i, x, y, z] for i, (x, y, z) in stuff if i != "-"]
else:
# Set beads/structure from head/link/tail
# Set bead names
if self.beads:
beads = list(self.beads)
else:
beads = [HEADBEADS[i] for i in self.head]
beads.extend([LINKBEADS[n] + str(i + 1)
for i, n in enumerate(self.link)])
for i, t in enumerate(self.tail):
beads.extend([n + chr(65 + i) + str(j + 1)
for j, n in enumerate(t)])
taillength = max([0]+[len(i) for i in self.tail])
length = len(self.head)+taillength
# Add the pseudocoordinates for the head
rl = range(len(self.head))
struc = [(0, 0, length-i) for i in rl]
# Add the linkers
rl = range(len(self.link))
struc.extend([(i%2, i//2, taillength) for i in rl ])
# Add the tails
for j, tail in enumerate(self.tail):
rl = range(len(tail))
struc.extend([(j%2, j//2, taillength-1-i) for i in rl])
mx, my, mz = [ (max(i)+min(i))/2 for i in zip(*struc) ]
self.coords = [
[i, 0.25 * (x - mx), 0.25 * (y - my), z]
for i, (x, y, z) in zip(beads, struc)
]
# Scale the x/y based on the lipid's APL - diameter is less than sqrt(APL)
diam = kwargs.get("diam", self.diam)
radius = diam*0.45
minmax = [ (min(i), max(i)) for i in list(zip(*self.coords))[1:] ]
mx, my, mz = [ sum(i)/2. for i in minmax ]
scale = radius/math.sqrt((minmax[0][0]-mx)**2 + (minmax[1][0]-my)**2)
for i in self.coords:
i[1] = scale*(i[1]-mx)
i[2] = scale*(i[2]-my)
i[3] -= minmax[2][0]
return self.coords
|
def build(self, **kwargs):
"""Build/return a list of [(bead, x, y, z), ...]"""
if not self.coords:
if self.beads and self.template:
stuff = zip(self.beads, self.template)
self.coords = [[i, x, y, z] for i, (x, y, z) in stuff if i != "-"]
else:
# Set beads/structure from head/link/tail
# Set bead names
if self.beads:
beads = list(self.beads)
else:
beads = [HEADBEADS[i] for i in self.head]
beads.extend([LINKBEADS[n] + str(i + 1)
for i, n in enumerate(self.link)])
for i, t in enumerate(self.tail):
beads.extend([n + chr(65 + i) + str(j + 1)
for j, n in enumerate(t)])
taillength = max([0]+[len(i) for i in self.tail])
length = len(self.head)+taillength
# Add the pseudocoordinates for the head
rl = range(len(self.head))
struc = [(0, 0, length-i) for i in rl]
# Add the linkers
rl = range(len(self.link))
struc.extend([(i%2, i//2, taillength) for i in rl ])
# Add the tails
for j, tail in enumerate(self.tail):
rl = range(len(tail))
struc.extend([(j%2, j//2, taillength-1-i) for i in rl])
mx, my, mz = [ (max(i)+min(i))/2 for i in zip(*struc) ]
self.coords = [
[i, 0.25 * (x - mx), 0.25 * (y - my), z]
for i, (x, y, z) in zip(beads, struc)
]
# Scale the x/y based on the lipid's APL - diameter is less than sqrt(APL)
diam = kwargs.get("diam", self.diam)
radius = diam*0.45
minmax = [ (min(i), max(i)) for i in list(zip(*self.coords))[1:] ]
mx, my, mz = [ sum(i)/2. for i in minmax ]
scale = radius/math.sqrt((minmax[0][0]-mx)**2 + (minmax[1][0]-my)**2)
for i in self.coords:
i[1] = scale*(i[1]-mx)
i[2] = scale*(i[2]-my)
i[3] -= minmax[2][0]
return self.coords
|
[
"Build",
"/",
"return",
"a",
"list",
"of",
"[",
"(",
"bead",
"x",
"y",
"z",
")",
"...",
"]"
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/lipids.py#L90-L144
|
[
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"coords",
":",
"if",
"self",
".",
"beads",
"and",
"self",
".",
"template",
":",
"stuff",
"=",
"zip",
"(",
"self",
".",
"beads",
",",
"self",
".",
"template",
")",
"self",
".",
"coords",
"=",
"[",
"[",
"i",
",",
"x",
",",
"y",
",",
"z",
"]",
"for",
"i",
",",
"(",
"x",
",",
"y",
",",
"z",
")",
"in",
"stuff",
"if",
"i",
"!=",
"\"-\"",
"]",
"else",
":",
"# Set beads/structure from head/link/tail",
"# Set bead names",
"if",
"self",
".",
"beads",
":",
"beads",
"=",
"list",
"(",
"self",
".",
"beads",
")",
"else",
":",
"beads",
"=",
"[",
"HEADBEADS",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"head",
"]",
"beads",
".",
"extend",
"(",
"[",
"LINKBEADS",
"[",
"n",
"]",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"self",
".",
"link",
")",
"]",
")",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"self",
".",
"tail",
")",
":",
"beads",
".",
"extend",
"(",
"[",
"n",
"+",
"chr",
"(",
"65",
"+",
"i",
")",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"for",
"j",
",",
"n",
"in",
"enumerate",
"(",
"t",
")",
"]",
")",
"taillength",
"=",
"max",
"(",
"[",
"0",
"]",
"+",
"[",
"len",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"tail",
"]",
")",
"length",
"=",
"len",
"(",
"self",
".",
"head",
")",
"+",
"taillength",
"# Add the pseudocoordinates for the head",
"rl",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"head",
")",
")",
"struc",
"=",
"[",
"(",
"0",
",",
"0",
",",
"length",
"-",
"i",
")",
"for",
"i",
"in",
"rl",
"]",
"# Add the linkers",
"rl",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"link",
")",
")",
"struc",
".",
"extend",
"(",
"[",
"(",
"i",
"%",
"2",
",",
"i",
"//",
"2",
",",
"taillength",
")",
"for",
"i",
"in",
"rl",
"]",
")",
"# Add the tails",
"for",
"j",
",",
"tail",
"in",
"enumerate",
"(",
"self",
".",
"tail",
")",
":",
"rl",
"=",
"range",
"(",
"len",
"(",
"tail",
")",
")",
"struc",
".",
"extend",
"(",
"[",
"(",
"j",
"%",
"2",
",",
"j",
"//",
"2",
",",
"taillength",
"-",
"1",
"-",
"i",
")",
"for",
"i",
"in",
"rl",
"]",
")",
"mx",
",",
"my",
",",
"mz",
"=",
"[",
"(",
"max",
"(",
"i",
")",
"+",
"min",
"(",
"i",
")",
")",
"/",
"2",
"for",
"i",
"in",
"zip",
"(",
"*",
"struc",
")",
"]",
"self",
".",
"coords",
"=",
"[",
"[",
"i",
",",
"0.25",
"*",
"(",
"x",
"-",
"mx",
")",
",",
"0.25",
"*",
"(",
"y",
"-",
"my",
")",
",",
"z",
"]",
"for",
"i",
",",
"(",
"x",
",",
"y",
",",
"z",
")",
"in",
"zip",
"(",
"beads",
",",
"struc",
")",
"]",
"# Scale the x/y based on the lipid's APL - diameter is less than sqrt(APL)",
"diam",
"=",
"kwargs",
".",
"get",
"(",
"\"diam\"",
",",
"self",
".",
"diam",
")",
"radius",
"=",
"diam",
"*",
"0.45",
"minmax",
"=",
"[",
"(",
"min",
"(",
"i",
")",
",",
"max",
"(",
"i",
")",
")",
"for",
"i",
"in",
"list",
"(",
"zip",
"(",
"*",
"self",
".",
"coords",
")",
")",
"[",
"1",
":",
"]",
"]",
"mx",
",",
"my",
",",
"mz",
"=",
"[",
"sum",
"(",
"i",
")",
"/",
"2.",
"for",
"i",
"in",
"minmax",
"]",
"scale",
"=",
"radius",
"/",
"math",
".",
"sqrt",
"(",
"(",
"minmax",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"mx",
")",
"**",
"2",
"+",
"(",
"minmax",
"[",
"1",
"]",
"[",
"0",
"]",
"-",
"my",
")",
"**",
"2",
")",
"for",
"i",
"in",
"self",
".",
"coords",
":",
"i",
"[",
"1",
"]",
"=",
"scale",
"*",
"(",
"i",
"[",
"1",
"]",
"-",
"mx",
")",
"i",
"[",
"2",
"]",
"=",
"scale",
"*",
"(",
"i",
"[",
"2",
"]",
"-",
"my",
")",
"i",
"[",
"3",
"]",
"-=",
"minmax",
"[",
"2",
"]",
"[",
"0",
"]",
"return",
"self",
".",
"coords"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
molspec
|
Parse a string for a lipid or a solvent as given on the command line
(MOLECULE[=NUMBER|:NUMBER]); where `=NUMBER` sets an absolute number of the
molecule, and `:NUMBER` sets a relative number of it.
If both absolute and relative number are set False, then relative count is 1.
|
insane/converters.py
|
def molspec(x):
"""
Parse a string for a lipid or a solvent as given on the command line
(MOLECULE[=NUMBER|:NUMBER]); where `=NUMBER` sets an absolute number of the
molecule, and `:NUMBER` sets a relative number of it.
If both absolute and relative number are set False, then relative count is 1.
"""
lip = x.split(":")
abn = lip[0].split("=")
names = abn[0]
if len(abn) > 1:
nrel = 0
nabs = int(abn[1])
else:
nabs = 0
if len(lip) > 1:
nrel = float(lip[1])
else:
nrel = 1
return abn[0], nabs, nrel
|
def molspec(x):
"""
Parse a string for a lipid or a solvent as given on the command line
(MOLECULE[=NUMBER|:NUMBER]); where `=NUMBER` sets an absolute number of the
molecule, and `:NUMBER` sets a relative number of it.
If both absolute and relative number are set False, then relative count is 1.
"""
lip = x.split(":")
abn = lip[0].split("=")
names = abn[0]
if len(abn) > 1:
nrel = 0
nabs = int(abn[1])
else:
nabs = 0
if len(lip) > 1:
nrel = float(lip[1])
else:
nrel = 1
return abn[0], nabs, nrel
|
[
"Parse",
"a",
"string",
"for",
"a",
"lipid",
"or",
"a",
"solvent",
"as",
"given",
"on",
"the",
"command",
"line",
"(",
"MOLECULE",
"[",
"=",
"NUMBER|",
":",
"NUMBER",
"]",
")",
";",
"where",
"=",
"NUMBER",
"sets",
"an",
"absolute",
"number",
"of",
"the",
"molecule",
"and",
":",
"NUMBER",
"sets",
"a",
"relative",
"number",
"of",
"it",
".",
"If",
"both",
"absolute",
"and",
"relative",
"number",
"are",
"set",
"False",
"then",
"relative",
"count",
"is",
"1",
"."
] |
Tsjerk/Insane
|
python
|
https://github.com/Tsjerk/Insane/blob/b73f08910ddb0b66597b20ff75ecee7f65f4ecf6/insane/converters.py#L51-L70
|
[
"def",
"molspec",
"(",
"x",
")",
":",
"lip",
"=",
"x",
".",
"split",
"(",
"\":\"",
")",
"abn",
"=",
"lip",
"[",
"0",
"]",
".",
"split",
"(",
"\"=\"",
")",
"names",
"=",
"abn",
"[",
"0",
"]",
"if",
"len",
"(",
"abn",
")",
">",
"1",
":",
"nrel",
"=",
"0",
"nabs",
"=",
"int",
"(",
"abn",
"[",
"1",
"]",
")",
"else",
":",
"nabs",
"=",
"0",
"if",
"len",
"(",
"lip",
")",
">",
"1",
":",
"nrel",
"=",
"float",
"(",
"lip",
"[",
"1",
"]",
")",
"else",
":",
"nrel",
"=",
"1",
"return",
"abn",
"[",
"0",
"]",
",",
"nabs",
",",
"nrel"
] |
b73f08910ddb0b66597b20ff75ecee7f65f4ecf6
|
test
|
message_user
|
Send a message to a particular user.
:param user: User instance
:param message: Message to show
:param level: Message level
|
async_messages/__init__.py
|
def message_user(user, message, level=constants.INFO):
"""
Send a message to a particular user.
:param user: User instance
:param message: Message to show
:param level: Message level
"""
# We store a list of messages in the cache so we can have multiple messages
# queued up for a user.
user_key = _user_key(user)
messages = cache.get(user_key) or []
messages.append((message, level))
cache.set(user_key, messages)
|
def message_user(user, message, level=constants.INFO):
"""
Send a message to a particular user.
:param user: User instance
:param message: Message to show
:param level: Message level
"""
# We store a list of messages in the cache so we can have multiple messages
# queued up for a user.
user_key = _user_key(user)
messages = cache.get(user_key) or []
messages.append((message, level))
cache.set(user_key, messages)
|
[
"Send",
"a",
"message",
"to",
"a",
"particular",
"user",
"."
] |
codeinthehole/django-async-messages
|
python
|
https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/__init__.py#L5-L18
|
[
"def",
"message_user",
"(",
"user",
",",
"message",
",",
"level",
"=",
"constants",
".",
"INFO",
")",
":",
"# We store a list of messages in the cache so we can have multiple messages",
"# queued up for a user.",
"user_key",
"=",
"_user_key",
"(",
"user",
")",
"messages",
"=",
"cache",
".",
"get",
"(",
"user_key",
")",
"or",
"[",
"]",
"messages",
".",
"append",
"(",
"(",
"message",
",",
"level",
")",
")",
"cache",
".",
"set",
"(",
"user_key",
",",
"messages",
")"
] |
292cb2fc517521dabc67b90e7ca5b1617f59e214
|
test
|
message_users
|
Send a message to a group of users.
:param users: Users queryset
:param message: Message to show
:param level: Message level
|
async_messages/__init__.py
|
def message_users(users, message, level=constants.INFO):
"""
Send a message to a group of users.
:param users: Users queryset
:param message: Message to show
:param level: Message level
"""
for user in users:
message_user(user, message, level)
|
def message_users(users, message, level=constants.INFO):
"""
Send a message to a group of users.
:param users: Users queryset
:param message: Message to show
:param level: Message level
"""
for user in users:
message_user(user, message, level)
|
[
"Send",
"a",
"message",
"to",
"a",
"group",
"of",
"users",
"."
] |
codeinthehole/django-async-messages
|
python
|
https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/__init__.py#L21-L30
|
[
"def",
"message_users",
"(",
"users",
",",
"message",
",",
"level",
"=",
"constants",
".",
"INFO",
")",
":",
"for",
"user",
"in",
"users",
":",
"message_user",
"(",
"user",
",",
"message",
",",
"level",
")"
] |
292cb2fc517521dabc67b90e7ca5b1617f59e214
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.