repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.search
|
def search(self, query, method="lucene", start=None,
rows=None, access_token=None):
"""Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param start: string
Index of the first record requested. Use for pagination.
:param rows: string
Number of records requested. Use for pagination.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Returns
-------
:returns: dict
Search result with error description available. The results can
be obtained by accessing key 'result'. To get the number
of all results, access the key 'num-found'.
"""
if access_token is None:
access_token = self. \
get_search_token_from_orcid()
headers = {'Accept': 'application/orcid+json',
'Authorization': 'Bearer %s' % access_token}
return self._search(query, method, start, rows, headers,
self._endpoint)
|
python
|
def search(self, query, method="lucene", start=None,
rows=None, access_token=None):
"""Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param start: string
Index of the first record requested. Use for pagination.
:param rows: string
Number of records requested. Use for pagination.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Returns
-------
:returns: dict
Search result with error description available. The results can
be obtained by accessing key 'result'. To get the number
of all results, access the key 'num-found'.
"""
if access_token is None:
access_token = self. \
get_search_token_from_orcid()
headers = {'Accept': 'application/orcid+json',
'Authorization': 'Bearer %s' % access_token}
return self._search(query, method, start, rows, headers,
self._endpoint)
|
[
"def",
"search",
"(",
"self",
",",
"query",
",",
"method",
"=",
"\"lucene\"",
",",
"start",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"access_token",
"is",
"None",
":",
"access_token",
"=",
"self",
".",
"get_search_token_from_orcid",
"(",
")",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/orcid+json'",
",",
"'Authorization'",
":",
"'Bearer %s'",
"%",
"access_token",
"}",
"return",
"self",
".",
"_search",
"(",
"query",
",",
"method",
",",
"start",
",",
"rows",
",",
"headers",
",",
"self",
".",
"_endpoint",
")"
] |
Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param start: string
Index of the first record requested. Use for pagination.
:param rows: string
Number of records requested. Use for pagination.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Returns
-------
:returns: dict
Search result with error description available. The results can
be obtained by accessing key 'result'. To get the number
of all results, access the key 'num-found'.
|
[
"Search",
"the",
"ORCID",
"database",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L132-L166
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.search_generator
|
def search_generator(self, query, method="lucene",
pagination=10, access_token=None):
"""Search the ORCID database with a generator.
The generator will yield every result.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param pagination: integer
How many papers should be fetched with the request.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Yields
-------
:yields: dict
Single profile from the search results.
"""
if access_token is None:
access_token = self. \
get_search_token_from_orcid()
headers = {'Accept': 'application/orcid+json',
'Authorization': 'Bearer %s' % access_token}
index = 0
while True:
paginated_result = self._search(query, method, index, pagination,
headers, self._endpoint)
if not paginated_result['result']:
return
for result in paginated_result['result']:
yield result
index += pagination
|
python
|
def search_generator(self, query, method="lucene",
pagination=10, access_token=None):
"""Search the ORCID database with a generator.
The generator will yield every result.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param pagination: integer
How many papers should be fetched with the request.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Yields
-------
:yields: dict
Single profile from the search results.
"""
if access_token is None:
access_token = self. \
get_search_token_from_orcid()
headers = {'Accept': 'application/orcid+json',
'Authorization': 'Bearer %s' % access_token}
index = 0
while True:
paginated_result = self._search(query, method, index, pagination,
headers, self._endpoint)
if not paginated_result['result']:
return
for result in paginated_result['result']:
yield result
index += pagination
|
[
"def",
"search_generator",
"(",
"self",
",",
"query",
",",
"method",
"=",
"\"lucene\"",
",",
"pagination",
"=",
"10",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"access_token",
"is",
"None",
":",
"access_token",
"=",
"self",
".",
"get_search_token_from_orcid",
"(",
")",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/orcid+json'",
",",
"'Authorization'",
":",
"'Bearer %s'",
"%",
"access_token",
"}",
"index",
"=",
"0",
"while",
"True",
":",
"paginated_result",
"=",
"self",
".",
"_search",
"(",
"query",
",",
"method",
",",
"index",
",",
"pagination",
",",
"headers",
",",
"self",
".",
"_endpoint",
")",
"if",
"not",
"paginated_result",
"[",
"'result'",
"]",
":",
"return",
"for",
"result",
"in",
"paginated_result",
"[",
"'result'",
"]",
":",
"yield",
"result",
"index",
"+=",
"pagination"
] |
Search the ORCID database with a generator.
The generator will yield every result.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
:param pagination: integer
How many papers should be fetched with the request.
:param access_token: string
If obtained before, the access token to use to pass through
authorization. Note that if this argument is not provided,
the function will take more time.
Yields
-------
:yields: dict
Single profile from the search results.
|
[
"Search",
"the",
"ORCID",
"database",
"with",
"a",
"generator",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L168-L209
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.get_search_token_from_orcid
|
def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
payload = {'client_id': self._key,
'client_secret': self._secret,
'scope': scope,
'grant_type': 'client_credentials'
}
url = "%s/oauth/token" % self._endpoint
headers = {'Accept': 'application/json'}
response = requests.post(url, data=payload, headers=headers,
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return response.json()['access_token']
|
python
|
def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
payload = {'client_id': self._key,
'client_secret': self._secret,
'scope': scope,
'grant_type': 'client_credentials'
}
url = "%s/oauth/token" % self._endpoint
headers = {'Accept': 'application/json'}
response = requests.post(url, data=payload, headers=headers,
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return response.json()['access_token']
|
[
"def",
"get_search_token_from_orcid",
"(",
"self",
",",
"scope",
"=",
"'/read-public'",
")",
":",
"payload",
"=",
"{",
"'client_id'",
":",
"self",
".",
"_key",
",",
"'client_secret'",
":",
"self",
".",
"_secret",
",",
"'scope'",
":",
"scope",
",",
"'grant_type'",
":",
"'client_credentials'",
"}",
"url",
"=",
"\"%s/oauth/token\"",
"%",
"self",
".",
"_endpoint",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"payload",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"response",
".",
"raise_for_status",
"(",
")",
"if",
"self",
".",
"do_store_raw_response",
":",
"self",
".",
"raw_response",
"=",
"response",
"return",
"response",
".",
"json",
"(",
")",
"[",
"'access_token'",
"]"
] |
Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
|
[
"Get",
"a",
"token",
"for",
"searching",
"ORCID",
"records",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L211-L238
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.get_token
|
def get_token(self, user_id, password, redirect_uri,
scope='/read-limited'):
"""Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
"""
response = self._authenticate(user_id, password, redirect_uri,
scope)
return response['access_token']
|
python
|
def get_token(self, user_id, password, redirect_uri,
scope='/read-limited'):
"""Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
"""
response = self._authenticate(user_id, password, redirect_uri,
scope)
return response['access_token']
|
[
"def",
"get_token",
"(",
"self",
",",
"user_id",
",",
"password",
",",
"redirect_uri",
",",
"scope",
"=",
"'/read-limited'",
")",
":",
"response",
"=",
"self",
".",
"_authenticate",
"(",
"user_id",
",",
"password",
",",
"redirect_uri",
",",
"scope",
")",
"return",
"response",
"[",
"'access_token'",
"]"
] |
Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
|
[
"Get",
"the",
"token",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L240-L263
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.get_token_from_authorization_code
|
def get_token_from_authorization_code(self,
authorization_code, redirect_uri):
"""Like `get_token`, but using an OAuth 2 authorization code.
Use this method if you run a webserver that serves as an endpoint for
the redirect URI. The webserver can retrieve the authorization code
from the URL that is requested by ORCID.
Parameters
----------
:param redirect_uri: string
The redirect uri of the institution.
:param authorization_code: string
The authorization code.
Returns
-------
:returns: dict
All data of the access token. The access token itself is in the
``"access_token"`` key.
"""
token_dict = {
"client_id": self._key,
"client_secret": self._secret,
"grant_type": "authorization_code",
"code": authorization_code,
"redirect_uri": redirect_uri,
}
response = requests.post(self._token_url, data=token_dict,
headers={'Accept': 'application/json'},
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return json.loads(response.text)
|
python
|
def get_token_from_authorization_code(self,
authorization_code, redirect_uri):
"""Like `get_token`, but using an OAuth 2 authorization code.
Use this method if you run a webserver that serves as an endpoint for
the redirect URI. The webserver can retrieve the authorization code
from the URL that is requested by ORCID.
Parameters
----------
:param redirect_uri: string
The redirect uri of the institution.
:param authorization_code: string
The authorization code.
Returns
-------
:returns: dict
All data of the access token. The access token itself is in the
``"access_token"`` key.
"""
token_dict = {
"client_id": self._key,
"client_secret": self._secret,
"grant_type": "authorization_code",
"code": authorization_code,
"redirect_uri": redirect_uri,
}
response = requests.post(self._token_url, data=token_dict,
headers={'Accept': 'application/json'},
timeout=self._timeout)
response.raise_for_status()
if self.do_store_raw_response:
self.raw_response = response
return json.loads(response.text)
|
[
"def",
"get_token_from_authorization_code",
"(",
"self",
",",
"authorization_code",
",",
"redirect_uri",
")",
":",
"token_dict",
"=",
"{",
"\"client_id\"",
":",
"self",
".",
"_key",
",",
"\"client_secret\"",
":",
"self",
".",
"_secret",
",",
"\"grant_type\"",
":",
"\"authorization_code\"",
",",
"\"code\"",
":",
"authorization_code",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_token_url",
",",
"data",
"=",
"token_dict",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
"}",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"response",
".",
"raise_for_status",
"(",
")",
"if",
"self",
".",
"do_store_raw_response",
":",
"self",
".",
"raw_response",
"=",
"response",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")"
] |
Like `get_token`, but using an OAuth 2 authorization code.
Use this method if you run a webserver that serves as an endpoint for
the redirect URI. The webserver can retrieve the authorization code
from the URL that is requested by ORCID.
Parameters
----------
:param redirect_uri: string
The redirect uri of the institution.
:param authorization_code: string
The authorization code.
Returns
-------
:returns: dict
All data of the access token. The access token itself is in the
``"access_token"`` key.
|
[
"Like",
"get_token",
"but",
"using",
"an",
"OAuth",
"2",
"authorization",
"code",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L265-L299
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
PublicAPI.read_record_public
|
def read_record_public(self, orcid_id, request_type, token, put_code=None,
accept_type='application/orcid+json'):
"""Get the public info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
"""
return self._get_info(orcid_id, self._get_public_info, request_type,
token, put_code, accept_type)
|
python
|
def read_record_public(self, orcid_id, request_type, token, put_code=None,
accept_type='application/orcid+json'):
"""Get the public info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
"""
return self._get_info(orcid_id, self._get_public_info, request_type,
token, put_code, accept_type)
|
[
"def",
"read_record_public",
"(",
"self",
",",
"orcid_id",
",",
"request_type",
",",
"token",
",",
"put_code",
"=",
"None",
",",
"accept_type",
"=",
"'application/orcid+json'",
")",
":",
"return",
"self",
".",
"_get_info",
"(",
"orcid_id",
",",
"self",
".",
"_get_public_info",
",",
"request_type",
",",
"token",
",",
"put_code",
",",
"accept_type",
")"
] |
Get the public info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
|
[
"Get",
"the",
"public",
"info",
"about",
"the",
"researcher",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L301-L327
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.add_record
|
def add_record(self, orcid_id, token, request_type, data,
content_type='application/orcid+json'):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param content_type: string
MIME type of the passed record.
Returns
-------
:returns: string
Put-code of the new work.
"""
return self._update_activities(orcid_id, token, requests.post,
request_type, data,
content_type=content_type)
|
python
|
def add_record(self, orcid_id, token, request_type, data,
content_type='application/orcid+json'):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param content_type: string
MIME type of the passed record.
Returns
-------
:returns: string
Put-code of the new work.
"""
return self._update_activities(orcid_id, token, requests.post,
request_type, data,
content_type=content_type)
|
[
"def",
"add_record",
"(",
"self",
",",
"orcid_id",
",",
"token",
",",
"request_type",
",",
"data",
",",
"content_type",
"=",
"'application/orcid+json'",
")",
":",
"return",
"self",
".",
"_update_activities",
"(",
"orcid_id",
",",
"token",
",",
"requests",
".",
"post",
",",
"request_type",
",",
"data",
",",
"content_type",
"=",
"content_type",
")"
] |
Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param content_type: string
MIME type of the passed record.
Returns
-------
:returns: string
Put-code of the new work.
|
[
"Add",
"a",
"record",
"to",
"a",
"profile",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L475-L502
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.get_token
|
def get_token(self, user_id, password, redirect_uri,
scope='/activities/update'):
"""Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
"""
return super(MemberAPI, self).get_token(user_id, password,
redirect_uri, scope)
|
python
|
def get_token(self, user_id, password, redirect_uri,
scope='/activities/update'):
"""Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
"""
return super(MemberAPI, self).get_token(user_id, password,
redirect_uri, scope)
|
[
"def",
"get_token",
"(",
"self",
",",
"user_id",
",",
"password",
",",
"redirect_uri",
",",
"scope",
"=",
"'/activities/update'",
")",
":",
"return",
"super",
"(",
"MemberAPI",
",",
"self",
")",
".",
"get_token",
"(",
"user_id",
",",
"password",
",",
"redirect_uri",
",",
"scope",
")"
] |
Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
:param scope: string
The desired scope. For example '/activities/update',
'/read-limited', etc.
Returns
-------
:returns: string
The token.
|
[
"Get",
"the",
"token",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L504-L527
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.get_user_orcid
|
def get_user_orcid(self, user_id, password, redirect_uri):
"""Get the user orcid from authentication process.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
Returns
-------
:returns: string
The orcid.
"""
response = self._authenticate(user_id, password, redirect_uri,
'/authenticate')
return response['orcid']
|
python
|
def get_user_orcid(self, user_id, password, redirect_uri):
"""Get the user orcid from authentication process.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
Returns
-------
:returns: string
The orcid.
"""
response = self._authenticate(user_id, password, redirect_uri,
'/authenticate')
return response['orcid']
|
[
"def",
"get_user_orcid",
"(",
"self",
",",
"user_id",
",",
"password",
",",
"redirect_uri",
")",
":",
"response",
"=",
"self",
".",
"_authenticate",
"(",
"user_id",
",",
"password",
",",
"redirect_uri",
",",
"'/authenticate'",
")",
"return",
"response",
"[",
"'orcid'",
"]"
] |
Get the user orcid from authentication process.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
:param redirect_uri: string
The redirect uri of the institution.
Returns
-------
:returns: string
The orcid.
|
[
"Get",
"the",
"user",
"orcid",
"from",
"authentication",
"process",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L529-L549
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.read_record_member
|
def read_record_member(self, orcid_id, request_type, token, put_code=None,
accept_type='application/orcid+json'):
"""Get the member info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values..
:param response_format: string
One of json, xml.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
"""
return self._get_info(orcid_id, self._get_member_info, request_type,
token, put_code, accept_type)
|
python
|
def read_record_member(self, orcid_id, request_type, token, put_code=None,
accept_type='application/orcid+json'):
"""Get the member info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values..
:param response_format: string
One of json, xml.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
"""
return self._get_info(orcid_id, self._get_member_info, request_type,
token, put_code, accept_type)
|
[
"def",
"read_record_member",
"(",
"self",
",",
"orcid_id",
",",
"request_type",
",",
"token",
",",
"put_code",
"=",
"None",
",",
"accept_type",
"=",
"'application/orcid+json'",
")",
":",
"return",
"self",
".",
"_get_info",
"(",
"orcid_id",
",",
"self",
".",
"_get_member_info",
",",
"request_type",
",",
"token",
",",
"put_code",
",",
"accept_type",
")"
] |
Get the member info about the researcher.
Parameters
----------
:param orcid_id: string
Id of the queried author.
:param request_type: string
For example: 'record'.
See https://members.orcid.org/api/tutorial/read-orcid-records
for possible values..
:param response_format: string
One of json, xml.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param put_code: string | list of strings
The id of the queried work. In case of 'works' request_type
might be a list of strings
:param accept_type: expected MIME type of received data
Returns
-------
:returns: dict | lxml.etree._Element
Record(s) in JSON-compatible dictionary representation or
in XML E-tree, depending on accept_type specified.
|
[
"Get",
"the",
"member",
"info",
"about",
"the",
"researcher",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L551-L579
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.remove_record
|
def remove_record(self, orcid_id, token, request_type, put_code):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
"""
self._update_activities(orcid_id, token, requests.delete, request_type,
put_code=put_code)
|
python
|
def remove_record(self, orcid_id, token, request_type, put_code):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
"""
self._update_activities(orcid_id, token, requests.delete, request_type,
put_code=put_code)
|
[
"def",
"remove_record",
"(",
"self",
",",
"orcid_id",
",",
"token",
",",
"request_type",
",",
"put_code",
")",
":",
"self",
".",
"_update_activities",
"(",
"orcid_id",
",",
"token",
",",
"requests",
".",
"delete",
",",
"request_type",
",",
"put_code",
"=",
"put_code",
")"
] |
Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
|
[
"Add",
"a",
"record",
"to",
"a",
"profile",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L581-L598
|
train
|
ORCID/python-orcid
|
orcid/orcid.py
|
MemberAPI.update_record
|
def update_record(self, orcid_id, token, request_type, data, put_code,
content_type='application/orcid+json'):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
:param content_type: string
MIME type of the data being sent.
"""
self._update_activities(orcid_id, token, requests.put, request_type,
data, put_code, content_type)
|
python
|
def update_record(self, orcid_id, token, request_type, data, put_code,
content_type='application/orcid+json'):
"""Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
:param content_type: string
MIME type of the data being sent.
"""
self._update_activities(orcid_id, token, requests.put, request_type,
data, put_code, content_type)
|
[
"def",
"update_record",
"(",
"self",
",",
"orcid_id",
",",
"token",
",",
"request_type",
",",
"data",
",",
"put_code",
",",
"content_type",
"=",
"'application/orcid+json'",
")",
":",
"self",
".",
"_update_activities",
"(",
"orcid_id",
",",
"token",
",",
"requests",
".",
"put",
",",
"request_type",
",",
"data",
",",
"put_code",
",",
"content_type",
")"
] |
Add a record to a profile.
Parameters
----------
:param orcid_id: string
Id of the author.
:param token: string
Token received from OAuth 2 3-legged authorization.
:param request_type: string
One of 'activities', 'education', 'employment', 'funding',
'peer-review', 'work'.
:param data: dict | lxml.etree._Element
The record in Python-friendly format, as either JSON-compatible
dictionary (content_type == 'application/orcid+json') or
XML (content_type == 'application/orcid+xml')
:param put_code: string
The id of the record. Can be retrieved using read_record_* method.
In the result of it, it will be called 'put-code'.
:param content_type: string
MIME type of the data being sent.
|
[
"Add",
"a",
"record",
"to",
"a",
"profile",
"."
] |
217a56a905f53aef94811e54b4e651a1b09c1f76
|
https://github.com/ORCID/python-orcid/blob/217a56a905f53aef94811e54b4e651a1b09c1f76/orcid/orcid.py#L674-L698
|
train
|
ambitioninc/django-entity
|
entity/migrations/0006_entity_relationship_unique.py
|
remove_duplicates
|
def remove_duplicates(apps, schema_editor):
"""
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
"""
# Get the model
EntityRelationship = apps.get_model('entity', 'EntityRelationship')
# Find the duplicates
duplicates = EntityRelationship.objects.all().order_by(
'sub_entity_id',
'super_entity_id'
).values(
'sub_entity_id',
'super_entity_id'
).annotate(
Count('sub_entity_id'),
Count('super_entity_id'),
max_id=Max('id')
).filter(
super_entity_id__count__gt=1
)
# Loop over the duplicates and delete
for duplicate in duplicates:
EntityRelationship.objects.filter(
sub_entity_id=duplicate['sub_entity_id'],
super_entity_id=duplicate['super_entity_id']
).exclude(
id=duplicate['max_id']
).delete()
|
python
|
def remove_duplicates(apps, schema_editor):
"""
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
"""
# Get the model
EntityRelationship = apps.get_model('entity', 'EntityRelationship')
# Find the duplicates
duplicates = EntityRelationship.objects.all().order_by(
'sub_entity_id',
'super_entity_id'
).values(
'sub_entity_id',
'super_entity_id'
).annotate(
Count('sub_entity_id'),
Count('super_entity_id'),
max_id=Max('id')
).filter(
super_entity_id__count__gt=1
)
# Loop over the duplicates and delete
for duplicate in duplicates:
EntityRelationship.objects.filter(
sub_entity_id=duplicate['sub_entity_id'],
super_entity_id=duplicate['super_entity_id']
).exclude(
id=duplicate['max_id']
).delete()
|
[
"def",
"remove_duplicates",
"(",
"apps",
",",
"schema_editor",
")",
":",
"# Get the model",
"EntityRelationship",
"=",
"apps",
".",
"get_model",
"(",
"'entity'",
",",
"'EntityRelationship'",
")",
"# Find the duplicates",
"duplicates",
"=",
"EntityRelationship",
".",
"objects",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"'sub_entity_id'",
",",
"'super_entity_id'",
")",
".",
"values",
"(",
"'sub_entity_id'",
",",
"'super_entity_id'",
")",
".",
"annotate",
"(",
"Count",
"(",
"'sub_entity_id'",
")",
",",
"Count",
"(",
"'super_entity_id'",
")",
",",
"max_id",
"=",
"Max",
"(",
"'id'",
")",
")",
".",
"filter",
"(",
"super_entity_id__count__gt",
"=",
"1",
")",
"# Loop over the duplicates and delete",
"for",
"duplicate",
"in",
"duplicates",
":",
"EntityRelationship",
".",
"objects",
".",
"filter",
"(",
"sub_entity_id",
"=",
"duplicate",
"[",
"'sub_entity_id'",
"]",
",",
"super_entity_id",
"=",
"duplicate",
"[",
"'super_entity_id'",
"]",
")",
".",
"exclude",
"(",
"id",
"=",
"duplicate",
"[",
"'max_id'",
"]",
")",
".",
"delete",
"(",
")"
] |
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
|
[
"Remove",
"any",
"duplicates",
"from",
"the",
"entity",
"relationship",
"table",
":",
"param",
"apps",
":",
":",
"param",
"schema_editor",
":",
":",
"return",
":"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/migrations/0006_entity_relationship_unique.py#L42-L75
|
train
|
wesleyfr/boxpython
|
boxpython/auth.py
|
BoxAuthenticateFlow.get_access_tokens
|
def get_access_tokens(self, authorization_code):
"""From the authorization code, get the "access token" and the "refresh token" from Box.
Args:
authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`.
Returns:
tuple. (access_token, refresh_token)
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
response = self.box_request.get_access_token(authorization_code)
try:
att = response.json()
except Exception, ex:
raise BoxHttpResponseError(ex)
if response.status_code >= 400:
raise BoxError(response.status_code, att)
return att['access_token'], att['refresh_token']
|
python
|
def get_access_tokens(self, authorization_code):
"""From the authorization code, get the "access token" and the "refresh token" from Box.
Args:
authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`.
Returns:
tuple. (access_token, refresh_token)
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
response = self.box_request.get_access_token(authorization_code)
try:
att = response.json()
except Exception, ex:
raise BoxHttpResponseError(ex)
if response.status_code >= 400:
raise BoxError(response.status_code, att)
return att['access_token'], att['refresh_token']
|
[
"def",
"get_access_tokens",
"(",
"self",
",",
"authorization_code",
")",
":",
"response",
"=",
"self",
".",
"box_request",
".",
"get_access_token",
"(",
"authorization_code",
")",
"try",
":",
"att",
"=",
"response",
".",
"json",
"(",
")",
"except",
"Exception",
",",
"ex",
":",
"raise",
"BoxHttpResponseError",
"(",
"ex",
")",
"if",
"response",
".",
"status_code",
">=",
"400",
":",
"raise",
"BoxError",
"(",
"response",
".",
"status_code",
",",
"att",
")",
"return",
"att",
"[",
"'access_token'",
"]",
",",
"att",
"[",
"'refresh_token'",
"]"
] |
From the authorization code, get the "access token" and the "refresh token" from Box.
Args:
authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`.
Returns:
tuple. (access_token, refresh_token)
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"From",
"the",
"authorization",
"code",
"get",
"the",
"access",
"token",
"and",
"the",
"refresh",
"token",
"from",
"Box",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/auth.py#L39-L64
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
unpack_frame
|
def unpack_frame(message):
"""Called to unpack a STOMP message into a dictionary.
returned = {
# STOMP Command:
'cmd' : '...',
# Headers e.g.
'headers' : {
'destination' : 'xyz',
'message-id' : 'some event',
:
etc,
}
# Body:
'body' : '...1234...\x00',
}
"""
body = []
returned = dict(cmd='', headers={}, body='')
breakdown = message.split('\n')
# Get the message command:
returned['cmd'] = breakdown[0]
breakdown = breakdown[1:]
def headD(field):
# find the first ':' everything to the left of this is a
# header, everything to the right is data:
index = field.find(':')
if index:
header = field[:index].strip()
data = field[index+1:].strip()
# print "header '%s' data '%s'" % (header, data)
returned['headers'][header.strip()] = data.strip()
def bodyD(field):
field = field.strip()
if field:
body.append(field)
# Recover the header fields and body data
handler = headD
for field in breakdown:
# print "field:", field
if field.strip() == '':
# End of headers, it body data next.
handler = bodyD
continue
handler(field)
# Stich the body data together:
# print "1. body: ", body
body = "".join(body)
returned['body'] = body.replace('\x00', '')
# print "2. body: <%s>" % returned['body']
return returned
|
python
|
def unpack_frame(message):
"""Called to unpack a STOMP message into a dictionary.
returned = {
# STOMP Command:
'cmd' : '...',
# Headers e.g.
'headers' : {
'destination' : 'xyz',
'message-id' : 'some event',
:
etc,
}
# Body:
'body' : '...1234...\x00',
}
"""
body = []
returned = dict(cmd='', headers={}, body='')
breakdown = message.split('\n')
# Get the message command:
returned['cmd'] = breakdown[0]
breakdown = breakdown[1:]
def headD(field):
# find the first ':' everything to the left of this is a
# header, everything to the right is data:
index = field.find(':')
if index:
header = field[:index].strip()
data = field[index+1:].strip()
# print "header '%s' data '%s'" % (header, data)
returned['headers'][header.strip()] = data.strip()
def bodyD(field):
field = field.strip()
if field:
body.append(field)
# Recover the header fields and body data
handler = headD
for field in breakdown:
# print "field:", field
if field.strip() == '':
# End of headers, it body data next.
handler = bodyD
continue
handler(field)
# Stich the body data together:
# print "1. body: ", body
body = "".join(body)
returned['body'] = body.replace('\x00', '')
# print "2. body: <%s>" % returned['body']
return returned
|
[
"def",
"unpack_frame",
"(",
"message",
")",
":",
"body",
"=",
"[",
"]",
"returned",
"=",
"dict",
"(",
"cmd",
"=",
"''",
",",
"headers",
"=",
"{",
"}",
",",
"body",
"=",
"''",
")",
"breakdown",
"=",
"message",
".",
"split",
"(",
"'\\n'",
")",
"# Get the message command:",
"returned",
"[",
"'cmd'",
"]",
"=",
"breakdown",
"[",
"0",
"]",
"breakdown",
"=",
"breakdown",
"[",
"1",
":",
"]",
"def",
"headD",
"(",
"field",
")",
":",
"# find the first ':' everything to the left of this is a",
"# header, everything to the right is data:",
"index",
"=",
"field",
".",
"find",
"(",
"':'",
")",
"if",
"index",
":",
"header",
"=",
"field",
"[",
":",
"index",
"]",
".",
"strip",
"(",
")",
"data",
"=",
"field",
"[",
"index",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"# print \"header '%s' data '%s'\" % (header, data)",
"returned",
"[",
"'headers'",
"]",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"data",
".",
"strip",
"(",
")",
"def",
"bodyD",
"(",
"field",
")",
":",
"field",
"=",
"field",
".",
"strip",
"(",
")",
"if",
"field",
":",
"body",
".",
"append",
"(",
"field",
")",
"# Recover the header fields and body data",
"handler",
"=",
"headD",
"for",
"field",
"in",
"breakdown",
":",
"# print \"field:\", field",
"if",
"field",
".",
"strip",
"(",
")",
"==",
"''",
":",
"# End of headers, it body data next.",
"handler",
"=",
"bodyD",
"continue",
"handler",
"(",
"field",
")",
"# Stich the body data together:",
"# print \"1. body: \", body",
"body",
"=",
"\"\"",
".",
"join",
"(",
"body",
")",
"returned",
"[",
"'body'",
"]",
"=",
"body",
".",
"replace",
"(",
"'\\x00'",
",",
"''",
")",
"# print \"2. body: <%s>\" % returned['body']",
"return",
"returned"
] |
Called to unpack a STOMP message into a dictionary.
returned = {
# STOMP Command:
'cmd' : '...',
# Headers e.g.
'headers' : {
'destination' : 'xyz',
'message-id' : 'some event',
:
etc,
}
# Body:
'body' : '...1234...\x00',
}
|
[
"Called",
"to",
"unpack",
"a",
"STOMP",
"message",
"into",
"a",
"dictionary",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L174-L236
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
ack
|
def ack(messageid, transactionid=None):
"""STOMP acknowledge command.
Acknowledge receipt of a specific message from the server.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
"""
header = 'message-id: %s' % messageid
if transactionid:
header = 'message-id: %s\ntransaction: %s' % (messageid, transactionid)
return "ACK\n%s\n\n\x00\n" % header
|
python
|
def ack(messageid, transactionid=None):
"""STOMP acknowledge command.
Acknowledge receipt of a specific message from the server.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
"""
header = 'message-id: %s' % messageid
if transactionid:
header = 'message-id: %s\ntransaction: %s' % (messageid, transactionid)
return "ACK\n%s\n\n\x00\n" % header
|
[
"def",
"ack",
"(",
"messageid",
",",
"transactionid",
"=",
"None",
")",
":",
"header",
"=",
"'message-id: %s'",
"%",
"messageid",
"if",
"transactionid",
":",
"header",
"=",
"'message-id: %s\\ntransaction: %s'",
"%",
"(",
"messageid",
",",
"transactionid",
")",
"return",
"\"ACK\\n%s\\n\\n\\x00\\n\"",
"%",
"header"
] |
STOMP acknowledge command.
Acknowledge receipt of a specific message from the server.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
|
[
"STOMP",
"acknowledge",
"command",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L251-L271
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
send
|
def send(dest, msg, transactionid=None):
"""STOMP send command.
dest:
This is the channel we wish to subscribe to
msg:
This is the message body to be sent.
transactionid:
This is an optional field and is not needed
by default.
"""
transheader = ''
if transactionid:
transheader = 'transaction: %s\n' % transactionid
return "SEND\ndestination: %s\n%s\n%s\x00\n" % (dest, transheader, msg)
|
python
|
def send(dest, msg, transactionid=None):
"""STOMP send command.
dest:
This is the channel we wish to subscribe to
msg:
This is the message body to be sent.
transactionid:
This is an optional field and is not needed
by default.
"""
transheader = ''
if transactionid:
transheader = 'transaction: %s\n' % transactionid
return "SEND\ndestination: %s\n%s\n%s\x00\n" % (dest, transheader, msg)
|
[
"def",
"send",
"(",
"dest",
",",
"msg",
",",
"transactionid",
"=",
"None",
")",
":",
"transheader",
"=",
"''",
"if",
"transactionid",
":",
"transheader",
"=",
"'transaction: %s\\n'",
"%",
"transactionid",
"return",
"\"SEND\\ndestination: %s\\n%s\\n%s\\x00\\n\"",
"%",
"(",
"dest",
",",
"transheader",
",",
"msg",
")"
] |
STOMP send command.
dest:
This is the channel we wish to subscribe to
msg:
This is the message body to be sent.
transactionid:
This is an optional field and is not needed
by default.
|
[
"STOMP",
"send",
"command",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L329-L348
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Frame.setCmd
|
def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (
cmd, VALID_COMMANDS, STOMP_VERSION)
)
else:
self._cmd = cmd
|
python
|
def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (
cmd, VALID_COMMANDS, STOMP_VERSION)
)
else:
self._cmd = cmd
|
[
"def",
"setCmd",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"cmd",
".",
"upper",
"(",
")",
"if",
"cmd",
"not",
"in",
"VALID_COMMANDS",
":",
"raise",
"FrameError",
"(",
"\"The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s).\"",
"%",
"(",
"cmd",
",",
"VALID_COMMANDS",
",",
"STOMP_VERSION",
")",
")",
"else",
":",
"self",
".",
"_cmd",
"=",
"cmd"
] |
Check the cmd is valid, FrameError will be raised if its not.
|
[
"Check",
"the",
"cmd",
"is",
"valid",
"FrameError",
"will",
"be",
"raised",
"if",
"its",
"not",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L119-L127
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Frame.pack
|
def pack(self):
"""Called to create a STOMP message from the internal values.
"""
headers = ''.join(
['%s:%s\n' % (f, v) for f, v in sorted(self.headers.items())]
)
stomp_message = "%s\n%s\n%s%s\n" % (self._cmd, headers, self.body, NULL)
# import pprint
# print "stomp_message: ", pprint.pprint(stomp_message)
return stomp_message
|
python
|
def pack(self):
"""Called to create a STOMP message from the internal values.
"""
headers = ''.join(
['%s:%s\n' % (f, v) for f, v in sorted(self.headers.items())]
)
stomp_message = "%s\n%s\n%s%s\n" % (self._cmd, headers, self.body, NULL)
# import pprint
# print "stomp_message: ", pprint.pprint(stomp_message)
return stomp_message
|
[
"def",
"pack",
"(",
"self",
")",
":",
"headers",
"=",
"''",
".",
"join",
"(",
"[",
"'%s:%s\\n'",
"%",
"(",
"f",
",",
"v",
")",
"for",
"f",
",",
"v",
"in",
"sorted",
"(",
"self",
".",
"headers",
".",
"items",
"(",
")",
")",
"]",
")",
"stomp_message",
"=",
"\"%s\\n%s\\n%s%s\\n\"",
"%",
"(",
"self",
".",
"_cmd",
",",
"headers",
",",
"self",
".",
"body",
",",
"NULL",
")",
"# import pprint",
"# print \"stomp_message: \", pprint.pprint(stomp_message)",
"return",
"stomp_message"
] |
Called to create a STOMP message from the internal values.
|
[
"Called",
"to",
"create",
"a",
"STOMP",
"message",
"from",
"the",
"internal",
"values",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L131-L142
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Frame.unpack
|
def unpack(self, message):
"""Called to extract a STOMP message into this instance.
message:
This is a text string representing a valid
STOMP (v1.0) message.
This method uses unpack_frame(...) to extract the
information, before it is assigned internally.
retuned:
The result of the unpack_frame(...) call.
"""
if not message:
raise FrameError("Unpack error! The given message isn't valid '%s'!" % message)
msg = unpack_frame(message)
self.cmd = msg['cmd']
self.headers = msg['headers']
# Assign directly as the message will have the null
# character in the message already.
self.body = msg['body']
return msg
|
python
|
def unpack(self, message):
"""Called to extract a STOMP message into this instance.
message:
This is a text string representing a valid
STOMP (v1.0) message.
This method uses unpack_frame(...) to extract the
information, before it is assigned internally.
retuned:
The result of the unpack_frame(...) call.
"""
if not message:
raise FrameError("Unpack error! The given message isn't valid '%s'!" % message)
msg = unpack_frame(message)
self.cmd = msg['cmd']
self.headers = msg['headers']
# Assign directly as the message will have the null
# character in the message already.
self.body = msg['body']
return msg
|
[
"def",
"unpack",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"message",
":",
"raise",
"FrameError",
"(",
"\"Unpack error! The given message isn't valid '%s'!\"",
"%",
"message",
")",
"msg",
"=",
"unpack_frame",
"(",
"message",
")",
"self",
".",
"cmd",
"=",
"msg",
"[",
"'cmd'",
"]",
"self",
".",
"headers",
"=",
"msg",
"[",
"'headers'",
"]",
"# Assign directly as the message will have the null",
"# character in the message already.",
"self",
".",
"body",
"=",
"msg",
"[",
"'body'",
"]",
"return",
"msg"
] |
Called to extract a STOMP message into this instance.
message:
This is a text string representing a valid
STOMP (v1.0) message.
This method uses unpack_frame(...) to extract the
information, before it is assigned internally.
retuned:
The result of the unpack_frame(...) call.
|
[
"Called",
"to",
"extract",
"a",
"STOMP",
"message",
"into",
"this",
"instance",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L145-L171
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Engine.react
|
def react(self, msg):
"""Called to provide a response to a message if needed.
msg:
This is a dictionary as returned by unpack_frame(...)
or it can be a straight STOMP message. This function
will attempt to determine which an deal with it.
returned:
A message to return or an empty string.
"""
returned = ""
# If its not a string assume its a dict.
mtype = type(msg)
if mtype in stringTypes:
msg = unpack_frame(msg)
elif mtype == dict:
pass
else:
raise FrameError("Unknown message type '%s', I don't know what to do with this!" % mtype)
if msg['cmd'] in self.states:
# print("reacting to message - %s" % msg['cmd'])
returned = self.states[msg['cmd']](msg)
return returned
|
python
|
def react(self, msg):
"""Called to provide a response to a message if needed.
msg:
This is a dictionary as returned by unpack_frame(...)
or it can be a straight STOMP message. This function
will attempt to determine which an deal with it.
returned:
A message to return or an empty string.
"""
returned = ""
# If its not a string assume its a dict.
mtype = type(msg)
if mtype in stringTypes:
msg = unpack_frame(msg)
elif mtype == dict:
pass
else:
raise FrameError("Unknown message type '%s', I don't know what to do with this!" % mtype)
if msg['cmd'] in self.states:
# print("reacting to message - %s" % msg['cmd'])
returned = self.states[msg['cmd']](msg)
return returned
|
[
"def",
"react",
"(",
"self",
",",
"msg",
")",
":",
"returned",
"=",
"\"\"",
"# If its not a string assume its a dict.",
"mtype",
"=",
"type",
"(",
"msg",
")",
"if",
"mtype",
"in",
"stringTypes",
":",
"msg",
"=",
"unpack_frame",
"(",
"msg",
")",
"elif",
"mtype",
"==",
"dict",
":",
"pass",
"else",
":",
"raise",
"FrameError",
"(",
"\"Unknown message type '%s', I don't know what to do with this!\"",
"%",
"mtype",
")",
"if",
"msg",
"[",
"'cmd'",
"]",
"in",
"self",
".",
"states",
":",
"# print(\"reacting to message - %s\" % msg['cmd'])",
"returned",
"=",
"self",
".",
"states",
"[",
"msg",
"[",
"'cmd'",
"]",
"]",
"(",
"msg",
")",
"return",
"returned"
] |
Called to provide a response to a message if needed.
msg:
This is a dictionary as returned by unpack_frame(...)
or it can be a straight STOMP message. This function
will attempt to determine which an deal with it.
returned:
A message to return or an empty string.
|
[
"Called",
"to",
"provide",
"a",
"response",
"to",
"a",
"message",
"if",
"needed",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L403-L430
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Engine.error
|
def error(self, msg):
"""Called to handle an error message received from the server.
This method just logs the error message
returned:
NO_RESPONSE_NEEDED
"""
body = msg['body'].replace(NULL, '')
brief_msg = ""
if 'message' in msg['headers']:
brief_msg = msg['headers']['message']
self.log.error("Received server error - message%s\n\n%s" % (brief_msg, body))
returned = NO_RESPONSE_NEEDED
if self.testing:
returned = 'error'
return returned
|
python
|
def error(self, msg):
"""Called to handle an error message received from the server.
This method just logs the error message
returned:
NO_RESPONSE_NEEDED
"""
body = msg['body'].replace(NULL, '')
brief_msg = ""
if 'message' in msg['headers']:
brief_msg = msg['headers']['message']
self.log.error("Received server error - message%s\n\n%s" % (brief_msg, body))
returned = NO_RESPONSE_NEEDED
if self.testing:
returned = 'error'
return returned
|
[
"def",
"error",
"(",
"self",
",",
"msg",
")",
":",
"body",
"=",
"msg",
"[",
"'body'",
"]",
".",
"replace",
"(",
"NULL",
",",
"''",
")",
"brief_msg",
"=",
"\"\"",
"if",
"'message'",
"in",
"msg",
"[",
"'headers'",
"]",
":",
"brief_msg",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'message'",
"]",
"self",
".",
"log",
".",
"error",
"(",
"\"Received server error - message%s\\n\\n%s\"",
"%",
"(",
"brief_msg",
",",
"body",
")",
")",
"returned",
"=",
"NO_RESPONSE_NEEDED",
"if",
"self",
".",
"testing",
":",
"returned",
"=",
"'error'",
"return",
"returned"
] |
Called to handle an error message received from the server.
This method just logs the error message
returned:
NO_RESPONSE_NEEDED
|
[
"Called",
"to",
"handle",
"an",
"error",
"message",
"received",
"from",
"the",
"server",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L469-L490
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_10.py
|
Engine.receipt
|
def receipt(self, msg):
"""Called to handle a receipt message received from the server.
This method just logs the receipt message
returned:
NO_RESPONSE_NEEDED
"""
body = msg['body'].replace(NULL, '')
brief_msg = ""
if 'receipt-id' in msg['headers']:
brief_msg = msg['headers']['receipt-id']
self.log.info("Received server receipt message - receipt-id:%s\n\n%s" % (brief_msg, body))
returned = NO_RESPONSE_NEEDED
if self.testing:
returned = 'receipt'
return returned
|
python
|
def receipt(self, msg):
"""Called to handle a receipt message received from the server.
This method just logs the receipt message
returned:
NO_RESPONSE_NEEDED
"""
body = msg['body'].replace(NULL, '')
brief_msg = ""
if 'receipt-id' in msg['headers']:
brief_msg = msg['headers']['receipt-id']
self.log.info("Received server receipt message - receipt-id:%s\n\n%s" % (brief_msg, body))
returned = NO_RESPONSE_NEEDED
if self.testing:
returned = 'receipt'
return returned
|
[
"def",
"receipt",
"(",
"self",
",",
"msg",
")",
":",
"body",
"=",
"msg",
"[",
"'body'",
"]",
".",
"replace",
"(",
"NULL",
",",
"''",
")",
"brief_msg",
"=",
"\"\"",
"if",
"'receipt-id'",
"in",
"msg",
"[",
"'headers'",
"]",
":",
"brief_msg",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'receipt-id'",
"]",
"self",
".",
"log",
".",
"info",
"(",
"\"Received server receipt message - receipt-id:%s\\n\\n%s\"",
"%",
"(",
"brief_msg",
",",
"body",
")",
")",
"returned",
"=",
"NO_RESPONSE_NEEDED",
"if",
"self",
".",
"testing",
":",
"returned",
"=",
"'receipt'",
"return",
"returned"
] |
Called to handle a receipt message received from the server.
This method just logs the receipt message
returned:
NO_RESPONSE_NEEDED
|
[
"Called",
"to",
"handle",
"a",
"receipt",
"message",
"received",
"from",
"the",
"server",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_10.py#L493-L514
|
train
|
oisinmulvihill/stomper
|
lib/stomper/utils.py
|
log_init
|
def log_init(level):
"""Set up a logger that catches all channels and logs it to stdout.
This is used to set up logging when testing.
"""
log = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
log.addHandler(hdlr)
log.setLevel(level)
|
python
|
def log_init(level):
"""Set up a logger that catches all channels and logs it to stdout.
This is used to set up logging when testing.
"""
log = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
log.addHandler(hdlr)
log.setLevel(level)
|
[
"def",
"log_init",
"(",
"level",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
")",
"hdlr",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(name)s %(levelname)s %(message)s'",
")",
"hdlr",
".",
"setFormatter",
"(",
"formatter",
")",
"log",
".",
"addHandler",
"(",
"hdlr",
")",
"log",
".",
"setLevel",
"(",
"level",
")"
] |
Set up a logger that catches all channels and logs it to stdout.
This is used to set up logging when testing.
|
[
"Set",
"up",
"a",
"logger",
"that",
"catches",
"all",
"channels",
"and",
"logs",
"it",
"to",
"stdout",
".",
"This",
"is",
"used",
"to",
"set",
"up",
"logging",
"when",
"testing",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/utils.py#L11-L22
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stomper_usage.py
|
Pong.ack
|
def ack(self, msg):
"""Override this and do some customer message handler.
"""
print("Got a message:\n%s\n" % msg['body'])
# do something with the message...
# Generate the ack or not if you subscribed with ack='auto'
return super(Pong, self).ack(msg)
|
python
|
def ack(self, msg):
"""Override this and do some customer message handler.
"""
print("Got a message:\n%s\n" % msg['body'])
# do something with the message...
# Generate the ack or not if you subscribed with ack='auto'
return super(Pong, self).ack(msg)
|
[
"def",
"ack",
"(",
"self",
",",
"msg",
")",
":",
"print",
"(",
"\"Got a message:\\n%s\\n\"",
"%",
"msg",
"[",
"'body'",
"]",
")",
"# do something with the message...",
"# Generate the ack or not if you subscribed with ack='auto'",
"return",
"super",
"(",
"Pong",
",",
"self",
")",
".",
"ack",
"(",
"msg",
")"
] |
Override this and do some customer message handler.
|
[
"Override",
"this",
"and",
"do",
"some",
"customer",
"message",
"handler",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stomper_usage.py#L87-L95
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
transaction_atomic_with_retry
|
def transaction_atomic_with_retry(num_retries=5, backoff=0.1):
"""
This is a decorator that will wrap the decorated method in an atomic transaction and
retry the transaction a given number of times
:param num_retries: How many times should we retry before we give up
:param backoff: How long should we wait after each try
"""
# Create the decorator
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
# Keep track of how many times we have tried
num_tries = 0
exception = None
# Call the main sync entities method and catch any exceptions
while num_tries <= num_retries:
# Try running the transaction
try:
with transaction.atomic():
return wrapped(*args, **kwargs)
# Catch any operation errors
except db.utils.OperationalError as e:
num_tries += 1
exception = e
sleep(backoff * num_tries)
# If we have an exception raise it
raise exception
# Return the decorator
return wrapper
|
python
|
def transaction_atomic_with_retry(num_retries=5, backoff=0.1):
"""
This is a decorator that will wrap the decorated method in an atomic transaction and
retry the transaction a given number of times
:param num_retries: How many times should we retry before we give up
:param backoff: How long should we wait after each try
"""
# Create the decorator
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
# Keep track of how many times we have tried
num_tries = 0
exception = None
# Call the main sync entities method and catch any exceptions
while num_tries <= num_retries:
# Try running the transaction
try:
with transaction.atomic():
return wrapped(*args, **kwargs)
# Catch any operation errors
except db.utils.OperationalError as e:
num_tries += 1
exception = e
sleep(backoff * num_tries)
# If we have an exception raise it
raise exception
# Return the decorator
return wrapper
|
[
"def",
"transaction_atomic_with_retry",
"(",
"num_retries",
"=",
"5",
",",
"backoff",
"=",
"0.1",
")",
":",
"# Create the decorator",
"@",
"wrapt",
".",
"decorator",
"def",
"wrapper",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"# Keep track of how many times we have tried",
"num_tries",
"=",
"0",
"exception",
"=",
"None",
"# Call the main sync entities method and catch any exceptions",
"while",
"num_tries",
"<=",
"num_retries",
":",
"# Try running the transaction",
"try",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Catch any operation errors",
"except",
"db",
".",
"utils",
".",
"OperationalError",
"as",
"e",
":",
"num_tries",
"+=",
"1",
"exception",
"=",
"e",
"sleep",
"(",
"backoff",
"*",
"num_tries",
")",
"# If we have an exception raise it",
"raise",
"exception",
"# Return the decorator",
"return",
"wrapper"
] |
This is a decorator that will wrap the decorated method in an atomic transaction and
retry the transaction a given number of times
:param num_retries: How many times should we retry before we give up
:param backoff: How long should we wait after each try
|
[
"This",
"is",
"a",
"decorator",
"that",
"will",
"wrap",
"the",
"decorated",
"method",
"in",
"an",
"atomic",
"transaction",
"and",
"retry",
"the",
"transaction",
"a",
"given",
"number",
"of",
"times"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L23-L55
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
defer_entity_syncing
|
def defer_entity_syncing(wrapped, instance, args, kwargs):
"""
A decorator that can be used to defer the syncing of entities until after the method has been run
This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand
why they are happening
"""
# Defer entity syncing while we run our method
sync_entities.defer = True
# Run the method
try:
return wrapped(*args, **kwargs)
# After we run the method disable the deferred syncing
# and sync all the entities that have been buffered to be synced
finally:
# Enable entity syncing again
sync_entities.defer = False
# Get the models that need to be synced
model_objs = list(sync_entities.buffer.values())
# If none is in the model objects we need to sync all
if None in sync_entities.buffer:
model_objs = list()
# Sync the entities that were deferred if any
if len(sync_entities.buffer):
sync_entities(*model_objs)
# Clear the buffer
sync_entities.buffer = {}
|
python
|
def defer_entity_syncing(wrapped, instance, args, kwargs):
"""
A decorator that can be used to defer the syncing of entities until after the method has been run
This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand
why they are happening
"""
# Defer entity syncing while we run our method
sync_entities.defer = True
# Run the method
try:
return wrapped(*args, **kwargs)
# After we run the method disable the deferred syncing
# and sync all the entities that have been buffered to be synced
finally:
# Enable entity syncing again
sync_entities.defer = False
# Get the models that need to be synced
model_objs = list(sync_entities.buffer.values())
# If none is in the model objects we need to sync all
if None in sync_entities.buffer:
model_objs = list()
# Sync the entities that were deferred if any
if len(sync_entities.buffer):
sync_entities(*model_objs)
# Clear the buffer
sync_entities.buffer = {}
|
[
"def",
"defer_entity_syncing",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"# Defer entity syncing while we run our method",
"sync_entities",
".",
"defer",
"=",
"True",
"# Run the method",
"try",
":",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# After we run the method disable the deferred syncing",
"# and sync all the entities that have been buffered to be synced",
"finally",
":",
"# Enable entity syncing again",
"sync_entities",
".",
"defer",
"=",
"False",
"# Get the models that need to be synced",
"model_objs",
"=",
"list",
"(",
"sync_entities",
".",
"buffer",
".",
"values",
"(",
")",
")",
"# If none is in the model objects we need to sync all",
"if",
"None",
"in",
"sync_entities",
".",
"buffer",
":",
"model_objs",
"=",
"list",
"(",
")",
"# Sync the entities that were deferred if any",
"if",
"len",
"(",
"sync_entities",
".",
"buffer",
")",
":",
"sync_entities",
"(",
"*",
"model_objs",
")",
"# Clear the buffer",
"sync_entities",
".",
"buffer",
"=",
"{",
"}"
] |
A decorator that can be used to defer the syncing of entities until after the method has been run
This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand
why they are happening
|
[
"A",
"decorator",
"that",
"can",
"be",
"used",
"to",
"defer",
"the",
"syncing",
"of",
"entities",
"until",
"after",
"the",
"method",
"has",
"been",
"run",
"This",
"is",
"being",
"introduced",
"to",
"help",
"avoid",
"deadlocks",
"in",
"the",
"meantime",
"as",
"we",
"attempt",
"to",
"better",
"understand",
"why",
"they",
"are",
"happening"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L59-L91
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
_get_super_entities_by_ctype
|
def _get_super_entities_by_ctype(model_objs_by_ctype, model_ids_to_sync, sync_all):
"""
Given model objects organized by content type and a dictionary of all model IDs that need
to be synced, organize all super entity relationships that need to be synced.
Ensure that the model_ids_to_sync dict is updated with any new super entities
that need to be part of the overall entity sync
"""
super_entities_by_ctype = defaultdict(lambda: defaultdict(list)) # pragma: no cover
for ctype, model_objs_for_ctype in model_objs_by_ctype.items():
entity_config = entity_registry.entity_registry.get(ctype.model_class())
super_entities = entity_config.get_super_entities(model_objs_for_ctype, sync_all)
super_entities_by_ctype[ctype] = {
ContentType.objects.get_for_model(model_class, for_concrete_model=False): relationships
for model_class, relationships in super_entities.items()
}
# Continue adding to the set of entities that need to be synced
for super_entity_ctype, relationships in super_entities_by_ctype[ctype].items():
for sub_entity_id, super_entity_id in relationships:
model_ids_to_sync[ctype].add(sub_entity_id)
model_ids_to_sync[super_entity_ctype].add(super_entity_id)
return super_entities_by_ctype
|
python
|
def _get_super_entities_by_ctype(model_objs_by_ctype, model_ids_to_sync, sync_all):
"""
Given model objects organized by content type and a dictionary of all model IDs that need
to be synced, organize all super entity relationships that need to be synced.
Ensure that the model_ids_to_sync dict is updated with any new super entities
that need to be part of the overall entity sync
"""
super_entities_by_ctype = defaultdict(lambda: defaultdict(list)) # pragma: no cover
for ctype, model_objs_for_ctype in model_objs_by_ctype.items():
entity_config = entity_registry.entity_registry.get(ctype.model_class())
super_entities = entity_config.get_super_entities(model_objs_for_ctype, sync_all)
super_entities_by_ctype[ctype] = {
ContentType.objects.get_for_model(model_class, for_concrete_model=False): relationships
for model_class, relationships in super_entities.items()
}
# Continue adding to the set of entities that need to be synced
for super_entity_ctype, relationships in super_entities_by_ctype[ctype].items():
for sub_entity_id, super_entity_id in relationships:
model_ids_to_sync[ctype].add(sub_entity_id)
model_ids_to_sync[super_entity_ctype].add(super_entity_id)
return super_entities_by_ctype
|
[
"def",
"_get_super_entities_by_ctype",
"(",
"model_objs_by_ctype",
",",
"model_ids_to_sync",
",",
"sync_all",
")",
":",
"super_entities_by_ctype",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"list",
")",
")",
"# pragma: no cover",
"for",
"ctype",
",",
"model_objs_for_ctype",
"in",
"model_objs_by_ctype",
".",
"items",
"(",
")",
":",
"entity_config",
"=",
"entity_registry",
".",
"entity_registry",
".",
"get",
"(",
"ctype",
".",
"model_class",
"(",
")",
")",
"super_entities",
"=",
"entity_config",
".",
"get_super_entities",
"(",
"model_objs_for_ctype",
",",
"sync_all",
")",
"super_entities_by_ctype",
"[",
"ctype",
"]",
"=",
"{",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model_class",
",",
"for_concrete_model",
"=",
"False",
")",
":",
"relationships",
"for",
"model_class",
",",
"relationships",
"in",
"super_entities",
".",
"items",
"(",
")",
"}",
"# Continue adding to the set of entities that need to be synced",
"for",
"super_entity_ctype",
",",
"relationships",
"in",
"super_entities_by_ctype",
"[",
"ctype",
"]",
".",
"items",
"(",
")",
":",
"for",
"sub_entity_id",
",",
"super_entity_id",
"in",
"relationships",
":",
"model_ids_to_sync",
"[",
"ctype",
"]",
".",
"add",
"(",
"sub_entity_id",
")",
"model_ids_to_sync",
"[",
"super_entity_ctype",
"]",
".",
"add",
"(",
"super_entity_id",
")",
"return",
"super_entities_by_ctype"
] |
Given model objects organized by content type and a dictionary of all model IDs that need
to be synced, organize all super entity relationships that need to be synced.
Ensure that the model_ids_to_sync dict is updated with any new super entities
that need to be part of the overall entity sync
|
[
"Given",
"model",
"objects",
"organized",
"by",
"content",
"type",
"and",
"a",
"dictionary",
"of",
"all",
"model",
"IDs",
"that",
"need",
"to",
"be",
"synced",
"organize",
"all",
"super",
"entity",
"relationships",
"that",
"need",
"to",
"be",
"synced",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L94-L117
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
_get_model_objs_to_sync
|
def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all):
"""
Given the model IDs to sync, fetch all model objects to sync
"""
model_objs_to_sync = {}
for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items():
model_qset = entity_registry.entity_registry.get(ctype.model_class()).queryset
if not sync_all:
model_objs_to_sync[ctype] = model_qset.filter(id__in=model_ids_to_sync_for_ctype)
else:
model_objs_to_sync[ctype] = [
model_objs_map[ctype, model_id] for model_id in model_ids_to_sync_for_ctype
]
return model_objs_to_sync
|
python
|
def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all):
"""
Given the model IDs to sync, fetch all model objects to sync
"""
model_objs_to_sync = {}
for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items():
model_qset = entity_registry.entity_registry.get(ctype.model_class()).queryset
if not sync_all:
model_objs_to_sync[ctype] = model_qset.filter(id__in=model_ids_to_sync_for_ctype)
else:
model_objs_to_sync[ctype] = [
model_objs_map[ctype, model_id] for model_id in model_ids_to_sync_for_ctype
]
return model_objs_to_sync
|
[
"def",
"_get_model_objs_to_sync",
"(",
"model_ids_to_sync",
",",
"model_objs_map",
",",
"sync_all",
")",
":",
"model_objs_to_sync",
"=",
"{",
"}",
"for",
"ctype",
",",
"model_ids_to_sync_for_ctype",
"in",
"model_ids_to_sync",
".",
"items",
"(",
")",
":",
"model_qset",
"=",
"entity_registry",
".",
"entity_registry",
".",
"get",
"(",
"ctype",
".",
"model_class",
"(",
")",
")",
".",
"queryset",
"if",
"not",
"sync_all",
":",
"model_objs_to_sync",
"[",
"ctype",
"]",
"=",
"model_qset",
".",
"filter",
"(",
"id__in",
"=",
"model_ids_to_sync_for_ctype",
")",
"else",
":",
"model_objs_to_sync",
"[",
"ctype",
"]",
"=",
"[",
"model_objs_map",
"[",
"ctype",
",",
"model_id",
"]",
"for",
"model_id",
"in",
"model_ids_to_sync_for_ctype",
"]",
"return",
"model_objs_to_sync"
] |
Given the model IDs to sync, fetch all model objects to sync
|
[
"Given",
"the",
"model",
"IDs",
"to",
"sync",
"fetch",
"all",
"model",
"objects",
"to",
"sync"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L120-L135
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
sync_entities
|
def sync_entities(*model_objs):
"""
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
"""
# Check if we are deferring processing
if sync_entities.defer:
# If we dont have any model objects passed add a none to let us know that we need to sync all
if not model_objs:
sync_entities.buffer[None] = None
else:
# Add each model obj to the buffer
for model_obj in model_objs:
sync_entities.buffer[(model_obj.__class__, model_obj.pk)] = model_obj
# Return false that we did not do anything
return False
# Create a syncer and sync
EntitySyncer(*model_objs).sync()
|
python
|
def sync_entities(*model_objs):
"""
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
"""
# Check if we are deferring processing
if sync_entities.defer:
# If we dont have any model objects passed add a none to let us know that we need to sync all
if not model_objs:
sync_entities.buffer[None] = None
else:
# Add each model obj to the buffer
for model_obj in model_objs:
sync_entities.buffer[(model_obj.__class__, model_obj.pk)] = model_obj
# Return false that we did not do anything
return False
# Create a syncer and sync
EntitySyncer(*model_objs).sync()
|
[
"def",
"sync_entities",
"(",
"*",
"model_objs",
")",
":",
"# Check if we are deferring processing",
"if",
"sync_entities",
".",
"defer",
":",
"# If we dont have any model objects passed add a none to let us know that we need to sync all",
"if",
"not",
"model_objs",
":",
"sync_entities",
".",
"buffer",
"[",
"None",
"]",
"=",
"None",
"else",
":",
"# Add each model obj to the buffer",
"for",
"model_obj",
"in",
"model_objs",
":",
"sync_entities",
".",
"buffer",
"[",
"(",
"model_obj",
".",
"__class__",
",",
"model_obj",
".",
"pk",
")",
"]",
"=",
"model_obj",
"# Return false that we did not do anything",
"return",
"False",
"# Create a syncer and sync",
"EntitySyncer",
"(",
"*",
"model_objs",
")",
".",
"sync",
"(",
")"
] |
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
|
[
"Syncs",
"entities"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L138-L160
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
sync_entities_watching
|
def sync_entities_watching(instance):
"""
Syncs entities watching changes of a model instance.
"""
for entity_model, entity_model_getter in entity_registry.entity_watching[instance.__class__]:
model_objs = list(entity_model_getter(instance))
if model_objs:
sync_entities(*model_objs)
|
python
|
def sync_entities_watching(instance):
"""
Syncs entities watching changes of a model instance.
"""
for entity_model, entity_model_getter in entity_registry.entity_watching[instance.__class__]:
model_objs = list(entity_model_getter(instance))
if model_objs:
sync_entities(*model_objs)
|
[
"def",
"sync_entities_watching",
"(",
"instance",
")",
":",
"for",
"entity_model",
",",
"entity_model_getter",
"in",
"entity_registry",
".",
"entity_watching",
"[",
"instance",
".",
"__class__",
"]",
":",
"model_objs",
"=",
"list",
"(",
"entity_model_getter",
"(",
"instance",
")",
")",
"if",
"model_objs",
":",
"sync_entities",
"(",
"*",
"model_objs",
")"
] |
Syncs entities watching changes of a model instance.
|
[
"Syncs",
"entities",
"watching",
"changes",
"of",
"a",
"model",
"instance",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L169-L176
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
EntitySyncer.upsert_entity_kinds
|
def upsert_entity_kinds(self, entity_kinds):
"""
Given a list of entity kinds ensure they are synced properly to the database.
This will ensure that only unchanged entity kinds are synced and will still return all
updated entity kinds
:param entity_kinds: The list of entity kinds to sync
"""
# Filter out unchanged entity kinds
unchanged_entity_kinds = {}
if entity_kinds:
unchanged_entity_kinds = {
(entity_kind.name, entity_kind.display_name): entity_kind
for entity_kind in EntityKind.all_objects.extra(
where=['(name, display_name) IN %s'],
params=[tuple(
(entity_kind.name, entity_kind.display_name)
for entity_kind in entity_kinds
)]
)
}
# Filter out the unchanged entity kinds
changed_entity_kinds = [
entity_kind
for entity_kind in entity_kinds
if (entity_kind.name, entity_kind.display_name) not in unchanged_entity_kinds
]
# If any of our kinds have changed upsert them
upserted_enitity_kinds = []
if changed_entity_kinds:
# Select all our existing entity kinds for update so we can do proper locking
# We have to select all here for some odd reason, if we only select the ones
# we are syncing we still run into deadlock issues
list(EntityKind.all_objects.all().select_for_update().values_list('id', flat=True))
# Upsert the entity kinds
upserted_enitity_kinds = manager_utils.bulk_upsert(
queryset=EntityKind.all_objects.filter(
name__in=[entity_kind.name for entity_kind in changed_entity_kinds]
),
model_objs=changed_entity_kinds,
unique_fields=['name'],
update_fields=['display_name'],
return_upserts=True
)
# Return all the entity kinds
return upserted_enitity_kinds + list(unchanged_entity_kinds.values())
|
python
|
def upsert_entity_kinds(self, entity_kinds):
"""
Given a list of entity kinds ensure they are synced properly to the database.
This will ensure that only unchanged entity kinds are synced and will still return all
updated entity kinds
:param entity_kinds: The list of entity kinds to sync
"""
# Filter out unchanged entity kinds
unchanged_entity_kinds = {}
if entity_kinds:
unchanged_entity_kinds = {
(entity_kind.name, entity_kind.display_name): entity_kind
for entity_kind in EntityKind.all_objects.extra(
where=['(name, display_name) IN %s'],
params=[tuple(
(entity_kind.name, entity_kind.display_name)
for entity_kind in entity_kinds
)]
)
}
# Filter out the unchanged entity kinds
changed_entity_kinds = [
entity_kind
for entity_kind in entity_kinds
if (entity_kind.name, entity_kind.display_name) not in unchanged_entity_kinds
]
# If any of our kinds have changed upsert them
upserted_enitity_kinds = []
if changed_entity_kinds:
# Select all our existing entity kinds for update so we can do proper locking
# We have to select all here for some odd reason, if we only select the ones
# we are syncing we still run into deadlock issues
list(EntityKind.all_objects.all().select_for_update().values_list('id', flat=True))
# Upsert the entity kinds
upserted_enitity_kinds = manager_utils.bulk_upsert(
queryset=EntityKind.all_objects.filter(
name__in=[entity_kind.name for entity_kind in changed_entity_kinds]
),
model_objs=changed_entity_kinds,
unique_fields=['name'],
update_fields=['display_name'],
return_upserts=True
)
# Return all the entity kinds
return upserted_enitity_kinds + list(unchanged_entity_kinds.values())
|
[
"def",
"upsert_entity_kinds",
"(",
"self",
",",
"entity_kinds",
")",
":",
"# Filter out unchanged entity kinds",
"unchanged_entity_kinds",
"=",
"{",
"}",
"if",
"entity_kinds",
":",
"unchanged_entity_kinds",
"=",
"{",
"(",
"entity_kind",
".",
"name",
",",
"entity_kind",
".",
"display_name",
")",
":",
"entity_kind",
"for",
"entity_kind",
"in",
"EntityKind",
".",
"all_objects",
".",
"extra",
"(",
"where",
"=",
"[",
"'(name, display_name) IN %s'",
"]",
",",
"params",
"=",
"[",
"tuple",
"(",
"(",
"entity_kind",
".",
"name",
",",
"entity_kind",
".",
"display_name",
")",
"for",
"entity_kind",
"in",
"entity_kinds",
")",
"]",
")",
"}",
"# Filter out the unchanged entity kinds",
"changed_entity_kinds",
"=",
"[",
"entity_kind",
"for",
"entity_kind",
"in",
"entity_kinds",
"if",
"(",
"entity_kind",
".",
"name",
",",
"entity_kind",
".",
"display_name",
")",
"not",
"in",
"unchanged_entity_kinds",
"]",
"# If any of our kinds have changed upsert them",
"upserted_enitity_kinds",
"=",
"[",
"]",
"if",
"changed_entity_kinds",
":",
"# Select all our existing entity kinds for update so we can do proper locking",
"# We have to select all here for some odd reason, if we only select the ones",
"# we are syncing we still run into deadlock issues",
"list",
"(",
"EntityKind",
".",
"all_objects",
".",
"all",
"(",
")",
".",
"select_for_update",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
")",
"# Upsert the entity kinds",
"upserted_enitity_kinds",
"=",
"manager_utils",
".",
"bulk_upsert",
"(",
"queryset",
"=",
"EntityKind",
".",
"all_objects",
".",
"filter",
"(",
"name__in",
"=",
"[",
"entity_kind",
".",
"name",
"for",
"entity_kind",
"in",
"changed_entity_kinds",
"]",
")",
",",
"model_objs",
"=",
"changed_entity_kinds",
",",
"unique_fields",
"=",
"[",
"'name'",
"]",
",",
"update_fields",
"=",
"[",
"'display_name'",
"]",
",",
"return_upserts",
"=",
"True",
")",
"# Return all the entity kinds",
"return",
"upserted_enitity_kinds",
"+",
"list",
"(",
"unchanged_entity_kinds",
".",
"values",
"(",
")",
")"
] |
Given a list of entity kinds ensure they are synced properly to the database.
This will ensure that only unchanged entity kinds are synced and will still return all
updated entity kinds
:param entity_kinds: The list of entity kinds to sync
|
[
"Given",
"a",
"list",
"of",
"entity",
"kinds",
"ensure",
"they",
"are",
"synced",
"properly",
"to",
"the",
"database",
".",
"This",
"will",
"ensure",
"that",
"only",
"unchanged",
"entity",
"kinds",
"are",
"synced",
"and",
"will",
"still",
"return",
"all",
"updated",
"entity",
"kinds"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L323-L373
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
EntitySyncer.upsert_entities
|
def upsert_entities(self, entities, sync=False):
"""
Upsert a list of entities to the database
:param entities: The entities to sync
:param sync: Do a sync instead of an upsert
"""
# Select the entities we are upserting for update to reduce deadlocks
if entities:
# Default select for update query when syncing all
select_for_update_query = (
'SELECT FROM {table_name} FOR NO KEY UPDATE'
).format(
table_name=Entity._meta.db_table
)
select_for_update_query_params = []
# If we are not syncing all, only select those we are updating
if not sync:
select_for_update_query = (
'SELECT FROM {table_name} WHERE (entity_type_id, entity_id) IN %s FOR NO KEY UPDATE'
).format(
table_name=Entity._meta.db_table
)
select_for_update_query_params = [tuple(
(entity.entity_type_id, entity.entity_id)
for entity in entities
)]
# Select the items for update
with connection.cursor() as cursor:
cursor.execute(select_for_update_query, select_for_update_query_params)
# If we are syncing run the sync logic
if sync:
upserted_entities = manager_utils.sync(
queryset=Entity.all_objects.all(),
model_objs=entities,
unique_fields=['entity_type_id', 'entity_id'],
update_fields=['entity_kind_id', 'entity_meta', 'display_name', 'is_active'],
return_upserts=True
)
# Otherwise we want to upsert our entities
else:
upserted_entities = manager_utils.bulk_upsert(
queryset=Entity.all_objects.extra(
where=['(entity_type_id, entity_id) IN %s'],
params=[tuple(
(entity.entity_type_id, entity.entity_id)
for entity in entities
)]
),
model_objs=entities,
unique_fields=['entity_type_id', 'entity_id'],
update_fields=['entity_kind_id', 'entity_meta', 'display_name', 'is_active'],
return_upserts=True
)
# Return the upserted entities
return upserted_entities
|
python
|
def upsert_entities(self, entities, sync=False):
"""
Upsert a list of entities to the database
:param entities: The entities to sync
:param sync: Do a sync instead of an upsert
"""
# Select the entities we are upserting for update to reduce deadlocks
if entities:
# Default select for update query when syncing all
select_for_update_query = (
'SELECT FROM {table_name} FOR NO KEY UPDATE'
).format(
table_name=Entity._meta.db_table
)
select_for_update_query_params = []
# If we are not syncing all, only select those we are updating
if not sync:
select_for_update_query = (
'SELECT FROM {table_name} WHERE (entity_type_id, entity_id) IN %s FOR NO KEY UPDATE'
).format(
table_name=Entity._meta.db_table
)
select_for_update_query_params = [tuple(
(entity.entity_type_id, entity.entity_id)
for entity in entities
)]
# Select the items for update
with connection.cursor() as cursor:
cursor.execute(select_for_update_query, select_for_update_query_params)
# If we are syncing run the sync logic
if sync:
upserted_entities = manager_utils.sync(
queryset=Entity.all_objects.all(),
model_objs=entities,
unique_fields=['entity_type_id', 'entity_id'],
update_fields=['entity_kind_id', 'entity_meta', 'display_name', 'is_active'],
return_upserts=True
)
# Otherwise we want to upsert our entities
else:
upserted_entities = manager_utils.bulk_upsert(
queryset=Entity.all_objects.extra(
where=['(entity_type_id, entity_id) IN %s'],
params=[tuple(
(entity.entity_type_id, entity.entity_id)
for entity in entities
)]
),
model_objs=entities,
unique_fields=['entity_type_id', 'entity_id'],
update_fields=['entity_kind_id', 'entity_meta', 'display_name', 'is_active'],
return_upserts=True
)
# Return the upserted entities
return upserted_entities
|
[
"def",
"upsert_entities",
"(",
"self",
",",
"entities",
",",
"sync",
"=",
"False",
")",
":",
"# Select the entities we are upserting for update to reduce deadlocks",
"if",
"entities",
":",
"# Default select for update query when syncing all",
"select_for_update_query",
"=",
"(",
"'SELECT FROM {table_name} FOR NO KEY UPDATE'",
")",
".",
"format",
"(",
"table_name",
"=",
"Entity",
".",
"_meta",
".",
"db_table",
")",
"select_for_update_query_params",
"=",
"[",
"]",
"# If we are not syncing all, only select those we are updating",
"if",
"not",
"sync",
":",
"select_for_update_query",
"=",
"(",
"'SELECT FROM {table_name} WHERE (entity_type_id, entity_id) IN %s FOR NO KEY UPDATE'",
")",
".",
"format",
"(",
"table_name",
"=",
"Entity",
".",
"_meta",
".",
"db_table",
")",
"select_for_update_query_params",
"=",
"[",
"tuple",
"(",
"(",
"entity",
".",
"entity_type_id",
",",
"entity",
".",
"entity_id",
")",
"for",
"entity",
"in",
"entities",
")",
"]",
"# Select the items for update",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"select_for_update_query",
",",
"select_for_update_query_params",
")",
"# If we are syncing run the sync logic",
"if",
"sync",
":",
"upserted_entities",
"=",
"manager_utils",
".",
"sync",
"(",
"queryset",
"=",
"Entity",
".",
"all_objects",
".",
"all",
"(",
")",
",",
"model_objs",
"=",
"entities",
",",
"unique_fields",
"=",
"[",
"'entity_type_id'",
",",
"'entity_id'",
"]",
",",
"update_fields",
"=",
"[",
"'entity_kind_id'",
",",
"'entity_meta'",
",",
"'display_name'",
",",
"'is_active'",
"]",
",",
"return_upserts",
"=",
"True",
")",
"# Otherwise we want to upsert our entities",
"else",
":",
"upserted_entities",
"=",
"manager_utils",
".",
"bulk_upsert",
"(",
"queryset",
"=",
"Entity",
".",
"all_objects",
".",
"extra",
"(",
"where",
"=",
"[",
"'(entity_type_id, entity_id) IN %s'",
"]",
",",
"params",
"=",
"[",
"tuple",
"(",
"(",
"entity",
".",
"entity_type_id",
",",
"entity",
".",
"entity_id",
")",
"for",
"entity",
"in",
"entities",
")",
"]",
")",
",",
"model_objs",
"=",
"entities",
",",
"unique_fields",
"=",
"[",
"'entity_type_id'",
",",
"'entity_id'",
"]",
",",
"update_fields",
"=",
"[",
"'entity_kind_id'",
",",
"'entity_meta'",
",",
"'display_name'",
",",
"'is_active'",
"]",
",",
"return_upserts",
"=",
"True",
")",
"# Return the upserted entities",
"return",
"upserted_entities"
] |
Upsert a list of entities to the database
:param entities: The entities to sync
:param sync: Do a sync instead of an upsert
|
[
"Upsert",
"a",
"list",
"of",
"entities",
"to",
"the",
"database",
":",
"param",
"entities",
":",
"The",
"entities",
"to",
"sync",
":",
"param",
"sync",
":",
"Do",
"a",
"sync",
"instead",
"of",
"an",
"upsert"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L376-L435
|
train
|
ambitioninc/django-entity
|
entity/sync.py
|
EntitySyncer.upsert_entity_relationships
|
def upsert_entity_relationships(self, queryset, entity_relationships):
"""
Upsert entity relationships to the database
:param queryset: The base queryset to use
:param entity_relationships: The entity relationships to ensure exist in the database
"""
# Select the relationships for update
if entity_relationships:
list(queryset.select_for_update().values_list(
'id',
flat=True
))
# Sync the relationships
return manager_utils.sync(
queryset=queryset,
model_objs=entity_relationships,
unique_fields=['sub_entity_id', 'super_entity_id'],
update_fields=[],
return_upserts=True
)
|
python
|
def upsert_entity_relationships(self, queryset, entity_relationships):
"""
Upsert entity relationships to the database
:param queryset: The base queryset to use
:param entity_relationships: The entity relationships to ensure exist in the database
"""
# Select the relationships for update
if entity_relationships:
list(queryset.select_for_update().values_list(
'id',
flat=True
))
# Sync the relationships
return manager_utils.sync(
queryset=queryset,
model_objs=entity_relationships,
unique_fields=['sub_entity_id', 'super_entity_id'],
update_fields=[],
return_upserts=True
)
|
[
"def",
"upsert_entity_relationships",
"(",
"self",
",",
"queryset",
",",
"entity_relationships",
")",
":",
"# Select the relationships for update",
"if",
"entity_relationships",
":",
"list",
"(",
"queryset",
".",
"select_for_update",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
")",
"# Sync the relationships",
"return",
"manager_utils",
".",
"sync",
"(",
"queryset",
"=",
"queryset",
",",
"model_objs",
"=",
"entity_relationships",
",",
"unique_fields",
"=",
"[",
"'sub_entity_id'",
",",
"'super_entity_id'",
"]",
",",
"update_fields",
"=",
"[",
"]",
",",
"return_upserts",
"=",
"True",
")"
] |
Upsert entity relationships to the database
:param queryset: The base queryset to use
:param entity_relationships: The entity relationships to ensure exist in the database
|
[
"Upsert",
"entity",
"relationships",
"to",
"the",
"database",
":",
"param",
"queryset",
":",
"The",
"base",
"queryset",
"to",
"use",
":",
"param",
"entity_relationships",
":",
"The",
"entity",
"relationships",
"to",
"ensure",
"exist",
"in",
"the",
"database"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/sync.py#L438-L459
|
train
|
ambitioninc/django-entity
|
entity/config.py
|
EntityConfig.get_entity_kind
|
def get_entity_kind(self, model_obj):
"""
Returns a tuple for a kind name and kind display name of an entity.
By default, uses the app_label and model of the model object's content
type as the kind.
"""
model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model)
return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))
|
python
|
def get_entity_kind(self, model_obj):
"""
Returns a tuple for a kind name and kind display name of an entity.
By default, uses the app_label and model of the model object's content
type as the kind.
"""
model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model)
return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))
|
[
"def",
"get_entity_kind",
"(",
"self",
",",
"model_obj",
")",
":",
"model_obj_ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
".",
"queryset",
".",
"model",
")",
"return",
"(",
"u'{0}.{1}'",
".",
"format",
"(",
"model_obj_ctype",
".",
"app_label",
",",
"model_obj_ctype",
".",
"model",
")",
",",
"u'{0}'",
".",
"format",
"(",
"model_obj_ctype",
")",
")"
] |
Returns a tuple for a kind name and kind display name of an entity.
By default, uses the app_label and model of the model object's content
type as the kind.
|
[
"Returns",
"a",
"tuple",
"for",
"a",
"kind",
"name",
"and",
"kind",
"display",
"name",
"of",
"an",
"entity",
".",
"By",
"default",
"uses",
"the",
"app_label",
"and",
"model",
"of",
"the",
"model",
"object",
"s",
"content",
"type",
"as",
"the",
"kind",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/config.py#L36-L43
|
train
|
ambitioninc/django-entity
|
entity/config.py
|
EntityRegistry.register_entity
|
def register_entity(self, entity_config):
"""
Registers an entity config
"""
if not issubclass(entity_config, EntityConfig):
raise ValueError('Must register entity config class of subclass EntityConfig')
if entity_config.queryset is None:
raise ValueError('Entity config must define queryset')
model = entity_config.queryset.model
self._entity_registry[model] = entity_config()
# Add watchers to the global look up table
for watching_model, entity_model_getter in entity_config.watching:
self._entity_watching[watching_model].append((model, entity_model_getter))
|
python
|
def register_entity(self, entity_config):
"""
Registers an entity config
"""
if not issubclass(entity_config, EntityConfig):
raise ValueError('Must register entity config class of subclass EntityConfig')
if entity_config.queryset is None:
raise ValueError('Entity config must define queryset')
model = entity_config.queryset.model
self._entity_registry[model] = entity_config()
# Add watchers to the global look up table
for watching_model, entity_model_getter in entity_config.watching:
self._entity_watching[watching_model].append((model, entity_model_getter))
|
[
"def",
"register_entity",
"(",
"self",
",",
"entity_config",
")",
":",
"if",
"not",
"issubclass",
"(",
"entity_config",
",",
"EntityConfig",
")",
":",
"raise",
"ValueError",
"(",
"'Must register entity config class of subclass EntityConfig'",
")",
"if",
"entity_config",
".",
"queryset",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Entity config must define queryset'",
")",
"model",
"=",
"entity_config",
".",
"queryset",
".",
"model",
"self",
".",
"_entity_registry",
"[",
"model",
"]",
"=",
"entity_config",
"(",
")",
"# Add watchers to the global look up table",
"for",
"watching_model",
",",
"entity_model_getter",
"in",
"entity_config",
".",
"watching",
":",
"self",
".",
"_entity_watching",
"[",
"watching_model",
"]",
".",
"append",
"(",
"(",
"model",
",",
"entity_model_getter",
")",
")"
] |
Registers an entity config
|
[
"Registers",
"an",
"entity",
"config"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/config.py#L96-L112
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
start
|
def start(host='localhost', port=61613, username='', password=''):
"""Start twisted event loop and the fun should begin...
"""
StompClientFactory.username = username
StompClientFactory.password = password
reactor.connectTCP(host, port, StompClientFactory())
reactor.run()
|
python
|
def start(host='localhost', port=61613, username='', password=''):
"""Start twisted event loop and the fun should begin...
"""
StompClientFactory.username = username
StompClientFactory.password = password
reactor.connectTCP(host, port, StompClientFactory())
reactor.run()
|
[
"def",
"start",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"61613",
",",
"username",
"=",
"''",
",",
"password",
"=",
"''",
")",
":",
"StompClientFactory",
".",
"username",
"=",
"username",
"StompClientFactory",
".",
"password",
"=",
"password",
"reactor",
".",
"connectTCP",
"(",
"host",
",",
"port",
",",
"StompClientFactory",
"(",
")",
")",
"reactor",
".",
"run",
"(",
")"
] |
Start twisted event loop and the fun should begin...
|
[
"Start",
"twisted",
"event",
"loop",
"and",
"the",
"fun",
"should",
"begin",
"..."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L131-L137
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
StompProtocol.connected
|
def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
stomper.Engine.connected(self, msg)
self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session'])
def setup_looping_call():
lc = LoopingCall(self.send)
lc.start(2)
reactor.callLater(1, setup_looping_call)
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
# ActiveMQ specific headers:
#
# prevent the messages we send comming back to us.
f.headers['activemq.noLocal'] = 'true'
return f.pack()
|
python
|
def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
stomper.Engine.connected(self, msg)
self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session'])
def setup_looping_call():
lc = LoopingCall(self.send)
lc.start(2)
reactor.callLater(1, setup_looping_call)
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
# ActiveMQ specific headers:
#
# prevent the messages we send comming back to us.
f.headers['activemq.noLocal'] = 'true'
return f.pack()
|
[
"def",
"connected",
"(",
"self",
",",
"msg",
")",
":",
"stomper",
".",
"Engine",
".",
"connected",
"(",
"self",
",",
"msg",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"Connected: session %s. Beginning say hello.\"",
"%",
"msg",
"[",
"'headers'",
"]",
"[",
"'session'",
"]",
")",
"def",
"setup_looping_call",
"(",
")",
":",
"lc",
"=",
"LoopingCall",
"(",
"self",
".",
"send",
")",
"lc",
".",
"start",
"(",
"2",
")",
"reactor",
".",
"callLater",
"(",
"1",
",",
"setup_looping_call",
")",
"f",
"=",
"stomper",
".",
"Frame",
"(",
")",
"f",
".",
"unpack",
"(",
"stomper",
".",
"subscribe",
"(",
"DESTINATION",
")",
")",
"# ActiveMQ specific headers:",
"#",
"# prevent the messages we send comming back to us.",
"f",
".",
"headers",
"[",
"'activemq.noLocal'",
"]",
"=",
"'true'",
"return",
"f",
".",
"pack",
"(",
")"
] |
Once I've connected I want to subscribe to my the message queue.
|
[
"Once",
"I",
"ve",
"connected",
"I",
"want",
"to",
"subscribe",
"to",
"my",
"the",
"message",
"queue",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L35-L56
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
StompProtocol.send
|
def send(self):
"""Send out a hello message periodically.
"""
self.log.info("Saying hello (%d)." % self.counter)
f = stomper.Frame()
f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter))
self.counter += 1
# ActiveMQ specific headers:
#
#f.headers['persistent'] = 'true'
self.transport.write(f.pack())
|
python
|
def send(self):
"""Send out a hello message periodically.
"""
self.log.info("Saying hello (%d)." % self.counter)
f = stomper.Frame()
f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter))
self.counter += 1
# ActiveMQ specific headers:
#
#f.headers['persistent'] = 'true'
self.transport.write(f.pack())
|
[
"def",
"send",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Saying hello (%d).\"",
"%",
"self",
".",
"counter",
")",
"f",
"=",
"stomper",
".",
"Frame",
"(",
")",
"f",
".",
"unpack",
"(",
"stomper",
".",
"send",
"(",
"DESTINATION",
",",
"'hello there (%d)'",
"%",
"self",
".",
"counter",
")",
")",
"self",
".",
"counter",
"+=",
"1",
"# ActiveMQ specific headers:",
"#",
"#f.headers['persistent'] = 'true'",
"self",
".",
"transport",
".",
"write",
"(",
"f",
".",
"pack",
"(",
")",
")"
] |
Send out a hello message periodically.
|
[
"Send",
"out",
"a",
"hello",
"message",
"periodically",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L68-L82
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
StompProtocol.connectionMade
|
def connectionMade(self):
"""Register with stomp server.
"""
cmd = stomper.connect(self.username, self.password)
self.transport.write(cmd)
|
python
|
def connectionMade(self):
"""Register with stomp server.
"""
cmd = stomper.connect(self.username, self.password)
self.transport.write(cmd)
|
[
"def",
"connectionMade",
"(",
"self",
")",
":",
"cmd",
"=",
"stomper",
".",
"connect",
"(",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"self",
".",
"transport",
".",
"write",
"(",
"cmd",
")"
] |
Register with stomp server.
|
[
"Register",
"with",
"stomp",
"server",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L85-L89
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
StompProtocol.dataReceived
|
def dataReceived(self, data):
"""Use stompbuffer to determine when a complete message has been received.
"""
self.stompBuffer.appendData(data)
while True:
msg = self.stompBuffer.getOneMessage()
if msg is None:
break
returned = self.react(msg)
if returned:
self.transport.write(returned)
|
python
|
def dataReceived(self, data):
"""Use stompbuffer to determine when a complete message has been received.
"""
self.stompBuffer.appendData(data)
while True:
msg = self.stompBuffer.getOneMessage()
if msg is None:
break
returned = self.react(msg)
if returned:
self.transport.write(returned)
|
[
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"stompBuffer",
".",
"appendData",
"(",
"data",
")",
"while",
"True",
":",
"msg",
"=",
"self",
".",
"stompBuffer",
".",
"getOneMessage",
"(",
")",
"if",
"msg",
"is",
"None",
":",
"break",
"returned",
"=",
"self",
".",
"react",
"(",
"msg",
")",
"if",
"returned",
":",
"self",
".",
"transport",
".",
"write",
"(",
"returned",
")"
] |
Use stompbuffer to determine when a complete message has been received.
|
[
"Use",
"stompbuffer",
"to",
"determine",
"when",
"a",
"complete",
"message",
"has",
"been",
"received",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L92-L104
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-tx.py
|
StompClientFactory.clientConnectionFailed
|
def clientConnectionFailed(self, connector, reason):
"""Connection failed
"""
print('Connection failed. Reason:', reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
|
python
|
def clientConnectionFailed(self, connector, reason):
"""Connection failed
"""
print('Connection failed. Reason:', reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
|
[
"def",
"clientConnectionFailed",
"(",
"self",
",",
"connector",
",",
"reason",
")",
":",
"print",
"(",
"'Connection failed. Reason:'",
",",
"reason",
")",
"ReconnectingClientFactory",
".",
"clientConnectionFailed",
"(",
"self",
",",
"connector",
",",
"reason",
")"
] |
Connection failed
|
[
"Connection",
"failed"
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L124-L128
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/receiver.py
|
MyStomp.ack
|
def ack(self, msg):
"""Process the message and determine what to do with it.
"""
self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg['body']))
#return super(MyStomp, self).ack(msg)
return stomper.NO_REPONSE_NEEDED
|
python
|
def ack(self, msg):
"""Process the message and determine what to do with it.
"""
self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg['body']))
#return super(MyStomp, self).ack(msg)
return stomper.NO_REPONSE_NEEDED
|
[
"def",
"ack",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"receiverId <%s> Received: <%s> \"",
"%",
"(",
"self",
".",
"receiverId",
",",
"msg",
"[",
"'body'",
"]",
")",
")",
"#return super(MyStomp, self).ack(msg) ",
"return",
"stomper",
".",
"NO_REPONSE_NEEDED"
] |
Process the message and determine what to do with it.
|
[
"Process",
"the",
"message",
"and",
"determine",
"what",
"to",
"do",
"with",
"it",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/receiver.py#L51-L57
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/receiver.py
|
StompProtocol.connectionMade
|
def connectionMade(self):
"""Register with the stomp server.
"""
cmd = self.sm.connect()
self.transport.write(cmd)
|
python
|
def connectionMade(self):
"""Register with the stomp server.
"""
cmd = self.sm.connect()
self.transport.write(cmd)
|
[
"def",
"connectionMade",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"sm",
".",
"connect",
"(",
")",
"self",
".",
"transport",
".",
"write",
"(",
"cmd",
")"
] |
Register with the stomp server.
|
[
"Register",
"with",
"the",
"stomp",
"server",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/receiver.py#L67-L71
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/receiver.py
|
StompProtocol.dataReceived
|
def dataReceived(self, data):
"""Data received, react to it and respond if needed.
"""
# print "receiver dataReceived: <%s>" % data
msg = stomper.unpack_frame(data)
returned = self.sm.react(msg)
# print "receiver returned <%s>" % returned
if returned:
self.transport.write(returned)
|
python
|
def dataReceived(self, data):
"""Data received, react to it and respond if needed.
"""
# print "receiver dataReceived: <%s>" % data
msg = stomper.unpack_frame(data)
returned = self.sm.react(msg)
# print "receiver returned <%s>" % returned
if returned:
self.transport.write(returned)
|
[
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"# print \"receiver dataReceived: <%s>\" % data",
"msg",
"=",
"stomper",
".",
"unpack_frame",
"(",
"data",
")",
"returned",
"=",
"self",
".",
"sm",
".",
"react",
"(",
"msg",
")",
"# print \"receiver returned <%s>\" % returned",
"if",
"returned",
":",
"self",
".",
"transport",
".",
"write",
"(",
"returned",
")"
] |
Data received, react to it and respond if needed.
|
[
"Data",
"received",
"react",
"to",
"it",
"and",
"respond",
"if",
"needed",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/receiver.py#L74-L86
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.find_id_in_folder
|
def find_id_in_folder(self, name, parent_folder_id=0):
"""Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID of the file or folder found. None if not found.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
if name is None or len(name) == 0:
return parent_folder_id
offset = 0
resp = self.get_folder_items(parent_folder_id,
limit=1000, offset=offset,
fields_list=['name'])
total = int(resp['total_count'])
while offset < total:
found = self.__find_name(resp, name)
if found is not None:
return found
offset += int(len(resp['entries']))
resp = self.get_folder_items(parent_folder_id,
limit=1000, offset=offset,
fields_list=['name'])
return None
|
python
|
def find_id_in_folder(self, name, parent_folder_id=0):
"""Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID of the file or folder found. None if not found.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
if name is None or len(name) == 0:
return parent_folder_id
offset = 0
resp = self.get_folder_items(parent_folder_id,
limit=1000, offset=offset,
fields_list=['name'])
total = int(resp['total_count'])
while offset < total:
found = self.__find_name(resp, name)
if found is not None:
return found
offset += int(len(resp['entries']))
resp = self.get_folder_items(parent_folder_id,
limit=1000, offset=offset,
fields_list=['name'])
return None
|
[
"def",
"find_id_in_folder",
"(",
"self",
",",
"name",
",",
"parent_folder_id",
"=",
"0",
")",
":",
"if",
"name",
"is",
"None",
"or",
"len",
"(",
"name",
")",
"==",
"0",
":",
"return",
"parent_folder_id",
"offset",
"=",
"0",
"resp",
"=",
"self",
".",
"get_folder_items",
"(",
"parent_folder_id",
",",
"limit",
"=",
"1000",
",",
"offset",
"=",
"offset",
",",
"fields_list",
"=",
"[",
"'name'",
"]",
")",
"total",
"=",
"int",
"(",
"resp",
"[",
"'total_count'",
"]",
")",
"while",
"offset",
"<",
"total",
":",
"found",
"=",
"self",
".",
"__find_name",
"(",
"resp",
",",
"name",
")",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"offset",
"+=",
"int",
"(",
"len",
"(",
"resp",
"[",
"'entries'",
"]",
")",
")",
"resp",
"=",
"self",
".",
"get_folder_items",
"(",
"parent_folder_id",
",",
"limit",
"=",
"1000",
",",
"offset",
"=",
"offset",
",",
"fields_list",
"=",
"[",
"'name'",
"]",
")",
"return",
"None"
] |
Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID of the file or folder found. None if not found.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Find",
"a",
"folder",
"or",
"a",
"file",
"ID",
"from",
"its",
"name",
"inside",
"a",
"given",
"folder",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L135-L169
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.create_folder
|
def create_folder(self, name, parent_folder_id=0):
"""Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("POST", "folders",
data={ "name": name,
"parent": {"id": unicode(parent_folder_id)} })
|
python
|
def create_folder(self, name, parent_folder_id=0):
"""Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("POST", "folders",
data={ "name": name,
"parent": {"id": unicode(parent_folder_id)} })
|
[
"def",
"create_folder",
"(",
"self",
",",
"name",
",",
"parent_folder_id",
"=",
"0",
")",
":",
"return",
"self",
".",
"__request",
"(",
"\"POST\"",
",",
"\"folders\"",
",",
"data",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"parent\"",
":",
"{",
"\"id\"",
":",
"unicode",
"(",
"parent_folder_id",
")",
"}",
"}",
")"
] |
Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Create",
"a",
"folder"
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L195-L217
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.delete_folder
|
def delete_folder(self, folder_id, recursive=True):
"""Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("DELETE", "folders/%s" % (folder_id, ),
querystring={'recursive': unicode(recursive).lower()})
|
python
|
def delete_folder(self, folder_id, recursive=True):
"""Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("DELETE", "folders/%s" % (folder_id, ),
querystring={'recursive': unicode(recursive).lower()})
|
[
"def",
"delete_folder",
"(",
"self",
",",
"folder_id",
",",
"recursive",
"=",
"True",
")",
":",
"return",
"self",
".",
"__request",
"(",
"\"DELETE\"",
",",
"\"folders/%s\"",
"%",
"(",
"folder_id",
",",
")",
",",
"querystring",
"=",
"{",
"'recursive'",
":",
"unicode",
"(",
"recursive",
")",
".",
"lower",
"(",
")",
"}",
")"
] |
Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Delete",
"an",
"existing",
"folder"
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L219-L237
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.get_folder_items
|
def get_folder_items(self, folder_id,
limit=100, offset=0, fields_list=None):
"""Get files and folders inside a given folder
Args:
folder_id (int): Where to get files and folders info.
limit (int): The number of items to return.
offset (int): The item at which to begin the response.
fields_list (list): List of attributes to get. All attributes if None.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
qs = { "limit": limit,
"offset": offset }
if fields_list:
qs['fields'] = ','.join(fields_list)
return self.__request("GET", "folders/%s/items" % (folder_id, ),
querystring=qs)
|
python
|
def get_folder_items(self, folder_id,
limit=100, offset=0, fields_list=None):
"""Get files and folders inside a given folder
Args:
folder_id (int): Where to get files and folders info.
limit (int): The number of items to return.
offset (int): The item at which to begin the response.
fields_list (list): List of attributes to get. All attributes if None.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
qs = { "limit": limit,
"offset": offset }
if fields_list:
qs['fields'] = ','.join(fields_list)
return self.__request("GET", "folders/%s/items" % (folder_id, ),
querystring=qs)
|
[
"def",
"get_folder_items",
"(",
"self",
",",
"folder_id",
",",
"limit",
"=",
"100",
",",
"offset",
"=",
"0",
",",
"fields_list",
"=",
"None",
")",
":",
"qs",
"=",
"{",
"\"limit\"",
":",
"limit",
",",
"\"offset\"",
":",
"offset",
"}",
"if",
"fields_list",
":",
"qs",
"[",
"'fields'",
"]",
"=",
"','",
".",
"join",
"(",
"fields_list",
")",
"return",
"self",
".",
"__request",
"(",
"\"GET\"",
",",
"\"folders/%s/items\"",
"%",
"(",
"folder_id",
",",
")",
",",
"querystring",
"=",
"qs",
")"
] |
Get files and folders inside a given folder
Args:
folder_id (int): Where to get files and folders info.
limit (int): The number of items to return.
offset (int): The item at which to begin the response.
fields_list (list): List of attributes to get. All attributes if None.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Get",
"files",
"and",
"folders",
"inside",
"a",
"given",
"folder"
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L239-L267
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.upload_file
|
def upload_file(self, name, folder_id, file_path):
"""Upload a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_upload_file(name, folder_id, file_path)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_upload_file(name, folder_id, file_path)
|
python
|
def upload_file(self, name, folder_id, file_path):
"""Upload a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_upload_file(name, folder_id, file_path)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_upload_file(name, folder_id, file_path)
|
[
"def",
"upload_file",
"(",
"self",
",",
"name",
",",
"folder_id",
",",
"file_path",
")",
":",
"try",
":",
"return",
"self",
".",
"__do_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
")",
"except",
"BoxError",
",",
"ex",
":",
"if",
"ex",
".",
"status",
"!=",
"401",
":",
"raise",
"#tokens had been refreshed, so we start again the upload",
"return",
"self",
".",
"__do_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
")"
] |
Upload a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Upload",
"a",
"file",
"into",
"a",
"folder",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L269-L297
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.upload_new_file_version
|
def upload_new_file_version(self, name, folder_id, file_id, file_path):
"""Upload a new version of a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function.
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_id (int): ID of the file to update.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_upload_file(name, folder_id, file_path, file_id)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_upload_file(name, folder_id, file_path, file_id)
|
python
|
def upload_new_file_version(self, name, folder_id, file_id, file_path):
"""Upload a new version of a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function.
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_id (int): ID of the file to update.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_upload_file(name, folder_id, file_path, file_id)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_upload_file(name, folder_id, file_path, file_id)
|
[
"def",
"upload_new_file_version",
"(",
"self",
",",
"name",
",",
"folder_id",
",",
"file_id",
",",
"file_path",
")",
":",
"try",
":",
"return",
"self",
".",
"__do_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
",",
"file_id",
")",
"except",
"BoxError",
",",
"ex",
":",
"if",
"ex",
".",
"status",
"!=",
"401",
":",
"raise",
"#tokens had been refreshed, so we start again the upload",
"return",
"self",
".",
"__do_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
",",
"file_id",
")"
] |
Upload a new version of a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function.
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_id (int): ID of the file to update.
file_path (str): Local path of the file to upload.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Upload",
"a",
"new",
"version",
"of",
"a",
"file",
"into",
"a",
"folder",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L299-L329
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.chunk_upload_file
|
def chunk_upload_file(self, name, folder_id, file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Upload a file chunk by chunk.
The whole file is never loaded in memory.
Use this function for big file.
The callback(transferred, total) to let you know the upload progress.
Upload can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Uploaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
progress_callback (func): Function called each time a chunk is uploaded.
chunk_size (int): Size of chunks.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_chunk_upload_file(name, folder_id, file_path,
progress_callback,
chunk_size)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_chunk_upload_file(name, folder_id, file_path,
progress_callback,
chunk_size)
|
python
|
def chunk_upload_file(self, name, folder_id, file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Upload a file chunk by chunk.
The whole file is never loaded in memory.
Use this function for big file.
The callback(transferred, total) to let you know the upload progress.
Upload can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Uploaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
progress_callback (func): Function called each time a chunk is uploaded.
chunk_size (int): Size of chunks.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
try:
return self.__do_chunk_upload_file(name, folder_id, file_path,
progress_callback,
chunk_size)
except BoxError, ex:
if ex.status != 401:
raise
#tokens had been refreshed, so we start again the upload
return self.__do_chunk_upload_file(name, folder_id, file_path,
progress_callback,
chunk_size)
|
[
"def",
"chunk_upload_file",
"(",
"self",
",",
"name",
",",
"folder_id",
",",
"file_path",
",",
"progress_callback",
"=",
"None",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"1",
")",
":",
"try",
":",
"return",
"self",
".",
"__do_chunk_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
",",
"progress_callback",
",",
"chunk_size",
")",
"except",
"BoxError",
",",
"ex",
":",
"if",
"ex",
".",
"status",
"!=",
"401",
":",
"raise",
"#tokens had been refreshed, so we start again the upload",
"return",
"self",
".",
"__do_chunk_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
",",
"progress_callback",
",",
"chunk_size",
")"
] |
Upload a file chunk by chunk.
The whole file is never loaded in memory.
Use this function for big file.
The callback(transferred, total) to let you know the upload progress.
Upload can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Uploaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload the file.
file_path (str): Local path of the file to upload.
progress_callback (func): Function called each time a chunk is uploaded.
chunk_size (int): Size of chunks.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Upload",
"a",
"file",
"chunk",
"by",
"chunk",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L346-L394
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.copy_file
|
def copy_file(self, file_id, dest_folder_id):
"""Copy file to new destination
Args:
file_id (int): ID of the folder.
dest_folder_id (int): ID of parent folder you are copying to.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxError: 409 - Item with the same name already exists.
In this case you will need download the file and upload a new version to your destination.
(Box currently doesn't have a method to copy a new verison.)
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("POST", "/files/" + unicode(file_id) + "/copy",
data={ "parent": {"id": unicode(dest_folder_id)} })
|
python
|
def copy_file(self, file_id, dest_folder_id):
"""Copy file to new destination
Args:
file_id (int): ID of the folder.
dest_folder_id (int): ID of parent folder you are copying to.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxError: 409 - Item with the same name already exists.
In this case you will need download the file and upload a new version to your destination.
(Box currently doesn't have a method to copy a new verison.)
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
return self.__request("POST", "/files/" + unicode(file_id) + "/copy",
data={ "parent": {"id": unicode(dest_folder_id)} })
|
[
"def",
"copy_file",
"(",
"self",
",",
"file_id",
",",
"dest_folder_id",
")",
":",
"return",
"self",
".",
"__request",
"(",
"\"POST\"",
",",
"\"/files/\"",
"+",
"unicode",
"(",
"file_id",
")",
"+",
"\"/copy\"",
",",
"data",
"=",
"{",
"\"parent\"",
":",
"{",
"\"id\"",
":",
"unicode",
"(",
"dest_folder_id",
")",
"}",
"}",
")"
] |
Copy file to new destination
Args:
file_id (int): ID of the folder.
dest_folder_id (int): ID of parent folder you are copying to.
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxError: 409 - Item with the same name already exists.
In this case you will need download the file and upload a new version to your destination.
(Box currently doesn't have a method to copy a new verison.)
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Copy",
"file",
"to",
"new",
"destination"
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L432-L456
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.download_file
|
def download_file(self, file_id, dest_file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Download a file.
The whole file is never loaded in memory.
The callback(transferred, total) to let you know the download progress.
Download can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Downloaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
file_id (int): ID of the file to download.
dest_file_path (str): Local path where to store the downloaded filed.
progress_callback (func): Function called each time a chunk is downloaded.
chunk_size (int): Size of chunks.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
with open(dest_file_path, 'wb') as fp:
req = self.__request("GET", "files/%s/content" % (file_id, ),
stream=True,
json_data=False)
total = -1
if hasattr(req, 'headers'):
lower_headers = {k.lower():v for k,v in req.headers.items()}
if 'content-length' in lower_headers:
total = lower_headers['content-length']
transferred = 0
for chunk in req.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
if progress_callback:
progress_callback(transferred, total)
fp.write(chunk)
fp.flush()
transferred += len(chunk)
if progress_callback:
progress_callback(transferred, total)
|
python
|
def download_file(self, file_id, dest_file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Download a file.
The whole file is never loaded in memory.
The callback(transferred, total) to let you know the download progress.
Download can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Downloaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
file_id (int): ID of the file to download.
dest_file_path (str): Local path where to store the downloaded filed.
progress_callback (func): Function called each time a chunk is downloaded.
chunk_size (int): Size of chunks.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
with open(dest_file_path, 'wb') as fp:
req = self.__request("GET", "files/%s/content" % (file_id, ),
stream=True,
json_data=False)
total = -1
if hasattr(req, 'headers'):
lower_headers = {k.lower():v for k,v in req.headers.items()}
if 'content-length' in lower_headers:
total = lower_headers['content-length']
transferred = 0
for chunk in req.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
if progress_callback:
progress_callback(transferred, total)
fp.write(chunk)
fp.flush()
transferred += len(chunk)
if progress_callback:
progress_callback(transferred, total)
|
[
"def",
"download_file",
"(",
"self",
",",
"file_id",
",",
"dest_file_path",
",",
"progress_callback",
"=",
"None",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"1",
")",
":",
"with",
"open",
"(",
"dest_file_path",
",",
"'wb'",
")",
"as",
"fp",
":",
"req",
"=",
"self",
".",
"__request",
"(",
"\"GET\"",
",",
"\"files/%s/content\"",
"%",
"(",
"file_id",
",",
")",
",",
"stream",
"=",
"True",
",",
"json_data",
"=",
"False",
")",
"total",
"=",
"-",
"1",
"if",
"hasattr",
"(",
"req",
",",
"'headers'",
")",
":",
"lower_headers",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"req",
".",
"headers",
".",
"items",
"(",
")",
"}",
"if",
"'content-length'",
"in",
"lower_headers",
":",
"total",
"=",
"lower_headers",
"[",
"'content-length'",
"]",
"transferred",
"=",
"0",
"for",
"chunk",
"in",
"req",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"if",
"chunk",
":",
"# filter out keep-alive new chunks",
"if",
"progress_callback",
":",
"progress_callback",
"(",
"transferred",
",",
"total",
")",
"fp",
".",
"write",
"(",
"chunk",
")",
"fp",
".",
"flush",
"(",
")",
"transferred",
"+=",
"len",
"(",
"chunk",
")",
"if",
"progress_callback",
":",
"progress_callback",
"(",
"transferred",
",",
"total",
")"
] |
Download a file.
The whole file is never loaded in memory.
The callback(transferred, total) to let you know the download progress.
Download can be cancelled if the callback raise an Exception.
>>> def progress_callback(transferred, total):
... print 'Downloaded %i bytes of %i' % (transferred, total, )
... if user_request_cancel:
... raise MyCustomCancelException()
Args:
file_id (int): ID of the file to download.
dest_file_path (str): Local path where to store the downloaded filed.
progress_callback (func): Function called each time a chunk is downloaded.
chunk_size (int): Size of chunks.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Download",
"a",
"file",
"."
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L458-L509
|
train
|
wesleyfr/boxpython
|
boxpython/session.py
|
BoxSession.search
|
def search(self, **kwargs):
"""Searches for files/folders
Args:
\*\*kwargs (dict): A dictionary containing necessary parameters
(check https://developers.box.com/docs/#search for
list of parameters)
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
query_string = {}
for key, value in kwargs.iteritems():
query_string[key] = value
return self.__request("GET","search",querystring=query_string)
|
python
|
def search(self, **kwargs):
"""Searches for files/folders
Args:
\*\*kwargs (dict): A dictionary containing necessary parameters
(check https://developers.box.com/docs/#search for
list of parameters)
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
"""
query_string = {}
for key, value in kwargs.iteritems():
query_string[key] = value
return self.__request("GET","search",querystring=query_string)
|
[
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query_string",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"query_string",
"[",
"key",
"]",
"=",
"value",
"return",
"self",
".",
"__request",
"(",
"\"GET\"",
",",
"\"search\"",
",",
"querystring",
"=",
"query_string",
")"
] |
Searches for files/folders
Args:
\*\*kwargs (dict): A dictionary containing necessary parameters
(check https://developers.box.com/docs/#search for
list of parameters)
Returns:
dict. Response from Box.
Raises:
BoxError: An error response is returned from Box (status_code >= 400).
BoxHttpResponseError: Response from Box is malformed.
requests.exceptions.*: Any connection related problem.
|
[
"Searches",
"for",
"files",
"/",
"folders"
] |
f00a8ada6dff2c7ffc88bf89d4e15965c5adb422
|
https://github.com/wesleyfr/boxpython/blob/f00a8ada6dff2c7ffc88bf89d4e15965c5adb422/boxpython/session.py#L529-L550
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.getmany
|
def getmany(self, *keys):
"""
Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dictionary
classes.
"""
pickled_keys = (self._pickle_key(k) for k in keys)
pickled_values = self.redis.hmget(self.key, *pickled_keys)
ret = []
for k, v in zip(keys, pickled_values):
value = self.cache.get(k, self._unpickle(v))
ret.append(value)
return ret
|
python
|
def getmany(self, *keys):
"""
Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dictionary
classes.
"""
pickled_keys = (self._pickle_key(k) for k in keys)
pickled_values = self.redis.hmget(self.key, *pickled_keys)
ret = []
for k, v in zip(keys, pickled_values):
value = self.cache.get(k, self._unpickle(v))
ret.append(value)
return ret
|
[
"def",
"getmany",
"(",
"self",
",",
"*",
"keys",
")",
":",
"pickled_keys",
"=",
"(",
"self",
".",
"_pickle_key",
"(",
"k",
")",
"for",
"k",
"in",
"keys",
")",
"pickled_values",
"=",
"self",
".",
"redis",
".",
"hmget",
"(",
"self",
".",
"key",
",",
"*",
"pickled_keys",
")",
"ret",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"keys",
",",
"pickled_values",
")",
":",
"value",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"k",
",",
"self",
".",
"_unpickle",
"(",
"v",
")",
")",
"ret",
".",
"append",
"(",
"value",
")",
"return",
"ret"
] |
Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dictionary
classes.
|
[
"Return",
"a",
"list",
"of",
"values",
"corresponding",
"to",
"the",
"keys",
"in",
"the",
"iterable",
"of",
"*",
"keys",
"*",
".",
"If",
"a",
"key",
"is",
"not",
"present",
"in",
"the",
"collection",
"its",
"corresponding",
"value",
"will",
"be",
":",
"obj",
":",
"None",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L125-L144
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict._data
|
def _data(self, pipe=None):
"""
Returns a Python dictionary with the same values as this object
(without checking the local cache).
"""
pipe = self.redis if pipe is None else pipe
items = pipe.hgetall(self.key).items()
return {self._unpickle_key(k): self._unpickle(v) for k, v in items}
|
python
|
def _data(self, pipe=None):
"""
Returns a Python dictionary with the same values as this object
(without checking the local cache).
"""
pipe = self.redis if pipe is None else pipe
items = pipe.hgetall(self.key).items()
return {self._unpickle_key(k): self._unpickle(v) for k, v in items}
|
[
"def",
"_data",
"(",
"self",
",",
"pipe",
"=",
"None",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"items",
"=",
"pipe",
".",
"hgetall",
"(",
"self",
".",
"key",
")",
".",
"items",
"(",
")",
"return",
"{",
"self",
".",
"_unpickle_key",
"(",
"k",
")",
":",
"self",
".",
"_unpickle",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"items",
"}"
] |
Returns a Python dictionary with the same values as this object
(without checking the local cache).
|
[
"Returns",
"a",
"Python",
"dictionary",
"with",
"the",
"same",
"values",
"as",
"this",
"object",
"(",
"without",
"checking",
"the",
"local",
"cache",
")",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L192-L200
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.iteritems
|
def iteritems(self, pipe=None):
"""Return an iterator over the dictionary's ``(key, value)`` pairs."""
pipe = self.redis if pipe is None else pipe
for k, v in self._data(pipe).items():
yield k, self.cache.get(k, v)
|
python
|
def iteritems(self, pipe=None):
"""Return an iterator over the dictionary's ``(key, value)`` pairs."""
pipe = self.redis if pipe is None else pipe
for k, v in self._data(pipe).items():
yield k, self.cache.get(k, v)
|
[
"def",
"iteritems",
"(",
"self",
",",
"pipe",
"=",
"None",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_data",
"(",
"pipe",
")",
".",
"items",
"(",
")",
":",
"yield",
"k",
",",
"self",
".",
"cache",
".",
"get",
"(",
"k",
",",
"v",
")"
] |
Return an iterator over the dictionary's ``(key, value)`` pairs.
|
[
"Return",
"an",
"iterator",
"over",
"the",
"dictionary",
"s",
"(",
"key",
"value",
")",
"pairs",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L206-L210
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.pop
|
def pop(self, key, default=__marker):
"""If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not
in the dictionary, a :exc:`KeyError` is raised.
"""
pickled_key = self._pickle_key(key)
if key in self.cache:
self.redis.hdel(self.key, pickled_key)
return self.cache.pop(key)
def pop_trans(pipe):
pickled_value = pipe.hget(self.key, pickled_key)
if pickled_value is None:
if default is self.__marker:
raise KeyError(key)
return default
pipe.hdel(self.key, pickled_key)
return self._unpickle(pickled_value)
value = self._transaction(pop_trans)
self.cache.pop(key, None)
return value
|
python
|
def pop(self, key, default=__marker):
"""If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not
in the dictionary, a :exc:`KeyError` is raised.
"""
pickled_key = self._pickle_key(key)
if key in self.cache:
self.redis.hdel(self.key, pickled_key)
return self.cache.pop(key)
def pop_trans(pipe):
pickled_value = pipe.hget(self.key, pickled_key)
if pickled_value is None:
if default is self.__marker:
raise KeyError(key)
return default
pipe.hdel(self.key, pickled_key)
return self._unpickle(pickled_value)
value = self._transaction(pop_trans)
self.cache.pop(key, None)
return value
|
[
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"__marker",
")",
":",
"pickled_key",
"=",
"self",
".",
"_pickle_key",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"cache",
":",
"self",
".",
"redis",
".",
"hdel",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"return",
"self",
".",
"cache",
".",
"pop",
"(",
"key",
")",
"def",
"pop_trans",
"(",
"pipe",
")",
":",
"pickled_value",
"=",
"pipe",
".",
"hget",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"if",
"pickled_value",
"is",
"None",
":",
"if",
"default",
"is",
"self",
".",
"__marker",
":",
"raise",
"KeyError",
"(",
"key",
")",
"return",
"default",
"pipe",
".",
"hdel",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"return",
"self",
".",
"_unpickle",
"(",
"pickled_value",
")",
"value",
"=",
"self",
".",
"_transaction",
"(",
"pop_trans",
")",
"self",
".",
"cache",
".",
"pop",
"(",
"key",
",",
"None",
")",
"return",
"value"
] |
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not
in the dictionary, a :exc:`KeyError` is raised.
|
[
"If",
"*",
"key",
"*",
"is",
"in",
"the",
"dictionary",
"remove",
"it",
"and",
"return",
"its",
"value",
"else",
"return",
"*",
"default",
"*",
".",
"If",
"*",
"default",
"*",
"is",
"not",
"given",
"and",
"*",
"key",
"*",
"is",
"not",
"in",
"the",
"dictionary",
"a",
":",
"exc",
":",
"KeyError",
"is",
"raised",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L234-L258
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.popitem
|
def popitem(self):
"""Remove and return an arbitrary ``(key, value)`` pair from
the dictionary.
:func:`popitem` is useful to destructively iterate over
a dictionary, as often used in set algorithms. If
the dictionary is empty, calling :func:`popitem` raises
a :exc:`KeyError`.
"""
def popitem_trans(pipe):
try:
pickled_key = pipe.hkeys(self.key)[0]
except IndexError:
raise KeyError
# pop its value
pipe.multi()
pipe.hget(self.key, pickled_key)
pipe.hdel(self.key, pickled_key)
pickled_value, __ = pipe.execute()
return (
self._unpickle_key(pickled_key), self._unpickle(pickled_value)
)
key, value = self._transaction(popitem_trans)
return key, self.cache.pop(key, value)
|
python
|
def popitem(self):
"""Remove and return an arbitrary ``(key, value)`` pair from
the dictionary.
:func:`popitem` is useful to destructively iterate over
a dictionary, as often used in set algorithms. If
the dictionary is empty, calling :func:`popitem` raises
a :exc:`KeyError`.
"""
def popitem_trans(pipe):
try:
pickled_key = pipe.hkeys(self.key)[0]
except IndexError:
raise KeyError
# pop its value
pipe.multi()
pipe.hget(self.key, pickled_key)
pipe.hdel(self.key, pickled_key)
pickled_value, __ = pipe.execute()
return (
self._unpickle_key(pickled_key), self._unpickle(pickled_value)
)
key, value = self._transaction(popitem_trans)
return key, self.cache.pop(key, value)
|
[
"def",
"popitem",
"(",
"self",
")",
":",
"def",
"popitem_trans",
"(",
"pipe",
")",
":",
"try",
":",
"pickled_key",
"=",
"pipe",
".",
"hkeys",
"(",
"self",
".",
"key",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"KeyError",
"# pop its value",
"pipe",
".",
"multi",
"(",
")",
"pipe",
".",
"hget",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"pipe",
".",
"hdel",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"pickled_value",
",",
"__",
"=",
"pipe",
".",
"execute",
"(",
")",
"return",
"(",
"self",
".",
"_unpickle_key",
"(",
"pickled_key",
")",
",",
"self",
".",
"_unpickle",
"(",
"pickled_value",
")",
")",
"key",
",",
"value",
"=",
"self",
".",
"_transaction",
"(",
"popitem_trans",
")",
"return",
"key",
",",
"self",
".",
"cache",
".",
"pop",
"(",
"key",
",",
"value",
")"
] |
Remove and return an arbitrary ``(key, value)`` pair from
the dictionary.
:func:`popitem` is useful to destructively iterate over
a dictionary, as often used in set algorithms. If
the dictionary is empty, calling :func:`popitem` raises
a :exc:`KeyError`.
|
[
"Remove",
"and",
"return",
"an",
"arbitrary",
"(",
"key",
"value",
")",
"pair",
"from",
"the",
"dictionary",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L260-L287
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.setdefault
|
def setdefault(self, key, default=None):
"""If *key* is in the dictionary, return its value.
If not, insert *key* with a value of *default* and
return *default*. *default* defaults to :obj:`None`.
"""
if key in self.cache:
return self.cache[key]
def setdefault_trans(pipe):
pickled_key = self._pickle_key(key)
pipe.multi()
pipe.hsetnx(self.key, pickled_key, self._pickle_value(default))
pipe.hget(self.key, pickled_key)
__, pickled_value = pipe.execute()
return self._unpickle(pickled_value)
value = self._transaction(setdefault_trans)
if self.writeback:
self.cache[key] = value
return value
|
python
|
def setdefault(self, key, default=None):
"""If *key* is in the dictionary, return its value.
If not, insert *key* with a value of *default* and
return *default*. *default* defaults to :obj:`None`.
"""
if key in self.cache:
return self.cache[key]
def setdefault_trans(pipe):
pickled_key = self._pickle_key(key)
pipe.multi()
pipe.hsetnx(self.key, pickled_key, self._pickle_value(default))
pipe.hget(self.key, pickled_key)
__, pickled_value = pipe.execute()
return self._unpickle(pickled_value)
value = self._transaction(setdefault_trans)
if self.writeback:
self.cache[key] = value
return value
|
[
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
"[",
"key",
"]",
"def",
"setdefault_trans",
"(",
"pipe",
")",
":",
"pickled_key",
"=",
"self",
".",
"_pickle_key",
"(",
"key",
")",
"pipe",
".",
"multi",
"(",
")",
"pipe",
".",
"hsetnx",
"(",
"self",
".",
"key",
",",
"pickled_key",
",",
"self",
".",
"_pickle_value",
"(",
"default",
")",
")",
"pipe",
".",
"hget",
"(",
"self",
".",
"key",
",",
"pickled_key",
")",
"__",
",",
"pickled_value",
"=",
"pipe",
".",
"execute",
"(",
")",
"return",
"self",
".",
"_unpickle",
"(",
"pickled_value",
")",
"value",
"=",
"self",
".",
"_transaction",
"(",
"setdefault_trans",
")",
"if",
"self",
".",
"writeback",
":",
"self",
".",
"cache",
"[",
"key",
"]",
"=",
"value",
"return",
"value"
] |
If *key* is in the dictionary, return its value.
If not, insert *key* with a value of *default* and
return *default*. *default* defaults to :obj:`None`.
|
[
"If",
"*",
"key",
"*",
"is",
"in",
"the",
"dictionary",
"return",
"its",
"value",
".",
"If",
"not",
"insert",
"*",
"key",
"*",
"with",
"a",
"value",
"of",
"*",
"default",
"*",
"and",
"return",
"*",
"default",
"*",
".",
"*",
"default",
"*",
"defaults",
"to",
":",
"obj",
":",
"None",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L289-L312
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.update
|
def update(self, other=None, **kwargs):
"""Update the dictionary with the key/value pairs from *other*,
overwriting existing keys. Return :obj:`None`.
:func:`update` accepts either another dictionary object or
an iterable of key/value pairs (as tuples or other iterables
of length two). If keyword arguments are specified, the
dictionary is then updated with those key/value pairs:
``d.update(red=1, blue=2)``.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other)
else:
self._update_helper({k: v for k, v in other})
if kwargs:
self._update_helper(kwargs)
|
python
|
def update(self, other=None, **kwargs):
"""Update the dictionary with the key/value pairs from *other*,
overwriting existing keys. Return :obj:`None`.
:func:`update` accepts either another dictionary object or
an iterable of key/value pairs (as tuples or other iterables
of length two). If keyword arguments are specified, the
dictionary is then updated with those key/value pairs:
``d.update(red=1, blue=2)``.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other)
else:
self._update_helper({k: v for k, v in other})
if kwargs:
self._update_helper(kwargs)
|
[
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_same_redis",
"(",
"other",
",",
"RedisCollection",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
",",
"use_redis",
"=",
"True",
")",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
")",
"else",
":",
"self",
".",
"_update_helper",
"(",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"other",
"}",
")",
"if",
"kwargs",
":",
"self",
".",
"_update_helper",
"(",
"kwargs",
")"
] |
Update the dictionary with the key/value pairs from *other*,
overwriting existing keys. Return :obj:`None`.
:func:`update` accepts either another dictionary object or
an iterable of key/value pairs (as tuples or other iterables
of length two). If keyword arguments are specified, the
dictionary is then updated with those key/value pairs:
``d.update(red=1, blue=2)``.
|
[
"Update",
"the",
"dictionary",
"with",
"the",
"key",
"/",
"value",
"pairs",
"from",
"*",
"other",
"*",
"overwriting",
"existing",
"keys",
".",
"Return",
":",
"obj",
":",
"None",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L341-L360
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.copy
|
def copy(self, key=None):
"""
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
"""
other = self.__class__(redis=self.redis, key=key)
other.update(self)
return other
|
python
|
def copy(self, key=None):
"""
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
"""
other = self.__class__(redis=self.redis, key=key)
other.update(self)
return other
|
[
"def",
"copy",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"other",
"=",
"self",
".",
"__class__",
"(",
"redis",
"=",
"self",
".",
"redis",
",",
"key",
"=",
"key",
")",
"other",
".",
"update",
"(",
"self",
")",
"return",
"other"
] |
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
|
[
"Return",
"a",
"new",
"collection",
"with",
"the",
"same",
"items",
"as",
"this",
"one",
".",
"If",
"*",
"key",
"*",
"is",
"specified",
"create",
"the",
"new",
"collection",
"with",
"the",
"given",
"Redis",
"key",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L362-L371
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.fromkeys
|
def fromkeys(cls, seq, value=None, **kwargs):
"""Create a new dictionary with keys from *seq* and values set to
*value*.
.. note::
:func:`fromkeys` is a class method that returns a new dictionary.
It is possible to specify additional keyword arguments to be passed
to :func:`__init__` of the new object.
"""
values = ((key, value) for key in seq)
return cls(values, **kwargs)
|
python
|
def fromkeys(cls, seq, value=None, **kwargs):
"""Create a new dictionary with keys from *seq* and values set to
*value*.
.. note::
:func:`fromkeys` is a class method that returns a new dictionary.
It is possible to specify additional keyword arguments to be passed
to :func:`__init__` of the new object.
"""
values = ((key, value) for key in seq)
return cls(values, **kwargs)
|
[
"def",
"fromkeys",
"(",
"cls",
",",
"seq",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
"in",
"seq",
")",
"return",
"cls",
"(",
"values",
",",
"*",
"*",
"kwargs",
")"
] |
Create a new dictionary with keys from *seq* and values set to
*value*.
.. note::
:func:`fromkeys` is a class method that returns a new dictionary.
It is possible to specify additional keyword arguments to be passed
to :func:`__init__` of the new object.
|
[
"Create",
"a",
"new",
"dictionary",
"with",
"keys",
"from",
"*",
"seq",
"*",
"and",
"values",
"set",
"to",
"*",
"value",
"*",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L380-L390
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Dict.scan_items
|
def scan_items(self):
"""
Yield each of the ``(key, value)`` pairs from the collection, without
pulling them all into memory.
.. warning::
This method is not available on the dictionary collections provided
by Python.
This method may return the same (key, value) pair multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for k, v in self.redis.hscan_iter(self.key):
yield self._unpickle_key(k), self._unpickle(v)
|
python
|
def scan_items(self):
"""
Yield each of the ``(key, value)`` pairs from the collection, without
pulling them all into memory.
.. warning::
This method is not available on the dictionary collections provided
by Python.
This method may return the same (key, value) pair multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for k, v in self.redis.hscan_iter(self.key):
yield self._unpickle_key(k), self._unpickle(v)
|
[
"def",
"scan_items",
"(",
"self",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"redis",
".",
"hscan_iter",
"(",
"self",
".",
"key",
")",
":",
"yield",
"self",
".",
"_unpickle_key",
"(",
"k",
")",
",",
"self",
".",
"_unpickle",
"(",
"v",
")"
] |
Yield each of the ``(key, value)`` pairs from the collection, without
pulling them all into memory.
.. warning::
This method is not available on the dictionary collections provided
by Python.
This method may return the same (key, value) pair multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
|
[
"Yield",
"each",
"of",
"the",
"(",
"key",
"value",
")",
"pairs",
"from",
"the",
"collection",
"without",
"pulling",
"them",
"all",
"into",
"memory",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L392-L406
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Counter.update
|
def update(self, other=None, **kwargs):
"""Elements are counted from an *iterable* or added-in from another
*mapping* (or counter). Like :func:`dict.update` but adds counts
instead of replacing them. Also, the *iterable* is expected to be
a sequence of elements, not a sequence of ``(key, value)`` pairs.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, operator.add, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other, operator.add)
else:
self._update_helper(collections.Counter(other), operator.add)
if kwargs:
self._update_helper(kwargs, operator.add)
|
python
|
def update(self, other=None, **kwargs):
"""Elements are counted from an *iterable* or added-in from another
*mapping* (or counter). Like :func:`dict.update` but adds counts
instead of replacing them. Also, the *iterable* is expected to be
a sequence of elements, not a sequence of ``(key, value)`` pairs.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, operator.add, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other, operator.add)
else:
self._update_helper(collections.Counter(other), operator.add)
if kwargs:
self._update_helper(kwargs, operator.add)
|
[
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_same_redis",
"(",
"other",
",",
"RedisCollection",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
",",
"operator",
".",
"add",
",",
"use_redis",
"=",
"True",
")",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
",",
"operator",
".",
"add",
")",
"else",
":",
"self",
".",
"_update_helper",
"(",
"collections",
".",
"Counter",
"(",
"other",
")",
",",
"operator",
".",
"add",
")",
"if",
"kwargs",
":",
"self",
".",
"_update_helper",
"(",
"kwargs",
",",
"operator",
".",
"add",
")"
] |
Elements are counted from an *iterable* or added-in from another
*mapping* (or counter). Like :func:`dict.update` but adds counts
instead of replacing them. Also, the *iterable* is expected to be
a sequence of elements, not a sequence of ``(key, value)`` pairs.
|
[
"Elements",
"are",
"counted",
"from",
"an",
"*",
"iterable",
"*",
"or",
"added",
"-",
"in",
"from",
"another",
"*",
"mapping",
"*",
"(",
"or",
"counter",
")",
".",
"Like",
":",
"func",
":",
"dict",
".",
"update",
"but",
"adds",
"counts",
"instead",
"of",
"replacing",
"them",
".",
"Also",
"the",
"*",
"iterable",
"*",
"is",
"expected",
"to",
"be",
"a",
"sequence",
"of",
"elements",
"not",
"a",
"sequence",
"of",
"(",
"key",
"value",
")",
"pairs",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L519-L534
|
train
|
honzajavorek/redis-collections
|
redis_collections/dicts.py
|
Counter.subtract
|
def subtract(self, other=None, **kwargs):
"""Elements are subtracted from an *iterable* or from another
*mapping* (or counter). Like :func:`dict.update` but subtracts
counts instead of replacing them.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, operator.sub, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other, operator.sub)
else:
self._update_helper(collections.Counter(other), operator.sub)
if kwargs:
self._update_helper(kwargs, operator.sub)
|
python
|
def subtract(self, other=None, **kwargs):
"""Elements are subtracted from an *iterable* or from another
*mapping* (or counter). Like :func:`dict.update` but subtracts
counts instead of replacing them.
"""
if other is not None:
if self._same_redis(other, RedisCollection):
self._update_helper(other, operator.sub, use_redis=True)
elif hasattr(other, 'keys'):
self._update_helper(other, operator.sub)
else:
self._update_helper(collections.Counter(other), operator.sub)
if kwargs:
self._update_helper(kwargs, operator.sub)
|
[
"def",
"subtract",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_same_redis",
"(",
"other",
",",
"RedisCollection",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
",",
"operator",
".",
"sub",
",",
"use_redis",
"=",
"True",
")",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"self",
".",
"_update_helper",
"(",
"other",
",",
"operator",
".",
"sub",
")",
"else",
":",
"self",
".",
"_update_helper",
"(",
"collections",
".",
"Counter",
"(",
"other",
")",
",",
"operator",
".",
"sub",
")",
"if",
"kwargs",
":",
"self",
".",
"_update_helper",
"(",
"kwargs",
",",
"operator",
".",
"sub",
")"
] |
Elements are subtracted from an *iterable* or from another
*mapping* (or counter). Like :func:`dict.update` but subtracts
counts instead of replacing them.
|
[
"Elements",
"are",
"subtracted",
"from",
"an",
"*",
"iterable",
"*",
"or",
"from",
"another",
"*",
"mapping",
"*",
"(",
"or",
"counter",
")",
".",
"Like",
":",
"func",
":",
"dict",
".",
"update",
"but",
"subtracts",
"counts",
"instead",
"of",
"replacing",
"them",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/dicts.py#L536-L550
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/sender.py
|
StompProtocol.ack
|
def ack(self, msg):
"""Processes the received message. I don't need to
generate an ack message.
"""
self.log.info("senderID:%s Received: %s " % (self.senderID, msg['body']))
return stomper.NO_REPONSE_NEEDED
|
python
|
def ack(self, msg):
"""Processes the received message. I don't need to
generate an ack message.
"""
self.log.info("senderID:%s Received: %s " % (self.senderID, msg['body']))
return stomper.NO_REPONSE_NEEDED
|
[
"def",
"ack",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"senderID:%s Received: %s \"",
"%",
"(",
"self",
".",
"senderID",
",",
"msg",
"[",
"'body'",
"]",
")",
")",
"return",
"stomper",
".",
"NO_REPONSE_NEEDED"
] |
Processes the received message. I don't need to
generate an ack message.
|
[
"Processes",
"the",
"received",
"message",
".",
"I",
"don",
"t",
"need",
"to",
"generate",
"an",
"ack",
"message",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/sender.py#L68-L74
|
train
|
honzajavorek/redis-collections
|
redis_collections/base.py
|
RedisCollection._clear
|
def _clear(self, pipe=None):
"""Helper for clear operations.
:param pipe: Redis pipe in case update is performed as a part
of transaction.
:type pipe: :class:`redis.client.StrictPipeline` or
:class:`redis.client.StrictRedis`
"""
redis = self.redis if pipe is None else pipe
redis.delete(self.key)
|
python
|
def _clear(self, pipe=None):
"""Helper for clear operations.
:param pipe: Redis pipe in case update is performed as a part
of transaction.
:type pipe: :class:`redis.client.StrictPipeline` or
:class:`redis.client.StrictRedis`
"""
redis = self.redis if pipe is None else pipe
redis.delete(self.key)
|
[
"def",
"_clear",
"(",
"self",
",",
"pipe",
"=",
"None",
")",
":",
"redis",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"redis",
".",
"delete",
"(",
"self",
".",
"key",
")"
] |
Helper for clear operations.
:param pipe: Redis pipe in case update is performed as a part
of transaction.
:type pipe: :class:`redis.client.StrictPipeline` or
:class:`redis.client.StrictRedis`
|
[
"Helper",
"for",
"clear",
"operations",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/base.py#L116-L125
|
train
|
honzajavorek/redis-collections
|
redis_collections/base.py
|
RedisCollection._normalize_index
|
def _normalize_index(self, index, pipe=None):
"""Convert negative indexes into their positive equivalents."""
pipe = self.redis if pipe is None else pipe
len_self = self.__len__(pipe)
positive_index = index if index >= 0 else len_self + index
return len_self, positive_index
|
python
|
def _normalize_index(self, index, pipe=None):
"""Convert negative indexes into their positive equivalents."""
pipe = self.redis if pipe is None else pipe
len_self = self.__len__(pipe)
positive_index = index if index >= 0 else len_self + index
return len_self, positive_index
|
[
"def",
"_normalize_index",
"(",
"self",
",",
"index",
",",
"pipe",
"=",
"None",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"len_self",
"=",
"self",
".",
"__len__",
"(",
"pipe",
")",
"positive_index",
"=",
"index",
"if",
"index",
">=",
"0",
"else",
"len_self",
"+",
"index",
"return",
"len_self",
",",
"positive_index"
] |
Convert negative indexes into their positive equivalents.
|
[
"Convert",
"negative",
"indexes",
"into",
"their",
"positive",
"equivalents",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/base.py#L152-L158
|
train
|
honzajavorek/redis-collections
|
redis_collections/base.py
|
RedisCollection._normalize_slice
|
def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
"""
if index.step == 0:
raise ValueError
pipe = self.redis if pipe is None else pipe
len_self = self.__len__(pipe)
step = index.step or 1
forward = step > 0
step = abs(step)
if index.start is None:
start = 0 if forward else len_self - 1
elif index.start < 0:
start = max(len_self + index.start, 0)
else:
start = min(index.start, len_self)
if index.stop is None:
stop = len_self if forward else -1
elif index.stop < 0:
stop = max(len_self + index.stop, 0)
else:
stop = min(index.stop, len_self)
if not forward:
start, stop = min(stop + 1, len_self), min(start + 1, len_self)
return start, stop, step, forward, len_self
|
python
|
def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
"""
if index.step == 0:
raise ValueError
pipe = self.redis if pipe is None else pipe
len_self = self.__len__(pipe)
step = index.step or 1
forward = step > 0
step = abs(step)
if index.start is None:
start = 0 if forward else len_self - 1
elif index.start < 0:
start = max(len_self + index.start, 0)
else:
start = min(index.start, len_self)
if index.stop is None:
stop = len_self if forward else -1
elif index.stop < 0:
stop = max(len_self + index.stop, 0)
else:
stop = min(index.stop, len_self)
if not forward:
start, stop = min(stop + 1, len_self), min(start + 1, len_self)
return start, stop, step, forward, len_self
|
[
"def",
"_normalize_slice",
"(",
"self",
",",
"index",
",",
"pipe",
"=",
"None",
")",
":",
"if",
"index",
".",
"step",
"==",
"0",
":",
"raise",
"ValueError",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"len_self",
"=",
"self",
".",
"__len__",
"(",
"pipe",
")",
"step",
"=",
"index",
".",
"step",
"or",
"1",
"forward",
"=",
"step",
">",
"0",
"step",
"=",
"abs",
"(",
"step",
")",
"if",
"index",
".",
"start",
"is",
"None",
":",
"start",
"=",
"0",
"if",
"forward",
"else",
"len_self",
"-",
"1",
"elif",
"index",
".",
"start",
"<",
"0",
":",
"start",
"=",
"max",
"(",
"len_self",
"+",
"index",
".",
"start",
",",
"0",
")",
"else",
":",
"start",
"=",
"min",
"(",
"index",
".",
"start",
",",
"len_self",
")",
"if",
"index",
".",
"stop",
"is",
"None",
":",
"stop",
"=",
"len_self",
"if",
"forward",
"else",
"-",
"1",
"elif",
"index",
".",
"stop",
"<",
"0",
":",
"stop",
"=",
"max",
"(",
"len_self",
"+",
"index",
".",
"stop",
",",
"0",
")",
"else",
":",
"stop",
"=",
"min",
"(",
"index",
".",
"stop",
",",
"len_self",
")",
"if",
"not",
"forward",
":",
"start",
",",
"stop",
"=",
"min",
"(",
"stop",
"+",
"1",
",",
"len_self",
")",
",",
"min",
"(",
"start",
"+",
"1",
",",
"len_self",
")",
"return",
"start",
",",
"stop",
",",
"step",
",",
"forward",
",",
"len_self"
] |
Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
|
[
"Given",
"a",
":",
"obj",
":",
"slice",
"*",
"index",
"*",
"return",
"a",
"4",
"-",
"tuple",
"(",
"start",
"stop",
"step",
"fowrward",
")",
".",
"The",
"first",
"three",
"items",
"can",
"be",
"used",
"with",
"the",
"range",
"function",
"to",
"retrieve",
"the",
"values",
"associated",
"with",
"the",
"slice",
";",
"the",
"last",
"item",
"indicates",
"the",
"direction",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/base.py#L160-L193
|
train
|
honzajavorek/redis-collections
|
redis_collections/base.py
|
RedisCollection._transaction
|
def _transaction(self, fn, *extra_keys):
"""Helper simplifying code within watched transaction.
Takes *fn*, function treated as a transaction. Returns whatever
*fn* returns. ``self.key`` is watched. *fn* takes *pipe* as the
only argument.
:param fn: Closure treated as a transaction.
:type fn: function *fn(pipe)*
:param extra_keys: Optional list of additional keys to watch.
:type extra_keys: list
:rtype: whatever *fn* returns
"""
results = []
def trans(pipe):
results.append(fn(pipe))
self.redis.transaction(trans, self.key, *extra_keys)
return results[0]
|
python
|
def _transaction(self, fn, *extra_keys):
"""Helper simplifying code within watched transaction.
Takes *fn*, function treated as a transaction. Returns whatever
*fn* returns. ``self.key`` is watched. *fn* takes *pipe* as the
only argument.
:param fn: Closure treated as a transaction.
:type fn: function *fn(pipe)*
:param extra_keys: Optional list of additional keys to watch.
:type extra_keys: list
:rtype: whatever *fn* returns
"""
results = []
def trans(pipe):
results.append(fn(pipe))
self.redis.transaction(trans, self.key, *extra_keys)
return results[0]
|
[
"def",
"_transaction",
"(",
"self",
",",
"fn",
",",
"*",
"extra_keys",
")",
":",
"results",
"=",
"[",
"]",
"def",
"trans",
"(",
"pipe",
")",
":",
"results",
".",
"append",
"(",
"fn",
"(",
"pipe",
")",
")",
"self",
".",
"redis",
".",
"transaction",
"(",
"trans",
",",
"self",
".",
"key",
",",
"*",
"extra_keys",
")",
"return",
"results",
"[",
"0",
"]"
] |
Helper simplifying code within watched transaction.
Takes *fn*, function treated as a transaction. Returns whatever
*fn* returns. ``self.key`` is watched. *fn* takes *pipe* as the
only argument.
:param fn: Closure treated as a transaction.
:type fn: function *fn(pipe)*
:param extra_keys: Optional list of additional keys to watch.
:type extra_keys: list
:rtype: whatever *fn* returns
|
[
"Helper",
"simplifying",
"code",
"within",
"watched",
"transaction",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/base.py#L195-L214
|
train
|
JoaoFelipe/ipython-unittest
|
setup.py
|
recursive_path
|
def recursive_path(pack, path):
"""Find paths recursively"""
matches = []
for root, _, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches
|
python
|
def recursive_path(pack, path):
"""Find paths recursively"""
matches = []
for root, _, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches
|
[
"def",
"recursive_path",
"(",
"pack",
",",
"path",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pack",
",",
"path",
")",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"matches",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
"[",
"len",
"(",
"pack",
")",
"+",
"1",
":",
"]",
")",
"return",
"matches"
] |
Find paths recursively
|
[
"Find",
"paths",
"recursively"
] |
2a1708e1fa575ce80e0ee2092d280979c1a77885
|
https://github.com/JoaoFelipe/ipython-unittest/blob/2a1708e1fa575ce80e0ee2092d280979c1a77885/setup.py#L7-L13
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_11.py
|
nack
|
def nack(messageid, subscriptionid, transactionid=None):
"""STOMP negative acknowledge command.
NACK is the opposite of ACK. It is used to tell the server that the client
did not consume the message. The server can then either send the message to
a different client, discard it, or put it in a dead letter queue. The exact
behavior is server specific.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
subscriptionid:
This is the id of the subscription that applies to the message.
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
"""
header = 'subscription:%s\nmessage-id:%s' % (subscriptionid, messageid)
if transactionid:
header += '\ntransaction:%s' % transactionid
return "NACK\n%s\n\n\x00\n" % header
|
python
|
def nack(messageid, subscriptionid, transactionid=None):
"""STOMP negative acknowledge command.
NACK is the opposite of ACK. It is used to tell the server that the client
did not consume the message. The server can then either send the message to
a different client, discard it, or put it in a dead letter queue. The exact
behavior is server specific.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
subscriptionid:
This is the id of the subscription that applies to the message.
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
"""
header = 'subscription:%s\nmessage-id:%s' % (subscriptionid, messageid)
if transactionid:
header += '\ntransaction:%s' % transactionid
return "NACK\n%s\n\n\x00\n" % header
|
[
"def",
"nack",
"(",
"messageid",
",",
"subscriptionid",
",",
"transactionid",
"=",
"None",
")",
":",
"header",
"=",
"'subscription:%s\\nmessage-id:%s'",
"%",
"(",
"subscriptionid",
",",
"messageid",
")",
"if",
"transactionid",
":",
"header",
"+=",
"'\\ntransaction:%s'",
"%",
"transactionid",
"return",
"\"NACK\\n%s\\n\\n\\x00\\n\"",
"%",
"header"
] |
STOMP negative acknowledge command.
NACK is the opposite of ACK. It is used to tell the server that the client
did not consume the message. The server can then either send the message to
a different client, discard it, or put it in a dead letter queue. The exact
behavior is server specific.
messageid:
This is the id of the message we are acknowledging,
what else could it be? ;)
subscriptionid:
This is the id of the subscription that applies to the message.
transactionid:
This is the id that all actions in this transaction
will have. If this is not given then a random UUID
will be generated for this.
|
[
"STOMP",
"negative",
"acknowledge",
"command",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_11.py#L275-L301
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_11.py
|
connect
|
def connect(username, password, host, heartbeats=(0,0)):
"""STOMP connect command.
username, password:
These are the needed auth details to connect to the
message server.
After sending this we will receive a CONNECTED
message which will contain our session id.
"""
if len(heartbeats) != 2:
raise ValueError('Invalid heartbeat %r' % heartbeats)
cx, cy = heartbeats
return "CONNECT\naccept-version:1.1\nhost:%s\nheart-beat:%i,%i\nlogin:%s\npasscode:%s\n\n\x00\n" % (host, cx, cy, username, password)
|
python
|
def connect(username, password, host, heartbeats=(0,0)):
"""STOMP connect command.
username, password:
These are the needed auth details to connect to the
message server.
After sending this we will receive a CONNECTED
message which will contain our session id.
"""
if len(heartbeats) != 2:
raise ValueError('Invalid heartbeat %r' % heartbeats)
cx, cy = heartbeats
return "CONNECT\naccept-version:1.1\nhost:%s\nheart-beat:%i,%i\nlogin:%s\npasscode:%s\n\n\x00\n" % (host, cx, cy, username, password)
|
[
"def",
"connect",
"(",
"username",
",",
"password",
",",
"host",
",",
"heartbeats",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"if",
"len",
"(",
"heartbeats",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid heartbeat %r'",
"%",
"heartbeats",
")",
"cx",
",",
"cy",
"=",
"heartbeats",
"return",
"\"CONNECT\\naccept-version:1.1\\nhost:%s\\nheart-beat:%i,%i\\nlogin:%s\\npasscode:%s\\n\\n\\x00\\n\"",
"%",
"(",
"host",
",",
"cx",
",",
"cy",
",",
"username",
",",
"password",
")"
] |
STOMP connect command.
username, password:
These are the needed auth details to connect to the
message server.
After sending this we will receive a CONNECTED
message which will contain our session id.
|
[
"STOMP",
"connect",
"command",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_11.py#L335-L349
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stomp_11.py
|
Engine.ack
|
def ack(self, msg):
"""Called when a MESSAGE has been received.
Override this method to handle received messages.
This function will generate an acknowledge message
for the given message and transaction (if present).
"""
message_id = msg['headers']['message-id']
subscription = msg['headers']['subscription']
transaction_id = None
if 'transaction-id' in msg['headers']:
transaction_id = msg['headers']['transaction-id']
# print "acknowledging message id <%s>." % message_id
return ack(message_id, subscription, transaction_id)
|
python
|
def ack(self, msg):
"""Called when a MESSAGE has been received.
Override this method to handle received messages.
This function will generate an acknowledge message
for the given message and transaction (if present).
"""
message_id = msg['headers']['message-id']
subscription = msg['headers']['subscription']
transaction_id = None
if 'transaction-id' in msg['headers']:
transaction_id = msg['headers']['transaction-id']
# print "acknowledging message id <%s>." % message_id
return ack(message_id, subscription, transaction_id)
|
[
"def",
"ack",
"(",
"self",
",",
"msg",
")",
":",
"message_id",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'message-id'",
"]",
"subscription",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'subscription'",
"]",
"transaction_id",
"=",
"None",
"if",
"'transaction-id'",
"in",
"msg",
"[",
"'headers'",
"]",
":",
"transaction_id",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'transaction-id'",
"]",
"# print \"acknowledging message id <%s>.\" % message_id",
"return",
"ack",
"(",
"message_id",
",",
"subscription",
",",
"transaction_id",
")"
] |
Called when a MESSAGE has been received.
Override this method to handle received messages.
This function will generate an acknowledge message
for the given message and transaction (if present).
|
[
"Called",
"when",
"a",
"MESSAGE",
"has",
"been",
"received",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stomp_11.py#L489-L507
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stompbuffer.py
|
StompBuffer.getOneMessage
|
def getOneMessage ( self ):
"""
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until I return None.
"""
( mbytes, hbytes ) = self._findMessageBytes ( self.buffer )
if not mbytes:
return None
msgdata = self.buffer[:mbytes]
self.buffer = self.buffer[mbytes:]
hdata = msgdata[:hbytes]
elems = hdata.split ( '\n' )
cmd = elems.pop ( 0 )
headers = {}
# We can't use a simple split because the value can legally contain
# colon characters (for example, the session returned by ActiveMQ).
for e in elems:
try:
i = e.find ( ':' )
except ValueError:
continue
k = e[:i].strip()
v = e[i+1:].strip()
headers [ k ] = v
# hbytes points to the start of the '\n\n' at the end of the header,
# so 2 bytes beyond this is the start of the body. The body EXCLUDES
# the final two bytes, which are '\x00\n'. Note that these 2 bytes
# are UNRELATED to the 2-byte '\n\n' that Frame.pack() used to insert
# into the data stream.
body = msgdata[hbytes+2:-2]
msg = { 'cmd' : cmd,
'headers' : headers,
'body' : body,
}
return msg
|
python
|
def getOneMessage ( self ):
"""
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until I return None.
"""
( mbytes, hbytes ) = self._findMessageBytes ( self.buffer )
if not mbytes:
return None
msgdata = self.buffer[:mbytes]
self.buffer = self.buffer[mbytes:]
hdata = msgdata[:hbytes]
elems = hdata.split ( '\n' )
cmd = elems.pop ( 0 )
headers = {}
# We can't use a simple split because the value can legally contain
# colon characters (for example, the session returned by ActiveMQ).
for e in elems:
try:
i = e.find ( ':' )
except ValueError:
continue
k = e[:i].strip()
v = e[i+1:].strip()
headers [ k ] = v
# hbytes points to the start of the '\n\n' at the end of the header,
# so 2 bytes beyond this is the start of the body. The body EXCLUDES
# the final two bytes, which are '\x00\n'. Note that these 2 bytes
# are UNRELATED to the 2-byte '\n\n' that Frame.pack() used to insert
# into the data stream.
body = msgdata[hbytes+2:-2]
msg = { 'cmd' : cmd,
'headers' : headers,
'body' : body,
}
return msg
|
[
"def",
"getOneMessage",
"(",
"self",
")",
":",
"(",
"mbytes",
",",
"hbytes",
")",
"=",
"self",
".",
"_findMessageBytes",
"(",
"self",
".",
"buffer",
")",
"if",
"not",
"mbytes",
":",
"return",
"None",
"msgdata",
"=",
"self",
".",
"buffer",
"[",
":",
"mbytes",
"]",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"mbytes",
":",
"]",
"hdata",
"=",
"msgdata",
"[",
":",
"hbytes",
"]",
"elems",
"=",
"hdata",
".",
"split",
"(",
"'\\n'",
")",
"cmd",
"=",
"elems",
".",
"pop",
"(",
"0",
")",
"headers",
"=",
"{",
"}",
"# We can't use a simple split because the value can legally contain",
"# colon characters (for example, the session returned by ActiveMQ).",
"for",
"e",
"in",
"elems",
":",
"try",
":",
"i",
"=",
"e",
".",
"find",
"(",
"':'",
")",
"except",
"ValueError",
":",
"continue",
"k",
"=",
"e",
"[",
":",
"i",
"]",
".",
"strip",
"(",
")",
"v",
"=",
"e",
"[",
"i",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"headers",
"[",
"k",
"]",
"=",
"v",
"# hbytes points to the start of the '\\n\\n' at the end of the header,",
"# so 2 bytes beyond this is the start of the body. The body EXCLUDES",
"# the final two bytes, which are '\\x00\\n'. Note that these 2 bytes",
"# are UNRELATED to the 2-byte '\\n\\n' that Frame.pack() used to insert",
"# into the data stream.",
"body",
"=",
"msgdata",
"[",
"hbytes",
"+",
"2",
":",
"-",
"2",
"]",
"msg",
"=",
"{",
"'cmd'",
":",
"cmd",
",",
"'headers'",
":",
"headers",
",",
"'body'",
":",
"body",
",",
"}",
"return",
"msg"
] |
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until I return None.
|
[
"I",
"pull",
"one",
"complete",
"message",
"off",
"the",
"buffer",
"and",
"return",
"it",
"decoded",
"as",
"a",
"dict",
".",
"If",
"there",
"is",
"no",
"complete",
"message",
"in",
"the",
"buffer",
"I",
"return",
"None",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stompbuffer.py#L69-L109
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stompbuffer.py
|
StompBuffer._findMessageBytes
|
def _findMessageBytes ( self, data ):
"""
I examine the data passed to me and return a 2-tuple of the form:
( message_length, header_length )
where message_length is the length in bytes of the first complete
message, if it contains at least one message, or 0 if it
contains no message.
If message_length is non-zero, header_length contains the length in
bytes of the header. If message_length is zero, header_length should
be ignored.
You should probably not call me directly. Call getOneMessage instead.
"""
# Sanity check. See the docstring for the method to see what it
# does an why we need it.
self.syncBuffer()
# If the string '\n\n' does not exist, we don't even have the complete
# header yet and we MUST exit.
try:
i = data.index ( '\n\n' )
except ValueError:
return ( 0, 0 )
# If the string '\n\n' exists, then we have the entire header and can
# check for the content-length header. If it exists, we can check
# the length of the buffer for the number of bytes, else we check for
# the existence of a null byte.
# Pull out the header before we perform the regexp search. This
# prevents us from matching (possibly malicious) strings in the
# body.
_hdr = self.buffer[:i]
match = content_length_re.search ( _hdr )
if match:
# There was a content-length header, so read out the value.
content_length = int ( match.groups()[0] )
# THIS IS NO LONGER THE CASE IF WE REMOVE THE '\n\n' in
# Frame.pack()
# This is the content length of the body up until the null
# byte, not the entire message. Note that this INCLUDES the 2
# '\n\n' bytes inserted by the STOMP encoder after the body
# (see the calculation of content_length in
# StompEngine.callRemote()), so we only need to add 2 final bytes
# for the footer.
#
#The message looks like:
#
# <header>\n\n<body>\n\n\x00\n
# ^ ^^^^
# (i) included in content_length!
#
# We have the location of the end of the header (i), so we
# need to ensure that the message contains at least:
#
# i + len ( '\n\n' ) + content_length + len ( '\x00\n' )
#
# Note that i is also the count of bytes in the header, because
# of the fact that str.index() returns a 0-indexed value.
req_len = i + len_sep + content_length + len_footer
# log.msg ( "We have [%s] bytes and need [%s] bytes" %
# ( len ( data ), req_len, ) )
if len ( data ) < req_len:
# We don't have enough bytes in the buffer.
return ( 0, 0 )
else:
# We have enough bytes in the buffer
return ( req_len, i )
else:
# There was no content-length header, so just look for the
# message terminator ('\x00\n' ).
try:
j = data.index ( '\x00\n' )
except ValueError:
return ( 0, 0 )
# j points to the 0-indexed location of the null byte. However,
# we need to add 1 (to turn it into a byte count) and 1 to take
# account of the final '\n' character after the null byte.
return ( j + 2, i )
|
python
|
def _findMessageBytes ( self, data ):
"""
I examine the data passed to me and return a 2-tuple of the form:
( message_length, header_length )
where message_length is the length in bytes of the first complete
message, if it contains at least one message, or 0 if it
contains no message.
If message_length is non-zero, header_length contains the length in
bytes of the header. If message_length is zero, header_length should
be ignored.
You should probably not call me directly. Call getOneMessage instead.
"""
# Sanity check. See the docstring for the method to see what it
# does an why we need it.
self.syncBuffer()
# If the string '\n\n' does not exist, we don't even have the complete
# header yet and we MUST exit.
try:
i = data.index ( '\n\n' )
except ValueError:
return ( 0, 0 )
# If the string '\n\n' exists, then we have the entire header and can
# check for the content-length header. If it exists, we can check
# the length of the buffer for the number of bytes, else we check for
# the existence of a null byte.
# Pull out the header before we perform the regexp search. This
# prevents us from matching (possibly malicious) strings in the
# body.
_hdr = self.buffer[:i]
match = content_length_re.search ( _hdr )
if match:
# There was a content-length header, so read out the value.
content_length = int ( match.groups()[0] )
# THIS IS NO LONGER THE CASE IF WE REMOVE THE '\n\n' in
# Frame.pack()
# This is the content length of the body up until the null
# byte, not the entire message. Note that this INCLUDES the 2
# '\n\n' bytes inserted by the STOMP encoder after the body
# (see the calculation of content_length in
# StompEngine.callRemote()), so we only need to add 2 final bytes
# for the footer.
#
#The message looks like:
#
# <header>\n\n<body>\n\n\x00\n
# ^ ^^^^
# (i) included in content_length!
#
# We have the location of the end of the header (i), so we
# need to ensure that the message contains at least:
#
# i + len ( '\n\n' ) + content_length + len ( '\x00\n' )
#
# Note that i is also the count of bytes in the header, because
# of the fact that str.index() returns a 0-indexed value.
req_len = i + len_sep + content_length + len_footer
# log.msg ( "We have [%s] bytes and need [%s] bytes" %
# ( len ( data ), req_len, ) )
if len ( data ) < req_len:
# We don't have enough bytes in the buffer.
return ( 0, 0 )
else:
# We have enough bytes in the buffer
return ( req_len, i )
else:
# There was no content-length header, so just look for the
# message terminator ('\x00\n' ).
try:
j = data.index ( '\x00\n' )
except ValueError:
return ( 0, 0 )
# j points to the 0-indexed location of the null byte. However,
# we need to add 1 (to turn it into a byte count) and 1 to take
# account of the final '\n' character after the null byte.
return ( j + 2, i )
|
[
"def",
"_findMessageBytes",
"(",
"self",
",",
"data",
")",
":",
"# Sanity check. See the docstring for the method to see what it",
"# does an why we need it.",
"self",
".",
"syncBuffer",
"(",
")",
"# If the string '\\n\\n' does not exist, we don't even have the complete",
"# header yet and we MUST exit.",
"try",
":",
"i",
"=",
"data",
".",
"index",
"(",
"'\\n\\n'",
")",
"except",
"ValueError",
":",
"return",
"(",
"0",
",",
"0",
")",
"# If the string '\\n\\n' exists, then we have the entire header and can",
"# check for the content-length header. If it exists, we can check",
"# the length of the buffer for the number of bytes, else we check for",
"# the existence of a null byte.",
"# Pull out the header before we perform the regexp search. This",
"# prevents us from matching (possibly malicious) strings in the",
"# body.",
"_hdr",
"=",
"self",
".",
"buffer",
"[",
":",
"i",
"]",
"match",
"=",
"content_length_re",
".",
"search",
"(",
"_hdr",
")",
"if",
"match",
":",
"# There was a content-length header, so read out the value.",
"content_length",
"=",
"int",
"(",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
")",
"# THIS IS NO LONGER THE CASE IF WE REMOVE THE '\\n\\n' in",
"# Frame.pack()",
"# This is the content length of the body up until the null",
"# byte, not the entire message. Note that this INCLUDES the 2",
"# '\\n\\n' bytes inserted by the STOMP encoder after the body",
"# (see the calculation of content_length in",
"# StompEngine.callRemote()), so we only need to add 2 final bytes",
"# for the footer.",
"#",
"#The message looks like:",
"#",
"# <header>\\n\\n<body>\\n\\n\\x00\\n",
"# ^ ^^^^",
"# (i) included in content_length!",
"#",
"# We have the location of the end of the header (i), so we",
"# need to ensure that the message contains at least:",
"#",
"# i + len ( '\\n\\n' ) + content_length + len ( '\\x00\\n' )",
"#",
"# Note that i is also the count of bytes in the header, because",
"# of the fact that str.index() returns a 0-indexed value.",
"req_len",
"=",
"i",
"+",
"len_sep",
"+",
"content_length",
"+",
"len_footer",
"# log.msg ( \"We have [%s] bytes and need [%s] bytes\" %",
"# ( len ( data ), req_len, ) )",
"if",
"len",
"(",
"data",
")",
"<",
"req_len",
":",
"# We don't have enough bytes in the buffer.",
"return",
"(",
"0",
",",
"0",
")",
"else",
":",
"# We have enough bytes in the buffer",
"return",
"(",
"req_len",
",",
"i",
")",
"else",
":",
"# There was no content-length header, so just look for the",
"# message terminator ('\\x00\\n' ).",
"try",
":",
"j",
"=",
"data",
".",
"index",
"(",
"'\\x00\\n'",
")",
"except",
"ValueError",
":",
"return",
"(",
"0",
",",
"0",
")",
"# j points to the 0-indexed location of the null byte. However,",
"# we need to add 1 (to turn it into a byte count) and 1 to take",
"# account of the final '\\n' character after the null byte.",
"return",
"(",
"j",
"+",
"2",
",",
"i",
")"
] |
I examine the data passed to me and return a 2-tuple of the form:
( message_length, header_length )
where message_length is the length in bytes of the first complete
message, if it contains at least one message, or 0 if it
contains no message.
If message_length is non-zero, header_length contains the length in
bytes of the header. If message_length is zero, header_length should
be ignored.
You should probably not call me directly. Call getOneMessage instead.
|
[
"I",
"examine",
"the",
"data",
"passed",
"to",
"me",
"and",
"return",
"a",
"2",
"-",
"tuple",
"of",
"the",
"form",
":",
"(",
"message_length",
"header_length",
")",
"where",
"message_length",
"is",
"the",
"length",
"in",
"bytes",
"of",
"the",
"first",
"complete",
"message",
"if",
"it",
"contains",
"at",
"least",
"one",
"message",
"or",
"0",
"if",
"it",
"contains",
"no",
"message",
".",
"If",
"message_length",
"is",
"non",
"-",
"zero",
"header_length",
"contains",
"the",
"length",
"in",
"bytes",
"of",
"the",
"header",
".",
"If",
"message_length",
"is",
"zero",
"header_length",
"should",
"be",
"ignored",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stompbuffer.py#L112-L195
|
train
|
oisinmulvihill/stomper
|
lib/stomper/stompbuffer.py
|
StompBuffer.syncBuffer
|
def syncBuffer( self ):
"""
I detect and correct corruption in the buffer.
Corruption in the buffer is defined as the following conditions
both being true:
1. The buffer contains at least one newline;
2. The text until the first newline is not a STOMP command.
In this case, we heuristically try to flush bits of the buffer until
one of the following conditions becomes true:
1. the buffer starts with a STOMP command;
2. the buffer does not contain a newline.
3. the buffer is empty;
If the buffer is deemed corrupt, the first step is to flush the buffer
up to and including the first occurrence of the string '\x00\n', which
is likely to be a frame boundary.
Note that this is not guaranteed to be a frame boundary, as a binary
payload could contain the string '\x00\n'. That condition would get
handled on the next loop iteration.
If the string '\x00\n' does not occur, the entire buffer is cleared.
An earlier version progressively removed strings until the next newline,
but this gets complicated because the body could contain strings that
look like STOMP commands.
Note that we do not check "partial" strings to see if they *could*
match a command; that would be too resource-intensive. In other words,
a buffer containing the string 'BUNK' with no newline is clearly
corrupt, but we sit and wait until the buffer contains a newline before
attempting to see if it's a STOMP command.
"""
while True:
if not self.buffer:
# Buffer is empty; no need to do anything.
break
m = command_re.match ( self.buffer )
if m is None:
# Buffer doesn't even contain a single newline, so we can't
# determine whether it's corrupt or not. Assume it's OK.
break
cmd = m.groups()[0]
if cmd in stomper.VALID_COMMANDS:
# Good: the buffer starts with a command.
break
else:
# Bad: the buffer starts with bunk, so strip it out. We first
# try to strip to the first occurrence of '\x00\n', which
# is likely to be a frame boundary, but if this fails, we
# strip until the first newline.
( self.buffer, nsubs ) = sync_re.subn ( '', self.buffer )
if nsubs:
# Good: we managed to strip something out, so restart the
# loop to see if things look better.
continue
else:
# Bad: we failed to strip anything out, so kill the
# entire buffer. Since this resets the buffer to a
# known good state, we can break out of the loop.
self.buffer = ''
break
|
python
|
def syncBuffer( self ):
"""
I detect and correct corruption in the buffer.
Corruption in the buffer is defined as the following conditions
both being true:
1. The buffer contains at least one newline;
2. The text until the first newline is not a STOMP command.
In this case, we heuristically try to flush bits of the buffer until
one of the following conditions becomes true:
1. the buffer starts with a STOMP command;
2. the buffer does not contain a newline.
3. the buffer is empty;
If the buffer is deemed corrupt, the first step is to flush the buffer
up to and including the first occurrence of the string '\x00\n', which
is likely to be a frame boundary.
Note that this is not guaranteed to be a frame boundary, as a binary
payload could contain the string '\x00\n'. That condition would get
handled on the next loop iteration.
If the string '\x00\n' does not occur, the entire buffer is cleared.
An earlier version progressively removed strings until the next newline,
but this gets complicated because the body could contain strings that
look like STOMP commands.
Note that we do not check "partial" strings to see if they *could*
match a command; that would be too resource-intensive. In other words,
a buffer containing the string 'BUNK' with no newline is clearly
corrupt, but we sit and wait until the buffer contains a newline before
attempting to see if it's a STOMP command.
"""
while True:
if not self.buffer:
# Buffer is empty; no need to do anything.
break
m = command_re.match ( self.buffer )
if m is None:
# Buffer doesn't even contain a single newline, so we can't
# determine whether it's corrupt or not. Assume it's OK.
break
cmd = m.groups()[0]
if cmd in stomper.VALID_COMMANDS:
# Good: the buffer starts with a command.
break
else:
# Bad: the buffer starts with bunk, so strip it out. We first
# try to strip to the first occurrence of '\x00\n', which
# is likely to be a frame boundary, but if this fails, we
# strip until the first newline.
( self.buffer, nsubs ) = sync_re.subn ( '', self.buffer )
if nsubs:
# Good: we managed to strip something out, so restart the
# loop to see if things look better.
continue
else:
# Bad: we failed to strip anything out, so kill the
# entire buffer. Since this resets the buffer to a
# known good state, we can break out of the loop.
self.buffer = ''
break
|
[
"def",
"syncBuffer",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"buffer",
":",
"# Buffer is empty; no need to do anything.",
"break",
"m",
"=",
"command_re",
".",
"match",
"(",
"self",
".",
"buffer",
")",
"if",
"m",
"is",
"None",
":",
"# Buffer doesn't even contain a single newline, so we can't",
"# determine whether it's corrupt or not. Assume it's OK.",
"break",
"cmd",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"if",
"cmd",
"in",
"stomper",
".",
"VALID_COMMANDS",
":",
"# Good: the buffer starts with a command.",
"break",
"else",
":",
"# Bad: the buffer starts with bunk, so strip it out. We first",
"# try to strip to the first occurrence of '\\x00\\n', which",
"# is likely to be a frame boundary, but if this fails, we",
"# strip until the first newline.",
"(",
"self",
".",
"buffer",
",",
"nsubs",
")",
"=",
"sync_re",
".",
"subn",
"(",
"''",
",",
"self",
".",
"buffer",
")",
"if",
"nsubs",
":",
"# Good: we managed to strip something out, so restart the",
"# loop to see if things look better.",
"continue",
"else",
":",
"# Bad: we failed to strip anything out, so kill the",
"# entire buffer. Since this resets the buffer to a",
"# known good state, we can break out of the loop.",
"self",
".",
"buffer",
"=",
"''",
"break"
] |
I detect and correct corruption in the buffer.
Corruption in the buffer is defined as the following conditions
both being true:
1. The buffer contains at least one newline;
2. The text until the first newline is not a STOMP command.
In this case, we heuristically try to flush bits of the buffer until
one of the following conditions becomes true:
1. the buffer starts with a STOMP command;
2. the buffer does not contain a newline.
3. the buffer is empty;
If the buffer is deemed corrupt, the first step is to flush the buffer
up to and including the first occurrence of the string '\x00\n', which
is likely to be a frame boundary.
Note that this is not guaranteed to be a frame boundary, as a binary
payload could contain the string '\x00\n'. That condition would get
handled on the next loop iteration.
If the string '\x00\n' does not occur, the entire buffer is cleared.
An earlier version progressively removed strings until the next newline,
but this gets complicated because the body could contain strings that
look like STOMP commands.
Note that we do not check "partial" strings to see if they *could*
match a command; that would be too resource-intensive. In other words,
a buffer containing the string 'BUNK' with no newline is clearly
corrupt, but we sit and wait until the buffer contains a newline before
attempting to see if it's a STOMP command.
|
[
"I",
"detect",
"and",
"correct",
"corruption",
"in",
"the",
"buffer",
".",
"Corruption",
"in",
"the",
"buffer",
"is",
"defined",
"as",
"the",
"following",
"conditions",
"both",
"being",
"true",
":",
"1",
".",
"The",
"buffer",
"contains",
"at",
"least",
"one",
"newline",
";",
"2",
".",
"The",
"text",
"until",
"the",
"first",
"newline",
"is",
"not",
"a",
"STOMP",
"command",
".",
"In",
"this",
"case",
"we",
"heuristically",
"try",
"to",
"flush",
"bits",
"of",
"the",
"buffer",
"until",
"one",
"of",
"the",
"following",
"conditions",
"becomes",
"true",
":",
"1",
".",
"the",
"buffer",
"starts",
"with",
"a",
"STOMP",
"command",
";",
"2",
".",
"the",
"buffer",
"does",
"not",
"contain",
"a",
"newline",
".",
"3",
".",
"the",
"buffer",
"is",
"empty",
";"
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/stompbuffer.py#L198-L263
|
train
|
oisinmulvihill/stomper
|
lib/stomper/examples/stompbuffer-rx.py
|
MyStomp.connected
|
def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
super(MyStomp, self).connected(msg)
self.log.info("connected: session %s" % msg['headers']['session'])
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
return f.pack()
|
python
|
def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
super(MyStomp, self).connected(msg)
self.log.info("connected: session %s" % msg['headers']['session'])
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
return f.pack()
|
[
"def",
"connected",
"(",
"self",
",",
"msg",
")",
":",
"super",
"(",
"MyStomp",
",",
"self",
")",
".",
"connected",
"(",
"msg",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"connected: session %s\"",
"%",
"msg",
"[",
"'headers'",
"]",
"[",
"'session'",
"]",
")",
"f",
"=",
"stomper",
".",
"Frame",
"(",
")",
"f",
".",
"unpack",
"(",
"stomper",
".",
"subscribe",
"(",
"DESTINATION",
")",
")",
"return",
"f",
".",
"pack",
"(",
")"
] |
Once I've connected I want to subscribe to my the message queue.
|
[
"Once",
"I",
"ve",
"connected",
"I",
"want",
"to",
"subscribe",
"to",
"my",
"the",
"message",
"queue",
"."
] |
842ed2353a4ddd638d35929ae5b7b70eb298305c
|
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-rx.py#L37-L45
|
train
|
ambitioninc/django-entity
|
entity/signal_handlers.py
|
delete_entity_signal_handler
|
def delete_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted.
"""
if instance.__class__ in entity_registry.entity_registry:
Entity.all_objects.delete_for_obj(instance)
|
python
|
def delete_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted.
"""
if instance.__class__ in entity_registry.entity_registry:
Entity.all_objects.delete_for_obj(instance)
|
[
"def",
"delete_entity_signal_handler",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"__class__",
"in",
"entity_registry",
".",
"entity_registry",
":",
"Entity",
".",
"all_objects",
".",
"delete_for_obj",
"(",
"instance",
")"
] |
Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted.
|
[
"Defines",
"a",
"signal",
"handler",
"for",
"syncing",
"an",
"individual",
"entity",
".",
"Called",
"when",
"an",
"entity",
"is",
"saved",
"or",
"deleted",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/signal_handlers.py#L9-L15
|
train
|
ambitioninc/django-entity
|
entity/signal_handlers.py
|
save_entity_signal_handler
|
def save_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table.
"""
if instance.__class__ in entity_registry.entity_registry:
sync_entities(instance)
if instance.__class__ in entity_registry.entity_watching:
sync_entities_watching(instance)
|
python
|
def save_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table.
"""
if instance.__class__ in entity_registry.entity_registry:
sync_entities(instance)
if instance.__class__ in entity_registry.entity_watching:
sync_entities_watching(instance)
|
[
"def",
"save_entity_signal_handler",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"__class__",
"in",
"entity_registry",
".",
"entity_registry",
":",
"sync_entities",
"(",
"instance",
")",
"if",
"instance",
".",
"__class__",
"in",
"entity_registry",
".",
"entity_watching",
":",
"sync_entities_watching",
"(",
"instance",
")"
] |
Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table.
|
[
"Defines",
"a",
"signal",
"handler",
"for",
"saving",
"an",
"entity",
".",
"Syncs",
"the",
"entity",
"to",
"the",
"entity",
"mirror",
"table",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/signal_handlers.py#L18-L27
|
train
|
ambitioninc/django-entity
|
entity/signal_handlers.py
|
m2m_changed_entity_signal_handler
|
def m2m_changed_entity_signal_handler(sender, instance, action, **kwargs):
"""
Defines a signal handler for a manytomany changed signal. Only listens for the
post actions so that entities are synced once (rather than twice for a pre and post action).
"""
if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
save_entity_signal_handler(sender, instance, **kwargs)
|
python
|
def m2m_changed_entity_signal_handler(sender, instance, action, **kwargs):
"""
Defines a signal handler for a manytomany changed signal. Only listens for the
post actions so that entities are synced once (rather than twice for a pre and post action).
"""
if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
save_entity_signal_handler(sender, instance, **kwargs)
|
[
"def",
"m2m_changed_entity_signal_handler",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'post_add'",
"or",
"action",
"==",
"'post_remove'",
"or",
"action",
"==",
"'post_clear'",
":",
"save_entity_signal_handler",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")"
] |
Defines a signal handler for a manytomany changed signal. Only listens for the
post actions so that entities are synced once (rather than twice for a pre and post action).
|
[
"Defines",
"a",
"signal",
"handler",
"for",
"a",
"manytomany",
"changed",
"signal",
".",
"Only",
"listens",
"for",
"the",
"post",
"actions",
"so",
"that",
"entities",
"are",
"synced",
"once",
"(",
"rather",
"than",
"twice",
"for",
"a",
"pre",
"and",
"post",
"action",
")",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/signal_handlers.py#L30-L36
|
train
|
ambitioninc/django-entity
|
entity/signal_handlers.py
|
turn_off_syncing
|
def turn_off_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=True):
"""
Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants
to turn off everything but one signal, for example the post_save signal, they would do:
turn_off_sync(for_post_save=False)
"""
if for_post_save:
post_save.disconnect(save_entity_signal_handler, dispatch_uid='save_entity_signal_handler')
if for_post_delete:
post_delete.disconnect(delete_entity_signal_handler, dispatch_uid='delete_entity_signal_handler')
if for_m2m_changed:
m2m_changed.disconnect(m2m_changed_entity_signal_handler, dispatch_uid='m2m_changed_entity_signal_handler')
if for_post_bulk_operation:
post_bulk_operation.disconnect(bulk_operation_signal_handler, dispatch_uid='bulk_operation_signal_handler')
|
python
|
def turn_off_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=True):
"""
Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants
to turn off everything but one signal, for example the post_save signal, they would do:
turn_off_sync(for_post_save=False)
"""
if for_post_save:
post_save.disconnect(save_entity_signal_handler, dispatch_uid='save_entity_signal_handler')
if for_post_delete:
post_delete.disconnect(delete_entity_signal_handler, dispatch_uid='delete_entity_signal_handler')
if for_m2m_changed:
m2m_changed.disconnect(m2m_changed_entity_signal_handler, dispatch_uid='m2m_changed_entity_signal_handler')
if for_post_bulk_operation:
post_bulk_operation.disconnect(bulk_operation_signal_handler, dispatch_uid='bulk_operation_signal_handler')
|
[
"def",
"turn_off_syncing",
"(",
"for_post_save",
"=",
"True",
",",
"for_post_delete",
"=",
"True",
",",
"for_m2m_changed",
"=",
"True",
",",
"for_post_bulk_operation",
"=",
"True",
")",
":",
"if",
"for_post_save",
":",
"post_save",
".",
"disconnect",
"(",
"save_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'save_entity_signal_handler'",
")",
"if",
"for_post_delete",
":",
"post_delete",
".",
"disconnect",
"(",
"delete_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'delete_entity_signal_handler'",
")",
"if",
"for_m2m_changed",
":",
"m2m_changed",
".",
"disconnect",
"(",
"m2m_changed_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'m2m_changed_entity_signal_handler'",
")",
"if",
"for_post_bulk_operation",
":",
"post_bulk_operation",
".",
"disconnect",
"(",
"bulk_operation_signal_handler",
",",
"dispatch_uid",
"=",
"'bulk_operation_signal_handler'",
")"
] |
Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants
to turn off everything but one signal, for example the post_save signal, they would do:
turn_off_sync(for_post_save=False)
|
[
"Disables",
"all",
"of",
"the",
"signals",
"for",
"syncing",
"entities",
".",
"By",
"default",
"everything",
"is",
"turned",
"off",
".",
"If",
"the",
"user",
"wants",
"to",
"turn",
"off",
"everything",
"but",
"one",
"signal",
"for",
"example",
"the",
"post_save",
"signal",
"they",
"would",
"do",
":"
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/signal_handlers.py#L51-L65
|
train
|
ambitioninc/django-entity
|
entity/signal_handlers.py
|
turn_on_syncing
|
def turn_on_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=False):
"""
Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation
signal. The reason for this is because when any bulk operation occurs on any mirrored entity model, it will
result in every single entity being synced again. This is not a desired behavior by the majority of users, and
should only be turned on explicitly.
"""
if for_post_save:
post_save.connect(save_entity_signal_handler, dispatch_uid='save_entity_signal_handler')
if for_post_delete:
post_delete.connect(delete_entity_signal_handler, dispatch_uid='delete_entity_signal_handler')
if for_m2m_changed:
m2m_changed.connect(m2m_changed_entity_signal_handler, dispatch_uid='m2m_changed_entity_signal_handler')
if for_post_bulk_operation:
post_bulk_operation.connect(bulk_operation_signal_handler, dispatch_uid='bulk_operation_signal_handler')
|
python
|
def turn_on_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=False):
"""
Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation
signal. The reason for this is because when any bulk operation occurs on any mirrored entity model, it will
result in every single entity being synced again. This is not a desired behavior by the majority of users, and
should only be turned on explicitly.
"""
if for_post_save:
post_save.connect(save_entity_signal_handler, dispatch_uid='save_entity_signal_handler')
if for_post_delete:
post_delete.connect(delete_entity_signal_handler, dispatch_uid='delete_entity_signal_handler')
if for_m2m_changed:
m2m_changed.connect(m2m_changed_entity_signal_handler, dispatch_uid='m2m_changed_entity_signal_handler')
if for_post_bulk_operation:
post_bulk_operation.connect(bulk_operation_signal_handler, dispatch_uid='bulk_operation_signal_handler')
|
[
"def",
"turn_on_syncing",
"(",
"for_post_save",
"=",
"True",
",",
"for_post_delete",
"=",
"True",
",",
"for_m2m_changed",
"=",
"True",
",",
"for_post_bulk_operation",
"=",
"False",
")",
":",
"if",
"for_post_save",
":",
"post_save",
".",
"connect",
"(",
"save_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'save_entity_signal_handler'",
")",
"if",
"for_post_delete",
":",
"post_delete",
".",
"connect",
"(",
"delete_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'delete_entity_signal_handler'",
")",
"if",
"for_m2m_changed",
":",
"m2m_changed",
".",
"connect",
"(",
"m2m_changed_entity_signal_handler",
",",
"dispatch_uid",
"=",
"'m2m_changed_entity_signal_handler'",
")",
"if",
"for_post_bulk_operation",
":",
"post_bulk_operation",
".",
"connect",
"(",
"bulk_operation_signal_handler",
",",
"dispatch_uid",
"=",
"'bulk_operation_signal_handler'",
")"
] |
Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation
signal. The reason for this is because when any bulk operation occurs on any mirrored entity model, it will
result in every single entity being synced again. This is not a desired behavior by the majority of users, and
should only be turned on explicitly.
|
[
"Enables",
"all",
"of",
"the",
"signals",
"for",
"syncing",
"entities",
".",
"Everything",
"is",
"True",
"by",
"default",
"except",
"for",
"the",
"post_bulk_operation",
"signal",
".",
"The",
"reason",
"for",
"this",
"is",
"because",
"when",
"any",
"bulk",
"operation",
"occurs",
"on",
"any",
"mirrored",
"entity",
"model",
"it",
"will",
"result",
"in",
"every",
"single",
"entity",
"being",
"synced",
"again",
".",
"This",
"is",
"not",
"a",
"desired",
"behavior",
"by",
"the",
"majority",
"of",
"users",
"and",
"should",
"only",
"be",
"turned",
"on",
"explicitly",
"."
] |
ebc61f34313c52f4ef5819eb1da25b2ad837e80c
|
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/signal_handlers.py#L68-L82
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.add
|
def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value))
|
python
|
def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value))
|
[
"def",
"add",
"(",
"self",
",",
"value",
")",
":",
"# Raise TypeError if value is not hashable",
"hash",
"(",
"value",
")",
"self",
".",
"redis",
".",
"sadd",
"(",
"self",
".",
"key",
",",
"self",
".",
"_pickle",
"(",
"value",
")",
")"
] |
Add element *value* to the set.
|
[
"Add",
"element",
"*",
"value",
"*",
"to",
"the",
"set",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L78-L83
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.discard
|
def discard(self, value):
"""Remove element *value* from the set if it is present."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.srem(self.key, self._pickle(value))
|
python
|
def discard(self, value):
"""Remove element *value* from the set if it is present."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.srem(self.key, self._pickle(value))
|
[
"def",
"discard",
"(",
"self",
",",
"value",
")",
":",
"# Raise TypeError if value is not hashable",
"hash",
"(",
"value",
")",
"self",
".",
"redis",
".",
"srem",
"(",
"self",
".",
"key",
",",
"self",
".",
"_pickle",
"(",
"value",
")",
")"
] |
Remove element *value* from the set if it is present.
|
[
"Remove",
"element",
"*",
"value",
"*",
"from",
"the",
"set",
"if",
"it",
"is",
"present",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L95-L100
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.isdisjoint
|
def isdisjoint(self, other):
"""
Return ``True`` if the set has no elements in common with *other*.
Sets are disjoint if and only if their intersection is the empty set.
:param other: Any kind of iterable.
:rtype: boolean
"""
def isdisjoint_trans_pure(pipe):
return not pipe.sinter(self.key, other.key)
def isdisjoint_trans_mixed(pipe):
self_values = set(self.__iter__(pipe))
if use_redis:
other_values = set(other.__iter__(pipe))
else:
other_values = set(other)
return self_values.isdisjoint(other_values)
if self._same_redis(other):
return self._transaction(isdisjoint_trans_pure, other.key)
if self._same_redis(other, RedisCollection):
use_redis = True
return self._transaction(isdisjoint_trans_mixed, other.key)
use_redis = False
return self._transaction(isdisjoint_trans_mixed)
|
python
|
def isdisjoint(self, other):
"""
Return ``True`` if the set has no elements in common with *other*.
Sets are disjoint if and only if their intersection is the empty set.
:param other: Any kind of iterable.
:rtype: boolean
"""
def isdisjoint_trans_pure(pipe):
return not pipe.sinter(self.key, other.key)
def isdisjoint_trans_mixed(pipe):
self_values = set(self.__iter__(pipe))
if use_redis:
other_values = set(other.__iter__(pipe))
else:
other_values = set(other)
return self_values.isdisjoint(other_values)
if self._same_redis(other):
return self._transaction(isdisjoint_trans_pure, other.key)
if self._same_redis(other, RedisCollection):
use_redis = True
return self._transaction(isdisjoint_trans_mixed, other.key)
use_redis = False
return self._transaction(isdisjoint_trans_mixed)
|
[
"def",
"isdisjoint",
"(",
"self",
",",
"other",
")",
":",
"def",
"isdisjoint_trans_pure",
"(",
"pipe",
")",
":",
"return",
"not",
"pipe",
".",
"sinter",
"(",
"self",
".",
"key",
",",
"other",
".",
"key",
")",
"def",
"isdisjoint_trans_mixed",
"(",
"pipe",
")",
":",
"self_values",
"=",
"set",
"(",
"self",
".",
"__iter__",
"(",
"pipe",
")",
")",
"if",
"use_redis",
":",
"other_values",
"=",
"set",
"(",
"other",
".",
"__iter__",
"(",
"pipe",
")",
")",
"else",
":",
"other_values",
"=",
"set",
"(",
"other",
")",
"return",
"self_values",
".",
"isdisjoint",
"(",
"other_values",
")",
"if",
"self",
".",
"_same_redis",
"(",
"other",
")",
":",
"return",
"self",
".",
"_transaction",
"(",
"isdisjoint_trans_pure",
",",
"other",
".",
"key",
")",
"if",
"self",
".",
"_same_redis",
"(",
"other",
",",
"RedisCollection",
")",
":",
"use_redis",
"=",
"True",
"return",
"self",
".",
"_transaction",
"(",
"isdisjoint_trans_mixed",
",",
"other",
".",
"key",
")",
"use_redis",
"=",
"False",
"return",
"self",
".",
"_transaction",
"(",
"isdisjoint_trans_mixed",
")"
] |
Return ``True`` if the set has no elements in common with *other*.
Sets are disjoint if and only if their intersection is the empty set.
:param other: Any kind of iterable.
:rtype: boolean
|
[
"Return",
"True",
"if",
"the",
"set",
"has",
"no",
"elements",
"in",
"common",
"with",
"*",
"other",
"*",
".",
"Sets",
"are",
"disjoint",
"if",
"and",
"only",
"if",
"their",
"intersection",
"is",
"the",
"empty",
"set",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L102-L129
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.pop
|
def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError
return self._unpickle(result)
|
python
|
def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError
return self._unpickle(result)
|
[
"def",
"pop",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"redis",
".",
"spop",
"(",
"self",
".",
"key",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"KeyError",
"return",
"self",
".",
"_unpickle",
"(",
"result",
")"
] |
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
|
[
"Remove",
"and",
"return",
"an",
"arbitrary",
"element",
"from",
"the",
"set",
".",
"Raises",
":",
"exc",
":",
"KeyError",
"if",
"the",
"set",
"is",
"empty",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L131-L140
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.random_sample
|
def random_sample(self, k=1):
"""
Return a *k* length list of unique elements chosen from the Set.
Elements are not removed. Similar to :func:`random.sample` function
from standard library.
:param k: Size of the sample, defaults to 1.
:rtype: :class:`list`
"""
# k == 0: no work to do
if k == 0:
results = []
# k == 1: same behavior on all versions of Redis
elif k == 1:
results = [self.redis.srandmember(self.key)]
# k != 1, Redis version >= 2.6: compute in Redis
else:
results = self.redis.srandmember(self.key, k)
return [self._unpickle(x) for x in results]
|
python
|
def random_sample(self, k=1):
"""
Return a *k* length list of unique elements chosen from the Set.
Elements are not removed. Similar to :func:`random.sample` function
from standard library.
:param k: Size of the sample, defaults to 1.
:rtype: :class:`list`
"""
# k == 0: no work to do
if k == 0:
results = []
# k == 1: same behavior on all versions of Redis
elif k == 1:
results = [self.redis.srandmember(self.key)]
# k != 1, Redis version >= 2.6: compute in Redis
else:
results = self.redis.srandmember(self.key, k)
return [self._unpickle(x) for x in results]
|
[
"def",
"random_sample",
"(",
"self",
",",
"k",
"=",
"1",
")",
":",
"# k == 0: no work to do",
"if",
"k",
"==",
"0",
":",
"results",
"=",
"[",
"]",
"# k == 1: same behavior on all versions of Redis",
"elif",
"k",
"==",
"1",
":",
"results",
"=",
"[",
"self",
".",
"redis",
".",
"srandmember",
"(",
"self",
".",
"key",
")",
"]",
"# k != 1, Redis version >= 2.6: compute in Redis",
"else",
":",
"results",
"=",
"self",
".",
"redis",
".",
"srandmember",
"(",
"self",
".",
"key",
",",
"k",
")",
"return",
"[",
"self",
".",
"_unpickle",
"(",
"x",
")",
"for",
"x",
"in",
"results",
"]"
] |
Return a *k* length list of unique elements chosen from the Set.
Elements are not removed. Similar to :func:`random.sample` function
from standard library.
:param k: Size of the sample, defaults to 1.
:rtype: :class:`list`
|
[
"Return",
"a",
"*",
"k",
"*",
"length",
"list",
"of",
"unique",
"elements",
"chosen",
"from",
"the",
"Set",
".",
"Elements",
"are",
"not",
"removed",
".",
"Similar",
"to",
":",
"func",
":",
"random",
".",
"sample",
"function",
"from",
"standard",
"library",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L142-L162
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.remove
|
def remove(self, value):
"""
Remove element *value* from the set. Raises :exc:`KeyError` if it
is not contained in the set.
"""
# Raise TypeError if value is not hashable
hash(value)
result = self.redis.srem(self.key, self._pickle(value))
if not result:
raise KeyError(value)
|
python
|
def remove(self, value):
"""
Remove element *value* from the set. Raises :exc:`KeyError` if it
is not contained in the set.
"""
# Raise TypeError if value is not hashable
hash(value)
result = self.redis.srem(self.key, self._pickle(value))
if not result:
raise KeyError(value)
|
[
"def",
"remove",
"(",
"self",
",",
"value",
")",
":",
"# Raise TypeError if value is not hashable",
"hash",
"(",
"value",
")",
"result",
"=",
"self",
".",
"redis",
".",
"srem",
"(",
"self",
".",
"key",
",",
"self",
".",
"_pickle",
"(",
"value",
")",
")",
"if",
"not",
"result",
":",
"raise",
"KeyError",
"(",
"value",
")"
] |
Remove element *value* from the set. Raises :exc:`KeyError` if it
is not contained in the set.
|
[
"Remove",
"element",
"*",
"value",
"*",
"from",
"the",
"set",
".",
"Raises",
":",
"exc",
":",
"KeyError",
"if",
"it",
"is",
"not",
"contained",
"in",
"the",
"set",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L164-L174
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.scan_elements
|
def scan_elements(self):
"""
Yield each of the elements from the collection, without pulling them
all into memory.
.. warning::
This method is not available on the set collections provided
by Python.
This method may return the element multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for x in self.redis.sscan_iter(self.key):
yield self._unpickle(x)
|
python
|
def scan_elements(self):
"""
Yield each of the elements from the collection, without pulling them
all into memory.
.. warning::
This method is not available on the set collections provided
by Python.
This method may return the element multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for x in self.redis.sscan_iter(self.key):
yield self._unpickle(x)
|
[
"def",
"scan_elements",
"(",
"self",
")",
":",
"for",
"x",
"in",
"self",
".",
"redis",
".",
"sscan_iter",
"(",
"self",
".",
"key",
")",
":",
"yield",
"self",
".",
"_unpickle",
"(",
"x",
")"
] |
Yield each of the elements from the collection, without pulling them
all into memory.
.. warning::
This method is not available on the set collections provided
by Python.
This method may return the element multiple times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
|
[
"Yield",
"each",
"of",
"the",
"elements",
"from",
"the",
"collection",
"without",
"pulling",
"them",
"all",
"into",
"memory",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L176-L190
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.intersection_update
|
def intersection_update(self, *others):
"""
Update the set, keeping only elements found in it and all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`difference_update` applies.
"""
return self._op_update_helper(
tuple(others), operator.and_, 'sinterstore', update=True
)
|
python
|
def intersection_update(self, *others):
"""
Update the set, keeping only elements found in it and all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`difference_update` applies.
"""
return self._op_update_helper(
tuple(others), operator.and_, 'sinterstore', update=True
)
|
[
"def",
"intersection_update",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"_op_update_helper",
"(",
"tuple",
"(",
"others",
")",
",",
"operator",
".",
"and_",
",",
"'sinterstore'",
",",
"update",
"=",
"True",
")"
] |
Update the set, keeping only elements found in it and all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`difference_update` applies.
|
[
"Update",
"the",
"set",
"keeping",
"only",
"elements",
"found",
"in",
"it",
"and",
"all",
"*",
"others",
"*",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L387-L399
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.update
|
def update(self, *others):
"""
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely in Redis. Otherwise, values are retrieved
from Redis and the operation is performed in Python.
"""
return self._op_update_helper(
tuple(others), operator.or_, 'sunionstore', update=True
)
|
python
|
def update(self, *others):
"""
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely in Redis. Otherwise, values are retrieved
from Redis and the operation is performed in Python.
"""
return self._op_update_helper(
tuple(others), operator.or_, 'sunionstore', update=True
)
|
[
"def",
"update",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"_op_update_helper",
"(",
"tuple",
"(",
"others",
")",
",",
"operator",
".",
"or_",
",",
"'sunionstore'",
",",
"update",
"=",
"True",
")"
] |
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely in Redis. Otherwise, values are retrieved
from Redis and the operation is performed in Python.
|
[
"Update",
"the",
"set",
"adding",
"elements",
"from",
"all",
"*",
"others",
"*",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L466-L480
|
train
|
honzajavorek/redis-collections
|
redis_collections/sets.py
|
Set.difference_update
|
def difference_update(self, *others):
"""
Update the set, removing elements found in *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`update` applies.
"""
return self._op_update_helper(
tuple(others), operator.sub, 'sdiffstore', update=True
)
|
python
|
def difference_update(self, *others):
"""
Update the set, removing elements found in *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`update` applies.
"""
return self._op_update_helper(
tuple(others), operator.sub, 'sdiffstore', update=True
)
|
[
"def",
"difference_update",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"_op_update_helper",
"(",
"tuple",
"(",
"others",
")",
",",
"operator",
".",
"sub",
",",
"'sdiffstore'",
",",
"update",
"=",
"True",
")"
] |
Update the set, removing elements found in *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`update` applies.
|
[
"Update",
"the",
"set",
"removing",
"elements",
"found",
"in",
"*",
"others",
"*",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L510-L522
|
train
|
honzajavorek/redis-collections
|
redis_collections/sortedsets.py
|
SortedSetBase.discard_member
|
def discard_member(self, member, pipe=None):
"""
Remove *member* from the collection, unconditionally.
"""
pipe = self.redis if pipe is None else pipe
pipe.zrem(self.key, self._pickle(member))
|
python
|
def discard_member(self, member, pipe=None):
"""
Remove *member* from the collection, unconditionally.
"""
pipe = self.redis if pipe is None else pipe
pipe.zrem(self.key, self._pickle(member))
|
[
"def",
"discard_member",
"(",
"self",
",",
"member",
",",
"pipe",
"=",
"None",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"pipe",
".",
"zrem",
"(",
"self",
".",
"key",
",",
"self",
".",
"_pickle",
"(",
"member",
")",
")"
] |
Remove *member* from the collection, unconditionally.
|
[
"Remove",
"*",
"member",
"*",
"from",
"the",
"collection",
"unconditionally",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L59-L64
|
train
|
honzajavorek/redis-collections
|
redis_collections/sortedsets.py
|
SortedSetBase.scan_items
|
def scan_items(self):
"""
Yield each of the ``(member, score)`` tuples from the collection,
without pulling them all into memory.
.. warning::
This method may return the same (member, score) tuple multiple
times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for m, s in self.redis.zscan_iter(self.key):
yield self._unpickle(m), s
|
python
|
def scan_items(self):
"""
Yield each of the ``(member, score)`` tuples from the collection,
without pulling them all into memory.
.. warning::
This method may return the same (member, score) tuple multiple
times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
"""
for m, s in self.redis.zscan_iter(self.key):
yield self._unpickle(m), s
|
[
"def",
"scan_items",
"(",
"self",
")",
":",
"for",
"m",
",",
"s",
"in",
"self",
".",
"redis",
".",
"zscan_iter",
"(",
"self",
".",
"key",
")",
":",
"yield",
"self",
".",
"_unpickle",
"(",
"m",
")",
",",
"s"
] |
Yield each of the ``(member, score)`` tuples from the collection,
without pulling them all into memory.
.. warning::
This method may return the same (member, score) tuple multiple
times.
See the `Redis SCAN documentation
<http://redis.io/commands/scan#scan-guarantees>`_ for details.
|
[
"Yield",
"each",
"of",
"the",
"(",
"member",
"score",
")",
"tuples",
"from",
"the",
"collection",
"without",
"pulling",
"them",
"all",
"into",
"memory",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L66-L78
|
train
|
honzajavorek/redis-collections
|
redis_collections/sortedsets.py
|
SortedSetBase.update
|
def update(self, other):
"""
Update the collection with items from *other*. Accepts other
:class:`SortedSetBase` instances, dictionaries mapping members to
numeric scores, or sequences of ``(member, score)`` tuples.
"""
def update_trans(pipe):
other_items = method(pipe=pipe) if use_redis else method()
pipe.multi()
for member, score in other_items:
pipe.zadd(self.key, {self._pickle(member): float(score)})
watches = []
if self._same_redis(other, RedisCollection):
use_redis = True
watches.append(other.key)
else:
use_redis = False
if hasattr(other, 'items'):
method = other.items
elif hasattr(other, '__iter__'):
method = other.__iter__
self._transaction(update_trans, *watches)
|
python
|
def update(self, other):
"""
Update the collection with items from *other*. Accepts other
:class:`SortedSetBase` instances, dictionaries mapping members to
numeric scores, or sequences of ``(member, score)`` tuples.
"""
def update_trans(pipe):
other_items = method(pipe=pipe) if use_redis else method()
pipe.multi()
for member, score in other_items:
pipe.zadd(self.key, {self._pickle(member): float(score)})
watches = []
if self._same_redis(other, RedisCollection):
use_redis = True
watches.append(other.key)
else:
use_redis = False
if hasattr(other, 'items'):
method = other.items
elif hasattr(other, '__iter__'):
method = other.__iter__
self._transaction(update_trans, *watches)
|
[
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"def",
"update_trans",
"(",
"pipe",
")",
":",
"other_items",
"=",
"method",
"(",
"pipe",
"=",
"pipe",
")",
"if",
"use_redis",
"else",
"method",
"(",
")",
"pipe",
".",
"multi",
"(",
")",
"for",
"member",
",",
"score",
"in",
"other_items",
":",
"pipe",
".",
"zadd",
"(",
"self",
".",
"key",
",",
"{",
"self",
".",
"_pickle",
"(",
"member",
")",
":",
"float",
"(",
"score",
")",
"}",
")",
"watches",
"=",
"[",
"]",
"if",
"self",
".",
"_same_redis",
"(",
"other",
",",
"RedisCollection",
")",
":",
"use_redis",
"=",
"True",
"watches",
".",
"append",
"(",
"other",
".",
"key",
")",
"else",
":",
"use_redis",
"=",
"False",
"if",
"hasattr",
"(",
"other",
",",
"'items'",
")",
":",
"method",
"=",
"other",
".",
"items",
"elif",
"hasattr",
"(",
"other",
",",
"'__iter__'",
")",
":",
"method",
"=",
"other",
".",
"__iter__",
"self",
".",
"_transaction",
"(",
"update_trans",
",",
"*",
"watches",
")"
] |
Update the collection with items from *other*. Accepts other
:class:`SortedSetBase` instances, dictionaries mapping members to
numeric scores, or sequences of ``(member, score)`` tuples.
|
[
"Update",
"the",
"collection",
"with",
"items",
"from",
"*",
"other",
"*",
".",
"Accepts",
"other",
":",
"class",
":",
"SortedSetBase",
"instances",
"dictionaries",
"mapping",
"members",
"to",
"numeric",
"scores",
"or",
"sequences",
"of",
"(",
"member",
"score",
")",
"tuples",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L80-L105
|
train
|
honzajavorek/redis-collections
|
redis_collections/sortedsets.py
|
SortedSetCounter.count_between
|
def count_between(self, min_score=None, max_score=None):
"""
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
"""
min_score = float('-inf') if min_score is None else float(min_score)
max_score = float('inf') if max_score is None else float(max_score)
return self.redis.zcount(self.key, min_score, max_score)
|
python
|
def count_between(self, min_score=None, max_score=None):
"""
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
"""
min_score = float('-inf') if min_score is None else float(min_score)
max_score = float('inf') if max_score is None else float(max_score)
return self.redis.zcount(self.key, min_score, max_score)
|
[
"def",
"count_between",
"(",
"self",
",",
"min_score",
"=",
"None",
",",
"max_score",
"=",
"None",
")",
":",
"min_score",
"=",
"float",
"(",
"'-inf'",
")",
"if",
"min_score",
"is",
"None",
"else",
"float",
"(",
"min_score",
")",
"max_score",
"=",
"float",
"(",
"'inf'",
")",
"if",
"max_score",
"is",
"None",
"else",
"float",
"(",
"max_score",
")",
"return",
"self",
".",
"redis",
".",
"zcount",
"(",
"self",
".",
"key",
",",
"min_score",
",",
"max_score",
")"
] |
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
|
[
"Returns",
"the",
"number",
"of",
"members",
"whose",
"score",
"is",
"between",
"*",
"min_score",
"*",
"and",
"*",
"max_score",
"*",
"(",
"inclusive",
")",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L178-L186
|
train
|
honzajavorek/redis-collections
|
redis_collections/sortedsets.py
|
SortedSetCounter.discard_between
|
def discard_between(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
):
"""
Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If no bounds are specified, no members will be removed.
"""
no_ranks = (min_rank is None) and (max_rank is None)
no_scores = (min_score is None) and (max_score is None)
# Default scope: nothing
if no_ranks and no_scores:
return
# Scope widens to given score range
if no_ranks and (not no_scores):
return self.discard_by_score(min_score, max_score)
# Scope widens to given rank range
if (not no_ranks) and no_scores:
return self.discard_by_rank(min_rank, max_rank)
# Scope widens to score range and then rank range
with self.redis.pipeline() as pipe:
self.discard_by_score(min_score, max_score, pipe)
self.discard_by_rank(min_rank, max_rank, pipe)
pipe.execute()
|
python
|
def discard_between(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
):
"""
Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If no bounds are specified, no members will be removed.
"""
no_ranks = (min_rank is None) and (max_rank is None)
no_scores = (min_score is None) and (max_score is None)
# Default scope: nothing
if no_ranks and no_scores:
return
# Scope widens to given score range
if no_ranks and (not no_scores):
return self.discard_by_score(min_score, max_score)
# Scope widens to given rank range
if (not no_ranks) and no_scores:
return self.discard_by_rank(min_rank, max_rank)
# Scope widens to score range and then rank range
with self.redis.pipeline() as pipe:
self.discard_by_score(min_score, max_score, pipe)
self.discard_by_rank(min_rank, max_rank, pipe)
pipe.execute()
|
[
"def",
"discard_between",
"(",
"self",
",",
"min_rank",
"=",
"None",
",",
"max_rank",
"=",
"None",
",",
"min_score",
"=",
"None",
",",
"max_score",
"=",
"None",
",",
")",
":",
"no_ranks",
"=",
"(",
"min_rank",
"is",
"None",
")",
"and",
"(",
"max_rank",
"is",
"None",
")",
"no_scores",
"=",
"(",
"min_score",
"is",
"None",
")",
"and",
"(",
"max_score",
"is",
"None",
")",
"# Default scope: nothing",
"if",
"no_ranks",
"and",
"no_scores",
":",
"return",
"# Scope widens to given score range",
"if",
"no_ranks",
"and",
"(",
"not",
"no_scores",
")",
":",
"return",
"self",
".",
"discard_by_score",
"(",
"min_score",
",",
"max_score",
")",
"# Scope widens to given rank range",
"if",
"(",
"not",
"no_ranks",
")",
"and",
"no_scores",
":",
"return",
"self",
".",
"discard_by_rank",
"(",
"min_rank",
",",
"max_rank",
")",
"# Scope widens to score range and then rank range",
"with",
"self",
".",
"redis",
".",
"pipeline",
"(",
")",
"as",
"pipe",
":",
"self",
".",
"discard_by_score",
"(",
"min_score",
",",
"max_score",
",",
"pipe",
")",
"self",
".",
"discard_by_rank",
"(",
"min_rank",
",",
"max_rank",
",",
"pipe",
")",
"pipe",
".",
"execute",
"(",
")"
] |
Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If no bounds are specified, no members will be removed.
|
[
"Remove",
"members",
"whose",
"ranking",
"is",
"between",
"*",
"min_rank",
"*",
"and",
"*",
"max_rank",
"*",
"OR",
"whose",
"score",
"is",
"between",
"*",
"min_score",
"*",
"and",
"*",
"max_score",
"*",
"(",
"both",
"ranges",
"inclusive",
")",
".",
"If",
"no",
"bounds",
"are",
"specified",
"no",
"members",
"will",
"be",
"removed",
"."
] |
07ca8efe88fb128f7dc7319dfa6a26cd39b3776b
|
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L204-L235
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.