INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statistics.
def print_stats(self, reset=True): '''Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statis...
Returns a root folder path for downloading models.
def get_model_home(): ''' Returns a root folder path for downloading models. ''' d = os.path.join(get_data_home(), 'nnp_models') if not os.path.isdir(d): os.makedirs(d) return d
Returns a root folder for models.
def get_model_url_base(): ''' Returns a root folder for models. ''' url_base = get_model_url_base_from_env() if url_base is not None: logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base)) else: url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return...
Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: the value of return array ranges from 0 to `max_range`. :return...
def load_image_imread(file, shape=None, max_range=1.0): ''' Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: ...
Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] if six.PY2: for row in csv.read...
Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering...
def save(self, vleaf, fpath, cleanup=False, format=None): """Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. ...
View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is True. ...
def view(self, vleaf, fpath=None, cleanup=True, format=None): """View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanu...
Create a :obj:`graphviz.Digraph` object given the leaf variable of a computation graph. One of nice things of getting ``Digraph`` directly is that the drawn graph can be displayed inline in a Jupyter notebook as described in `Graphviz documentation <https://graphviz.readthedocs.io/en/st...
def create_graphviz_digraph(self, vleaf, format=None): ''' Create a :obj:`graphviz.Digraph` object given the leaf variable of a computation graph. One of nice things of getting ``Digraph`` directly is that the drawn graph can be displayed inline in a Jupyter notebook as describe...
Get parameters. Args: grad_only (bool, optional): Return parameters with `need_grad` option as `True`. If you set this option as `False`, All parameters are returned. Default is `True`. Returns: dict: The dictionary of parameter name (`str`) to Variable (:obj:`~nnabl...
def get_parameters(self, grad_only=True): """Get parameters. Args: grad_only (bool, optional): Return parameters with `need_grad` option as `True`. If you set this option as `False`, All parameters are returned. Default is `True`. Returns: dict: The dictionar...
Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. Yields: `Module`: The module class.
def get_modules(self, memo=None, prefix=""): """Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. ...
Save all parameters into a file with the specified format. Currently hdf5 and protobuf formats are supported. Args: path : path or file object grad_only (bool, optional): Return parameters with `need_grad` option as `True`.
def save_parameters(self, path, grad_only=False): """Save all parameters into a file with the specified format. Currently hdf5 and protobuf formats are supported. Args: path : path or file object grad_only (bool, optional): Return parameters with `need_grad` option as `...
Load parameters from a file with the specified format. Args: path : path or file object
def load_parameters(self, path): """Load parameters from a file with the specified format. Args: path : path or file object """ nn.load_parameters(path) for v in self.get_modules(): if not isinstance(v, tuple): continue prefix,...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update
def update(self, i): """Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update ""...
Return the integer value to be stored from the hex string
def get_prep_value(self, value): """ Return the integer value to be stored from the hex string """ if value is None or value == "": return None if isinstance(value, six.string_types): value = _hex_string_to_unsigned_integer(value) if _using_signed_storage(): value = _unsigned_to_signed_integer(value) ...
Return an unsigned int representation from all db backends
def from_db_value(self, value, expression, connection, context): """ Return an unsigned int representation from all db backends """ if value is None: return value if _using_signed_storage(): value = _signed_to_unsigned_integer(value) return value
Return a str representation of the hexadecimal
def to_python(self, value): """ Return a str representation of the hexadecimal """ if isinstance(value, six.string_types): return value if value is None: return value return _unsigned_integer_to_hex_string(value)
Sends an APNS notification to a single registration_id. This will send the notification as form data. If sending multiple notifications, it is more efficient to use apns_send_bulk_message() Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need ...
def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs): """ Sends an APNS notification to a single registration_id. This will send the notification as form data. If sending multiple notifications, it is more efficient to use apns_send_bulk_message() Note that if set alert sho...
Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need to pass None to this for silent notifications.
def apns_send_bulk_message( registration_ids, alert, application_id=None, certfile=None, **kwargs ): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the no...
Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list.
def _cm_send_request( registration_ids, data, cloud_type="GCM", application_id=None, use_fcm_notifications=True, **kwargs ): """ Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list. """ payload = {"registration_ids": registration_ids} if registra...
Handle situation when FCM server response contains canonical ID
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type): """ Handle situation when FCM server response contains canonical ID """ devices = GCMDevice.objects.filter(cloud_message_type=cloud_type) if devices.filter(registration_id=canonical_id, active=True).exists(): devices.filter(registration_id=curren...
Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids can be a list or a single string. This will send the notification as json data. A reference of extra keyword arguments sent to the server is available here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs): """ Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids can be a list or a single string. This will send the notification as json data. A reference of extra keyword arguments sent to the server ...
Legacy behaviour
def _get_application_settings(self, application_id, settings_key, error_message): """Legacy behaviour""" if not application_id: value = SETTINGS.get(settings_key, empty) if value is empty: raise ImproperlyConfigured(error_message) return value else: msg = ( "LegacySettings does not support ap...
Validate the application collection
def _validate_applications(self, apps): """Validate the application collection""" for application_id, application_config in apps.items(): self._validate_config(application_id, application_config) application_config["APPLICATION_ID"] = application_id
Confirm only allowed settings are present.
def _validate_allowed_settings(self, application_id, application_config, allowed_settings): """Confirm only allowed settings are present.""" for setting_key in application_config.keys(): if setting_key not in allowed_settings: raise ImproperlyConfigured( "Platform {}, app {} does not support the settin...
All required keys must be present
def _validate_required_settings( self, application_id, application_config, required_settings ): """All required keys must be present""" for setting_key in required_settings: if setting_key not in application_config.keys(): raise ImproperlyConfigured( MISSING_SETTING.format( application_id=appl...
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured.
def _get_application_settings(self, application_id, platform, settings_key): """ Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured. """ if not application_id: conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured( "{} requ...
Provides error handling for DeviceAdmin send_message and send_bulk_message methods.
def send_messages(self, request, queryset, bulk=False): """ Provides error handling for DeviceAdmin send_message and send_bulk_message methods. """ ret = [] errors = [] r = "" for device in queryset: try: if bulk: r = queryset.send_message("Test bulk notification") else: r = device.s...
Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
def _wns_authenticate(scope="notify.windows.com", application_id=None): """ Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} """ client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().g...
Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return:
def _wns_send(uri, data, wns_type="wns/toast", application_id=None): """ Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return: """ access_token = _wns_authenticate(application_id=application_id) ...
Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str
def _wns_prepare_toast(data, **kwargs): """ Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str """ root = ET.Element("toast") visu...
Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more information: https://msdn.microsoft.com/en-us/library/windows/apps/br212853...
def wns_send_message( uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/lau...
WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sen...
def wns_send_bulk_message( uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. ...
Input a dictionary to be converted to xml. There should be only one key at the top level. The value must be a dict with (required) `children` key and (optional) `attrs` key. This will be called the `sub-element dictionary`. The `attrs` value must be a dictionary; each value will be added to the element's xml tag a...
def dict_to_xml_schema(data): """ Input a dictionary to be converted to xml. There should be only one key at the top level. The value must be a dict with (required) `children` key and (optional) `attrs` key. This will be called the `sub-element dictionary`. The `attrs` value must be a dictionary; each value will ...
Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"example": { "attrs": { "key1": "value1", ... ...
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"e...
Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element
def _add_element_attrs(elem, attrs): """ Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element """ for attr, value...
Call the sdkmanager in our Android SDK with the given arguments.
def _sdkmanager(self, *args, **kwargs): """Call the sdkmanager in our Android SDK with the given arguments.""" # Use the android-sdk dir as cwd by default kwargs['cwd'] = kwargs.get('cwd', self.android_sdk_dir) command = self.sdkmanager_path + ' ' + ' '.join(args) return_child = ...
Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spec: string :param username: Username to use for login ...
def login(self, host_spec="", username="", password=""): """ Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spe...
If JAVA_HOME is in the environ, return $JAVA_HOME/bin/s. Otherwise, return s.
def _locate_java(self, s): '''If JAVA_HOME is in the environ, return $JAVA_HOME/bin/s. Otherwise, return s. ''' if 'JAVA_HOME' in self.buildozer.environ: return join(self.buildozer.environ['JAVA_HOME'], 'bin', s) else: return s
Crudely parse out the installed platform-tools version
def _android_get_installed_platform_tools_version(self): """ Crudely parse out the installed platform-tools version """ platform_tools_dir = os.path.join( self.android_sdk_dir, 'platform-tools') if not os.path.exists(platform_tools_dir): retu...
Update the tools and package-tools if possible
def _android_update_sdk(self, *sdkmanager_commands): """Update the tools and package-tools if possible""" auto_accept_license = self.buildozer.config.getbooldefault( 'app', 'android.accept_sdk_license', False) if auto_accept_license: # `SIGPIPE` is not being reported som...
Run p4a commands. Args must come after --, or use --alias to make an alias
def cmd_p4a(self, *args): ''' Run p4a commands. Args must come after --, or use --alias to make an alias ''' self.check_requirements() self.install_platform() args = args[0] if args and args[0] == '--alias': print('To set up p4a in this shell s...
Show the log from the device
def cmd_logcat(self, *args): '''Show the log from the device ''' self.check_requirements() serial = self.serials[0:] if not serial: return filters = self.buildozer.config.getrawdefault( "app", "android.logcat_filters", "", section_sep=":", split_ch...
Run adb from the Android SDK. Args must come after --, or use --alias to make an alias
def cmd_adb(self, *args): ''' Run adb from the Android SDK. Args must come after --, or use --alias to make an alias ''' self.check_requirements() self.install_platform() args = args[0] if args and args[0] == '--alias': print('To set up...
Get source location for a git checkout This method will check the `buildozer.spec` for the keys: {repo}_dir {repo}_url {repo}_branch and use them to determine the source location for a git checkout. If a `platform` is specified, {platform}.{repo} will be us...
def path_or_git_url(self, repo, owner='kivy', branch='master', url_format='https://github.com/{owner}/{repo}.git', platform=None, squash_hyphen=True): """Get source location for a git checkout This method will check the `buildozer....
Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) directory name. :Parameters: **k...
def install_or_update_repo(self, repo, **kwargs): """Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) ...
Takes a ConfigParser, and checks every section/token for an environment variable of the form SECTION_TOKEN, with any dots replaced by underscores. If the variable exists, sets the config variable to the env value.
def set_config_from_envs(config): '''Takes a ConfigParser, and checks every section/token for an environment variable of the form SECTION_TOKEN, with any dots replaced by underscores. If the variable exists, sets the config variable to the env value. ''' for section in config.sections(): ...
Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replaced by underscores. Returns True if the environment variab...
def set_config_token_from_env(section, token, config): '''Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replac...
Set the target to use (one of buildozer.targets, such as "android")
def set_target(self, target): '''Set the target to use (one of buildozer.targets, such as "android") ''' self.targetname = target m = __import__('buildozer.targets.{0}'.format(target), fromlist=['buildozer']) self.target = m.get_target(self) self.ch...
Prepare the build.
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_r...
Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.)
def build(self): '''Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.) ''' assert(self.target is not None) assert(hasattr(self.target, '_build_prepared')) ...
dump env into debug logger in readable format
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
Ensure the spec file is 'correct'.
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): ...
Ensure the build (local and global) directory layout and files are ready.
def check_build_layout(self): '''Ensure the build (local and global) directory layout and files are ready. ''' self.info('Ensure build layout') if not exists(self.specfilename): print('No {0} found in the current directory. Abandon.'.format( self.spec...
Ensure the application requirements are all available and ready to be packaged as well.
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' requirements = self.config.getlist('app', 'requirements', '') target_available_packages = self.target.get_available_packages() if targe...
Ensure required garden packages are available to be included.
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' garden_requirements = self.config.getlist('app', 'garden_requirements', '') # have we installed the garden packages? if exists(self.gardenlibs_dir) and \ ...
If effective user id is 0, display a warning and require user input to continue (or to cancel)
def check_root(self): '''If effective user id is 0, display a warning and require user input to continue (or to cancel)''' if IS_PY3: input_func = input else: input_func = raw_input warn_on_root = self.config.getdefault('buildozer', 'warn_on_root', '1') ...
Create a initial buildozer.spec in the current directory
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' if exists('buildozer.spec'): print('ERROR: You already have a buildozer.spec file.') exit(1) copyfile(join(dirname(__file__), 'default.spec'), 'buildozer.spec') prin...
Clean the whole Buildozer environment.
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' print("Warning: Your ndk, sdk and all other cached packages will be" " removed. Continue? (y/n)") if sys.stdin.readline().lower()[0] == 'y': self.info('Clean the global build directory...
Serve the bin directory via SimpleHTTPServer
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler ...
Open the xcode project.
def cmd_xcode(self, *args): '''Open the xcode project. ''' app_name = self.buildozer.namify(self.buildozer.config.get('app', 'package.name')) app_name = app_name.lower() ios_dir = ios_dir = join(self.buildozer.platform_dir, 'kivy-ios') self.buildozer.cmd('ope...
List the available identities to use for signing.
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
If the request body is a string, encode it to bytes (for python3 support) By default yaml serializes to utf-8 encoded bytestrings. When this cassette is loaded by python3, it's automatically decoded into unicode strings. This makes sure that it stays a bytestring, since that's what all the internal htt...
def convert_body_to_bytes(resp): """ If the request body is a string, encode it to bytes (for python3 support) By default yaml serializes to utf-8 encoded bytestrings. When this cassette is loaded by python3, it's automatically decoded into unicode strings. This makes sure that it stays a bytestrin...
If the string is bytes, decode it to a string (for python3 support)
def _convert_string_to_unicode(string): """ If the string is bytes, decode it to a string (for python3 support) """ result = string try: if string is not None and not isinstance(string, six.text_type): result = string.decode('utf-8') except (TypeError, UnicodeDecodeError, At...
If the request or responses body is bytes, decode it to a string (for python3 support)
def convert_body_to_unicode(resp): """ If the request or responses body is bytes, decode it to a string (for python3 support) """ if type(resp) is not dict: # Some of the tests just serialize and deserialize a string. return _convert_string_to_unicode(resp) else: body = r...
Wraps a generator so that we're inside the cassette context for the duration of the generator.
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.c...
Add a request, response pair to this cassette
def append(self, request, response): """Add a request, response pair to this cassette""" request = self._before_record_request(request) if not request: return # Deepcopy is here because mutation of `response` will corrupt the # real response. response = copy.d...
internal API, returns an iterator with all responses matching the request.
def _responses(self, request): """ internal API, returns an iterator with all responses matching the request. """ request = self._before_record_request(request) for index, (stored_request, response) in enumerate(self.data): if requests_match(request, stored_re...
Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ for index, response in self._responses(request): if self.play_counts[index] == 0: self.play_coun...
Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API.
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ responses = [response for index, response in self._responses(request)] if responses: ...
Convert headers from our serialized dict with lists for keys to a HTTPMessage
def parse_headers(header_list): """ Convert headers from our serialized dict with lists for keys to a HTTPMessage """ header_string = b"" for key, values in header_list.items(): for v in values: header_string += \ key.encode('utf-8') + b":" + v.encode('utf-8')...
Returns empty string for the default port and ':port' otherwise
def _port_postfix(self): """ Returns empty string for the default port and ':port' otherwise """ port = self.real_connection.port default_port = {'https': 443, 'http': 80}[self._protocol] return ':{}'.format(port) if port != default_port else ''
Returns request absolute URI
def _uri(self, url): """Returns request absolute URI""" if url and not url.startswith('/'): # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}".format( self._protocol, self.real_connection.host, self._port_postfix(),...
Returns request selector url from absolute URI
def _url(self, uri): """Returns request selector url from absolute URI""" prefix = "{}://{}{}".format( self._protocol, self.real_connection.host, self._port_postfix(), ) return uri.replace(prefix, '', 1)
Persist the request metadata in self._vcr_request
def request(self, method, url, body=None, headers=None, *args, **kwargs): '''Persist the request metadata in self._vcr_request''' self._vcr_request = Request( method=method, uri=self._uri(url), body=body, headers=headers or {} ) log.debug('...
httplib gives you more than one way to do it. This is a way to start building up a request. Usually followed by a bunch of putheader() calls.
def putrequest(self, method, url, *args, **kwargs): """ httplib gives you more than one way to do it. This is a way to start building up a request. Usually followed by a bunch of putheader() calls. """ self._vcr_request = Request( method=method, ...
This method is called after request(), to add additional data to the body of the request. So if that happens, let's just append the data onto the most recent request in the cassette.
def send(self, data): ''' This method is called after request(), to add additional data to the body of the request. So if that happens, let's just append the data onto the most recent request in the cassette. ''' self._vcr_request.body = self._vcr_request.body + data \ ...
Retrieve the response
def getresponse(self, _=False, **kwargs): '''Retrieve the response''' # Check to see if the cassette has a response for this request. If so, # then return it if self.cassette.can_play_response_for(self._vcr_request): log.info( "Playing response for {} from cas...
httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected.
def connect(self, *args, **kwargs): """ httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected. """ if hasattr(self, '_vcr_request') and \ self.cassette.can_pl...
One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute assigned to `self._cassette`. This behavior is necessary to properly support nest...
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj): """One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute a...
Replace headers in request according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the given header. 3. A callable which accepts (key, value, request) and returns a string val...
def replace_headers(request, replacements): """ Replace headers in request according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the given header. 3. A callable which accepts...
Wrap replace_headers() for API backward compatibility.
def remove_headers(request, headers_to_remove): """ Wrap replace_headers() for API backward compatibility. """ replacements = [(k, None) for k in headers_to_remove] return replace_headers(request, replacements)
Replace query parameters in request according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the given header. 3. A callable which accepts (key, value, request) and returns a string...
def replace_query_parameters(request, replacements): """ Replace query parameters in request according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the given header. 3. A ...
Wrap replace_query_parameters() for API backward compatibility.
def remove_query_parameters(request, query_parameters_to_remove): """ Wrap replace_query_parameters() for API backward compatibility. """ replacements = [(k, None) for k in query_parameters_to_remove] return replace_query_parameters(request, replacements)
Replace post data in request--either form data or json--according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the given header. 3. A callable which accepts (key, value, request) ...
def replace_post_data_parameters(request, replacements): """ Replace post data in request--either form data or json--according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the g...
Wrap replace_post_data_parameters() for API backward compatibility.
def remove_post_data_parameters(request, post_data_parameters_to_remove): """ Wrap replace_post_data_parameters() for API backward compatibility. """ replacements = [(k, None) for k in post_data_parameters_to_remove] return replace_post_data_parameters(request, replacements)
If the response is compressed with gzip or deflate: 1. decompress the response body 2. delete the content-encoding header 3. update content-length header to decompressed length
def decode_response(response): """ If the response is compressed with gzip or deflate: 1. decompress the response body 2. delete the content-encoding header 3. update content-length header to decompressed length """ def is_compressed(headers): encoding = headers.get('content-en...
Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces.
def _Widget_fontdict(): """Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces. """ flist = Widget_fontobjects[2:-2].splitlines() fdict = {} for f in flist: k, v = f.split(" ") fdict[k[1:]] = v return fdict
Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text.
def getTextlength(text, fontname="helv", fontsize=11, encoding=0): """Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length...
Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of ...
def getPDFstr(s): """ Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the ...
Return a PDF string enclosed in [] brackets, suitable for the PDF TJ operator. Notes: The input string is converted to either 2 or 4 hex digits per character. Args: simple: no glyphs: 2-chars, use char codes as the glyph glyphs: 2-chars, use glyphs instead of char codes (Sym...
def getTJstr(text, glyphs, simple, ordering): """ Return a PDF string enclosed in [] brackets, suitable for the PDF TJ operator. Notes: The input string is converted to either 2 or 4 hex digits per character. Args: simple: no glyphs: 2-chars, use char codes as the glyph ...
Return a tuple (width, height) for a given paper format string. 'A4-L' will return (842, 595), the values for A4 landscape. Suffix '-P' and no suffix returns portrait.
def PaperSize(s): """Return a tuple (width, height) for a given paper format string. 'A4-L' will return (842, 595), the values for A4 landscape. Suffix '-P' and no suffix returns portrait.""" size = s.lower() f = "p" if size.endswith("-l"): f = "l" size = size[:-2] if size.en...
Return an entry in the page's font list if reference name matches.
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing.
def invert(self, src=None): """Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing. """ if src is None: dst = TOOLS._invert_matrix(self) else: dst = TOOLS._invert_matrix(src) if dst[0] == 1: ...
Calculate pre translation and replace current matrix.
def preTranslate(self, tx, ty): """Calculate pre translation and replace current matrix.""" self.e += tx * self.a + ty * self.c self.f += tx * self.b + ty * self.d return self
Calculate pre scaling and replace current matrix.
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
Calculate pre shearing and replace current matrix.
def preShear(self, h, v): """Calculate pre shearing and replace current matrix.""" a, b = self.a, self.b self.a += v * self.c self.b += v * self.d self.c += h * a self.d += h * b return self
Calculate pre rotation and replace current matrix.
def preRotate(self, theta): """Calculate pre rotation and replace current matrix.""" while theta < 0: theta += 360 while theta >= 360: theta -= 360 epsilon = 1e-5 if abs(0 - theta) < epsilon: pass elif abs(90.0 - theta) < epsilon: a = self.a ...
Multiply two matrices and replace current one.
def concat(self, one, two): """Multiply two matrices and replace current one.""" if not len(one) == len(two) == 6: raise ValueError("bad sequ. length") self.a, self.b, self.c, self.d, self.e, self.f = TOOLS._concat_matrix(one, two) return self
Replace point by its transformation with matrix-like m.
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self