INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Convert a generic JSON message * The entire message is converted to JSON and treated as the message data * The timestamp of the message is the time that the message is RECEIVED | def decode(message):
"""
Convert a generic JSON message
* The entire message is converted to JSON and treated as the message data
* The timestamp of the message is the time that the message is RECEIVED
"""
try:
data = json.loads(message.payload.decode... |
The decoder understands the comma - seperated format produced by the encoder and allocates the two values to the correct keys: data [ hello ] = world data [ x ] = 10 | def decode(message):
'''
The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10
'''
(hello, x) = message.payload.split(",")
data = {}
... |
Retrieve the organization - specific status of each of the services offered by the IBM Watson IoT Platform. In case of failure it throws APIException | def dataTransfer(self, start, end, detail=False):
"""
Retrieve the organization-specific status of each of the services offered by the IBM Watson IoT Platform.
In case of failure it throws APIException
"""
r = self._apiClient.get(
"api/v0002/usage/data-traffic?start=... |
Initiates a device management request such as reboot. In case of failure it throws APIException | def initiate(self, request):
"""
Initiates a device management request, such as reboot.
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtRequests
r = self._apiClient.post(url, request)
if r.status_code == 202:
return r.json()
... |
Clears the status of a device management request. You can use this operation to clear the status for a completed request or for an in - progress request which may never complete due to a problem. It accepts requestId ( string ) as parameters In case of failure it throws APIException | def delete(self, requestId):
"""
Clears the status of a device management request.
You can use this operation to clear the status for a completed request, or for an in-progress request which may never complete due to a problem.
It accepts requestId (string) as parameters
In case ... |
Gets details of a device management request. It accepts requestId ( string ) as parameters In case of failure it throws APIException | def get(self, requestId):
"""
Gets details of a device management request.
It accepts requestId (string) as parameters
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtSingleRequest % (requestId)
r = self._apiClient.get(url)
if r.statu... |
Get a list of device management request device statuses. Get an individual device mangaement request device status. | def getStatus(self, requestId, typeId=None, deviceId=None):
"""
Get a list of device management request device statuses.
Get an individual device mangaement request device status.
"""
if typeId is None or deviceId is None:
url = MgmtRequests.mgmtRequestStatus % (reque... |
Force a flush of the index to storage. Renders index inaccessible. | def close(self):
"""Force a flush of the index to storage. Renders index
inaccessible."""
if self.handle:
self.handle.destroy()
self.handle = None
else:
raise IOError("Unclosable index") |
Inserts an item into the index with the given coordinates. | def insert(self, id, coordinates, obj=None):
"""Inserts an item into the index with the given coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it is up
to the u... |
Return number of objects that intersect the given coordinates. | def count(self, coordinates):
"""Return number of objects that intersect the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
pairs representing the ... |
Return ids or objects in the index that intersect the given coordinates. | def intersection(self, coordinates, objects=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordi... |
Returns the k - nearest objects to the given coordinates. | def nearest(self, coordinates, num_results=1, objects=False):
"""Returns the ``k``-nearest objects to the given coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate
... |
Returns the bounds of the index | def get_bounds(self, coordinate_interleaved=None):
"""Returns the bounds of the index
:param coordinate_interleaved: If True, the coordinates are turned
in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
otherwise they are returned as
[xmin, xmax, ymin, ymax... |
Deletes items from the index with the given id within the specified coordinates. | def delete(self, id, coordinates):
"""Deletes items from the index with the given ``'id'`` within the
specified coordinates.
:param id: long integer
A long integer that is the identifier for this index entry. IDs
need not be unique to be inserted into the index, and it ... |
[ xmin ymin xmax ymax ] = > [ xmin xmax ymin ymax ] | def deinterleave(self, interleaved):
"""
[xmin, ymin, xmax, ymax] => [xmin, xmax, ymin, ymax]
>>> Index.deinterleave([0, 10, 1, 11])
[0, 1, 10, 11]
>>> Index.deinterleave([0, 1, 2, 10, 11, 12])
[0, 10, 1, 11, 2, 12]
"""
assert len(interleaved) % 2 == 0,... |
[ xmin xmax ymin ymax zmin zmax ] = > [ xmin ymin zmin xmax ymax zmax ] | def interleave(self, deinterleaved):
"""
[xmin, xmax, ymin, ymax, zmin, zmax]
=> [xmin, ymin, zmin, xmax, ymax, zmax]
>>> Index.interleave([0, 1, 10, 11])
[0, 10, 1, 11]
>>> Index.interleave([0, 10, 1, 11, 2, 12])
[0, 1, 2, 10, 11, 12]
>>> Index.int... |
This function is used to instantiate the index given an iterable stream of data. | def _create_idx_from_stream(self, stream):
"""This function is used to instantiate the index given an
iterable stream of data."""
stream_iter = iter(stream)
dimension = self.properties.dimension
darray = ctypes.c_double * dimension
mins = darray()
maxs = darray()... |
please override | def destroy(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") |
please override | def loadByteArray(self, context, page, resultLen, resultData, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") |
please override | def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") |
please override | def deleteByteArray(self, context, page, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") |
please override | def flush(self, context, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") |
Must be overridden. Must return a string with the loaded data. | def loadByteArray(self, page, returnError):
"""Must be overridden. Must return a string with the loaded data."""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
return '' |
Inserts an item into the index with the given coordinates. | def insert(self, obj, coordinates):
"""Inserts an item into the index with the given coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimens... |
Return ids or objects in the index that intersect the given coordinates. | def intersection(self, coordinates, bbox=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinat... |
Deletes the item from the container within the specified coordinates. | def delete(self, obj, coordinates):
"""Deletes the item from the container within the specified
coordinates.
:param obj: object
Any object.
:param coordinates: sequence or array
Dimension * 2 coordinate pairs, representing the min
and max coordinates... |
Error checking for Error calls | def check_return(result, func, cargs):
"Error checking for Error calls"
if result != 0:
s = rt.Error_GetLastErrorMsg().decode()
msg = 'LASError in "%s": %s' % \
(func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return True |
Error checking for void * returns | def check_void(result, func, cargs):
"Error checking for void* returns"
if not bool(result):
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result |
Error checking for void * returns that might be empty with no error | def check_void_done(result, func, cargs):
"Error checking for void* returns that might be empty with no error"
if rt.Error_GetErrorCount():
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return res... |
Attempt an import of the specified application | def load(self):
""" Attempt an import of the specified application """
if isinstance(self.application, str):
return util.import_app(self.application)
else:
return self.application |
Initializes the Flask application with Common. | def init_app(self, app):
"""Initializes the Flask application with Common."""
if not hasattr(app, 'extensions'):
app.extensions = {}
if 'common' in app.extensions:
raise RuntimeError("Flask-Common extension already initialized")
app.extensions['common'] = self
... |
Serves the Flask application. | def serve(self, workers=None, **kwargs):
"""Serves the Flask application."""
if self.app.debug:
print(crayons.yellow('Booting Flask development server...'))
self.app.run()
else:
print(crayons.yellow('Booting Gunicorn...'))
# Start the web server.... |
For djangorestframework < = 2. 3. 14 | def to_native(self, value):
"""For djangorestframework <=2.3.14"""
context_request = None
if self.context:
context_request = self.context.get('request', None)
return build_versatileimagefield_url_set(
value,
self.sizes,
request=context_requ... |
Return a PIL Image instance cropped from image. | def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)):
"""
Return a PIL Image instance cropped from `image`.
Image has an aspect ratio provided by dividing `width` / `height`),
sized down to `width`x`height`. Any 'excess pixels' are trimmed away
in respect to the ... |
Return a BytesIO instance of image cropped to width and height. | def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of I... |
Return a BytesIO instance of image that fits in a bounding box. | def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
"""
imagefile = BytesIO()
image.thumbnail(
(wid... |
Return a BytesIO instance of image with inverted colors. | def process_image(self, image, image_format, save_kwargs={}):
"""Return a BytesIO instance of `image` with inverted colors."""
imagefile = BytesIO()
inv_image = ImageOps.invert(image)
inv_image.save(
imagefile,
**save_kwargs
)
return imagefile |
Ensure data is prepped properly before handing off to ImageField. | def to_python(self, data):
"""Ensure data is prepped properly before handing off to ImageField."""
if data is not None:
if hasattr(data, 'open'):
data.open()
return super(VersatileImageFormField, self).to_python(data) |
Process the field s placeholder image. | def process_placeholder_image(self):
"""
Process the field's placeholder image.
Ensures the placeholder image has been saved to the same storage class
as the field in a top level folder with a name specified by
settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name']
... |
Return field s value just before saving. | def pre_save(self, model_instance, add):
"""Return field's value just before saving."""
file = super(VersatileImageField, self).pre_save(model_instance, add)
self.update_ppoi_field(model_instance)
return file |
Update field s ppoi field if defined. | def update_ppoi_field(self, instance, *args, **kwargs):
"""
Update field's ppoi field, if defined.
This method is hooked up this field's pre_save method to update
the ppoi immediately before the model instance (`instance`)
it is associated with is saved.
This field's pp... |
Handle data sent from MultiValueField forms that set ppoi values. | def save_form_data(self, instance, data):
"""
Handle data sent from MultiValueField forms that set ppoi values.
`instance`: The model instance that is being altered via a form
`data`: The data sent from the form to this field which can be either:
* `None`: This is unset data fro... |
Return a formfield. | def formfield(self, **kwargs):
"""Return a formfield."""
# This is a fairly standard way to set up some defaults
# while letting the caller override them.
defaults = {}
if self.ppoi_field:
defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField
if ... |
Prepare field for serialization. | def value_to_string(self, obj):
"""Prepare field for serialization."""
if DJANGO_VERSION > (1, 9):
value = self.value_from_object(obj)
else:
value = self._get_val_from_obj(obj)
return self.get_prep_value(value) |
Prints out a Yum - style progress bar ( via sys. stdout. write ). start: The current value of the progress bar. end: The 100% value of the progress bar. bar_length: The size of the overall progress bar. | def cli_progress_bar(start, end, bar_length=50):
"""
Prints out a Yum-style progress bar (via sys.stdout.write).
`start`: The 'current' value of the progress bar.
`end`: The '100%' value of the progress bar.
`bar_length`: The size of the overall progress bar.
Example output with start=20, end=1... |
Returns a 2 - tuple: 0: bool signifying whether the image was successfully pre - warmed 1: The url of the successfully created image OR the path on storage of the image that was not able to be successfully created. | def _prewarm_versatileimagefield(size_key, versatileimagefieldfile):
"""
Returns a 2-tuple:
0: bool signifying whether the image was successfully pre-warmed
1: The url of the successfully created image OR the path on storage of
the image that was not able to be successfully cr... |
Returns a 2 - tuple: [ 0 ]: Number of images successfully pre - warmed [ 1 ]: A list of paths on the storage class associated with the VersatileImageField field being processed by self of files that could not be successfully seeded. | def warm(self):
"""
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded.
"""
... |
Discover versatileimagefield. py modules. | def autodiscover():
"""
Discover versatileimagefield.py modules.
Iterate over django.apps.get_app_configs() and discover
versatileimagefield.py modules.
"""
from importlib import import_module
from django.apps import apps
from django.utils.module_loading import module_has_submodule
... |
Register a new SizedImage subclass ( sizedimage_cls ). | def register_sizer(self, attr_name, sizedimage_cls):
"""
Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`).
"""
if attr_name.startswith(
'_'
) or attr_name in self.unallowed_sizer_names:
raise Unallo... |
Unregister the SizedImage subclass currently assigned to attr_name. | def unregister_sizer(self, attr_name):
"""
Unregister the SizedImage subclass currently assigned to `attr_name`.
If a SizedImage subclass isn't already registered to `attr_name`
NotRegistered will raise.
"""
if attr_name not in self._sizedimage_registry:
rais... |
Register a new FilteredImage subclass ( filterimage_cls ). | def register_filter(self, attr_name, filterimage_cls):
"""
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
"""
if attr_name.startswith('_'):
raise UnallowedFilterName(
'`%s` is an unallowed... |
Unregister the FilteredImage subclass currently assigned to attr_name. | def unregister_filter(self, attr_name):
"""
Unregister the FilteredImage subclass currently assigned to attr_name.
If a FilteredImage subclass isn't already registered to filters.
`attr_name` NotRegistered will raise.
"""
if attr_name not in self._filter_registry:
... |
Return the appropriate URL. | def url(self):
"""
Return the appropriate URL.
URL is constructed based on these field conditions:
* If empty (not `self.name`) and a placeholder is defined, the
URL to the placeholder is returned.
* Otherwise, defaults to vanilla ImageFieldFile behavior.
... |
Primary Point of Interest ( ppoi ) setter. | def ppoi(self, value):
"""Primary Point of Interest (ppoi) setter."""
ppoi = validate_ppoi(
value,
return_converted_tuple=True
)
if ppoi is not False:
self._ppoi_value = ppoi
self.build_filters_and_sizers(ppoi, self.create_on_demand) |
Build the filters and sizers for a field. | def build_filters_and_sizers(self, ppoi_value, create_on_demand):
"""Build the filters and sizers for a field."""
name = self.name
if not name and self.field.placeholder_image_name:
name = self.field.placeholder_image_name
self.filters = FilterLibrary(
name,
... |
Return the location where filtered images are stored. | def get_filtered_root_folder(self):
"""Return the location where filtered images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '') |
Return the location where sized images are stored. | def get_sized_root_folder(self):
"""Return the location where sized images are stored."""
folder, filename = os.path.split(self.name)
return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '') |
Return the location where filtered + sized images are stored. | def get_filtered_sized_root_folder(self):
"""Return the location where filtered + sized images are stored."""
sized_root_folder = self.get_sized_root_folder()
return os.path.join(
sized_root_folder,
VERSATILEIMAGEFIELD_FILTERED_DIRNAME
) |
Delete files in root_folder which match regex before file ext. | def delete_matching_files_from_storage(self, root_folder, regex):
"""
Delete files in `root_folder` which match `regex` before file ext.
Example values:
* root_folder = 'foo/'
* self.name = 'bar.jpg'
* regex = re.compile('-baz')
Result:
... |
Validates that a tuple ( value )...... has a len of exactly 2... both values are floats/ ints that are greater - than - or - equal - to 0 AND less - than - or - equal - to 1 | def validate_ppoi_tuple(value):
"""
Validates that a tuple (`value`)...
...has a len of exactly 2
...both values are floats/ints that are greater-than-or-equal-to 0
AND less-than-or-equal-to 1
"""
valid = True
while valid is True:
if len(value) == 2 and isinstance(value, tuple... |
Converts validates and optionally returns a string with formatting: % ( x_axis ) dx% ( y_axis ) d into a two position tuple. | def validate_ppoi(value, return_converted_tuple=False):
"""
Converts, validates and optionally returns a string with formatting:
'%(x_axis)dx%(y_axis)d' into a two position tuple.
If a tuple is passed to `value` it is also validated.
Both x_axis and y_axis must be floats or ints greater
than 0... |
Preprocess an image. | def preprocess(self, image, image_format):
"""
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`... |
Receive a PIL Image instance of a GIF and return 2 - tuple. | def preprocess_GIF(self, image, **kwargs):
"""
Receive a PIL Image instance of a GIF and return 2-tuple.
Args:
* [0]: Original Image instance (passed to `image`)
* [1]: Dict with a transparency key (to GIF transparency layer)
"""
if 'transparency' in imag... |
Receive a PIL Image instance of a JPEG and returns 2 - tuple. | def preprocess_JPEG(self, image, **kwargs):
"""
Receive a PIL Image instance of a JPEG and returns 2-tuple.
Args:
* [0]: Image instance, converted to RGB
* [1]: Dict with a quality key (mapped to the value of `QUAL` as
defined by the `VERSATILEIMAGEFIE... |
Return a PIL Image instance stored at path_to_image. | def retrieve_image(self, path_to_image):
"""Return a PIL Image instance stored at `path_to_image`."""
image = self.storage.open(path_to_image, 'rb')
file_ext = path_to_image.rsplit('.')[-1]
image_format, mime_type = get_image_metadata_from_file_ext(file_ext)
return (
... |
Save an image to self. storage at save_path. | def save_image(self, imagefile, save_path, file_ext, mime_type):
"""
Save an image to self.storage at `save_path`.
Arguments:
`imagefile`: Raw image data, typically a BytesIO instance.
`save_path`: The path within self.storage where the image should
... |
Return PPOI value as a string. | def ppoi_as_str(self):
"""Return PPOI value as a string."""
return "%s__%s" % (
str(self.ppoi[0]).replace('.', '-'),
str(self.ppoi[1]).replace('.', '-')
) |
Create a resized image. | def create_resized_image(self, path_to_image, save_path_on_storage,
width, height):
"""
Create a resized image.
`path_to_image`: The path to the image with the media directory to
resize. If `None`, the
VERSATILEIMAGE... |
Render the widget as an HTML string. | def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget as an HTML string.
Overridden here to support Django < 1.11.
"""
if self.has_template_widget_rendering:
return super(ClearableFileInputWithImagePreview, self).render(
name... |
Get the context to render this widget with. | def get_context(self, name, value, attrs):
"""Get the context to render this widget with."""
if self.has_template_widget_rendering:
context = super(ClearableFileInputWithImagePreview, self).get_context(name, value, attrs)
else:
# Build the context manually.
co... |
Build an attribute dictionary. | def build_attrs(self, base_attrs, extra_attrs=None):
"""Build an attribute dictionary."""
attrs = base_attrs.copy()
if extra_attrs is not None:
attrs.update(extra_attrs)
return attrs |
Return the resized filename ( according to width height and filename_key ) in the following format: filename - filename_key - width x height. ext | def get_resized_filename(filename, width, height, filename_key):
"""
Return the 'resized filename' (according to `width`, `height` and
`filename_key`) in the following format:
`filename`-`filename_key`-`width`x`height`.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except Val... |
Return a path_to_image location on storage as dictated by width height and filename_key | def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_fi... |
Return the filtered filename ( according to filename_key ) in the following format: filename __ filename_key __. ext | def get_filtered_filename(filename, filename_key):
"""
Return the 'filtered filename' (according to `filename_key`)
in the following format:
`filename`__`filename_key`__.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ex... |
Return the filtered path | def get_filtered_path(path_to_image, filename_key, storage):
"""
Return the 'filtered path'
"""
containing_folder, filename = os.path.split(path_to_image)
filtered_filename = get_filtered_filename(filename, filename_key)
path_to_return = os.path.join(*[
containing_folder,
VERSAT... |
Validate a list of size keys. | def validate_versatileimagefield_sizekey_list(sizes):
"""
Validate a list of size keys.
`sizes`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('medium', 'crop__400x400'),
('small', 'thumbnail__100x100')
]
"""
try:
for key, size_key in s... |
Build a URL from image_key. | def get_url_from_image_key(image_instance, image_key):
"""Build a URL from `image_key`."""
img_key_split = image_key.split('__')
if 'x' in img_key_split[-1]:
size_key = img_key_split.pop(-1)
else:
size_key = None
img_url = reduce(getattr, img_key_split, image_instance)
if size_ke... |
Return a dictionary of urls corresponding to size_set - image_instance: A VersatileImageFieldFile - size_set: An iterable of 2 - tuples both strings. Example: [ ( large url ) ( medium crop__400x400 ) ( small thumbnail__100x100 ) ] | def build_versatileimagefield_url_set(image_instance, size_set, request=None):
"""
Return a dictionary of urls corresponding to size_set
- `image_instance`: A VersatileImageFieldFile
- `size_set`: An iterable of 2-tuples, both strings. Example:
[
('large', 'url'),
('mediu... |
Retrieve a validated and prepped Rendition Key Set from settings. VERSATILEIMAGEFIELD_RENDITION_KEY_SETS | def get_rendition_key_set(key):
"""
Retrieve a validated and prepped Rendition Key Set from
settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
"""
try:
rendition_key_set = IMAGE_SETS[key]
except KeyError:
raise ImproperlyConfigured(
"No Rendition Key Set exists at "
... |
Takes a raw Instruction and translates it into a human readable text representation. As of writing the text representation for WASM is not yet standardized so we just emit some generic format. | def format_instruction(insn):
"""
Takes a raw `Instruction` and translates it into a human readable text
representation. As of writing, the text representation for WASM is not yet
standardized, so we just emit some generic format.
"""
text = insn.op.mnemonic
if not insn.imm:
return ... |
Takes a FunctionBody and optionally a FunctionType yielding the string representation of the function line by line. The function type is required for formatting function parameter and return value information. | def format_function(
func_body,
func_type=None,
indent=2,
format_locals=True,
):
"""
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
representation of the function line by line. The function type is required
for formatting function parameter and return value ... |
Decodes raw bytecode yielding Instruction s. | def decode_bytecode(bytecode):
"""Decodes raw bytecode, yielding `Instruction`s."""
bytecode_wnd = memoryview(bytecode)
while bytecode_wnd:
opcode_id = byte2int(bytecode_wnd[0])
opcode = OPCODE_MAP[opcode_id]
if opcode.imm_struct is not None:
offs, imm, _ = opcode.imm_st... |
Decodes raw WASM modules yielding ModuleFragment s. | def decode_module(module, decode_name_subsections=False):
"""Decodes raw WASM modules, yielding `ModuleFragment`s."""
module_wnd = memoryview(module)
# Read & yield module header.
hdr = ModuleHeader()
hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd)
yield ModuleFragment(hdr, hdr_data)
... |
Deprecates a function printing a warning on the first usage. | def deprecated_func(func):
"""Deprecates a function, printing a warning on the first usage."""
# We use a mutable container here to work around Py2's lack of
# the `nonlocal` keyword.
first_usage = [True]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if first_usage[0]:
... |
Send an: class: ~panoramisk. actions. Action to the server: | def send_action(self, action, as_list=None, **kwargs):
"""Send an :class:`~panoramisk.actions.Action` to the server:
:param action: an Action or dict with action name and parameters to
send
:type action: Action or dict or Command
:param as_list: If True, the actio... |
Send a: class: ~panoramisk. actions. Command to the server:: | def send_command(self, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/... |
Send a: class: ~panoramisk. actions. Command to the server: | def send_agi_command(self, channel, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server:
:param channel: Channel name where to launch command.
Ex: 'SIP/000000-00000a53'
:type channel: String
:param command: command to launch. Ex: 'GET VAR... |
connect to the server | def connect(self):
"""connect to the server"""
if self.loop is None: # pragma: no cover
self.loop = asyncio.get_event_loop()
t = asyncio.Task(
self.loop.create_connection(
self.config['protocol_factory'],
self.config['host'], self.config['... |
register an event. See: class: ~panoramisk. message. Message: | def register_event(self, pattern, callback=None):
"""register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('M... |
Close the connection | def close(self):
"""Close the connection"""
if self.pinger:
self.pinger.cancel()
self.pinger = None
if getattr(self, 'protocol', None):
self.protocol.close() |
Send a command for FastAGI request: | def send_command(self, command):
"""Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
... |
Parse read a response from the AGI and parse it. | def _read_result(self):
"""Parse read a response from the AGI and parse it.
:return dict: The AGI response parsed into a dict.
"""
response = yield from self.reader.readline()
return parse_agi_result(response.decode(self.encoding)[:-1]) |
Add a route for FastAGI requests: | def add_route(self, path, endpoint):
"""Add a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:param endpoint: command to launch. Ex: start
:type endpoint: callable
:Example:
::
@asyncio.coroutine
... |
Delete a route for FastAGI requests: | def del_route(self, path):
"""Delete a route for FastAGI requests:
:param path: URI to answer. Ex: 'calls/start'
:type path: String
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
p... |
AsyncIO coroutine handler to launch socket listening. | def handler(self, reader, writer):
"""AsyncIO coroutine handler to launch socket listening.
:Example:
::
@asyncio.coroutine
def start(request):
print('Receive a FastAGI request')
print(['AGI variables:', request.headers])
fa... |
Parse AGI results using Regular expression. | def parse_agi_result(line):
"""Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Pr... |
Check the AGI code and return a dict to help on error handling. | def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code... |
Mostly used for unit testing. Allow to use a static uuid and reset all counter | def reset(cls, uid=None):
"""Mostly used for unit testing. Allow to use a static uuid and reset
all counter"""
for instance in cls.instances:
if uid:
instance.uid = uid
instance.generator = instance.get_generator() |
Mostly used for debugging | def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances] |
return True if a response status is Success or Follows: | def success(self):
"""return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.