sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def process_node(e): """ Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual node element in downloaded OSM json Returns ------- node : dict """ node = {'id': e['id'], 'lat': e['...
Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual node element in downloaded OSM json Returns ------- node : dict
entailment
def process_way(e): """ Process a way element entry into a list of dicts suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual way element in downloaded OSM json Returns ------- way : dict waynodes : list of dict """ way = {'id':...
Process a way element entry into a list of dicts suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual way element in downloaded OSM json Returns ------- way : dict waynodes : list of dict
entailment
def parse_network_osm_query(data): """ Convert OSM query data to DataFrames of ways and way-nodes. Parameters ---------- data : dict Result of an OSM query. Returns ------- nodes, ways, waynodes : pandas.DataFrame """ if len(data['elements']) == 0: raise Runtim...
Convert OSM query data to DataFrames of ways and way-nodes. Parameters ---------- data : dict Result of an OSM query. Returns ------- nodes, ways, waynodes : pandas.DataFrame
entailment
def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Get DataFrames of OSM data in a bounding box. Parameters ---------- lat_min : float ...
Get DataFrames of OSM data in a bounding box. Parameters ---------- lat_min : float southern latitude of bounding box lng_min : float eastern longitude of bounding box lat_max : float northern latitude of bounding box lng_max : float western longitude of bounding...
entailment
def intersection_nodes(waynodes): """ Returns a set of all the nodes that appear in 2 or more ways. Parameters ---------- waynodes : pandas.DataFrame Mapping of way IDs to node IDs as returned by `ways_in_bbox`. Returns ------- intersections : set Node IDs that appear i...
Returns a set of all the nodes that appear in 2 or more ways. Parameters ---------- waynodes : pandas.DataFrame Mapping of way IDs to node IDs as returned by `ways_in_bbox`. Returns ------- intersections : set Node IDs that appear in 2 or more ways.
entailment
def node_pairs(nodes, ways, waynodes, two_way=True): """ Create a table of node pairs with the distances between them. Parameters ---------- nodes : pandas.DataFrame Must have 'lat' and 'lon' columns. ways : pandas.DataFrame Table of way metadata. waynodes : pandas.DataFrame...
Create a table of node pairs with the distances between them. Parameters ---------- nodes : pandas.DataFrame Must have 'lat' and 'lon' columns. ways : pandas.DataFrame Table of way metadata. waynodes : pandas.DataFrame Table linking way IDs to node IDs. Way IDs should be in ...
entailment
def network_from_bbox(lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None, network_type='walk', two_way=True, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Make a g...
Make a graph network from a bounding lat/lon box composed of nodes and edges for use in Pandana street network accessibility calculations. You may either enter a lat/long box via the four lat_min, lng_min, lat_max, lng_max parameters or the bbox parameter as a tuple. Parameters ---------- lat_m...
entailment
def read_lines(in_file): """Returns a list of lines from a input markdown file.""" with open(in_file, 'r') as inf: in_contents = inf.read().split('\n') return in_contents
Returns a list of lines from a input markdown file.
entailment
def remove_lines(lines, remove=('[[back to top]', '<a class="mk-toclify"')): """Removes existing [back to top] links and <a id> tags.""" if not remove: return lines[:] out = [] for l in lines: if l.startswith(remove): continue out.append(l) return out
Removes existing [back to top] links and <a id> tags.
entailment
def slugify_headline(line, remove_dashes=False): """ Takes a header line from a Markdown document and returns a tuple of the '#'-stripped version of the head line, a string version for <a id=''></a> anchor tags, and the level of the headline as integer. E.g., >>> dashify_head...
Takes a header line from a Markdown document and returns a tuple of the '#'-stripped version of the head line, a string version for <a id=''></a> anchor tags, and the level of the headline as integer. E.g., >>> dashify_headline('### some header lvl3') ('Some header lvl3', 'some-h...
entailment
def tag_and_collect(lines, id_tag=True, back_links=False, exclude_h=None, remove_dashes=False): """ Gets headlines from the markdown document and creates anchor tags. Keyword arguments: lines: a list of sublists where every sublist represents a line from a Markdown document. id_...
Gets headlines from the markdown document and creates anchor tags. Keyword arguments: lines: a list of sublists where every sublist represents a line from a Markdown document. id_tag: if true, creates inserts a the <a id> tags (not req. by GitHub) back_links: if true, adds "back...
entailment
def positioning_headlines(headlines): """ Strips unnecessary whitespaces/tabs if first header is not left-aligned """ left_just = False for row in headlines: if row[-1] == 1: left_just = True break if not left_just: for row in headlines: row[-1...
Strips unnecessary whitespaces/tabs if first header is not left-aligned
entailment
def create_toc(headlines, hyperlink=True, top_link=False, no_toc_header=False): """ Creates the table of contents from the headline list that was returned by the tag_and_collect function. Keyword Arguments: headlines: list of lists e.g., ['Some header lvl3', 'some-header-lvl3', 3] ...
Creates the table of contents from the headline list that was returned by the tag_and_collect function. Keyword Arguments: headlines: list of lists e.g., ['Some header lvl3', 'some-header-lvl3', 3] hyperlink: Creates hyperlinks in Markdown format if True, e.g., '- [Some ...
entailment
def build_markdown(toc_headlines, body, spacer=0, placeholder=None): """ Returns a string with the Markdown output contents incl. the table of contents. Keyword arguments: toc_headlines: lines for the table of contents as created by the create_toc function. body: contents of...
Returns a string with the Markdown output contents incl. the table of contents. Keyword arguments: toc_headlines: lines for the table of contents as created by the create_toc function. body: contents of the Markdown file including ID-anchor tags as returned by the ...
entailment
def output_markdown(markdown_cont, output_file): """ Writes to an output file if `outfile` is a valid path. """ if output_file: with open(output_file, 'w') as out: out.write(markdown_cont)
Writes to an output file if `outfile` is a valid path.
entailment
def markdown_toclify(input_file, output_file=None, github=False, back_to_top=False, nolink=False, no_toc_header=False, spacer=0, placeholder=None, exclude_h=None, remove_dashes=False): """ Function to add table of contents to markdown files. Parame...
Function to add table of contents to markdown files. Parameters ----------- input_file: str Path to the markdown input file. output_file: str (defaul: None) Path to the markdown output file. github: bool (default: False) Uses GitHub TOC syntax if True. back_to...
entailment
def url_parse(name): """parse urls with different prefixes""" position = name.find("github.com") if position >= 0: if position != 0: position_1 = name.find("www.github.com") position_2 = name.find("http://github.com") position_3 = name.find("https://github.com") ...
parse urls with different prefixes
entailment
def get_req(url): """simple get request""" request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response = urllib.request.urlopen(request).read().decode('utf-8') return response except urllib.error.HTTPError: exception() ...
simple get request
entailment
def geturl_req(url): """get request that returns 302""" request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response_url = urllib.request.urlopen(request).geturl() return response_url except urllib.error.HTTPError: exception(...
get request that returns 302
entailment
def main(): """main function""" parser = argparse.ArgumentParser( description='Github within the Command Line') group = parser.add_mutually_exclusive_group() group.add_argument('-n', '--url', type=str, help="Get repos from the user profile's URL") group.add_argument('-...
main function
entailment
def do_capture(parser, token): """ Capture the contents of a tag output. Usage: .. code-block:: html+django {% capture %}..{% endcapture %} # output in {{ capture }} {% capture silent %}..{% endcapture %} # output in {{ capture }} only {% capture ...
Capture the contents of a tag output. Usage: .. code-block:: html+django {% capture %}..{% endcapture %} # output in {{ capture }} {% capture silent %}..{% endcapture %} # output in {{ capture }} only {% capture as varname %}..{% endcapture %} # o...
entailment
def _parse_special_fields(self, data): """ Helper method that parses special fields to Python objects :param data: response from Monzo API request :type data: dict """ self.created = parse_date(data.pop('created')) if data.get('settled'): # Not always returned ...
Helper method that parses special fields to Python objects :param data: response from Monzo API request :type data: dict
entailment
def _save_token_on_disk(self): """Helper function that saves the token on disk""" token = self._token.copy() # Client secret is needed for token refreshing and isn't returned # as a pared of OAuth token by default token.update(client_secret=self._client_secret) with cod...
Helper function that saves the token on disk
entailment
def _get_oauth_token(self): """ Get Monzo access token via OAuth2 `authorization code` grant type. Official docs: https://monzo.com/docs/#acquire-an-access-token :returns: OAuth 2 access token :rtype: dict """ url = urljoin(self.api_url, '/oauth2/tok...
Get Monzo access token via OAuth2 `authorization code` grant type. Official docs: https://monzo.com/docs/#acquire-an-access-token :returns: OAuth 2 access token :rtype: dict
entailment
def _refresh_oath_token(self): """ Refresh Monzo OAuth 2 token. Official docs: https://monzo.com/docs/#refreshing-access :raises UnableToRefreshTokenException: when token couldn't be refreshed """ url = urljoin(self.api_url, '/oauth2/token') data = {...
Refresh Monzo OAuth 2 token. Official docs: https://monzo.com/docs/#refreshing-access :raises UnableToRefreshTokenException: when token couldn't be refreshed
entailment
def _get_response(self, method, endpoint, params=None): """ Helper method to handle HTTP requests and catch API errors :param method: valid HTTP method :type method: str :param endpoint: API endpoint :type endpoint: str :param params: extra parameters passed with...
Helper method to handle HTTP requests and catch API errors :param method: valid HTTP method :type method: str :param endpoint: API endpoint :type endpoint: str :param params: extra parameters passed with the request :type params: dict :returns: API response ...
entailment
def whoami(self): """ Get information about the access token. Official docs: https://monzo.com/docs/#authenticating-requests :returns: access token details :rtype: dict """ endpoint = '/ping/whoami' response = self._get_response( ...
Get information about the access token. Official docs: https://monzo.com/docs/#authenticating-requests :returns: access token details :rtype: dict
entailment
def accounts(self, refresh=False): """ Returns a list of accounts owned by the currently authorised user. It's often used when deciding whether to require explicit account ID or use the only available one, so we cache the response by default. Official docs: https://m...
Returns a list of accounts owned by the currently authorised user. It's often used when deciding whether to require explicit account ID or use the only available one, so we cache the response by default. Official docs: https://monzo.com/docs/#list-accounts :param refresh: d...
entailment
def balance(self, account_id=None): """ Returns balance information for a specific account. Official docs: https://monzo.com/docs/#read-balance :param account_id: Monzo account ID :type account_id: str :raises: ValueError :returns: Monzo balance inst...
Returns balance information for a specific account. Official docs: https://monzo.com/docs/#read-balance :param account_id: Monzo account ID :type account_id: str :raises: ValueError :returns: Monzo balance instance :rtype: MonzoBalance
entailment
def pots(self, refresh=False): """ Returns a list of pots owned by the currently authorised user. Official docs: https://monzo.com/docs/#pots :param refresh: decides if the pots information should be refreshed. :type refresh: bool :returns: list of Monzo pot...
Returns a list of pots owned by the currently authorised user. Official docs: https://monzo.com/docs/#pots :param refresh: decides if the pots information should be refreshed. :type refresh: bool :returns: list of Monzo pots :rtype: list of MonzoPot
entailment
def transactions(self, account_id=None, reverse=True, limit=None): """ Returns a list of transactions on the user's account. Official docs: https://monzo.com/docs/#list-transactions :param account_id: Monzo account ID :type account_id: str :param reverse: wh...
Returns a list of transactions on the user's account. Official docs: https://monzo.com/docs/#list-transactions :param account_id: Monzo account ID :type account_id: str :param reverse: whether transactions should be in in descending order :type reverse: bool ...
entailment
def transaction(self, transaction_id, expand_merchant=False): """ Returns an individual transaction, fetched by its id. Official docs: https://monzo.com/docs/#retrieve-transaction :param transaction_id: Monzo transaction ID :type transaction_id: str :param e...
Returns an individual transaction, fetched by its id. Official docs: https://monzo.com/docs/#retrieve-transaction :param transaction_id: Monzo transaction ID :type transaction_id: str :param expand_merchant: whether merchant data should be included :type expand_merc...
entailment
def launcher(): """Launch it.""" parser = OptionParser() parser.add_option( '-f', '--file', dest='filename', default='agents.csv', help='snmposter configuration file' ) options, args = parser.parse_args() factory = SNMPosterFactory() snmpd_status = s...
Launch it.
entailment
def get_auth_string(self): """Create auth string from credentials.""" auth_info = '{}:{}'.format(self.sauce_username, self.sauce_access_key) return base64.b64encode(auth_info.encode('utf-8')).decode('utf-8')
Create auth string from credentials.
entailment
def make_auth_headers(self, content_type): """Add authorization header.""" headers = self.make_headers(content_type) headers['Authorization'] = 'Basic {}'.format(self.get_auth_string()) return headers
Add authorization header.
entailment
def request(self, method, url, body=None, content_type='application/json'): """Send http request.""" headers = self.make_auth_headers(content_type) connection = http_client.HTTPSConnection(self.apibase) connection.request(method, url, body, headers=headers) response = connection....
Send http request.
entailment
def get_user(self): """Access basic account information.""" method = 'GET' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) return self.client.request(method, endpoint)
Access basic account information.
entailment
def create_user(self, username, password, name, email): """Create a sub account.""" method = 'POST' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) body = json.dumps({'username': username, 'password': password, 'name': name, 'email': email, })...
Create a sub account.
entailment
def get_concurrency(self): """Check account concurrency limits.""" method = 'GET' endpoint = '/rest/v1.1/users/{}/concurrency'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Check account concurrency limits.
entailment
def get_subaccounts(self): """Get a list of sub accounts associated with a parent account.""" method = 'GET' endpoint = '/rest/v1/users/{}/list-subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Get a list of sub accounts associated with a parent account.
entailment
def get_siblings(self): """Get a list of sibling accounts associated with provided account.""" method = 'GET' endpoint = '/rest/v1.1/users/{}/siblings'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Get a list of sibling accounts associated with provided account.
entailment
def get_subaccount_info(self): """Get information about a sub account.""" method = 'GET' endpoint = '/rest/v1/users/{}/subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Get information about a sub account.
entailment
def change_access_key(self): """Change access key of your account.""" method = 'POST' endpoint = '/rest/v1/users/{}/accesskey/change'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Change access key of your account.
entailment
def get_activity(self): """Check account concurrency limits.""" method = 'GET' endpoint = '/rest/v1/{}/activity'.format(self.client.sauce_username) return self.client.request(method, endpoint)
Check account concurrency limits.
entailment
def get_usage(self, start=None, end=None): """Access historical account usage data.""" method = 'GET' endpoint = '/rest/v1/users/{}/usage'.format(self.client.sauce_username) data = {} if start: data['start'] = start if end: data['end'] = end ...
Access historical account usage data.
entailment
def get_platforms(self, automation_api='all'): """Get a list of objects describing all the OS and browser platforms currently supported on Sauce Labs.""" method = 'GET' endpoint = '/rest/v1/info/platforms/{}'.format(automation_api) return self.client.request(method, endpoint)
Get a list of objects describing all the OS and browser platforms currently supported on Sauce Labs.
entailment
def get_jobs(self, full=None, limit=None, skip=None, start=None, end=None, output_format=None): """List jobs belonging to a specific user.""" method = 'GET' endpoint = '/rest/v1/{}/jobs'.format(self.client.sauce_username) data = {} if full is not None: ...
List jobs belonging to a specific user.
entailment
def update_job(self, job_id, build=None, custom_data=None, name=None, passed=None, public=None, tags=None): """Edit an existing job.""" method = 'PUT' endpoint = '/rest/v1/{}/jobs/{}'.format(self.client.sauce_username, job_id) ...
Edit an existing job.
entailment
def stop_job(self, job_id): """Terminates a running job.""" method = 'PUT' endpoint = '/rest/v1/{}/jobs/{}/stop'.format( self.client.sauce_username, job_id) return self.client.request(method, endpoint)
Terminates a running job.
entailment
def get_job_asset_url(self, job_id, filename): """Get details about the static assets collected for a specific job.""" return 'https://saucelabs.com/rest/v1/{}/jobs/{}/assets/{}'.format( self.client.sauce_username, job_id, filename)
Get details about the static assets collected for a specific job.
entailment
def get_auth_token(self, job_id, date_range=None): """Get an auth token to access protected job resources. https://wiki.saucelabs.com/display/DOCS/Building+Links+to+Test+Results """ key = '{}:{}'.format(self.client.sauce_username, self.client.sauce_access_ke...
Get an auth token to access protected job resources. https://wiki.saucelabs.com/display/DOCS/Building+Links+to+Test+Results
entailment
def upload_file(self, filepath, overwrite=True): """Uploads a file to the temporary sauce storage.""" method = 'POST' filename = os.path.split(filepath)[1] endpoint = '/rest/v1/storage/{}/{}?overwrite={}'.format( self.client.sauce_username, filename, "true" if overwrite else ...
Uploads a file to the temporary sauce storage.
entailment
def get_stored_files(self): """Check which files are in your temporary storage.""" method = 'GET' endpoint = '/rest/v1/storage/{}'.format(self.client.sauce_username) return self.client.request(method, endpoint)
Check which files are in your temporary storage.
entailment
def get_tunnels(self): """Retrieves all running tunnels for a specific user.""" method = 'GET' endpoint = '/rest/v1/{}/tunnels'.format(self.client.sauce_username) return self.client.request(method, endpoint)
Retrieves all running tunnels for a specific user.
entailment
def get_tunnel(self, tunnel_id): """Get information for a tunnel given its ID.""" method = 'GET' endpoint = '/rest/v1/{}/tunnels/{}'.format( self.client.sauce_username, tunnel_id) return self.client.request(method, endpoint)
Get information for a tunnel given its ID.
entailment
def apply(patch): """Apply a patch. The patch's :attr:`~Patch.obj` attribute is injected into the patch's :attr:`~Patch.destination` under the patch's :attr:`~Patch.name`. This is a wrapper around calling ``setattr(patch.destination, patch.name, patch.obj)``. Parameters ---------- pat...
Apply a patch. The patch's :attr:`~Patch.obj` attribute is injected into the patch's :attr:`~Patch.destination` under the patch's :attr:`~Patch.name`. This is a wrapper around calling ``setattr(patch.destination, patch.name, patch.obj)``. Parameters ---------- patch : gorilla.Patch ...
entailment
def patch(destination, name=None, settings=None): """Decorator to create a patch. The object being decorated becomes the :attr:`~Patch.obj` attribute of the patch. Parameters ---------- destination : object Patch destination. name : str Name of the attribute at the destinat...
Decorator to create a patch. The object being decorated becomes the :attr:`~Patch.obj` attribute of the patch. Parameters ---------- destination : object Patch destination. name : str Name of the attribute at the destination. settings : gorilla.Settings Settings. ...
entailment
def patches(destination, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): """Decorator to create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. settings : gorilla.Setti...
Decorator to create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. settings : gorilla.Settings Settings. traverse_bases : bool If the object is a class, the base classes are also traversed. filter : function ...
entailment
def destination(value): """Modifier decorator to update a patch's destination. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- value : object ...
Modifier decorator to update a patch's destination. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- value : object Patch destination. ...
entailment
def settings(**kwargs): """Modifier decorator to update a patch's settings. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- kwargs Sett...
Modifier decorator to update a patch's settings. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- kwargs Settings to update. See :class:`Set...
entailment
def filter(value): """Modifier decorator to force the inclusion or exclusion of an attribute. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- v...
Modifier decorator to force the inclusion or exclusion of an attribute. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- value : bool ``True...
entailment
def create_patches(destination, root, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): """Create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. root : object ...
Create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. root : object Root object, either a module or a class. settings : gorilla.Settings Settings. traverse_bases : bool If the object is a class, the b...
entailment
def find_patches(modules, recursive=True): """Find all the patches created through decorators. Parameters ---------- modules : list of module Modules and/or packages to search the patches in. recursive : bool ``True`` to search recursively in subpackages. Returns ------- ...
Find all the patches created through decorators. Parameters ---------- modules : list of module Modules and/or packages to search the patches in. recursive : bool ``True`` to search recursively in subpackages. Returns ------- list of gorilla.Patch Patches found. ...
entailment
def get_attribute(obj, name): """Retrieve an attribute while bypassing the descriptor protocol. As per the built-in |getattr()|_ function, if the input object is a class then its base classes might also be searched until the attribute is found. Parameters ---------- obj : object Object...
Retrieve an attribute while bypassing the descriptor protocol. As per the built-in |getattr()|_ function, if the input object is a class then its base classes might also be searched until the attribute is found. Parameters ---------- obj : object Object to search the attribute in. name...
entailment
def get_decorator_data(obj, set_default=False): """Retrieve any decorator data from an object. Parameters ---------- obj : object Object. set_default : bool If no data is found, a default one is set on the object and returned, otherwise ``None`` is returned. Returns ...
Retrieve any decorator data from an object. Parameters ---------- obj : object Object. set_default : bool If no data is found, a default one is set on the object and returned, otherwise ``None`` is returned. Returns ------- gorilla.DecoratorData The decorato...
entailment
def _get_base(obj): """Unwrap decorators to retrieve the base object.""" if hasattr(obj, '__func__'): obj = obj.__func__ elif isinstance(obj, property): obj = obj.fget elif isinstance(obj, (classmethod, staticmethod)): # Fallback for Python < 2.7 back when no `__func__` attribute...
Unwrap decorators to retrieve the base object.
entailment
def _get_members(obj, traverse_bases=True, filter=default_filter, recursive=True): """Retrieve the member attributes of a module or a class. The descriptor protocol is bypassed.""" if filter is None: filter = _true out = [] stack = collections.deque((obj,)) while stack...
Retrieve the member attributes of a module or a class. The descriptor protocol is bypassed.
entailment
def _module_iterator(root, recursive=True): """Iterate over modules.""" yield root stack = collections.deque((root,)) while stack: package = stack.popleft() # The '__path__' attribute of a package might return a list of paths if # the package is referenced as a namespace. ...
Iterate over modules.
entailment
def _update(self, **kwargs): """Update some attributes. If a 'settings' attribute is passed as a dict, then it updates the content of the settings, if any, instead of completely overwriting it. """ for key, value in _iteritems(kwargs): if key == 'settings': ...
Update some attributes. If a 'settings' attribute is passed as a dict, then it updates the content of the settings, if any, instead of completely overwriting it.
entailment
def request(self, path, action, data=''): """To make a request to the API.""" # Check if the path includes URL or not. head = self.base_url if path.startswith(head): path = path[len(head):] path = quote_plus(path, safe='/') if not path.startswith(self.api)...
To make a request to the API.
entailment
def get_collection(self, path): """To get pagewise data.""" while True: items = self.get(path) req = self.req for item in items: yield item if req.links and req.links['next'] and\ req.links['next']['rel'] == 'next': ...
To get pagewise data.
entailment
def collection(self, path): """To return all items generated by get collection.""" data = [] for item in self.get_collection(path): data.append(item) return data
To return all items generated by get collection.
entailment
def list_projects_search(self, searchstring): """List projects with searchstring.""" log.debug('List all projects with: %s' % searchstring) return self.collection('projects/search/%s.json' % quote_plus(searchstring))
List projects with searchstring.
entailment
def create_project(self, data): """Create a project.""" # http://teampasswordmanager.com/docs/api-projects/#create_project log.info('Create project: %s' % data) NewID = self.post('projects.json', data).get('id') log.info('Project has been created with ID %s' % NewID) retu...
Create a project.
entailment
def update_project(self, ID, data): """Update a project.""" # http://teampasswordmanager.com/docs/api-projects/#update_project log.info('Update project %s with %s' % (ID, data)) self.put('projects/%s.json' % ID, data)
Update a project.
entailment
def change_parent_of_project(self, ID, NewParrentID): """Change parent of project.""" # http://teampasswordmanager.com/docs/api-projects/#change_parent log.info('Change parrent for project %s to %s' % (ID, NewParrentID)) data = {'parent_id': NewParrentID} self.put('projects/%s/ch...
Change parent of project.
entailment
def update_security_of_project(self, ID, data): """Update security of project.""" # http://teampasswordmanager.com/docs/api-projects/#update_project_security log.info('Update project %s security %s' % (ID, data)) self.put('projects/%s/security.json' % ID, data)
Update security of project.
entailment
def list_passwords_search(self, searchstring): """List passwords with searchstring.""" log.debug('List all passwords with: %s' % searchstring) return self.collection('passwords/search/%s.json' % quote_plus(searchstring))
List passwords with searchstring.
entailment
def create_password(self, data): """Create a password.""" # http://teampasswordmanager.com/docs/api-passwords/#create_password log.info('Create new password %s' % data) NewID = self.post('passwords.json', data).get('id') log.info('Password has been created with ID %s' % NewID) ...
Create a password.
entailment
def update_password(self, ID, data): """Update a password.""" # http://teampasswordmanager.com/docs/api-passwords/#update_password log.info('Update Password %s with %s' % (ID, data)) self.put('passwords/%s.json' % ID, data)
Update a password.
entailment
def update_security_of_password(self, ID, data): """Update security of a password.""" # http://teampasswordmanager.com/docs/api-passwords/#update_security_password log.info('Update security of password %s with %s' % (ID, data)) self.put('passwords/%s/security.json' % ID, data)
Update security of a password.
entailment
def update_custom_fields_of_password(self, ID, data): """Update custom fields definitions of a password.""" # http://teampasswordmanager.com/docs/api-passwords/#update_cf_password log.info('Update custom fields of password %s with %s' % (ID, data)) self.put('passwords/%s/custom_fields.js...
Update custom fields definitions of a password.
entailment
def unlock_password(self, ID, reason): """Unlock a password.""" # http://teampasswordmanager.com/docs/api-passwords/#unlock_password log.info('Unlock password %s, Reason: %s' % (ID, reason)) self.unlock_reason = reason self.put('passwords/%s/unlock.json' % ID)
Unlock a password.
entailment
def list_mypasswords_search(self, searchstring): """List my passwords with searchstring.""" # http://teampasswordmanager.com/docs/api-my-passwords/#list_passwords log.debug('List MyPasswords with %s' % searchstring) return self.collection('my_passwords/search/%s.json' % ...
List my passwords with searchstring.
entailment
def create_mypassword(self, data): """Create my password.""" # http://teampasswordmanager.com/docs/api-my-passwords/#create_password log.info('Create MyPassword with %s' % data) NewID = self.post('my_passwords.json', data).get('id') log.info('MyPassword has been created with %s' ...
Create my password.
entailment
def update_mypassword(self, ID, data): """Update my password.""" # http://teampasswordmanager.com/docs/api-my-passwords/#update_password log.info('Update MyPassword %s with %s' % (ID, data)) self.put('my_passwords/%s.json' % ID, data)
Update my password.
entailment
def create_user(self, data): """Create a User.""" # http://teampasswordmanager.com/docs/api-users/#create_user log.info('Create user with %s' % data) NewID = self.post('users.json', data).get('id') log.info('User has been created with ID %s' % NewID) return NewID
Create a User.
entailment
def update_user(self, ID, data): """Update a User.""" # http://teampasswordmanager.com/docs/api-users/#update_user log.info('Update user %s with %s' % (ID, data)) self.put('users/%s.json' % ID, data)
Update a User.
entailment
def change_user_password(self, ID, data): """Change password of a User.""" # http://teampasswordmanager.com/docs/api-users/#change_password log.info('Change user %s password' % ID) self.put('users/%s/change_password.json' % ID, data)
Change password of a User.
entailment
def convert_user_to_ldap(self, ID, DN): """Convert a normal user to a LDAP user.""" # http://teampasswordmanager.com/docs/api-users/#convert_to_ldap data = {'login_dn': DN} log.info('Convert User %s to LDAP DN %s' % (ID, DN)) self.put('users/%s/convert_to_ldap.json' % ID, data)
Convert a normal user to a LDAP user.
entailment
def create_group(self, data): """Create a Group.""" # http://teampasswordmanager.com/docs/api-groups/#create_group log.info('Create group with %s' % data) NewID = self.post('groups.json', data).get('id') log.info('Group has been created with ID %s' % NewID) return NewID
Create a Group.
entailment
def update_group(self, ID, data): """Update a Group.""" # http://teampasswordmanager.com/docs/api-groups/#update_group log.info('Update group %s with %s' % (ID, data)) self.put('groups/%s.json' % ID, data)
Update a Group.
entailment
def add_user_to_group(self, GroupID, UserID): """Add a user to a group.""" # http://teampasswordmanager.com/docs/api-groups/#add_user log.info('Add User %s to Group %s' % (UserID, GroupID)) self.put('groups/%s/add_user/%s.json' % (GroupID, UserID))
Add a user to a group.
entailment
def delete_user_from_group(self, GroupID, UserID): """Delete a user from a group.""" # http://teampasswordmanager.com/docs/api-groups/#del_user log.info('Delete user %s from group %s' % (UserID, GroupID)) self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID))
Delete a user from a group.
entailment
def up_to_date(self): """Check if Team Password Manager is up to date.""" VersionInfo = self.get_latest_version() CurrentVersion = VersionInfo.get('version') LatestVersion = VersionInfo.get('latest_version') if CurrentVersion == LatestVersion: log.info('TeamPasswordM...
Check if Team Password Manager is up to date.
entailment
def convert_exception(from_exception, to_exception, *to_args, **to_kw): """ Decorator: Catch exception ``from_exception`` and instead raise ``to_exception(*to_args, **to_kw)``. Useful when modules you're using in a method throw their own errors that you want to convert to your own exceptions that you h...
Decorator: Catch exception ``from_exception`` and instead raise ``to_exception(*to_args, **to_kw)``. Useful when modules you're using in a method throw their own errors that you want to convert to your own exceptions that you handle higher in the stack. Example: :: class FooError(Exception): ...
entailment
def iterate_date_values(d, start_date=None, stop_date=None, default=0): """ Convert (date, value) sorted lists into contiguous value-per-day data sets. Great for sparklines. Example:: [(datetime.date(2011, 1, 1), 1), (datetime.date(2011, 1, 4), 2)] -> [1, 0, 0, 2] """ dataiter = iter(d) ...
Convert (date, value) sorted lists into contiguous value-per-day data sets. Great for sparklines. Example:: [(datetime.date(2011, 1, 1), 1), (datetime.date(2011, 1, 4), 2)] -> [1, 0, 0, 2]
entailment
def truncate_datetime(t, resolution): """ Given a datetime ``t`` and a ``resolution``, flatten the precision beyond the given resolution. ``resolution`` can be one of: year, month, day, hour, minute, second, microsecond Example:: >>> t = datetime.datetime(2000, 1, 2, 3, 4, 5, 6000) # Or, 2000...
Given a datetime ``t`` and a ``resolution``, flatten the precision beyond the given resolution. ``resolution`` can be one of: year, month, day, hour, minute, second, microsecond Example:: >>> t = datetime.datetime(2000, 1, 2, 3, 4, 5, 6000) # Or, 2000-01-02 03:04:05.006000 >>> truncate_datet...
entailment
def to_timezone(dt, timezone): """ Return an aware datetime which is ``dt`` converted to ``timezone``. If ``dt`` is naive, it is assumed to be UTC. For example, if ``dt`` is "06:00 UTC+0000" and ``timezone`` is "EDT-0400", then the result will be "02:00 EDT-0400". This method follows the guid...
Return an aware datetime which is ``dt`` converted to ``timezone``. If ``dt`` is naive, it is assumed to be UTC. For example, if ``dt`` is "06:00 UTC+0000" and ``timezone`` is "EDT-0400", then the result will be "02:00 EDT-0400". This method follows the guidelines in http://pytz.sourceforge.net/
entailment
def now(timezone=None): """ Return a naive datetime object for the given ``timezone``. A ``timezone`` is any pytz- like or datetime.tzinfo-like timezone object. If no timezone is given, then UTC is assumed. This method is best used with pytz installed:: pip install pytz """ d = dat...
Return a naive datetime object for the given ``timezone``. A ``timezone`` is any pytz- like or datetime.tzinfo-like timezone object. If no timezone is given, then UTC is assumed. This method is best used with pytz installed:: pip install pytz
entailment