signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def _determine_checkout_url(self, platform, action): | api_version = settings.API_CHECKOUT_VERSION<EOL>if platform == "<STR_LIT:test>":<EOL><INDENT>base_uri = settings.ENDPOINT_CHECKOUT_TEST<EOL><DEDENT>elif self.live_endpoint_prefix is not None and platform == "<STR_LIT>":<EOL><INDENT>base_uri = settings.ENDPOINT_CHECKOUT_LIVE_SUFFIX.format(<EOL>self.live_endpoint_prefix)<EOL><DEDENT>elif self.live_endpoint_prefix is None and platform == "<STR_LIT>":<EOL><INDENT>errorstring = """<STR_LIT>"""<EOL>raise AdyenEndpointInvalidFormat(errorstring)<EOL><DEDENT>if action == "<STR_LIT>":<EOL><INDENT>action = "<STR_LIT>"<EOL><DEDENT>if action == "<STR_LIT>":<EOL><INDENT>action = "<STR_LIT>"<EOL><DEDENT>if action == "<STR_LIT>":<EOL><INDENT>api_version = settings.API_CHECKOUT_UTILITY_VERSION<EOL><DEDENT>return '<STR_LIT:/>'.join([base_uri, api_version, action])<EOL> | This returns the Adyen API endpoint based on the provided platform,
service and action.
Args:
platform (str): Adyen platform, ie 'live' or 'test'.
action (str): the API action to perform. | f729:c1:m3 |
def call_api(self, request_data, service, action, idempotency=False,<EOL>**kwargs): | if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>if self.xapikey:<EOL><INDENT>xapikey = self.xapikey<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>xapikey = kwargs.pop("<STR_LIT>")<EOL><DEDENT>if self.username:<EOL><INDENT>username = self.username<EOL><DEDENT>elif '<STR_LIT:username>' in kwargs:<EOL><INDENT>username = kwargs.pop("<STR_LIT:username>")<EOL><DEDENT>elif service == "<STR_LIT>":<EOL><INDENT>if any(substring in action for substring in<EOL>["<STR_LIT:store>", "<STR_LIT>"]):<EOL><INDENT>username = self._store_payout_username(**kwargs)<EOL><DEDENT>else:<EOL><INDENT>username = self._review_payout_username(**kwargs)<EOL><DEDENT><DEDENT>if not username:<EOL><INDENT>errorstring = """<STR_LIT>"""<EOL>raise AdyenInvalidRequestError(errorstring)<EOL><DEDENT>if self.password:<EOL><INDENT>password = self.password<EOL><DEDENT>elif '<STR_LIT:password>' in kwargs:<EOL><INDENT>password = kwargs.pop("<STR_LIT:password>")<EOL><DEDENT>elif service == "<STR_LIT>":<EOL><INDENT>if any(substring in action for substring in<EOL>["<STR_LIT:store>", "<STR_LIT>"]):<EOL><INDENT>password = self._store_payout_pass(**kwargs)<EOL><DEDENT>else:<EOL><INDENT>password = self._review_payout_pass(**kwargs)<EOL><DEDENT><DEDENT>if not password:<EOL><INDENT>errorstring = """<STR_LIT>"""<EOL>raise AdyenInvalidRequestError(errorstring)<EOL><DEDENT>if self.platform:<EOL><INDENT>platform = self.platform<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>platform = kwargs.pop('<STR_LIT>')<EOL><DEDENT>if not isinstance(platform, str):<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise TypeError(errorstring)<EOL><DEDENT>elif platform.lower() not in ['<STR_LIT>', '<STR_LIT:test>']:<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise ValueError(errorstring)<EOL><DEDENT>message = request_data<EOL>if not message.get('<STR_LIT>'):<EOL><INDENT>message['<STR_LIT>'] = self.merchant_account<EOL><DEDENT>request_data['<STR_LIT>'] = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:name>": settings.LIB_NAME,<EOL>"<STR_LIT:version>": settings.LIB_VERSION<EOL>}<EOL>}<EOL>headers = {}<EOL>if idempotency:<EOL><INDENT>headers['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>url = self._determine_api_url(platform, service, action)<EOL>raw_response, raw_request, status_code, headers =self.http_client.request(url, json=message, username=username,<EOL>password=password, headers=headers,<EOL>**kwargs)<EOL>adyen_result = self._handle_response(url, raw_response, raw_request,<EOL>status_code, headers, message)<EOL>return adyen_result<EOL> | This will call the adyen api. username, password, merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an exception
is raised.
Args:
request_data (dict): The dictionary of the request to place. This
should be in the structure of the Adyen API.
https://docs.adyen.com/manuals/api-manual
service (str): This is the API service to be called.
action (str): The specific action of the API service to be called
idempotency (bool, optional): Whether the transaction should be
processed idempotently.
https://docs.adyen.com/manuals/api-manual#apiidempotency
Returns:
AdyenResult: The AdyenResult is returned when a request was
succesful. | f729:c1:m8 |
def call_hpp(self, message, action, hmac_key="<STR_LIT>", **kwargs): | if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>hmac = hmac_key<EOL>if self.hmac:<EOL><INDENT>hmac = self.hmac<EOL><DEDENT>elif not hmac:<EOL><INDENT>errorstring = """<STR_LIT>"""<EOL>raise AdyenInvalidRequestError(errorstring)<EOL><DEDENT>platform = self.platform<EOL>if not isinstance(platform, str):<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise TypeError(errorstring)<EOL><DEDENT>elif platform.lower() not in ['<STR_LIT>', '<STR_LIT:test>']:<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise ValueError(errorstring)<EOL><DEDENT>if '<STR_LIT>' not in message:<EOL><INDENT>message['<STR_LIT>'] = self.skin_code<EOL><DEDENT>if '<STR_LIT>' not in message:<EOL><INDENT>message['<STR_LIT>'] = self.merchant_account<EOL><DEDENT>if message['<STR_LIT>'] == "<STR_LIT>":<EOL><INDENT>message['<STR_LIT>'] = self.merchant_account<EOL><DEDENT>message["<STR_LIT>"] = util.generate_hpp_sig(message, hmac)<EOL>url = self._determine_hpp_url(platform, action)<EOL>raw_response, raw_request, status_code, headers =self.http_client.request(url, data=message,<EOL>username="<STR_LIT>", password="<STR_LIT>", **kwargs)<EOL>adyen_result = self._handle_response(url, raw_response, raw_request,<EOL>status_code, headers, message)<EOL>return adyen_result<EOL> | This will call the adyen hpp. hmac_key and platform are pulled from
root module level and or self object.
AdyenResult will be returned on 200 response.
Otherwise, an exception is raised.
Args:
request_data (dict): The dictionary of the request to place. This
should be in the structure of the Adyen API.
https://docs.adyen.com/manuals/api-manual
service (str): This is the API service to be called.
action (str): The specific action of the API service to be called
idempotency (bool, optional): Whether the transaction should be
processed idempotently.
https://docs.adyen.com/manuals/api-manual#apiidempotency
Returns:
AdyenResult: The AdyenResult is returned when a request was
succesful.
:param message:
:param hmac_key: | f729:c1:m9 |
def call_checkout_api(self, request_data, action, **kwargs): | if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>if self.xapikey:<EOL><INDENT>xapikey = self.xapikey<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>xapikey = kwargs.pop("<STR_LIT>")<EOL><DEDENT>if not xapikey:<EOL><INDENT>errorstring = """<STR_LIT>"""<EOL>raise AdyenInvalidRequestError(errorstring)<EOL><DEDENT>if self.platform:<EOL><INDENT>platform = self.platform<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>platform = kwargs.pop('<STR_LIT>')<EOL><DEDENT>if not isinstance(platform, str):<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise TypeError(errorstring)<EOL><DEDENT>elif platform.lower() not in ['<STR_LIT>', '<STR_LIT:test>']:<EOL><INDENT>errorstring = "<STR_LIT>"<EOL>raise ValueError(errorstring)<EOL><DEDENT>if not request_data.get('<STR_LIT>'):<EOL><INDENT>request_data['<STR_LIT>'] = self.merchant_account<EOL><DEDENT>request_data['<STR_LIT>'] = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:name>": settings.LIB_NAME,<EOL>"<STR_LIT:version>": settings.LIB_VERSION<EOL>}<EOL>}<EOL>headers = {}<EOL>url = self._determine_checkout_url(platform, action)<EOL>raw_response, raw_request, status_code, headers =self.http_client.request(url, json=request_data,<EOL>xapikey=xapikey, headers=headers,<EOL>**kwargs)<EOL>adyen_result = self._handle_response(url, raw_response, raw_request,<EOL>status_code, headers,<EOL>request_data)<EOL>return adyen_result<EOL> | This will call the checkout adyen api. xapi key merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an exception
is raised.
Args:
request_data (dict): The dictionary of the request to place. This
should be in the structure of the Adyen API.
https://docs.adyen.com/developers/checkout/api-integration
service (str): This is the API service to be called.
action (str): The specific action of the API service to be called | f729:c1:m10 |
def _handle_response(self, url, raw_response, raw_request,<EOL>status_code, headers, request_dict): | if status_code != <NUM_LIT:200>:<EOL><INDENT>response = {}<EOL>if raw_response:<EOL><INDENT>response = json_lib.loads(raw_response)<EOL><DEDENT>self._handle_http_error(url, response, status_code,<EOL>headers.get('<STR_LIT>'),<EOL>raw_request, raw_response,<EOL>headers, request_dict)<EOL>try:<EOL><INDENT>if response['<STR_LIT>']:<EOL><INDENT>raise AdyenAPICommunicationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>raw_response,<EOL>status_code,<EOL>headers.get('<STR_LIT>')),<EOL>status_code=status_code,<EOL>raw_request=raw_request,<EOL>raw_response=raw_response,<EOL>url=url,<EOL>psp=headers.get('<STR_LIT>'),<EOL>headers=headers,<EOL>error_code=response['<STR_LIT>'])<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>erstr = '<STR_LIT>'<EOL>raise AdyenAPICommunicationError(erstr)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>response = json_lib.loads(raw_response)<EOL>psp = headers.get('<STR_LIT>', response.get('<STR_LIT>'))<EOL>return AdyenResult(message=response, status_code=status_code,<EOL>psp=psp, raw_request=raw_request,<EOL>raw_response=raw_response)<EOL><DEDENT>except ValueError:<EOL><INDENT>error = self._error_from_hpp(raw_response)<EOL>message = request_dict<EOL>reference = message.get("<STR_LIT>",<EOL>message.get("<STR_LIT>"))<EOL>errorstring = """<STR_LIT>""".format(error, reference),<EOL>raise AdyenInvalidRequestError(errorstring)<EOL><DEDENT><DEDENT> | This parses the content from raw communication, raising an error if
anything other than 200 was returned.
Args:
url (str): URL where request was made
raw_response (str): The raw communication sent to Adyen
raw_request (str): The raw response returned by Adyen
status_code (int): The HTTP status code
headers (dict): Key/Value of the headers.
request_dict (dict): The original request dictionary that was given
to the HTTPClient.
Returns:
AdyenResult: Result object if successful. | f729:c1:m12 |
def _handle_http_error(self, url, response_obj, status_code, psp_ref,<EOL>raw_request, raw_response, headers, message): | if status_code == <NUM_LIT>:<EOL><INDENT>if url == self.merchant_specific_url:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>".format(url)<EOL>raise AdyenAPICommunicationError(erstr,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>raise AdyenAPICommunicationError(erstr,<EOL>raw_request=raw_request,<EOL>raw_response=raw_response,<EOL>url=url,<EOL>psp=psp_ref,<EOL>headers=headers,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT><DEDENT>elif status_code == <NUM_LIT>:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>" % (<EOL>response_obj["<STR_LIT>"], response_obj["<STR_LIT:message>"],<EOL>status_code, psp_ref)<EOL>raise AdyenAPIValidationError(erstr, error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>elif status_code == <NUM_LIT>:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>raise AdyenAPIAuthenticationError(erstr,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>elif status_code == <NUM_LIT>:<EOL><INDENT>if response_obj.get("<STR_LIT:message>") == "<STR_LIT>":<EOL><INDENT>erstr = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")% raw_request['<STR_LIT>']<EOL>raise AdyenAPIInvalidPermission(erstr,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>" % (<EOL>response_obj["<STR_LIT:message>"], self.username, psp_ref)<EOL>raise AdyenAPIInvalidPermission(erstr, error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>elif status_code == <NUM_LIT>:<EOL><INDENT>if response_obj.get("<STR_LIT:message>") == "<STR_LIT>":<EOL><INDENT>raise AdyenAPIInvalidAmount(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>error_code=response_obj.get("<STR_LIT>"))<EOL><DEDENT><DEDENT>elif status_code == <NUM_LIT>:<EOL><INDENT>if response_obj.get("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>err_args = (response_obj.get("<STR_LIT>"),<EOL>response_obj.get("<STR_LIT:message>"),<EOL>status_code)<EOL>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>" % err_args<EOL>raise AdyenAPIValidationError(erstr,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>if response_obj.get("<STR_LIT:message>") == "<STR_LIT>""<STR_LIT>""<STR_LIT>":<EOL><INDENT>raise AdyenAPIInvalidFormat(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>error_code=response_obj.get("<STR_LIT>")<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AdyenAPICommunicationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(raw_response, status_code, psp_ref),<EOL>status_code=status_code,<EOL>raw_request=raw_request,<EOL>raw_response=raw_response,<EOL>url=url,<EOL>psp=psp_ref,<EOL>headers=headers, error_code=response_obj.get("<STR_LIT>"))<EOL><DEDENT> | This function handles the non 200 responses from Adyen, raising an
error that should provide more information.
Args:
url (str): url of the request
response_obj (dict): Dict containing the parsed JSON response from
Adyen
status_code (int): HTTP status code of the request
psp_ref (str): Psp reference of the request attempt
raw_request (str): The raw request placed to Adyen
raw_response (str): The raw response(body) returned by Adyen
headers(dict): headers of the response
Returns:
None | f729:c1:m13 |
def _pycurl_post(self,<EOL>url,<EOL>json=None,<EOL>data=None,<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers={},<EOL>timeout=<NUM_LIT:30>): | response_headers = {}<EOL>curl = pycurl.Curl()<EOL>curl.setopt(curl.URL, url)<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stringbuffer = BytesIO()<EOL><DEDENT>else:<EOL><INDENT>stringbuffer = StringIO()<EOL><DEDENT>curl.setopt(curl.WRITEDATA, stringbuffer)<EOL>headers['<STR_LIT>'] = self.user_agent<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>header_list = ["<STR_LIT>" % (k, v) for k, v in headers.items()]<EOL><DEDENT>else:<EOL><INDENT>header_list = ["<STR_LIT>" % (k, v) for k, v in headers.iteritems()]<EOL><DEDENT>if json:<EOL><INDENT>header_list.append("<STR_LIT>")<EOL><DEDENT>curl.setopt(pycurl.HTTPHEADER, header_list)<EOL>raw_store = json<EOL>raw_request = json_lib.dumps(json) if json else urlencode(data)<EOL>curl.setopt(curl.POSTFIELDS, raw_request)<EOL>if username and password:<EOL><INDENT>curl.setopt(curl.USERPWD, '<STR_LIT>' % (username, password))<EOL><DEDENT>curl.setopt(curl.TIMEOUT, timeout)<EOL>curl.perform()<EOL>result = stringbuffer.getvalue()<EOL>status_code = curl.getinfo(curl.RESPONSE_CODE)<EOL>curl.close()<EOL>raw_request = raw_store<EOL>return result, raw_request, status_code, response_headers<EOL> | This function will POST to the url endpoint using pycurl. returning
an AdyenResult object on 200 HTTP responce. Either json or data has to
be provided. If username and password are provided, basic auth will be
used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure
of key/value of request to place
username (str, optional): Username for basic auth. Must be included
as part of password.
password (str, optional): Password for basic auth. Must be included
as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received. | f733:c0:m1 |
def _requests_post(self, url,<EOL>json=None,<EOL>data=None,<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>xapikey="<STR_LIT>",<EOL>headers=None,<EOL>timeout=<NUM_LIT:30>): | if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>auth = None<EOL>if username and password:<EOL><INDENT>auth = requests.auth.HTTPBasicAuth(username, password)<EOL><DEDENT>elif xapikey:<EOL><INDENT>headers['<STR_LIT>'] = xapikey<EOL><DEDENT>headers['<STR_LIT>'] = self.user_agent<EOL>request = requests.post(url, auth=auth, data=data, json=json,<EOL>headers=headers, timeout=timeout)<EOL>message = json<EOL>return request.text, message, request.status_code, request.headers<EOL> | This function will POST to the url endpoint using requests.
Returning an AdyenResult object on 200 HTTP response.
Either json or data has to be provided.
If username and password are provided, basic auth will be used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure of key/value
of request to place
username (str, optionl): Username for basic auth. Must be included
as part of password.
password (str, optional): Password for basic auth. Must be included
as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received. | f733:c0:m2 |
def _urllib_post(self, url,<EOL>json="<STR_LIT>",<EOL>data="<STR_LIT>",<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers=None,<EOL>timeout=<NUM_LIT:30>): | if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>raw_store = json<EOL>raw_request = json_lib.dumps(json) if json else urlencode(data)<EOL>url_request = Request(url, data=raw_request.encode('<STR_LIT:utf8>'))<EOL>if json:<EOL><INDENT>url_request.add_header('<STR_LIT:Content-Type>', '<STR_LIT:application/json>')<EOL><DEDENT>elif not data:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>headers['<STR_LIT>'] = self.user_agent<EOL>raw_request = raw_store<EOL>if username and password:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>basic_authstring = base64.encodebytes(('<STR_LIT>' %<EOL>(username, password))<EOL>.encode()).decode().replace('<STR_LIT:\n>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>basic_authstring = base64.encodestring('<STR_LIT>' % (username,<EOL>password)).replace('<STR_LIT:\n>', '<STR_LIT>')<EOL><DEDENT>url_request.add_header("<STR_LIT>",<EOL>"<STR_LIT>" % basic_authstring)<EOL><DEDENT>for key, value in headers.items():<EOL><INDENT>url_request.add_header(key, str(value))<EOL><DEDENT>try:<EOL><INDENT>response = urlopen(url_request, timeout=timeout)<EOL><DEDENT>except HTTPError as e:<EOL><INDENT>raw_response = e.read()<EOL>return raw_response, raw_request, e.getcode(), e.headers<EOL><DEDENT>else:<EOL><INDENT>raw_response = response.read()<EOL>response.close()<EOL>return (raw_response, raw_request,<EOL>response.getcode(), dict(response.info()))<EOL><DEDENT> | This function will POST to the url endpoint using urllib2. returning
an AdyenResult object on 200 HTTP responce. Either json or data has to
be provided. If username and password are provided, basic auth will be
used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure of
key/value of request to place as
www-form
username (str, optional): Username for basic auth. Must be
uncluded as part of password.
password (str, optional): Password for basic auth. Must be
included as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received. | f733:c0:m3 |
def request(self, url,<EOL>json="<STR_LIT>",<EOL>data="<STR_LIT>",<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers=None,<EOL>timout=<NUM_LIT:30>): | raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL> | This is overridden on module initialization. This function will make
an HTTP POST to a given url. Either json/data will be what is posted to
the end point. he HTTP request needs to be basicAuth when username and
password are provided. a headers dict maybe provided,
whatever the values are should be applied.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure of
key/value of request to place as
www-form
username (str, optional): Username for basic auth. Must be
uncluded as part of password.
password (str, optional): Password for basic auth. Must be
included as part of username.
headers (dict, optional): Key/Value pairs of headers to include
Returns:
str: Raw request placed
str: Raw response received
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received.
:param timout: | f733:c0:m4 |
def get_github_content(repo,path,auth=None): | request = requests.get(file_url.format(repo=repo, path=path), auth=auth)<EOL>if not request.ok:<EOL><INDENT>print("<STR_LIT>")<EOL>print(file_url.format(repo=repo, path=path))<EOL>print(request.json())<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>if not request.json()['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(path,repo,request.json()['<STR_LIT>']))<EOL><DEDENT>return request.json()['<STR_LIT:content>'].decode('<STR_LIT>').decode('<STR_LIT:utf8>')<EOL> | Retrieve text files from a github repo | f746:m0 |
def collect_reponames(): | reponames = []<EOL>try:<EOL><INDENT>with open(os.devnull) as devnull:<EOL><INDENT>remote_data = subprocess.check_output(["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"],stderr=devnull)<EOL><DEDENT>branches = {}<EOL>for line in remote_data.decode('<STR_LIT:utf-8>').split("<STR_LIT:\n>"):<EOL><INDENT>if line.strip() == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>remote_match = re_mote.match(line)<EOL>if not remote_match is None:<EOL><INDENT>branches[remote_match.group(<NUM_LIT:1>)] = remote_match.group(<NUM_LIT:5>)<EOL><DEDENT><DEDENT>if len(branches) > <NUM_LIT:0>:<EOL><INDENT>if "<STR_LIT>" in branches:<EOL><INDENT>reponames.append(branches["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>reponames.append(branches.values()[<NUM_LIT:0>])<EOL><DEDENT><DEDENT><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>pass<EOL><DEDENT>for fname in glob.iglob("<STR_LIT>"):<EOL><INDENT>fid = open(fname,"<STR_LIT:r>","<STR_LIT:utf8>")<EOL>fid.readline()<EOL>line = fid.readline()<EOL>match = re.match(repo_marker_re,line)<EOL>if not match is None:<EOL><INDENT>reponames.append(match.group(<NUM_LIT:1>))<EOL><DEDENT>reponames = list(set(reponames))<EOL><DEDENT>return reponames<EOL> | Try to figure out a list of repos to consider by default from the contents of the working directory. | f746:m3 |
def collect_github_config(): | github_config = {}<EOL>for field in ["<STR_LIT:user>", "<STR_LIT>"]:<EOL><INDENT>try:<EOL><INDENT>github_config[field] = subprocess.check_output(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>".format(field)]).decode('<STR_LIT:utf-8>').strip()<EOL><DEDENT>except (OSError, subprocess.CalledProcessError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return github_config<EOL> | Try load Github configuration such as usernames from the local or global git config | f746:m4 |
def yearplot(data, year=None, how='<STR_LIT>', vmin=None, vmax=None, cmap='<STR_LIT>',<EOL>fillcolor='<STR_LIT>', linewidth=<NUM_LIT:1>, linecolor=None,<EOL>daylabels=calendar.day_abbr[:], dayticks=True,<EOL>monthlabels=calendar.month_abbr[<NUM_LIT:1>:], monthticks=True, ax=None,<EOL>**kwargs): | if year is None:<EOL><INDENT>year = data.index.sort_values()[<NUM_LIT:0>].year<EOL><DEDENT>if how is None:<EOL><INDENT>by_day = data<EOL><DEDENT>else:<EOL><INDENT>if _pandas_18:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>').agg(how)<EOL><DEDENT>else:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>', how=how)<EOL><DEDENT><DEDENT>if vmin is None:<EOL><INDENT>vmin = by_day.min()<EOL><DEDENT>if vmax is None:<EOL><INDENT>vmax = by_day.max()<EOL><DEDENT>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if linecolor is None:<EOL><INDENT>linecolor = ax.get_axis_bgcolor()<EOL>if ColorConverter().to_rgba(linecolor)[-<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>linecolor = '<STR_LIT>'<EOL><DEDENT><DEDENT>by_day = by_day[str(year)]<EOL>by_day = by_day.reindex(<EOL>pd.date_range(start=str(year), end=str(year + <NUM_LIT:1>), freq='<STR_LIT:D>')[:-<NUM_LIT:1>])<EOL>by_day = pd.DataFrame({'<STR_LIT:data>': by_day,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT>': by_day.index.dayofweek,<EOL>'<STR_LIT>': by_day.index.week})<EOL>by_day.loc[(by_day.index.month == <NUM_LIT:1>) & (by_day.week > <NUM_LIT:50>), '<STR_LIT>'] = <NUM_LIT:0><EOL>by_day.loc[(by_day.index.month == <NUM_LIT:12>) & (by_day.week < <NUM_LIT:10>), '<STR_LIT>']= by_day.week.max() + <NUM_LIT:1><EOL>plot_data = by_day.pivot('<STR_LIT>', '<STR_LIT>', '<STR_LIT:data>').values[::-<NUM_LIT:1>]<EOL>plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data)<EOL>fill_data = by_day.pivot('<STR_LIT>', '<STR_LIT>', '<STR_LIT>').values[::-<NUM_LIT:1>]<EOL>fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data)<EOL>ax.pcolormesh(fill_data, vmin=<NUM_LIT:0>, vmax=<NUM_LIT:1>, cmap=ListedColormap([fillcolor]))<EOL>kwargs['<STR_LIT>'] = linewidth<EOL>kwargs['<STR_LIT>'] = linecolor<EOL>ax.pcolormesh(plot_data, vmin=vmin, vmax=vmax, cmap=cmap, **kwargs)<EOL>ax.set(xlim=(<NUM_LIT:0>, plot_data.shape[<NUM_LIT:1>]), ylim=(<NUM_LIT:0>, plot_data.shape[<NUM_LIT:0>]))<EOL>ax.set_aspect('<STR_LIT>')<EOL>for side in ('<STR_LIT>', '<STR_LIT:right>', '<STR_LIT:left>', '<STR_LIT>'):<EOL><INDENT>ax.spines[side].set_visible(False)<EOL><DEDENT>ax.xaxis.set_tick_params(which='<STR_LIT>', length=<NUM_LIT:0>)<EOL>ax.yaxis.set_tick_params(which='<STR_LIT>', length=<NUM_LIT:0>)<EOL>if monthticks is True:<EOL><INDENT>monthticks = range(len(monthlabels))<EOL><DEDENT>elif monthticks is False:<EOL><INDENT>monthticks = []<EOL><DEDENT>elif isinstance(monthticks, int):<EOL><INDENT>monthticks = range(len(monthlabels))[monthticks // <NUM_LIT:2>::monthticks]<EOL><DEDENT>if dayticks is True:<EOL><INDENT>dayticks = range(len(daylabels))<EOL><DEDENT>elif dayticks is False:<EOL><INDENT>dayticks = []<EOL><DEDENT>elif isinstance(dayticks, int):<EOL><INDENT>dayticks = range(len(daylabels))[dayticks // <NUM_LIT:2>::dayticks]<EOL><DEDENT>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_xticks([by_day.ix[datetime.date(year, i + <NUM_LIT:1>, <NUM_LIT:15>)].week<EOL>for i in monthticks])<EOL>ax.set_xticklabels([monthlabels[i] for i in monthticks], ha='<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.yaxis.set_ticks_position('<STR_LIT:right>')<EOL>ax.set_yticks([<NUM_LIT:6> - i + <NUM_LIT:0.5> for i in dayticks])<EOL>ax.set_yticklabels([daylabels[i] for i in dayticks], rotation='<STR_LIT>',<EOL>va='<STR_LIT>')<EOL>return ax<EOL> | Plot one year from a timeseries as a calendar heatmap.
Parameters
----------
data : Series
Data for the plot. Must be indexed by a DatetimeIndex.
year : integer
Only data indexed by this year will be plotted. If `None`, the first
year for which there is data will be plotted.
how : string
Method for resampling data by day. If `None`, assume data is already
sampled by day and don't resample. Otherwise, this is passed to Pandas
`Series.resample`.
vmin, vmax : floats
Values to anchor the colormap. If `None`, min and max are used after
resampling data by day.
cmap : matplotlib colormap name or object
The mapping from data values to color space.
fillcolor : matplotlib color
Color to use for days without data.
linewidth : float
Width of the lines that will divide each day.
linecolor : color
Color of the lines that will divide each day. If `None`, the axes
background color is used, or 'white' if it is transparent.
daylabels : list
Strings to use as labels for days, must be of length 7.
dayticks : list or int or bool
If `True`, label all days. If `False`, don't label days. If a list,
only label days with these indices. If an integer, label every n day.
monthlabels : list
Strings to use as labels for months, must be of length 12.
monthticks : list or int or bool
If `True`, label all months. If `False`, don't label months. If a
list, only label months with these indices. If an integer, label every
n month.
ax : matplotlib Axes
Axes in which to draw the plot, otherwise use the currently-active
Axes.
kwargs : other keyword arguments
All other keyword arguments are passed to matplotlib `ax.pcolormesh`.
Returns
-------
ax : matplotlib Axes
Axes object with the calendar heatmap.
Examples
--------
By default, `yearplot` plots the first year and sums the values per day:
.. plot::
:context: close-figs
calmap.yearplot(events)
We can choose which year is plotted with the `year` keyword argment:
.. plot::
:context: close-figs
calmap.yearplot(events, year=2015)
The appearance can be changed by using another colormap. Here we also use
a darker fill color for days without data and remove the lines:
.. plot::
:context: close-figs
calmap.yearplot(events, cmap='YlGn', fillcolor='grey',
linewidth=0)
The axis tick labels can look a bit crowded. We can ask to draw only every
nth label, or explicitely supply the label indices. The labels themselves
can also be customized:
.. plot::
:context: close-figs
calmap.yearplot(events, monthticks=3, daylabels='MTWTFSS',
dayticks=[0, 2, 4, 6]) | f749:m0 |
def calendarplot(data, how='<STR_LIT>', yearlabels=True, yearascending=True, yearlabel_kws=None,<EOL>subplot_kws=None, gridspec_kws=None, fig_kws=None, **kwargs): | yearlabel_kws = yearlabel_kws or {}<EOL>subplot_kws = subplot_kws or {}<EOL>gridspec_kws = gridspec_kws or {}<EOL>fig_kws = fig_kws or {}<EOL>years = np.unique(data.index.year)<EOL>if not yearascending:<EOL><INDENT>years = years[::-<NUM_LIT:1>]<EOL><DEDENT>fig, axes = plt.subplots(nrows=len(years), ncols=<NUM_LIT:1>, squeeze=False,<EOL>subplot_kw=subplot_kws,<EOL>gridspec_kw=gridspec_kws, **fig_kws)<EOL>axes = axes.T[<NUM_LIT:0>]<EOL>if how is None:<EOL><INDENT>by_day = data<EOL><DEDENT>else:<EOL><INDENT>if _pandas_18:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>').agg(how)<EOL><DEDENT>else:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>', how=how)<EOL><DEDENT><DEDENT>ylabel_kws = dict(<EOL>fontsize=<NUM_LIT:32>,<EOL>color=kwargs.get('<STR_LIT>', '<STR_LIT>'),<EOL>fontweight='<STR_LIT>',<EOL>fontname='<STR_LIT>',<EOL>ha='<STR_LIT>')<EOL>ylabel_kws.update(yearlabel_kws)<EOL>max_weeks = <NUM_LIT:0><EOL>for year, ax in zip(years, axes):<EOL><INDENT>yearplot(by_day, year=year, how=None, ax=ax, **kwargs)<EOL>max_weeks = max(max_weeks, ax.get_xlim()[<NUM_LIT:1>])<EOL>if yearlabels:<EOL><INDENT>ax.set_ylabel(str(year), **ylabel_kws)<EOL><DEDENT><DEDENT>for ax in axes:<EOL><INDENT>ax.set_xlim(<NUM_LIT:0>, max_weeks)<EOL><DEDENT>plt.tight_layout()<EOL>return fig, axes<EOL> | Plot a timeseries as a calendar heatmap.
Parameters
----------
data : Series
Data for the plot. Must be indexed by a DatetimeIndex.
how : string
Method for resampling data by day. If `None`, assume data is already
sampled by day and don't resample. Otherwise, this is passed to Pandas
`Series.resample`.
yearlabels : bool
Whether or not to draw the year for each subplot.
yearascending : bool
Sort the calendar in ascending or descending order.
yearlabel_kws : dict
Keyword arguments passed to the matplotlib `set_ylabel` call which is
used to draw the year for each subplot.
subplot_kws : dict
Keyword arguments passed to the matplotlib `add_subplot` call used to
create each subplot.
gridspec_kws : dict
Keyword arguments passed to the matplotlib `GridSpec` constructor used
to create the grid the subplots are placed on.
fig_kws : dict
Keyword arguments passed to the matplotlib `figure` call.
kwargs : other keyword arguments
All other keyword arguments are passed to `yearplot`.
Returns
-------
fig, axes : matplotlib Figure and Axes
Tuple where `fig` is the matplotlib Figure object `axes` is an array
of matplotlib Axes objects with the calendar heatmaps, one per year.
Examples
--------
With `calendarplot` we can plot several years in one figure:
.. plot::
:context: close-figs
calmap.calendarplot(events) | f749:m1 |
def mark_plot_labels(app, document): | for name, explicit in six.iteritems(document.nametypes):<EOL><INDENT>if not explicit:<EOL><INDENT>continue<EOL><DEDENT>labelid = document.nameids[name]<EOL>if labelid is None:<EOL><INDENT>continue<EOL><DEDENT>node = document.ids[labelid]<EOL>if node.tagname in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>for n in node:<EOL><INDENT>if n.tagname == '<STR_LIT>':<EOL><INDENT>sectname = name<EOL>for c in n:<EOL><INDENT>if c.tagname == '<STR_LIT>':<EOL><INDENT>sectname = c.astext()<EOL>break<EOL><DEDENT><DEDENT>node['<STR_LIT>'].remove(labelid)<EOL>node['<STR_LIT>'].remove(name)<EOL>n['<STR_LIT>'].append(labelid)<EOL>n['<STR_LIT>'].append(name)<EOL>document.settings.env.labels[name] =document.settings.env.docname, labelid, sectname<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | To make plots referenceable, we need to move the reference from
the "htmlonly" (or "latexonly") node to the actual figure node
itself. | f750:m5 |
def split_code_at_show(text): | parts = []<EOL>is_doctest = contains_doctest(text)<EOL>part = []<EOL>for line in text.split("<STR_LIT:\n>"):<EOL><INDENT>if (not is_doctest and line.strip() == '<STR_LIT>') or(is_doctest and line.strip() == '<STR_LIT>'):<EOL><INDENT>part.append(line)<EOL>parts.append("<STR_LIT:\n>".join(part))<EOL>part = []<EOL><DEDENT>else:<EOL><INDENT>part.append(line)<EOL><DEDENT><DEDENT>if "<STR_LIT:\n>".join(part).strip():<EOL><INDENT>parts.append("<STR_LIT:\n>".join(part))<EOL><DEDENT>return parts<EOL> | Split code at plt.show() | f750:m9 |
def remove_coding(text): | sub_re = re.compile("<STR_LIT>", flags=re.MULTILINE)<EOL>return sub_re.sub("<STR_LIT>", text)<EOL> | Remove the coding comment, which six.exec_ doesn't like. | f750:m10 |
def out_of_date(original, derived): | return (not os.path.exists(derived) or<EOL>(os.path.exists(original) and<EOL>os.stat(derived).st_mtime < os.stat(original).st_mtime))<EOL> | Returns True if derivative is out-of-date wrt original,
both of which are full file paths. | f750:m11 |
def run_code(code, code_path, ns=None, function_name=None): | <EOL>if six.PY2:<EOL><INDENT>pwd = os.getcwdu()<EOL><DEDENT>else:<EOL><INDENT>pwd = os.getcwd()<EOL><DEDENT>old_sys_path = list(sys.path)<EOL>if setup.config.plot_working_directory is not None:<EOL><INDENT>try:<EOL><INDENT>os.chdir(setup.config.plot_working_directory)<EOL><DEDENT>except OSError as err:<EOL><INDENT>raise OSError(str(err) + '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>except TypeError as err:<EOL><INDENT>raise TypeError(str(err) + '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT:None>')<EOL><DEDENT>sys.path.insert(<NUM_LIT:0>, setup.config.plot_working_directory)<EOL><DEDENT>elif code_path is not None:<EOL><INDENT>dirname = os.path.abspath(os.path.dirname(code_path))<EOL>os.chdir(dirname)<EOL>sys.path.insert(<NUM_LIT:0>, dirname)<EOL><DEDENT>old_sys_argv = sys.argv<EOL>sys.argv = [code_path]<EOL>stdout = sys.stdout<EOL>if six.PY3:<EOL><INDENT>sys.stdout = io.StringIO()<EOL><DEDENT>else:<EOL><INDENT>sys.stdout = cStringIO.StringIO()<EOL><DEDENT>def _dummy_print(*arg, **kwarg):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>try:<EOL><INDENT>code = unescape_doctest(code)<EOL>if ns is None:<EOL><INDENT>ns = {}<EOL><DEDENT>if not ns:<EOL><INDENT>if setup.config.plot_pre_code is None:<EOL><INDENT>six.exec_(six.text_type("<STR_LIT>" +<EOL>"<STR_LIT>"), ns)<EOL><DEDENT>else:<EOL><INDENT>six.exec_(six.text_type(setup.config.plot_pre_code), ns)<EOL><DEDENT><DEDENT>ns['<STR_LIT>'] = _dummy_print<EOL>if "<STR_LIT:__main__>" in code:<EOL><INDENT>six.exec_("<STR_LIT>", ns)<EOL><DEDENT>code = remove_coding(code)<EOL>six.exec_(code, ns)<EOL>if function_name is not None:<EOL><INDENT>six.exec_(function_name + "<STR_LIT>", ns)<EOL><DEDENT><DEDENT>except (Exception, SystemExit) as err:<EOL><INDENT>raise PlotError(traceback.format_exc())<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>os.chdir(pwd)<EOL>sys.argv = old_sys_argv<EOL>sys.path[:] = old_sys_path<EOL>sys.stdout = stdout<EOL><DEDENT>return ns<EOL> | Import a Python module from a path, and run the function given by
name, if function_name is not None. | f750:m12 |
def render_figures(code, code_path, output_dir, output_base, context,<EOL>function_name, config, context_reset=False,<EOL>close_figs=False): | <EOL>default_dpi = {'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:200>, '<STR_LIT>': <NUM_LIT:200>}<EOL>formats = []<EOL>plot_formats = config.plot_formats<EOL>if isinstance(plot_formats, six.string_types):<EOL><INDENT>plot_formats = plot_formats.split('<STR_LIT:U+002C>')<EOL><DEDENT>for fmt in plot_formats:<EOL><INDENT>if isinstance(fmt, six.string_types):<EOL><INDENT>if '<STR_LIT::>' in fmt:<EOL><INDENT>suffix,dpi = fmt.split('<STR_LIT::>')<EOL>formats.append((str(suffix), int(dpi)))<EOL><DEDENT>else:<EOL><INDENT>formats.append((fmt, default_dpi.get(fmt, <NUM_LIT>)))<EOL><DEDENT><DEDENT>elif type(fmt) in (tuple, list) and len(fmt)==<NUM_LIT:2>:<EOL><INDENT>formats.append((str(fmt[<NUM_LIT:0>]), int(fmt[<NUM_LIT:1>])))<EOL><DEDENT>else:<EOL><INDENT>raise PlotError('<STR_LIT>' % fmt)<EOL><DEDENT><DEDENT>code_pieces = split_code_at_show(code)<EOL>all_exists = True<EOL>img = ImageFile(output_base, output_dir)<EOL>for format, dpi in formats:<EOL><INDENT>if out_of_date(code_path, img.filename(format)):<EOL><INDENT>all_exists = False<EOL>break<EOL><DEDENT>img.formats.append(format)<EOL><DEDENT>if all_exists:<EOL><INDENT>return [(code, [img])]<EOL><DEDENT>results = []<EOL>all_exists = True<EOL>for i, code_piece in enumerate(code_pieces):<EOL><INDENT>images = []<EOL>for j in xrange(<NUM_LIT:1000>):<EOL><INDENT>if len(code_pieces) > <NUM_LIT:1>:<EOL><INDENT>img = ImageFile('<STR_LIT>' % (output_base, i, j), output_dir)<EOL><DEDENT>else:<EOL><INDENT>img = ImageFile('<STR_LIT>' % (output_base, j), output_dir)<EOL><DEDENT>for format, dpi in formats:<EOL><INDENT>if out_of_date(code_path, img.filename(format)):<EOL><INDENT>all_exists = False<EOL>break<EOL><DEDENT>img.formats.append(format)<EOL><DEDENT>if not all_exists:<EOL><INDENT>all_exists = (j > <NUM_LIT:0>)<EOL>break<EOL><DEDENT>images.append(img)<EOL><DEDENT>if not all_exists:<EOL><INDENT>break<EOL><DEDENT>results.append((code_piece, images))<EOL><DEDENT>if all_exists:<EOL><INDENT>return results<EOL><DEDENT>results = []<EOL>if context:<EOL><INDENT>ns = plot_context<EOL><DEDENT>else:<EOL><INDENT>ns = {}<EOL><DEDENT>if context_reset:<EOL><INDENT>clear_state(config.plot_rcparams)<EOL>plot_context.clear()<EOL><DEDENT>close_figs = not context or close_figs<EOL>for i, code_piece in enumerate(code_pieces):<EOL><INDENT>if not context or config.plot_apply_rcparams:<EOL><INDENT>clear_state(config.plot_rcparams, close_figs)<EOL><DEDENT>elif close_figs:<EOL><INDENT>plt.close('<STR_LIT:all>')<EOL><DEDENT>run_code(code_piece, code_path, ns, function_name)<EOL>images = []<EOL>fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()<EOL>for j, figman in enumerate(fig_managers):<EOL><INDENT>if len(fig_managers) == <NUM_LIT:1> and len(code_pieces) == <NUM_LIT:1>:<EOL><INDENT>img = ImageFile(output_base, output_dir)<EOL><DEDENT>elif len(code_pieces) == <NUM_LIT:1>:<EOL><INDENT>img = ImageFile("<STR_LIT>" % (output_base, j), output_dir)<EOL><DEDENT>else:<EOL><INDENT>img = ImageFile("<STR_LIT>" % (output_base, i, j),<EOL>output_dir)<EOL><DEDENT>images.append(img)<EOL>for format, dpi in formats:<EOL><INDENT>try:<EOL><INDENT>figman.canvas.figure.tight_layout()<EOL>figman.canvas.figure.savefig(img.filename(format),<EOL>dpi=dpi,<EOL>bbox_inches='<STR_LIT>')<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise PlotError(traceback.format_exc())<EOL><DEDENT>img.formats.append(format)<EOL><DEDENT><DEDENT>results.append((code_piece, images))<EOL><DEDENT>if not context or config.plot_apply_rcparams:<EOL><INDENT>clear_state(config.plot_rcparams, close=not context)<EOL><DEDENT>return results<EOL> | Run a pyplot script and save the low and high res PNGs and a PDF
in *output_dir*.
Save the images under *output_dir* with file names derived from
*output_base* | f750:m14 |
def get_forwarders(resolv="<STR_LIT>"): | ns = []<EOL>if os.path.exists(resolv):<EOL><INDENT>for l in open(resolv):<EOL><INDENT>if l.startswith("<STR_LIT>"):<EOL><INDENT>address = l.strip().split("<STR_LIT:U+0020>", <NUM_LIT:2>)[<NUM_LIT:1>]<EOL>if not address.startswith("<STR_LIT>"):<EOL><INDENT>ns.append(address)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not ns:<EOL><INDENT>ns = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>return ns<EOL> | Find the forwarders in /etc/resolv.conf, default to 8.8.8.8 and
8.8.4.4 | f753:m0 |
def spawn(opts, conf): | if opts.config is not None:<EOL><INDENT>os.environ["<STR_LIT>"] = opts.config<EOL><DEDENT>sys.argv[<NUM_LIT:1>:] = [<EOL>"<STR_LIT>", sibpath(__file__, "<STR_LIT>"),<EOL>"<STR_LIT>", conf['<STR_LIT>'],<EOL>"<STR_LIT>", conf['<STR_LIT>'],<EOL>]<EOL>twistd.run()<EOL> | Acts like twistd | f764:m0 |
def __init__(self, file_encoding=None, string_encoding=None,<EOL>decode_errors=None, search_dirs=None, file_extension=None,<EOL>escape=None, partials=None, missing_tags=None): | if decode_errors is None:<EOL><INDENT>decode_errors = defaults.DECODE_ERRORS<EOL><DEDENT>if escape is None:<EOL><INDENT>escape = defaults.TAG_ESCAPE<EOL><DEDENT>if file_encoding is None:<EOL><INDENT>file_encoding = defaults.FILE_ENCODING<EOL><DEDENT>if file_extension is None:<EOL><INDENT>file_extension = defaults.TEMPLATE_EXTENSION<EOL><DEDENT>if missing_tags is None:<EOL><INDENT>missing_tags = defaults.MISSING_TAGS<EOL><DEDENT>if search_dirs is None:<EOL><INDENT>search_dirs = defaults.SEARCH_DIRS<EOL><DEDENT>if string_encoding is None:<EOL><INDENT>string_encoding = defaults.STRING_ENCODING<EOL><DEDENT>if isinstance(search_dirs, basestring):<EOL><INDENT>search_dirs = [search_dirs]<EOL><DEDENT>self._context = None<EOL>self.decode_errors = decode_errors<EOL>self.escape = escape<EOL>self.file_encoding = file_encoding<EOL>self.file_extension = file_extension<EOL>self.missing_tags = missing_tags<EOL>self.partials = partials<EOL>self.search_dirs = search_dirs<EOL>self.string_encoding = string_encoding<EOL> | Construct an instance.
Arguments:
file_encoding: the name of the encoding to use by default when
reading template files. All templates are converted to unicode
prior to parsing. Defaults to the package default.
string_encoding: the name of the encoding to use when converting
to unicode any byte strings (type str in Python 2) encountered
during the rendering process. This name will be passed as the
encoding argument to the built-in function unicode().
Defaults to the package default.
decode_errors: the string to pass as the errors argument to the
built-in function unicode() when converting byte strings to
unicode. Defaults to the package default.
search_dirs: the list of directories in which to search when
loading a template by name or file name. If given a string,
the method interprets the string as a single directory.
Defaults to the package default.
file_extension: the template file extension. Pass False for no
extension (i.e. to use extensionless template files).
Defaults to the package default.
partials: an object (e.g. a dictionary) for custom partial loading
during the rendering process.
The object should have a get() method that accepts a string
and returns the corresponding template as a string, preferably
as a unicode string. If there is no template with that name,
the get() method should either return None (as dict.get() does)
or raise an exception.
If this argument is None, the rendering process will use
the normal procedure of locating and reading templates from
the file system -- using relevant instance attributes like
search_dirs, file_encoding, etc.
escape: the function used to escape variable tag values when
rendering a template. The function should accept a unicode
string (or subclass of unicode) and return an escaped string
that is again unicode (or a subclass of unicode).
This function need not handle strings of type `str` because
this class will only pass it unicode strings. The constructor
assigns this function to the constructed instance's escape()
method.
To disable escaping entirely, one can pass `lambda u: u`
as the escape function, for example. One may also wish to
consider using markupsafe's escape function: markupsafe.escape().
This argument defaults to the package default.
missing_tags: a string specifying how to handle missing tags.
If 'strict', an error is raised on a missing tag. If 'ignore',
the value of the tag is the empty string. Defaults to the
package default. | f766:c0:m0 |
@property<EOL><INDENT>def context(self):<DEDENT> | return self._context<EOL> | Return the current rendering context [experimental]. | f766:c0:m1 |
def str_coerce(self, val): | return str(val)<EOL> | Coerce a non-string value to a string.
This method is called whenever a non-string is encountered during the
rendering process when a string is needed (e.g. if a context value
for string interpolation is not a string). To customize string
coercion, you can override this method. | f766:c0:m2 |
def _to_unicode_soft(self, s): | <EOL>if isinstance(s, unicode):<EOL><INDENT>return s<EOL><DEDENT>return self.unicode(s)<EOL> | Convert a basestring to unicode, preserving any unicode subclass. | f766:c0:m3 |
def _to_unicode_hard(self, s): | return unicode(self._to_unicode_soft(s))<EOL> | Convert a basestring to a string with type unicode (not subclass). | f766:c0:m4 |
def _escape_to_unicode(self, s): | return unicode(self.escape(self._to_unicode_soft(s)))<EOL> | Convert a basestring to unicode (preserving any unicode subclass), and escape it.
Returns a unicode string (not subclass). | f766:c0:m5 |
def unicode(self, b, encoding=None): | if encoding is None:<EOL><INDENT>encoding = self.string_encoding<EOL><DEDENT>return unicode(b, encoding, self.decode_errors)<EOL> | Convert a byte string to unicode, using string_encoding and decode_errors.
Arguments:
b: a byte string.
encoding: the name of an encoding. Defaults to the string_encoding
attribute for this instance.
Raises:
TypeError: Because this method calls Python's built-in unicode()
function, this method raises the following exception if the
given string is already unicode:
TypeError: decoding Unicode is not supported | f766:c0:m6 |
def _make_loader(self): | return Loader(file_encoding=self.file_encoding, extension=self.file_extension,<EOL>to_unicode=self.unicode, search_dirs=self.search_dirs)<EOL> | Create a Loader instance using current attributes. | f766:c0:m7 |
def _make_load_template(self): | loader = self._make_loader()<EOL>def load_template(template_name):<EOL><INDENT>return loader.load_name(template_name)<EOL><DEDENT>return load_template<EOL> | Return a function that loads a template by name. | f766:c0:m8 |
def _make_load_partial(self): | if self.partials is None:<EOL><INDENT>return self._make_load_template()<EOL><DEDENT>partials = self.partials<EOL>def load_partial(name):<EOL><INDENT>template = partials.get(name)<EOL>if template is None:<EOL><INDENT>raise TemplateNotFoundError("<STR_LIT>" %<EOL>(repr(name), type(partials)))<EOL><DEDENT>return self._to_unicode_hard(template)<EOL><DEDENT>return load_partial<EOL> | Return a function that loads a partial by name. | f766:c0:m9 |
def _is_missing_tags_strict(self): | val = self.missing_tags<EOL>if val == MissingTags.strict:<EOL><INDENT>return True<EOL><DEDENT>elif val == MissingTags.ignore:<EOL><INDENT>return False<EOL><DEDENT>raise Exception("<STR_LIT>" % repr(val))<EOL> | Return whether missing_tags is set to strict. | f766:c0:m10 |
def _make_resolve_partial(self): | load_partial = self._make_load_partial()<EOL>if self._is_missing_tags_strict():<EOL><INDENT>return load_partial<EOL><DEDENT>def resolve_partial(name):<EOL><INDENT>try:<EOL><INDENT>return load_partial(name)<EOL><DEDENT>except TemplateNotFoundError:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT><DEDENT>return resolve_partial<EOL> | Return the resolve_partial function to pass to RenderEngine.__init__(). | f766:c0:m11 |
def _make_resolve_context(self): | if self._is_missing_tags_strict():<EOL><INDENT>return context_get<EOL><DEDENT>def resolve_context(stack, name):<EOL><INDENT>try:<EOL><INDENT>return context_get(stack, name)<EOL><DEDENT>except KeyNotFoundError:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT><DEDENT>return resolve_context<EOL> | Return the resolve_context function to pass to RenderEngine.__init__(). | f766:c0:m12 |
def _make_render_engine(self): | resolve_context = self._make_resolve_context()<EOL>resolve_partial = self._make_resolve_partial()<EOL>engine = RenderEngine(literal=self._to_unicode_hard,<EOL>escape=self._escape_to_unicode,<EOL>resolve_context=resolve_context,<EOL>resolve_partial=resolve_partial,<EOL>to_str=self.str_coerce)<EOL>return engine<EOL> | Return a RenderEngine instance for rendering. | f766:c0:m13 |
def load_template(self, template_name): | load_template = self._make_load_template()<EOL>return load_template(template_name)<EOL> | Load a template by name from the file system. | f766:c0:m14 |
def _render_object(self, obj, *context, **kwargs): | loader = self._make_loader()<EOL>if isinstance(obj, TemplateSpec):<EOL><INDENT>loader = SpecLoader(loader)<EOL>template = loader.load(obj)<EOL><DEDENT>else:<EOL><INDENT>template = loader.load_object(obj)<EOL><DEDENT>context = [obj] + list(context)<EOL>return self._render_string(template, *context, **kwargs)<EOL> | Render the template associated with the given object. | f766:c0:m15 |
def render_name(self, template_name, *context, **kwargs): | loader = self._make_loader()<EOL>template = loader.load_name(template_name)<EOL>return self._render_string(template, *context, **kwargs)<EOL> | Render the template with the given name using the given context.
See the render() docstring for more information. | f766:c0:m16 |
def render_path(self, template_path, *context, **kwargs): | loader = self._make_loader()<EOL>template = loader.read(template_path)<EOL>return self._render_string(template, *context, **kwargs)<EOL> | Render the template at the given path using the given context.
Read the render() docstring for more information. | f766:c0:m17 |
def _render_string(self, template, *context, **kwargs): | <EOL>template = self._to_unicode_hard(template)<EOL>render_func = lambda engine, stack: engine.render(template, stack)<EOL>return self._render_final(render_func, *context, **kwargs)<EOL> | Render the given template string using the given context. | f766:c0:m18 |
def _render_final(self, render_func, *context, **kwargs): | stack = ContextStack.create(*context, **kwargs)<EOL>self._context = stack<EOL>engine = self._make_render_engine()<EOL>return render_func(engine, stack)<EOL> | Arguments:
render_func: a function that accepts a RenderEngine and ContextStack
instance and returns a template rendering as a unicode string. | f766:c0:m19 |
def render(self, template, *context, **kwargs): | if is_string(template):<EOL><INDENT>return self._render_string(template, *context, **kwargs)<EOL><DEDENT>if isinstance(template, ParsedTemplate):<EOL><INDENT>render_func = lambda engine, stack: template.render(engine, stack)<EOL>return self._render_final(render_func, *context, **kwargs)<EOL><DEDENT>return self._render_object(template, *context, **kwargs)<EOL> | Render the given template string, view template, or parsed template.
Returns a unicode string.
Prior to rendering, this method will convert a template that is a
byte string (type str in Python 2) to unicode using the string_encoding
and decode_errors attributes. See the constructor docstring for
more information.
Arguments:
template: a template string that is unicode or a byte string,
a ParsedTemplate instance, or another object instance. In the
final case, the function first looks for the template associated
to the object by calling this class's get_associated_template()
method. The rendering process also uses the passed object as
the first element of the context stack when rendering.
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments are skipped. Items in the *context list are added to
the context stack in order so that later items in the argument
list take precedence over earlier items.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. | f766:c0:m20 |
def parse(template, delimiters=None): | if type(template) is not str:<EOL><INDENT>raise Exception("<STR_LIT>" % type(template))<EOL><DEDENT>parser = _Parser(delimiters)<EOL>return parser.parse(template)<EOL> | Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])] | f767:m0 |
def _compile_template_re(delimiters): | <EOL>tag_types = "<STR_LIT>"<EOL>tag = r"""<STR_LIT>""" % {'<STR_LIT>': tag_types, '<STR_LIT>': re.escape(delimiters[<NUM_LIT:0>]), '<STR_LIT>': re.escape(delimiters[<NUM_LIT:1>])}<EOL>return re.compile(tag, re.VERBOSE)<EOL> | Return a regular expression object (re.RegexObject) instance. | f767:m1 |
def parse(self, template): | self._compile_delimiters()<EOL>start_index = <NUM_LIT:0><EOL>content_end_index, parsed_section, section_key = None, None, None<EOL>parsed_template = ParsedTemplate()<EOL>states = []<EOL>while True:<EOL><INDENT>match = self._template_re.search(template, start_index)<EOL>if match is None:<EOL><INDENT>break<EOL><DEDENT>match_index = match.start()<EOL>end_index = match.end()<EOL>matches = match.groupdict()<EOL>if matches['<STR_LIT>'] is not None:<EOL><INDENT>matches.update(tag='<STR_LIT:=>', tag_key=matches['<STR_LIT>'])<EOL><DEDENT>elif matches['<STR_LIT>'] is not None:<EOL><INDENT>matches.update(tag='<STR_LIT:&>', tag_key=matches['<STR_LIT>'])<EOL><DEDENT>tag_type = matches['<STR_LIT>']<EOL>tag_key = matches['<STR_LIT>']<EOL>leading_whitespace = matches['<STR_LIT>']<EOL>did_tag_begin_line = match_index == <NUM_LIT:0> or template[match_index - <NUM_LIT:1>] in END_OF_LINE_CHARACTERS<EOL>did_tag_end_line = end_index == len(template) or template[end_index] in END_OF_LINE_CHARACTERS<EOL>is_tag_interpolating = tag_type in ['<STR_LIT>', '<STR_LIT:&>']<EOL>if did_tag_begin_line and did_tag_end_line and not is_tag_interpolating:<EOL><INDENT>if end_index < len(template):<EOL><INDENT>end_index += template[end_index] == '<STR_LIT:\r>' and <NUM_LIT:1> or <NUM_LIT:0><EOL><DEDENT>if end_index < len(template):<EOL><INDENT>end_index += template[end_index] == '<STR_LIT:\n>' and <NUM_LIT:1> or <NUM_LIT:0><EOL><DEDENT><DEDENT>elif leading_whitespace:<EOL><INDENT>match_index += len(leading_whitespace)<EOL>leading_whitespace = '<STR_LIT>'<EOL><DEDENT>if start_index != match_index:<EOL><INDENT>parsed_template.add(template[start_index:match_index])<EOL><DEDENT>start_index = end_index<EOL>if tag_type in ('<STR_LIT:#>', '<STR_LIT>'):<EOL><INDENT>state = (tag_type, end_index, section_key, parsed_template)<EOL>states.append(state)<EOL>section_key, parsed_template = tag_key, ParsedTemplate()<EOL>continue<EOL><DEDENT>if tag_type == '<STR_LIT:/>':<EOL><INDENT>if tag_key != section_key:<EOL><INDENT>raise ParsingError("<STR_LIT>" % (tag_key, section_key))<EOL><DEDENT>parsed_section = parsed_template<EOL>(tag_type, section_start_index, section_key, parsed_template) = states.pop()<EOL>node = self._make_section_node(template, tag_type, tag_key, parsed_section,<EOL>section_start_index, match_index)<EOL><DEDENT>else:<EOL><INDENT>node = self._make_interpolation_node(tag_type, tag_key, leading_whitespace)<EOL><DEDENT>parsed_template.add(node)<EOL><DEDENT>if start_index != len(template):<EOL><INDENT>parsed_template.add(template[start_index:])<EOL><DEDENT>return parsed_template<EOL> | Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
a ParsedTemplate instance. | f767:c8:m3 |
def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace): | <EOL>if tag_type == '<STR_LIT:!>':<EOL><INDENT>return _CommentNode()<EOL><DEDENT>if tag_type == '<STR_LIT:=>':<EOL><INDENT>delimiters = tag_key.split()<EOL>self._change_delimiters(delimiters)<EOL>return _ChangeNode(delimiters)<EOL><DEDENT>if tag_type == '<STR_LIT>':<EOL><INDENT>return _EscapeNode(tag_key)<EOL><DEDENT>if tag_type == '<STR_LIT:&>':<EOL><INDENT>return _LiteralNode(tag_key)<EOL><DEDENT>if tag_type == '<STR_LIT:>>':<EOL><INDENT>return _PartialNode(tag_key, leading_whitespace)<EOL><DEDENT>raise Exception("<STR_LIT>" % repr(tag_type))<EOL> | Create and return a non-section node for the parse tree. | f767:c8:m4 |
def _make_section_node(self, template, tag_type, tag_key, parsed_section,<EOL>section_start_index, section_end_index): | if tag_type == '<STR_LIT:#>':<EOL><INDENT>return _SectionNode(tag_key, parsed_section, self._delimiters,<EOL>template, section_start_index, section_end_index)<EOL><DEDENT>if tag_type == '<STR_LIT>':<EOL><INDENT>return _InvertedNode(tag_key, parsed_section)<EOL><DEDENT>raise Exception("<STR_LIT>" % repr(tag_type))<EOL> | Create and return a section node for the parse tree. | f767:c8:m5 |
def mock_literal(s): | if isinstance(s, str):<EOL><INDENT>u = str(s)<EOL><DEDENT>else:<EOL><INDENT>u = str(s, encoding='<STR_LIT:ascii>')<EOL><DEDENT>return u.upper()<EOL> | For use as the literal keyword argument to the RenderEngine constructor.
Arguments:
s: a byte string or unicode string. | f768:m1 |
def _engine(self): | renderer = Renderer(string_encoding='<STR_LIT:utf-8>', missing_tags='<STR_LIT:strict>')<EOL>engine = renderer._make_render_engine()<EOL>return engine<EOL> | Create and return a default RenderEngine for testing. | f768:c1:m0 |
def _assert_render(self, expected, template, *context, **kwargs): | partials = kwargs.get('<STR_LIT>')<EOL>engine = kwargs.get('<STR_LIT>', self._engine())<EOL>if partials is not None:<EOL><INDENT>engine.resolve_partial = lambda key: str(partials[key])<EOL><DEDENT>context = ContextStack(*context)<EOL>actual = engine.render(str(template), context)<EOL>self.assertString(actual=actual, expected=expected)<EOL> | Test rendering the given template using the given context. | f768:c1:m1 |
def _make_specloader(): | <EOL>def to_unicode(s, encoding=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT:ascii>'<EOL><DEDENT>return unicode(s, encoding, '<STR_LIT:strict>')<EOL><DEDENT>loader = Loader(file_encoding='<STR_LIT:ascii>', to_unicode=to_unicode)<EOL>return SpecLoader(loader=loader)<EOL> | Return a default SpecLoader instance for testing purposes. | f769:m0 |
def setUp(self): | defaults = [<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>]<EOL>self.saved = {}<EOL>for e in defaults:<EOL><INDENT>self.saved[e] = getattr(pystache.defaults, e)<EOL><DEDENT> | Save the defaults. | f771:c0:m0 |
def _make_renderer(): | renderer = Renderer(string_encoding='<STR_LIT:ascii>', file_encoding='<STR_LIT:ascii>')<EOL>return renderer<EOL> | Return a default Renderer instance for testing purposes. | f772:m0 |
def _make_renderer(self): | return _make_renderer()<EOL> | Return a default Renderer instance for testing purposes. | f772:c2:m0 |
def assertNotFound(self, item, key): | self.assertIs(_get_value(item, key), _NOT_FOUND)<EOL> | Assert that a call to _get_value() returns _NOT_FOUND. | f773:c2:m0 |
def _assert_paths(self, actual, expected): | self.assertEqual(actual, expected)<EOL> | Assert that two paths are the same. | f775:c0:m2 |
def main(sys_argv): | <EOL>print("<STR_LIT>" % repr(sys_argv))<EOL>should_source_exist = False<EOL>spec_test_dir = None<EOL>project_dir = None<EOL>if len(sys_argv) > <NUM_LIT:1> and sys_argv[<NUM_LIT:1>] == FROM_SOURCE_OPTION:<EOL><INDENT>should_source_exist = True<EOL>sys_argv.pop(<NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>project_dir = sys_argv[<NUM_LIT:1>]<EOL>sys_argv.pop(<NUM_LIT:1>)<EOL><DEDENT>except IndexError:<EOL><INDENT>if should_source_exist:<EOL><INDENT>project_dir = PROJECT_DIR<EOL><DEDENT><DEDENT>try:<EOL><INDENT>spec_test_dir = sys_argv[<NUM_LIT:1>]<EOL>sys_argv.pop(<NUM_LIT:1>)<EOL><DEDENT>except IndexError:<EOL><INDENT>if project_dir is not None:<EOL><INDENT>_spec_test_dir = get_spec_test_dir(project_dir)<EOL>if not os.path.exists(_spec_test_dir):<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>spec_test_dir = _spec_test_dir<EOL><DEDENT><DEDENT><DEDENT>if len(sys_argv) <= <NUM_LIT:1> or sys_argv[-<NUM_LIT:1>].startswith("<STR_LIT:->"):<EOL><INDENT>module_names = _discover_test_modules(PACKAGE_DIR)<EOL>sys_argv.extend(module_names)<EOL>if project_dir is not None:<EOL><INDENT>sys_argv.append(__name__)<EOL><DEDENT><DEDENT>SetupTests.project_dir = project_dir<EOL>extra_tests = make_extra_tests(project_dir, spec_test_dir)<EOL>test_program_class = make_test_program_class(extra_tests)<EOL>test_program_class(argv=sys_argv, module=None)<EOL> | Run all tests in the project.
Arguments:
sys_argv: a reference to sys.argv. | f779:m2 |
def html_escape(u): | u = _DEFAULT_TAG_ESCAPE(u)<EOL>return u.replace("<STR_LIT:'>", '<STR_LIT>')<EOL> | An html escape function that behaves the same in both Python 2 and 3.
This function is needed because single quotes are escaped in Python 3
(to '''), but not in Python 2.
The global defaults.TAG_ESCAPE can be set to this function in the
setUp() and tearDown() of unittest test cases, for example, for
consistent test results. | f781:m1 |
def get_data_path(file_name=None): | if file_name is None:<EOL><INDENT>file_name = "<STR_LIT>"<EOL><DEDENT>return os.path.join(DATA_DIR, file_name)<EOL> | Return the path to a file in the test data directory. | f781:m2 |
def _find_files(root_dir, should_include): | paths = [] <EOL>is_module = lambda path: path.endswith("<STR_LIT>")<EOL>for dir_path, dir_names, file_names in os.walk(root_dir):<EOL><INDENT>new_paths = [os.path.join(dir_path, file_name) for file_name in file_names]<EOL>new_paths = list(filter(is_module, new_paths))<EOL>new_paths = list(filter(should_include, new_paths))<EOL>paths.extend(new_paths)<EOL><DEDENT>return paths<EOL> | Return a list of paths to all modules below the given directory.
Arguments:
should_include: a function that accepts a file path and returns True or False. | f781:m3 |
def _make_module_names(package_dir, paths): | package_dir = os.path.abspath(package_dir)<EOL>package_name = os.path.split(package_dir)[<NUM_LIT:1>]<EOL>prefix_length = len(package_dir)<EOL>module_names = []<EOL>for path in paths:<EOL><INDENT>path = os.path.abspath(path) <EOL>rel_path = path[prefix_length:] <EOL>rel_path = os.path.splitext(rel_path)[<NUM_LIT:0>] <EOL>parts = []<EOL>while True:<EOL><INDENT>(rel_path, tail) = os.path.split(rel_path)<EOL>if not tail:<EOL><INDENT>break<EOL><DEDENT>parts.insert(<NUM_LIT:0>, tail)<EOL><DEDENT>parts.insert(<NUM_LIT:0>, package_name)<EOL>module = "<STR_LIT:.>".join(parts)<EOL>module_names.append(module)<EOL><DEDENT>return module_names<EOL> | Return a list of fully-qualified module names given a list of module paths. | f781:m4 |
def get_module_names(package_dir=None, should_include=None): | if package_dir is None:<EOL><INDENT>package_dir = PACKAGE_DIR<EOL><DEDENT>if should_include is None:<EOL><INDENT>should_include = lambda path: True<EOL><DEDENT>paths = _find_files(package_dir, should_include)<EOL>names = _make_module_names(package_dir, paths)<EOL>names.sort()<EOL>return names<EOL> | Return a list of fully-qualified module names in the given package. | f781:m5 |
def assertString(self, actual, expected, format=None): | if format is None:<EOL><INDENT>format = "<STR_LIT:%s>"<EOL><DEDENT>details = """<STR_LIT>""" % (expected, actual, repr(expected), repr(actual))<EOL>def make_message(reason):<EOL><INDENT>description = details % reason<EOL>return format % description<EOL><DEDENT>self.assertEqual(actual, expected, make_message("<STR_LIT>"))<EOL>reason = "<STR_LIT>" % (repr(type(expected)), repr(type(actual)))<EOL>self.assertEqual(type(expected), type(actual), make_message(reason))<EOL> | Assert that the given strings are equal and have the same type.
Arguments:
format: a format string containing a single conversion specifier %s.
Defaults to "%s". | f781:c0:m0 |
def _convert_children(node): | if not isinstance(node, (list, dict)):<EOL><INDENT>return<EOL><DEDENT>if isinstance(node, list):<EOL><INDENT>for child in node:<EOL><INDENT>_convert_children(child)<EOL><DEDENT>return<EOL><DEDENT>for key in list(node.keys()):<EOL><INDENT>val = node[key]<EOL>if not isinstance(val, dict) or val.get('<STR_LIT>') != '<STR_LIT:code>':<EOL><INDENT>_convert_children(val)<EOL>continue<EOL><DEDENT>val = eval(val['<STR_LIT>'])<EOL>node[key] = val<EOL>continue<EOL><DEDENT> | Recursively convert to functions all "code strings" below the node.
This function is needed only for the json format. | f799:m3 |
def parse(u): | <EOL>if yaml is None:<EOL><INDENT>return json.loads(u)<EOL><DEDENT>def code_constructor(loader, node):<EOL><INDENT>value = loader.construct_mapping(node)<EOL>return eval(value['<STR_LIT>'], {})<EOL><DEDENT>yaml.add_constructor('<STR_LIT>', code_constructor)<EOL>return yaml.load(u)<EOL> | Parse the contents of a spec test file, and return a dict.
Arguments:
u: a unicode string. | f799:m6 |
def _convert_2to3(path): | base, ext = os.path.splitext(path)<EOL>new_path = "<STR_LIT>" % (base, ext)<EOL>copyfile(path, new_path)<EOL>args = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', new_path]<EOL>lib2to3main("<STR_LIT>", args=args)<EOL>return new_path<EOL> | Convert the given file, and return the path to the converted files. | f802:m1 |
def _convert_paths(paths): | new_paths = []<EOL>for path in paths:<EOL><INDENT>new_path = _convert_2to3(path)<EOL>new_paths.append(new_path)<EOL><DEDENT>return new_paths<EOL> | Convert the given files, and return the paths to the converted files. | f802:m2 |
def _get_value(context, key): | if isinstance(context, dict):<EOL><INDENT>if key in context:<EOL><INDENT>return context[key]<EOL><DEDENT><DEDENT>elif type(context).__module__ != _BUILTIN_MODULE:<EOL><INDENT>try:<EOL><INDENT>attr = getattr(context, key)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if callable(attr):<EOL><INDENT>return attr()<EOL><DEDENT>return attr<EOL><DEDENT><DEDENT>return _NOT_FOUND<EOL> | Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior. | f803:m0 |
def __init__(self, *items): | self._stack = list(items)<EOL> | Construct an instance, and initialize the private stack.
The *items arguments are the items with which to populate the
initial stack. Items in the argument list are added to the
stack in order so that, in particular, items at the end of
the argument list are queried first when querying the stack.
Caution: items should not themselves be ContextStack instances, as
recursive nesting does not behave as one might expect. | f803:c2:m0 |
def __repr__(self): | return "<STR_LIT>" % (self.__class__.__name__, tuple(self._stack))<EOL> | Return a string representation of the instance.
For example--
>>> context = ContextStack({'alpha': 'abc'}, {'numeric': 123})
>>> repr(context)
"ContextStack({'alpha': 'abc'}, {'numeric': 123})" | f803:c2:m1 |
@staticmethod<EOL><INDENT>def create(*context, **kwargs):<DEDENT> | items = context<EOL>context = ContextStack()<EOL>for item in items:<EOL><INDENT>if item is None:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(item, ContextStack):<EOL><INDENT>context._stack.extend(item._stack)<EOL><DEDENT>else:<EOL><INDENT>context.push(item)<EOL><DEDENT><DEDENT>if kwargs:<EOL><INDENT>context.push(kwargs)<EOL><DEDENT>return context<EOL> | Build a ContextStack instance from a sequence of context-like items.
This factory-style method is more general than the ContextStack class's
constructor in that, unlike the constructor, the argument list
can itself contain ContextStack instances.
Here is an example illustrating various aspects of this method:
>>> obj1 = {'animal': 'cat', 'vegetable': 'carrot', 'mineral': 'copper'}
>>> obj2 = ContextStack({'vegetable': 'spinach', 'mineral': 'silver'})
>>>
>>> context = ContextStack.create(obj1, None, obj2, mineral='gold')
>>>
>>> context.get('animal')
'cat'
>>> context.get('vegetable')
'spinach'
>>> context.get('mineral')
'gold'
Arguments:
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments will be skipped. Items in the *context list are
added to the stack in order so that later items in the argument
list take precedence over earlier items. This behavior is the
same as the constructor's.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. This behavior is the same as
the constructor's. | f803:c2:m2 |
def get(self, name): | if name == '<STR_LIT:.>':<EOL><INDENT>try:<EOL><INDENT>return self.top()<EOL><DEDENT>except IndexError:<EOL><INDENT>raise KeyNotFoundError("<STR_LIT:.>", "<STR_LIT>")<EOL><DEDENT><DEDENT>parts = name.split('<STR_LIT:.>')<EOL>try:<EOL><INDENT>result = self._get_simple(parts[<NUM_LIT:0>])<EOL><DEDENT>except KeyNotFoundError:<EOL><INDENT>raise KeyNotFoundError(name, "<STR_LIT>")<EOL><DEDENT>for part in parts[<NUM_LIT:1>:]:<EOL><INDENT>result = _get_value(result, part)<EOL>if result is _NOT_FOUND:<EOL><INDENT>raise KeyNotFoundError(name, "<STR_LIT>" % repr(part))<EOL><DEDENT><DEDENT>return result<EOL> | Resolve a dotted name against the current context stack.
This function follows the rules outlined in the section of the
spec regarding tag interpolation. This function returns the value
as is and does not coerce the return value to a string.
Arguments:
name: a dotted or non-dotted name.
default: the value to return if name resolution fails at any point.
Defaults to the empty string per the Mustache spec.
This method queries items in the stack in order from last-added
objects to first (last in, first out). The value returned is
the value of the key in the first item that contains the key.
If the key is not found in any item in the stack, then the default
value is returned. The default value defaults to None.
In accordance with the spec, this method queries items in the
stack for a key differently depending on whether the item is a
hash, object, or neither (as defined in the module docstring):
(1) Hash: if the item is a hash, then the key's value is the
dictionary value of the key. If the dictionary doesn't contain
the key, then the key is considered not found.
(2) Object: if the item is an an object, then the method looks for
an attribute with the same name as the key. If an attribute
with that name exists, the value of the attribute is returned.
If the attribute is callable, however (i.e. if the attribute
is a method), then the attribute is called with no arguments
and that value is returned. If there is no attribute with
the same name as the key, then the key is considered not found.
(3) Neither: if the item is neither a hash nor an object, then
the key is considered not found.
*Caution*:
Callables are handled differently depending on whether they are
dictionary values, as in (1) above, or attributes, as in (2).
The former are returned as-is, while the latter are first
called and that value returned.
Here is an example to illustrate:
>>> def greet():
... return "Hi Bob!"
>>>
>>> class Greeter(object):
... greet = None
>>>
>>> dct = {'greet': greet}
>>> obj = Greeter()
>>> obj.greet = greet
>>>
>>> dct['greet'] is obj.greet
True
>>> ContextStack(dct).get('greet') #doctest: +ELLIPSIS
<function greet at 0x...>
>>> ContextStack(obj).get('greet')
'Hi Bob!'
TODO: explain the rationale for this difference in treatment. | f803:c2:m3 |
def _get_simple(self, name): | for item in reversed(self._stack):<EOL><INDENT>result = _get_value(item, name)<EOL>if result is not _NOT_FOUND:<EOL><INDENT>return result<EOL><DEDENT><DEDENT>raise KeyNotFoundError(name, "<STR_LIT>")<EOL> | Query the stack for a non-dotted name. | f803:c2:m4 |
def push(self, item): | self._stack.append(item)<EOL> | Push an item onto the stack. | f803:c2:m5 |
def pop(self): | return self._stack.pop()<EOL> | Pop an item off of the stack, and return it. | f803:c2:m6 |
def top(self): | return self._stack[-<NUM_LIT:1>]<EOL> | Return the item last added to the stack. | f803:c2:m7 |
def copy(self): | return ContextStack(*self._stack)<EOL> | Return a copy of this instance. | f803:c2:m8 |
def context_get(stack, name): | return stack.get(name)<EOL> | Find and return a name from a ContextStack instance. | f805:m0 |
def __init__(self, literal=None, escape=None, resolve_context=None,<EOL>resolve_partial=None, to_str=None): | self.escape = escape<EOL>self.literal = literal<EOL>self.resolve_context = resolve_context<EOL>self.resolve_partial = resolve_partial<EOL>self.to_str = to_str<EOL> | Arguments:
literal: the function used to convert unescaped variable tag
values to unicode, e.g. the value corresponding to a tag
"{{{name}}}". The function should accept a string of type
str or unicode (or a subclass) and return a string of type
unicode (but not a proper subclass of unicode).
This class will only pass basestring instances to this
function. For example, it will call str() on integer variable
values prior to passing them to this function.
escape: the function used to escape and convert variable tag
values to unicode, e.g. the value corresponding to a tag
"{{name}}". The function should obey the same properties
described above for the "literal" function argument.
This function should take care to convert any str
arguments to unicode just as the literal function should, as
this class will not pass tag values to literal prior to passing
them to this function. This allows for more flexibility,
for example using a custom escape function that handles
incoming strings of type markupsafe.Markup differently
from plain unicode strings.
resolve_context: the function to call to resolve a name against
a context stack. The function should accept two positional
arguments: a ContextStack instance and a name to resolve.
resolve_partial: the function to call when loading a partial.
The function should accept a template name string and return a
template string of type unicode (not a subclass).
to_str: a function that accepts an object and returns a string (e.g.
the built-in function str). This function is used for string
coercion whenever a string is required (e.g. for converting None
or 0 to a string). | f805:c0:m0 |
def fetch_string(self, context, name): | val = self.resolve_context(context, name)<EOL>if callable(val):<EOL><INDENT>return self._render_value(val(), context)<EOL><DEDENT>if not is_string(val):<EOL><INDENT>return self.to_str(val)<EOL><DEDENT>return val<EOL> | Get a value from the given context as a basestring instance. | f805:c0:m1 |
def fetch_section_data(self, context, name): | data = self.resolve_context(context, name)<EOL>if not data:<EOL><INDENT>data = []<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>iter(data)<EOL><DEDENT>except TypeError:<EOL><INDENT>data = [data]<EOL><DEDENT>else:<EOL><INDENT>if is_string(data) or isinstance(data, dict):<EOL><INDENT>data = [data]<EOL><DEDENT><DEDENT><DEDENT>return data<EOL> | Fetch the value of a section as a list. | f805:c0:m2 |
def _render_value(self, val, context, delimiters=None): | if not is_string(val):<EOL><INDENT>val = self.to_str(val)<EOL><DEDENT>if type(val) is not unicode:<EOL><INDENT>val = self.literal(val)<EOL><DEDENT>return self.render(val, context, delimiters)<EOL> | Render an arbitrary value. | f805:c0:m3 |
def render(self, template, context_stack, delimiters=None): | parsed_template = parse(template, delimiters)<EOL>return parsed_template.render(self, context_stack)<EOL> | Render a unicode template string, and return as unicode.
Arguments:
template: a template string of type unicode (but not a proper
subclass of unicode).
context_stack: a ContextStack instance. | f805:c0:m4 |
def render(template, context=None, **kwargs): | renderer = Renderer()<EOL>return renderer.render(template, context, **kwargs)<EOL> | Return the given template string rendered using the given context. | f806:m0 |
def _find_relative(self, spec): | if spec.template_rel_path is not None:<EOL><INDENT>return os.path.split(spec.template_rel_path)<EOL><DEDENT>locator = self.loader._make_locator()<EOL>if spec.template_name is not None:<EOL><INDENT>template_name = spec.template_name<EOL><DEDENT>else:<EOL><INDENT>template_name = locator.make_template_name(spec)<EOL><DEDENT>file_name = locator.make_file_name(template_name, spec.template_extension)<EOL>return (spec.template_rel_directory, file_name)<EOL> | Return the path to the template as a relative (dir, file_name) pair.
The directory returned is relative to the directory containing the
class definition of the given object. The method returns None for
this directory if the directory is unknown without first searching
the search directories. | f807:c0:m1 |
def _find(self, spec): | if spec.template_path is not None:<EOL><INDENT>return spec.template_path<EOL><DEDENT>dir_path, file_name = self._find_relative(spec)<EOL>locator = self.loader._make_locator()<EOL>if dir_path is None:<EOL><INDENT>path = locator.find_object(spec, self.loader.search_dirs, file_name=file_name)<EOL><DEDENT>else:<EOL><INDENT>obj_dir = locator.get_object_directory(spec)<EOL>path = os.path.join(obj_dir, dir_path, file_name)<EOL><DEDENT>return path<EOL> | Find and return the path to the template associated to the instance. | f807:c0:m2 |
def load(self, spec): | if spec.template is not None:<EOL><INDENT>return self.loader.unicode(spec.template, spec.template_encoding)<EOL><DEDENT>path = self._find(spec)<EOL>return self.loader.read(path, spec.template_encoding)<EOL> | Find and return the template associated to a TemplateSpec instance.
Returns the template as a unicode string.
Arguments:
spec: a TemplateSpec instance. | f807:c0:m3 |
def parse_args(sys_argv, usage): | args = sys_argv[<NUM_LIT:1>:]<EOL>parser = OptionParser(usage=usage)<EOL>options, args = parser.parse_args(args)<EOL>template, context = args<EOL>return template, context<EOL> | Return an OptionParser for the script. | f808:m0 |
def is_string(obj): | return isinstance(obj, _STRING_TYPES)<EOL> | Return whether the given object is a byte string or unicode string.
This function is provided for compatibility with both Python 2 and 3
when using 2to3. | f811:m1 |
def read(path): | <EOL>f = open(path, '<STR_LIT:rb>')<EOL>try:<EOL><INDENT>return f.read()<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT> | Return the contents of a text file as a byte string. | f811:m2 |
def __init__(self, file_encoding=None, extension=None, to_unicode=None,<EOL>search_dirs=None): | if extension is None:<EOL><INDENT>extension = defaults.TEMPLATE_EXTENSION<EOL><DEDENT>if file_encoding is None:<EOL><INDENT>file_encoding = defaults.FILE_ENCODING<EOL><DEDENT>if search_dirs is None:<EOL><INDENT>search_dirs = defaults.SEARCH_DIRS<EOL><DEDENT>if to_unicode is None:<EOL><INDENT>to_unicode = _make_to_unicode()<EOL><DEDENT>self.extension = extension<EOL>self.file_encoding = file_encoding<EOL>self.search_dirs = search_dirs<EOL>self.to_unicode = to_unicode<EOL> | Construct a template loader instance.
Arguments:
extension: the template file extension, without the leading dot.
Pass False for no extension (e.g. to use extensionless template
files). Defaults to the package default.
file_encoding: the name of the encoding to use when converting file
contents to unicode. Defaults to the package default.
search_dirs: the list of directories in which to search when loading
a template by name or file name. Defaults to the package default.
to_unicode: the function to use when converting strings of type
str to unicode. The function should have the signature:
to_unicode(s, encoding=None)
It should accept a string of type str and an optional encoding
name and return a string of type unicode. Defaults to calling
Python's built-in function unicode() using the package string
encoding and decode errors defaults. | f812:c0:m0 |
def unicode(self, s, encoding=None): | if isinstance(s, unicode):<EOL><INDENT>return unicode(s)<EOL><DEDENT>return self.to_unicode(s, encoding)<EOL> | Convert a string to unicode using the given encoding, and return it.
This function uses the underlying to_unicode attribute.
Arguments:
s: a basestring instance to convert to unicode. Unlike Python's
built-in unicode() function, it is okay to pass unicode strings
to this function. (Passing a unicode string to Python's unicode()
with the encoding argument throws the error, "TypeError: decoding
Unicode is not supported.")
encoding: the encoding to pass to the to_unicode attribute.
Defaults to None. | f812:c0:m2 |
def read(self, path, encoding=None): | b = common.read(path)<EOL>if encoding is None:<EOL><INDENT>encoding = self.file_encoding<EOL><DEDENT>return self.unicode(b, encoding)<EOL> | Read the template at the given path, and return it as a unicode string. | f812:c0:m3 |
def load_file(self, file_name): | locator = self._make_locator()<EOL>path = locator.find_file(file_name, self.search_dirs)<EOL>return self.read(path)<EOL> | Find and return the template with the given file name.
Arguments:
file_name: the file name of the template. | f812:c0:m4 |
def load_name(self, name): | locator = self._make_locator()<EOL>path = locator.find_name(name, self.search_dirs)<EOL>return self.read(path)<EOL> | Find and return the template with the given template name.
Arguments:
name: the name of the template. | f812:c0:m5 |
def load_object(self, obj): | locator = self._make_locator()<EOL>path = locator.find_object(obj, self.search_dirs)<EOL>return self.read(path)<EOL> | Find and return the template associated to the given object.
Arguments:
obj: an instance of a user-defined class.
search_dirs: the list of directories in which to search. | f812:c0:m6 |
def add(self, node): | self._parse_tree.append(node)<EOL> | Arguments:
node: a unicode string or node object instance. See the class
docstring for information. | f814:c0:m2 |
def render(self, engine, context): | <EOL>def get_unicode(node):<EOL><INDENT>if type(node) is unicode:<EOL><INDENT>return node<EOL><DEDENT>return node.render(engine, context)<EOL><DEDENT>parts = map(get_unicode, self._parse_tree)<EOL>s = '<STR_LIT>'.join(parts)<EOL>return unicode(s)<EOL> | Returns: a string of type unicode. | f814:c0:m3 |