Best Python code snippet using localstack_python
writer.py
Source:writer.py  
1"""2 Copyright 2013 Aarhus University3 Licensed under the Apache License, Version 2.0 (the "License");4 you may not use this file except in compliance with the License.5 You may obtain a copy of the License at6     http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, software8 distributed under the License is distributed on an "AS IS" BASIS,9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 See the License for the specific language governing permissions and11 limitations under the License.12"""13import os14import re15from ajaxinterface.requestpatterns.data import wildcardify16from ajaxinterface.responsetypes.json import structures17LIMIT = 3018UNQUOTE_STRING = re.compile(r'^[a-zA-Z0-9_\-*\.\[\]]+$')19def _limit(value):20    try:21        value = unicode(value)22    except:23        value = '<unicode error>'24    if len(value) > LIMIT:25        return u'%s...' % value[:LIMIT]26    else:27        return value28def _quote(value):29    if UNQUOTE_STRING.match(value) is None:30        return '"%s"' % value31    else:32        return value33LINEWRAP = 8034def _linelength(*args):35    return sum([sum([len(value) for value in values]) for values in args])36def _write_request_pattern(request_pattern):37    assert(request_pattern is not None)38    kwargs = [u'%s:%s' % (key, _quote(_limit((wildcardify(value))))) for key,value in request_pattern.kwargs.iteritems()]39    args = [wildcardify(arg) for arg in request_pattern.args]40    if _linelength(args, kwargs) > LINEWRAP:41        kwarg_delimiter = u',\n\t'42    else:43        kwarg_delimiter = u', '44    return u'%s %s(%s)' % (request_pattern.request_method,45                         u'/'.join(args),46                         kwarg_delimiter.join(kwargs))47response_type_counter = 048def _write_response_types(interface_path, basename, response_types):49    global response_type_counter50    files = []51    for response_type in response_types:52        filename = '%s.%s.json' % (basename, response_type_counter)53        54        response_type_counter += 155        files.append('@%s' % filename)56        57        fp = open(os.path.join(interface_path, filename), 'w')58        write_schema(fp, response_type._structure, 0)59        fp.close()60    61    return '|'.join(files)62def write_to_file(interface_path, basename, ail_specification, debug=False):63    fp = open(os.path.join(interface_path, '%s.ail' % basename), 'w')64    try:65        rrpair = ail_specification.lines[0].sample_rrpairs[0]66        domain = '/'.join(rrpair.request.url.split('/')[:3])67        fp.write('URL %s\n\n' % domain)68    except IndexError:69        fp.write('URL \n\n')70    for line in ail_specification.lines:71        fp.write('%s : %s' % (_write_request_pattern(line.request_pattern),72                              _write_response_types(interface_path,73                                                    basename,74                                                    line.response_types)))75        if debug:76            fp.write('DEBUG')77            fp.write('Number of rrpairs : %s' % len(line.sample_rrpairs))78            for rrpair in line.sample_rrpairs:79                fp.write('\n%s' % rrpair.uuid)80        fp.write('\n\n')81    fp.close()82def _iprint(fp, text, ident, omit_newline=False):83    if ident != 0:84        fp.write('   ' * (ident-1))85    fp.write(text)86    87    if not omit_newline:88        fp.write('\n')89def _insert_optional(fp, _ident, optional):90    required = 'false' if optional else 'true'91    _iprint(fp, '"required": %s,' % required, _ident+1)92def write_schema(fp, structure, _ident, optional=False):93    if isinstance(structure, structures.AbstractPrimitiveType):94        _iprint(fp, '{', _ident)95        _insert_optional(fp, _ident, optional)96        _iprint(fp, '"type": "%s"' % structure.jlabel, _ident+1)97        _iprint(fp, '}', _ident, omit_newline=True)98    elif isinstance(structure, structures.UnionType):99        _iprint(fp, '{', _ident)100        _insert_optional(fp, _ident, optional)101        _iprint(fp, '"type": [', _ident+1)102        num_types = len(structure.types)103        for x in xrange(num_types):104            write_schema(fp, structure.types[x], _ident+2)105            106            if num_types == x+1:107                # the last element108                fp.write("\n")109            else:110                fp.write(",\n")111        _iprint(fp, ']', _ident+1)112        _iprint(fp, '}', _ident, omit_newline=True)113    elif isinstance(structure, structures.ArrayType):114        _iprint(fp, '{', _ident)115        _insert_optional(fp, _ident, optional)116        _iprint(fp, '"type": "array",', _ident+1)117        if structure.element_types is not None:118            _iprint(fp, '"items": [', _ident+1)119            num_types = len(structure.element_types)120            for x in xrange(num_types):121                write_schema(fp, structure.element_types[x], _ident+2)122                123                if num_types == x+1:124                    # last element125                    fp.write("\n")126                else:127                    fp.write(",\n")128            _iprint(fp, ']', _ident+1)129        else:130            _iprint(fp, '"items": []', _ident+1)131        _iprint(fp, '}', _ident, omit_newline=True)132    elif isinstance(structure, structures.ObjectType):133        # needs required134        _iprint(fp, '{', _ident)135        _insert_optional(fp, _ident, optional)136        _iprint(fp, '"type": "object",', _ident+1)137        _iprint(fp, '"properties": {', _ident+1)138        139        labels = list(structure._labels)140        num_labels = len(labels)141        142        for x in xrange(num_labels):143            _iprint(fp, '"%s": ' % labels[x], _ident+2)144            optional = False145            if labels[x] in structure._optional:146                optional = True147            148            write_schema(fp, structure._record[labels[x]], _ident+2, optional=optional)149            150            if num_labels == x+1:151                # last element152                fp.write("\n")153            else:154                fp.write(",\n")155        _iprint(fp, '}', _ident+1)156        _iprint(fp, '}', _ident, omit_newline=True)157    else:...expressions.py
Source:expressions.py  
1from __future__ import annotations2import copy3from typing import Optional, Union4from xdrone.visitors.compiler_utils.type import ListType, Type5class AbstractExpression:6    def to_expression(self) -> Optional[Expression]:7        raise NotImplementedError("to_expression not supported in AbstractExpression")8class Expression(AbstractExpression):9    def __init__(self, type: Type, value: Union[int, float, str, bool, list], ident: Optional[str] = None):10        self._type = type11        self._value = value12        self._ident = ident13    @property14    def type(self) -> Type:15        return copy.deepcopy(self._type)16    @property17    def value(self) -> Union[int, float, str, bool, list]:18        return copy.deepcopy(self._value)19    @property20    def ident(self) -> Optional[str]:21        return copy.deepcopy(self._ident)22    def to_expression(self) -> Optional[Expression]:23        return Expression(self._type, self._value, self._ident)24    def __str__(self):25        return "Expression: {{ type: {}, value: {}, ident: {} }}".format(self._type, self._value, self._ident)26    def __eq__(self, other):27        if isinstance(other, Expression):28            return other._type == self._type and other._value == self._value and other.ident == self._ident29        return False30class Identifier(AbstractExpression):31    def __init__(self, ident: str, expression: Optional[Expression]):32        self._ident = ident33        self._expression = expression34    @property35    def ident(self) -> str:36        return copy.deepcopy(self._ident)37    def to_expression(self) -> Optional[Expression]:38        return copy.deepcopy(self._expression)39    def __str__(self):40        return "Identifier: {{ ident: {}, expression: {} }}".format(self._ident, self._expression)41    def __eq__(self, other):42        if isinstance(other, Identifier):43            return other._ident == self._ident and other._expression == self._expression44        return False45class ListElem(AbstractExpression):46    def __init__(self, ident: str, container: Expression, index: int):47        assert isinstance(container.type, ListType)48        self._ident = ident49        self._container = container50        self._index = index51        self._expression = Expression(container.type.elem_type, container.value[index],52                                      ident="{}[{}]".format(ident, index))53    @property54    def ident(self) -> str:55        return copy.deepcopy(self._ident)56    @property57    def container(self) -> Expression:58        return copy.deepcopy(self._container)59    @property60    def index(self) -> int:61        return copy.deepcopy(self._index)62    def to_expression(self) -> Optional[Expression]:63        return copy.deepcopy(self._expression)64    def __str__(self):65        return "ListElem: {{ ident: {}, container: {}, index: {}, expression: {} }}".format(66            self._ident, self._container, self.index, self._expression)67    def __eq__(self, other):68        if isinstance(other, ListElem):69            return other._ident == self._ident and other._container == self._container \70                   and other._index == self._index and other._expression == self._expression71        return False72class VectorElem(AbstractExpression):73    def __init__(self, ident: str, container: Expression, index: int):74        assert container.type == Type.vector()75        self._ident = ident76        self._container = container77        self._index = index78        self._expression = Expression(Type.decimal(), container.value[index])79    @property80    def ident(self) -> str:81        return copy.deepcopy(self._ident)82    @property83    def container(self) -> Expression:84        return copy.deepcopy(self._container)85    @property86    def index(self) -> int:87        return copy.deepcopy(self._index)88    def to_expression(self) -> Optional[Expression]:89        return copy.deepcopy(self._expression)90    def __str__(self):91        return "ListElem: {{ ident: {}, container: {}, index: {}, expression: {} }}".format(92            self._ident, self._container, self.index, self._expression)93    def __eq__(self, other):94        if isinstance(other, VectorElem):95            return other._ident == self._ident and other._container == self._container \96                   and other._index == self._index and other._expression == self._expression...helpFunctions.py
Source:helpFunctions.py  
1from cv_bridge import CvBridge, CvBridgeError2from sensor_msgs.msg import Image3import rospy4import cv25import numpy as np6_magic = [0.299, 0.587, 0.114]7_zero = [0, 0, 0]8_ident = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]9true_anaglyph = ([_magic, _zero, _zero], [_zero, _zero, _magic])10gray_anaglyph = ([_magic, _zero, _zero], [_zero, _magic, _magic])11color_anaglyph = ([_ident[0], _zero, _zero], [_zero, _ident[1], _ident[2]])12half_color_anaglyph = ([_magic, _zero, _zero], [_zero, _ident[1], _ident[2]])13optimized_anaglyph = ([[0, 0.7, 0.3], _zero, _zero], [_zero, _ident[1], _ident[2]])14methods = [true_anaglyph, gray_anaglyph, color_anaglyph, half_color_anaglyph, optimized_anaglyph]15class GetImageClass:16    def __init__(self,topicName):17        self.topicName = '/stereo/' + topicName + '/image_color'18        self.image = None19        self.image_sub = rospy.Subscriber(self.topicName, Image, self.image_callback, queue_size=1) #/stereo/right/image_color20        self.bridge = CvBridge()21    def convertROSToCV(self, data):22        try:23            cv_image = self.bridge.imgmsg_to_cv2(data, 'bgr8')24            return cv_image25        except CvBridgeError, e:26            print e27    def image_callback(self, data):28        self.image = self.convertROSToCV(data)29    def getImage(self):30        return self.image31class CreateAnaglyphImage:32    def __init__(self):33        self._magic = [0.299, 0.587, 0.114]34        self._zero = [0, 0, 0]35        self._ident = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]36        self.true_anaglyph = ([self._magic, self._zero, self._zero], [self._zero, self._zero, self._magic])37        self.gray_anaglyph = ([self._magic, self._zero, self._zero], [self._zero, self._magic, self._magic])38        self.color_anaglyph = ([self._ident[0], self._zero, self._zero], [self._zero, self._ident[1], self._ident[2]])39        self.half_color_anaglyph = ([self._magic, self._zero, self._zero], [self._zero, self._ident[1], self._ident[2]])40        self.optimized_anaglyph = ([[0, 0.7, 0.3], self._zero, self._zero], [self._zero, self._ident[1], self._ident[2]])41        self.methods = [self.true_anaglyph, self.gray_anaglyph, self.color_anaglyph, self.half_color_anaglyph, self.optimized_anaglyph]42    # http://bytes.com/topic/python/answers/486627-anaglyph-3d-stereo-imaging-pil-numpy43    def anaglyph(self, image1, image2, method=true_anaglyph):44        m1, m2 = [np.array(m).transpose() for m in method]45        image1 = np.dot(image1, m1) # float6446        image2 = np.dot(image2, m2) # int6447        composite = cv2.add(np.asarray(image1, dtype="uint8"), np.asarray(image2, dtype="uint8"))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
