sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def construct_request_uri(local_dir, base_path, **kwargs):
"""
Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to start with
:para... | Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to start with
:param kwargs:
:return: 2-tuple with (filename, url) | entailment |
def init_services(service_definitions, service_context, state_db,
client_authn_factory=None):
"""
Initiates a set of services
:param service_definitions: A dictionary cotaining service definitions
:param service_context: A reference to the service context, this is the same
for... | Initiates a set of services
:param service_definitions: A dictionary cotaining service definitions
:param service_context: A reference to the service context, this is the same
for all service instances.
:param state_db: A reference to the state database. Shared by all the
services.
:par... | entailment |
def gather_request_args(self, **kwargs):
"""
Go through the attributes that the message class can contain and
add values if they are missing but exists in the client info or
when there are default values.
:param kwargs: Initial set of attributes.
:return: Possibly augmen... | Go through the attributes that the message class can contain and
add values if they are missing but exists in the client info or
when there are default values.
:param kwargs: Initial set of attributes.
:return: Possibly augmented set of attributes | entailment |
def method_args(self, context, **kwargs):
"""
Collect the set of arguments that should be used by a set of methods
:param context: Which service we're working for
:param kwargs: A set of keyword arguments that are added at run-time.
:return: A set of keyword arguments
""... | Collect the set of arguments that should be used by a set of methods
:param context: Which service we're working for
:param kwargs: A set of keyword arguments that are added at run-time.
:return: A set of keyword arguments | entailment |
def do_pre_construct(self, request_args, **kwargs):
"""
Will run the pre_construct methods one by one in the order given.
:param request_args: Request arguments
:param kwargs: Extra key word arguments
:return: A tuple of request_args and post_args. post_args are to be
... | Will run the pre_construct methods one by one in the order given.
:param request_args: Request arguments
:param kwargs: Extra key word arguments
:return: A tuple of request_args and post_args. post_args are to be
used by the post_construct methods. | entailment |
def do_post_construct(self, request_args, **kwargs):
"""
Will run the post_construct methods one at the time in order.
:param request_args: Request arguments
:param kwargs: Arguments used by the post_construct method
:return: Possible modified set of request arguments.
"... | Will run the post_construct methods one at the time in order.
:param request_args: Request arguments
:param kwargs: Arguments used by the post_construct method
:return: Possible modified set of request arguments. | entailment |
def construct(self, request_args=None, **kwargs):
"""
Instantiate the request as a message class instance with
attribute values gathered in a pre_construct method or in the
gather_request_args method.
:param request_args:
:param kwargs: extra keyword arguments
:r... | Instantiate the request as a message class instance with
attribute values gathered in a pre_construct method or in the
gather_request_args method.
:param request_args:
:param kwargs: extra keyword arguments
:return: message class instance | entailment |
def init_authentication_method(self, request, authn_method,
http_args=None, **kwargs):
"""
Will run the proper client authentication method.
Each such method will place the necessary information in the necessary
place. A method may modify the request.
... | Will run the proper client authentication method.
Each such method will place the necessary information in the necessary
place. A method may modify the request.
:param request: The request, a Message class instance
:param authn_method: Client authentication method
:param http_ar... | entailment |
def construct_request(self, request_args=None, **kwargs):
"""
The method where everything is setup for sending the request.
The request information is gathered and the where and how of sending the
request is decided.
:param request_args: Initial request arguments
:param ... | The method where everything is setup for sending the request.
The request information is gathered and the where and how of sending the
request is decided.
:param request_args: Initial request arguments
:param kwargs: Extra keyword arguments
:return: A dictionary with the keys 'u... | entailment |
def get_endpoint(self):
"""
Find the service endpoint
:return: The service endpoint (a URL)
"""
if self.endpoint:
return self.endpoint
else:
return self.service_context.provider_info[self.endpoint_name] | Find the service endpoint
:return: The service endpoint (a URL) | entailment |
def get_authn_header(self, request, authn_method, **kwargs):
"""
Construct an authorization specification to be sent in the
HTTP header.
:param request: The service request
:param authn_method: Which authentication/authorization method to use
:param kwargs: Extra keyword... | Construct an authorization specification to be sent in the
HTTP header.
:param request: The service request
:param authn_method: Which authentication/authorization method to use
:param kwargs: Extra keyword arguments
:return: A set of keyword arguments to be sent in the HTTP hea... | entailment |
def get_request_parameters(self, request_body_type="", method="",
authn_method='', request_args=None,
http_args=None, **kwargs):
"""
Builds the request message and constructs the HTTP headers.
This is the starting point for a pipelin... | Builds the request message and constructs the HTTP headers.
This is the starting point for a pipeline that will:
- construct the request message
- add/remove information to/from the request message in the way a
specific client authentication method requires.
- gather a set ... | entailment |
def get_urlinfo(info):
"""
Pick out the fragment or query part from a URL.
:param info: A URL possibly containing a query or a fragment part
:return: the query/fragment part
"""
# If info is a whole URL pick out the query or fragment part
if '?' in info or '#' in... | Pick out the fragment or query part from a URL.
:param info: A URL possibly containing a query or a fragment part
:return: the query/fragment part | entailment |
def gather_verify_arguments(self):
"""
Need to add some information before running verify()
:return: dictionary with arguments to the verify call
"""
kwargs = {'client_id': self.service_context.client_id,
'iss': self.service_context.issuer,
'... | Need to add some information before running verify()
:return: dictionary with arguments to the verify call | entailment |
def parse_response(self, info, sformat="", state="", **kwargs):
"""
This the start of a pipeline that will:
1 Deserializes a response into it's response message class.
Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error
message
2 verifies the... | This the start of a pipeline that will:
1 Deserializes a response into it's response message class.
Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error
message
2 verifies the correctness of the response by running the
verify method belonging to... | entailment |
def get_conf_attr(self, attr, default=None):
"""
Get the value of a attribute in the configuration
:param attr: The attribute
:param default: If the attribute doesn't appear in the configuration
return this value
:return: The value of attribute in the configuration o... | Get the value of a attribute in the configuration
:param attr: The attribute
:param default: If the attribute doesn't appear in the configuration
return this value
:return: The value of attribute in the configuration or the default
value | entailment |
def add_code_challenge(request_args, service, **kwargs):
"""
PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.Authorization` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:para... | PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.Authorization` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:param kwargs: Extra set of keyword arguments
:return: Updated set of ... | entailment |
def add_code_verifier(request_args, service, **kwargs):
"""
PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.AccessToken` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:return:... | PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.AccessToken` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:return: updated set of request arguments | entailment |
def gather_verify_arguments(self):
"""
Need to add some information before running verify()
:return: dictionary with arguments to the verify call
"""
_ctx = self.service_context
kwargs = {
'client_id': _ctx.client_id, 'iss': _ctx.issuer,
'keyjar':... | Need to add some information before running verify()
:return: dictionary with arguments to the verify call | entailment |
def post_parse_response(self, response, **kwargs):
"""
Add scope claim to response, from the request, if not present in the
response
:param response: The response
:param kwargs: Extra Keyword arguments
:return: A possibly augmented response
"""
if "scope... | Add scope claim to response, from the request, if not present in the
response
:param response: The response
:param kwargs: Extra Keyword arguments
:return: A possibly augmented response | entailment |
def get_id_token_hint(self, request_args=None, **kwargs):
"""
Add id_token_hint to request
:param request_args:
:param kwargs:
:return:
"""
request_args = self.multiple_extend_request_args(
request_args, kwargs['state'], ['id_token'],
['au... | Add id_token_hint to request
:param request_args:
:param kwargs:
:return: | entailment |
def get_state(self, key):
"""
Get the state connected to a given key.
:param key: Key into the state database
:return: A :py:class:´oidcservice.state_interface.State` instance
"""
_data = self.state_db.get(key)
if not _data:
raise KeyError(key)
... | Get the state connected to a given key.
:param key: Key into the state database
:return: A :py:class:´oidcservice.state_interface.State` instance | entailment |
def store_item(self, item, item_type, key):
"""
Store a service response.
:param item: The item as a :py:class:`oidcmsg.message.Message`
subclass instance or a JSON document.
:param item_type: The type of request or response
:param key: The key under which the inform... | Store a service response.
:param item: The item as a :py:class:`oidcmsg.message.Message`
subclass instance or a JSON document.
:param item_type: The type of request or response
:param key: The key under which the information should be stored in
the state database | entailment |
def get_iss(self, key):
"""
Get the Issuer ID
:param key: Key to the information in the state database
:return: The issuer ID
"""
_state = self.get_state(key)
if not _state:
raise KeyError(key)
return _state['iss'] | Get the Issuer ID
:param key: Key to the information in the state database
:return: The issuer ID | entailment |
def get_item(self, item_cls, item_type, key):
"""
Get a piece of information (a request or a response) from the state
database.
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
that described the item.
:param item_type: Which request/response that is... | Get a piece of information (a request or a response) from the state
database.
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
that described the item.
:param item_type: Which request/response that is wanted
:param key: The key to the information in the stat... | entailment |
def extend_request_args(self, args, item_cls, item_type, key,
parameters, orig=False):
"""
Add a set of parameters and their value to a set of request arguments.
:param args: A dictionary
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
... | Add a set of parameters and their value to a set of request arguments.
:param args: A dictionary
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
that describes the item
:param item_type: The type of item, this is one of the parameter
names in the :py:cl... | entailment |
def multiple_extend_request_args(self, args, key, parameters, item_types,
orig=False):
"""
Go through a set of items (by their type) and add the attribute-value
that match the list of parameters to the arguments
If the same parameter occurs in 2 diffe... | Go through a set of items (by their type) and add the attribute-value
that match the list of parameters to the arguments
If the same parameter occurs in 2 different items then the value in
the later one will be the one used.
:param args: Initial set of arguments
:param key: Key ... | entailment |
def store_X2state(self, x, state, xtyp):
"""
Store the connection between some value (x) and a state value.
This allows us later in the game to find the state if we have x.
:param x: The value of x
:param state: The state value
:param xtyp: The type of value x is (e.g. n... | Store the connection between some value (x) and a state value.
This allows us later in the game to find the state if we have x.
:param x: The value of x
:param state: The state value
:param xtyp: The type of value x is (e.g. nonce, ...) | entailment |
def get_state_by_X(self, x, xtyp):
"""
Find the state value by providing the x value.
Will raise an exception if the x value is absent from the state
data base.
:param x: The x value
:return: The state value
"""
_state = self.state_db.get(KEY_PATTERN[xtyp... | Find the state value by providing the x value.
Will raise an exception if the x value is absent from the state
data base.
:param x: The x value
:return: The state value | entailment |
def filename_from_webname(self, webname):
"""
A 1<->1 map is maintained between a URL pointing to a file and
the name of the file in the file system.
As an example if the base_url is 'https://example.com' and a jwks_uri
is 'https://example.com/jwks_uri.json' then the filename of... | A 1<->1 map is maintained between a URL pointing to a file and
the name of the file in the file system.
As an example if the base_url is 'https://example.com' and a jwks_uri
is 'https://example.com/jwks_uri.json' then the filename of the
corresponding file on the local filesystem would ... | entailment |
def generate_request_uris(self, path):
"""
Need to generate a redirect_uri path that is unique for a OP/RP combo
This is to counter the mix-up attack.
:param path: Leading path
:return: A list of one unique URL
"""
m = hashlib.sha256()
try:
m.... | Need to generate a redirect_uri path that is unique for a OP/RP combo
This is to counter the mix-up attack.
:param path: Leading path
:return: A list of one unique URL | entailment |
def import_keys(self, keyspec):
"""
The client needs it's own set of keys. It can either dynamically
create them or load them from local storage.
This method can also fetch other entities keys provided the
URL points to a JWKS.
:param keyspec:
"""
for whe... | The client needs it's own set of keys. It can either dynamically
create them or load them from local storage.
This method can also fetch other entities keys provided the
URL points to a JWKS.
:param keyspec: | entailment |
def assertion_jwt(client_id, keys, audience, algorithm, lifetime=600):
"""
Create a signed Json Web Token containing some information.
:param client_id: The Client ID
:param keys: Signing keys
:param audience: Who is the receivers for this assertion
:param algorithm: Signing algorithm
:para... | Create a signed Json Web Token containing some information.
:param client_id: The Client ID
:param keys: Signing keys
:param audience: Who is the receivers for this assertion
:param algorithm: Signing algorithm
:param lifetime: The lifetime of the signed Json Web Token
:return: A Signed Json We... | entailment |
def find_token(request, token_type, service, **kwargs):
"""
The access token can be in a number of places.
There are priority rules as to which one to use, abide by those:
1 If it's among the request parameters use that
2 If among the extra keyword arguments
3 Acquired by a previous run service... | The access token can be in a number of places.
There are priority rules as to which one to use, abide by those:
1 If it's among the request parameters use that
2 If among the extra keyword arguments
3 Acquired by a previous run service.
:param request:
:param token_type:
:param service:
... | entailment |
def valid_service_context(service_context, when=0):
"""
Check if the client_secret has expired
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:param when: A time stamp against which the expiration time is to be checked
:return: True if the client_s... | Check if the client_secret has expired
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:param when: A time stamp against which the expiration time is to be checked
:return: True if the client_secret is still valid | entailment |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Construct a dictionary to be added to the HTTP request headers
:param request: The request
:param service: A
:py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
... | Construct a dictionary to be added to the HTTP request headers
:param request: The request
:param service: A
:py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
:return: dictionary of HTTP arguments | entailment |
def construct(self, request=None, service=None, http_args=None,
**kwargs):
"""
Constructing the Authorization header. The value of
the Authorization header is "Bearer <access_token>".
:param request: Request class instance
:param service: Service
:param... | Constructing the Authorization header. The value of
the Authorization header is "Bearer <access_token>".
:param request: Request class instance
:param service: Service
:param http_args: HTTP header arguments
:param kwargs: extra keyword arguments
:return: | entailment |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Will add a token to the request if not present
:param request: The request
:param service_context: A
:py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
:p... | Will add a token to the request if not present
:param request: The request
:param service_context: A
:py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
:param kwargs: extra keyword arguments
:return: A possibly modified dictionary with ... | entailment |
def choose_algorithm(self, context, **kwargs):
"""
Pick signing algorithm
:param context: Signing context
:param kwargs: extra keyword arguments
:return: Name of a signing algorithm
"""
try:
algorithm = kwargs["algorithm"]
except KeyError:
... | Pick signing algorithm
:param context: Signing context
:param kwargs: extra keyword arguments
:return: Name of a signing algorithm | entailment |
def get_signing_key(self, algorithm, service_context):
"""
Pick signing key based on signing algorithm to be used
:param algorithm: Signing algorithm
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:return: A key
"""
... | Pick signing key based on signing algorithm to be used
:param algorithm: Signing algorithm
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:return: A key | entailment |
def get_key_by_kid(self, kid, algorithm, service_context):
"""
Pick a key that matches a given key ID and signing algorithm.
:param kid: Key ID
:param algorithm: Signing algorithm
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instan... | Pick a key that matches a given key ID and signing algorithm.
:param kid: Key ID
:param algorithm: Signing algorithm
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:return: A matching key | entailment |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Constructs a client assertion and signs it with a key.
The request is modified as a side effect.
:param request: The request
:param service: A :py:class:`oidcservice.service.Service` instance
:para... | Constructs a client assertion and signs it with a key.
The request is modified as a side effect.
:param request: The request
:param service: A :py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
:param kwargs: Extra arguments
:return: Constr... | entailment |
def get_endpoint(self):
"""
Find the issuer ID and from it construct the service endpoint
:return: Service endpoint
"""
try:
_iss = self.service_context.issuer
except AttributeError:
_iss = self.endpoint
if _iss.endswith('/'):
... | Find the issuer ID and from it construct the service endpoint
:return: Service endpoint | entailment |
def _update_service_context(self, resp, **kwargs):
"""
Deal with Provider Config Response. Based on the provider info
response a set of parameters in different places needs to be set.
:param resp: The provider info response
:param service_context: Information collected/used by s... | Deal with Provider Config Response. Based on the provider info
response a set of parameters in different places needs to be set.
:param resp: The provider info response
:param service_context: Information collected/used by services | entailment |
def query(self, resource):
"""
Given a resource identifier find the domain specifier and then
construct the webfinger request. Implements
http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps
:param resource:
"""
if resource[0] in ['=', '@'... | Given a resource identifier find the domain specifier and then
construct the webfinger request. Implements
http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps
:param resource: | entailment |
def get_http_url(url, req, method='GET'):
"""
Add a query part representing the request to a url that may already contain
a query part. Only done if the HTTP method used is 'GET' or 'DELETE'.
:param url: The URL
:param req: The request as a :py:class:`oidcmsg.message.Message` instance
:param me... | Add a query part representing the request to a url that may already contain
a query part. Only done if the HTTP method used is 'GET' or 'DELETE'.
:param url: The URL
:param req: The request as a :py:class:`oidcmsg.message.Message` instance
:param method: The HTTP method
:return: A possibly modified... | entailment |
def get_http_body(req, content_type=URL_ENCODED):
"""
Get the message into the format that should be places in the body part
of a HTTP request.
:param req: The service request as a :py:class:`oidcmsg.message.Message`
instance
:param content_type: The format of the body part.
:return: T... | Get the message into the format that should be places in the body part
of a HTTP request.
:param req: The service request as a :py:class:`oidcmsg.message.Message`
instance
:param content_type: The format of the body part.
:return: The correctly formatet service request. | entailment |
def modsplit(s):
"""Split importable"""
if ':' in s:
c = s.split(':')
if len(c) != 2:
raise ValueError("Syntax error: {s}")
return c[0], c[1]
else:
c = s.split('.')
if len(c) < 2:
raise ValueError("Syntax error: {s}")
return '.'.join(c[... | Split importable | entailment |
def importer(name):
"""Import by name"""
c1, c2 = modsplit(name)
module = importlib.import_module(c1)
return getattr(module, c2) | Import by name | entailment |
def rndstr(size=16):
"""
Returns a string of random ascii characters or digits
:param size: The length of the string
:return: string
"""
_basech = string.ascii_letters + string.digits
return "".join([rnd.choice(_basech) for _ in range(size)]) | Returns a string of random ascii characters or digits
:param size: The length of the string
:return: string | entailment |
def add_redirect_uris(request_args, service=None, **kwargs):
"""
Add redirect_uris to the request arguments.
:param request_args: Incomming request arguments
:param service: A link to the service
:param kwargs: Possible extra keyword arguments
:return: A possibly augmented set of request argume... | Add redirect_uris to the request arguments.
:param request_args: Incomming request arguments
:param service: A link to the service
:param kwargs: Possible extra keyword arguments
:return: A possibly augmented set of request arguments. | entailment |
def match_preferences(self, pcr=None, issuer=None):
"""
Match the clients preferences against what the provider can do.
This is to prepare for later client registration and or what
functionality the client actually will use.
In the client configuration the client preferences are ... | Match the clients preferences against what the provider can do.
This is to prepare for later client registration and or what
functionality the client actually will use.
In the client configuration the client preferences are expressed.
These are then compared with the Provider Configurati... | entailment |
def soundexCode(self, char):
'''Return the soundex code for given character
:param char:
Character whose soundex code is needed
:return:
Returns soundex code if character is found in charmap
else returns 0
'''
lang = get_languag... | Return the soundex code for given character
:param char:
Character whose soundex code is needed
:return:
Returns soundex code if character is found in charmap
else returns 0 | entailment |
def soundex(self, name, length=8):
'''Calculate soundex of given string
This function calculates soundex for Indian language string
as well as English string.
This function is exposed as service method for JSONRPC in
SILPA framework.
:param name: String ... | Calculate soundex of given string
This function calculates soundex for Indian language string
as well as English string.
This function is exposed as service method for JSONRPC in
SILPA framework.
:param name: String whose Soundex value to be calculated
... | entailment |
def compare(self, string1, string2):
'''Compare soundex of given strings
This function checks if 2 given strings are phonetically
sounds same by doing soundex code comparison
:param string1: First string for comparison
:param string2: Second string for comparison
... | Compare soundex of given strings
This function checks if 2 given strings are phonetically
sounds same by doing soundex code comparison
:param string1: First string for comparison
:param string2: Second string for comparison
:return: Returns 0 if both strings are... | entailment |
def get_response_for_url(self, url):
"""
Accepts a fully-qualified url.
Returns an HttpResponse, passing through all headers and the status code.
"""
if not url or "//" not in url:
raise ValueError("Missing or invalid url: %s" % url)
render_url = self.BASE_U... | Accepts a fully-qualified url.
Returns an HttpResponse, passing through all headers and the status code. | entailment |
def update_url(self, url=None, regex=None):
"""
Accepts a fully-qualified url, or regex.
Returns True if successful, False if not successful.
"""
if not url and not regex:
raise ValueError("Neither a url or regex was provided to update_url.")
headers = {
... | Accepts a fully-qualified url, or regex.
Returns True if successful, False if not successful. | entailment |
def update_url(self, url=None):
"""
Accepts a fully-qualified url.
Returns True if successful, False if not successful.
"""
if not url:
raise ValueError("Neither a url or regex was provided to update_url.")
post_url = "%s%s" % (self.BASE_URL, url)
r = ... | Accepts a fully-qualified url.
Returns True if successful, False if not successful. | entailment |
def create(self, validated_data):
"""Override ``create`` to provide a user via request.user by default.
This is required since the read_only ``user`` field is not included by
default anymore since
https://github.com/encode/django-rest-framework/pull/5886.
"""
if 'user' n... | Override ``create`` to provide a user via request.user by default.
This is required since the read_only ``user`` field is not included by
default anymore since
https://github.com/encode/django-rest-framework/pull/5886. | entailment |
def has_object_permission(self, request, view, obj):
"""
Allow staff or superusers, and the owner of the object itself.
"""
user = request.user
if not user.is_authenticated:
return False
elif user.is_staff or user.is_superuser:
return True
... | Allow staff or superusers, and the owner of the object itself. | entailment |
def clear(self):
"""Release the semaphore of all of its bounds, setting the internal
counter back to its original bind limit. Notify an equivalent amount
of threads that they can run."""
with self._cond:
to_notify = self._initial - self._value
self._value = self._... | Release the semaphore of all of its bounds, setting the internal
counter back to its original bind limit. Notify an equivalent amount
of threads that they can run. | entailment |
def _api_wrapper(fn):
"""API function decorator that performs rate limiting and error checking."""
def _convert(value):
if isinstance(value, _datetime.date):
return value.strftime('%s')
return value
@_six.wraps(fn)
def _fn(self, command, **params):
# sanitize the pa... | API function decorator that performs rate limiting and error checking. | entailment |
def _public(self, command, **params):
"""Invoke the 'command' public API with optional params."""
params['command'] = command
response = self.session.get(self._public_url, params=params)
return response | Invoke the 'command' public API with optional params. | entailment |
def returnOrderBook(self, currencyPair='all', depth='50'):
"""Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all market... | Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all markets. | entailment |
def returnTradeHistory(self, currencyPair, start=None, end=None):
"""Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters."""
return self._public('returnTradeHistory', currencyPair=curr... | Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters. | entailment |
def returnChartData(self, currencyPair, period, start=0, end=2**32-1):
"""Returns candlestick chart data. Required GET parameters are
"currencyPair", "period" (candlestick period in seconds; valid values
are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end".
"Start" and "end" a... | Returns candlestick chart data. Required GET parameters are
"currencyPair", "period" (candlestick period in seconds; valid values
are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end".
"Start" and "end" are given in UNIX timestamp format and used to
specify the date range for t... | entailment |
def _private(self, command, **params):
"""Invoke the 'command' public API with optional params."""
if not self._apikey or not self._secret:
raise PoloniexCredentialsException('missing apikey/secret')
with self.nonce_lock:
params.update({'command': command, 'nonce': next(... | Invoke the 'command' public API with optional params. | entailment |
def returnDepositsWithdrawals(self, start=0, end=2**32-1):
"""Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps."""
return self._private('returnDepositsWithdrawals', start=start... | Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps. | entailment |
def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500):
"""Returns your trade history for a given market, specified by the
"currencyPair" POST parameter. You may specify "all" as the
currencyPair to receive your trade history for all markets. You may
optionally... | Returns your trade history for a given market, specified by the
"currencyPair" POST parameter. You may specify "all" as the
currencyPair to receive your trade history for all markets. You may
optionally specify a range via "start" and/or "end" POST parameters,
given in UNIX timestamp for... | entailment |
def returnTradeHistoryPublic(self, currencyPair, start=None, end=None):
"""Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters."""
return super(Poloniex, self).returnTradeHistory(curre... | Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters. | entailment |
def buy(self, currencyPair, rate, amount, fillOrKill=None,
immediateOrCancel=None, postOnly=None):
"""Places a limit buy order in a given market. Required POST parameters
are "currencyPair", "rate", and "amount". If successful, the method
will return the order number.
You may... | Places a limit buy order in a given market. Required POST parameters
are "currencyPair", "rate", and "amount". If successful, the method
will return the order number.
You may optionally set "fillOrKill", "immediateOrCancel", "postOnly"
to 1. A fill-or-kill order will either fill in its e... | entailment |
def moveOrder(self, orderNumber, rate, amount=None, postOnly=None,
immediateOrCancel=None):
"""Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "or... | Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "orderNumber" and "rate"; you
may optionally specify "amount" if you wish to change the amount of
the new ... | entailment |
def withdraw(self, currency, amount, address, paymentId=None):
"""Immediately places a withdrawal for a given currency, with no email
confirmation. In order to use this method, the withdrawal privilege
must be enabled for your API key. Required POST parameters are
"currency", "amount", a... | Immediately places a withdrawal for a given currency, with no email
confirmation. In order to use this method, the withdrawal privilege
must be enabled for your API key. Required POST parameters are
"currency", "amount", and "address". For XMR withdrawals, you may
optionally specify "pay... | entailment |
def transferBalance(self, currency, amount, fromAccount, toAccount):
"""Transfers funds from one account to another (e.g. from your exchange
account to your margin account). Required POST parameters are
"currency", "amount", "fromAccount", and "toAccount"."""
return self._private('tran... | Transfers funds from one account to another (e.g. from your exchange
account to your margin account). Required POST parameters are
"currency", "amount", "fromAccount", and "toAccount". | entailment |
def marginBuy(self, currencyPair, rate, amount, lendingRate=None):
"""Places a margin buy order in a given market. Required POST
parameters are "currencyPair", "rate", and "amount". You may optionally
specify a maximum lending rate using the "lendingRate" parameter.
If successful, the ... | Places a margin buy order in a given market. Required POST
parameters are "currencyPair", "rate", and "amount". You may optionally
specify a maximum lending rate using the "lendingRate" parameter.
If successful, the method will return the order number and any trades
immediately result... | entailment |
def marginSell(self, currencyPair, rate, amount, lendingRate=None):
"""Places a margin sell order in a given market. Parameters and output
are the same as for the marginBuy method."""
return self._private('marginSell', currencyPair=currencyPair, rate=rate,
amount=amo... | Places a margin sell order in a given market. Parameters and output
are the same as for the marginBuy method. | entailment |
def createLoanOffer(self, currency, amount, duration, autoRenew,
lendingRate):
"""Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), and
"lendingRate". """
return self._private('createLoa... | Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), and
"lendingRate". | entailment |
def returnLendingHistory(self, start=0, end=2**32-1, limit=None):
"""Returns your lending history within a time range specified by the
"start" and "end" POST parameters as UNIX timestamps. "limit" may also
be specified to limit the number of rows returned. """
return self._private('retur... | Returns your lending history within a time range specified by the
"start" and "end" POST parameters as UNIX timestamps. "limit" may also
be specified to limit the number of rows returned. | entailment |
def get_cid():
"""Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thin... | Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thing here and let `genera... | entailment |
def generate_new_cid(upstream_cid=None):
"""Generate a new correlation id, possibly based on the given one."""
if upstream_cid is None:
return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None
if (
getattr(settings, 'CID_CONCATENATE_IDS', False)
and geta... | Generate a new correlation id, possibly based on the given one. | entailment |
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_p... | Attempt to import a class from a string representation. | entailment |
def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
rema... | OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
remain off. | entailment |
def check_ups_input_frequency(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency.
"""
a_frequency = calc_frequency_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_f... | OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency. | entailment |
def check_ups_output_current(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.4.4.1.3.1
MIB excerpt
The present output current.
"""
a_current = calc_output_current_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
val... | OID .1.3.6.1.2.1.33.1.4.4.1.3.1
MIB excerpt
The present output current. | entailment |
def check_ups_alarms_present(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.6.1.0
MIB excerpt
The present number of active alarm conditions.
"""
if the_snmp_value != '0':
the_helper.add_status(pynag.Plugins.critical)
else:
the_helper.add_status(pynag.Plug... | OID .1.3.6.1.2.1.33.1.6.1.0
MIB excerpt
The present number of active alarm conditions. | entailment |
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge.
"""
the_helper.add_metric(
label=the_helper.options.type,
value=a_snmp_value,
uom='%')
the_helper.set_summary("Remaining Batter... | OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge. | entailment |
def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1):
"""
OID .1.3.6.1.4.1.534.1.6.1.0
MIB Excerpt
The reading of the ambient temperature in the vicinity of the
UPS or SNMP agent.
"""
the_helper.add_metric(
label=the_helper.options.type,
... | OID .1.3.6.1.4.1.534.1.6.1.0
MIB Excerpt
The reading of the ambient temperature in the vicinity of the
UPS or SNMP agent. | entailment |
def check_ressources(sess):
"""
check the Ressources of the Fortinet Controller
all thresholds are currently hard coded. should be fine.
"""
# get the data
cpu_value = get_data(sess, cpu_oid, helper)
memory_value = get_data(sess, memory_oid, helper)
fil... | check the Ressources of the Fortinet Controller
all thresholds are currently hard coded. should be fine. | entailment |
def check_controller(sess):
"""
check the status of the controller
"""
controller_operational = get_data(sess, operational_oid, helper)
controller_availability = get_data(sess, availability_oid, helper)
controller_alarm = get_data(sess, alarm_oid, helper)... | check the status of the controller | entailment |
def check_accesspoints(sess):
"""
check the status of all connected access points
"""
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
... | check the status of all connected access points | entailment |
def normal_check(name, status, device_type):
"""if the status is "ok" in the NORMAL_STATE dict, return ok + string
if the status is not "ok", return critical + string"""
status_string = NORMAL_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_typ... | if the status is "ok" in the NORMAL_STATE dict, return ok + string
if the status is not "ok", return critical + string | entailment |
def probe_check(name, status, device_type):
"""if the status is "ok" in the PROBE_STATE dict, return ok + string
if the status is not "ok", return critical + string"""
status_string = PROBE_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_type, ... | if the status is "ok" in the PROBE_STATE dict, return ok + string
if the status is not "ok", return critical + string | entailment |
def add_device_information(helper, session):
""" add general device information to summary """
host_name_data = helper.get_snmp_value(session, helper,
DEVICE_INFORMATION_OIDS['oid_host_name'])
product_type_data = helper.get_snmp_value(session, help... | add general device information to summary | entailment |
def process_status(self, helper, session, check):
""""process a single status"""
snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check])
if check == "system_lcd":
helper.update_status(helper, normal_check("global", snmp_result_status, "LCD sta... | process a single status | entailment |
def process_states(self, helper, session, check):
"""process status values from a table"""
snmp_result_status = helper.walk_snmp_values(session, helper,
DEVICE_STATES_OIDS["oid_" + check],
check)
... | process status values from a table | entailment |
def process_temperature_sensors(helper, session):
"""process the temperature sensors"""
snmp_result_temp_sensor_names = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors")
snmp_result_temp_sensor_stat... | process the temperature sensors | entailment |
def check_drives(drivename, drivestatus):
""" check the drive status """
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
drivename, DISK_STATES[int(drivestatus)]["result"]) | check the drive status | entailment |
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data):
""" check the status of the power units """
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"],
"Power unit '{}' redundancy: {}".format(power_unit_name_data,
... | check the status of the power units | entailment |
def check_global_status(flag, name, oid):
"""
check a global status
check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0')
"""
# only check the status, if the "no" flag is not set
if flag:
# get the data via snmp
myData = get_data(sess, oid, helper)
data_... | check a global status
check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0') | entailment |
def check_server_power():
"""
Check if the server is powered on
Skip this check, if the --noPowerState is set
"""
if power_state_flag:
power_state = get_data(sess, oid_power_state, helper)
power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power'... | Check if the server is powered on
Skip this check, if the --noPowerState is set | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.