bits = token.split_contents()<EOL>tag_name = bits[<NUM_LIT:0>]<EOL>if len(bits) < <NUM_LIT:2>:<EOL><INDENT>raise TemplateSyntaxError("<STR_LIT>" %<EOL>tag_name)<EOL><DEDENT>args = []<EOL>kwargs = {}<EOL>bits = bits[<NUM_LIT:1>:]<EOL>if len(bits):<EOL><INDENT>for bit in bits:<EOL><INDENT>match = kwarg_re.match(bit)<EOL>if not match:<EOL><INDENT>raise TemplateSyntaxError("<STR_LIT>" %<EOL>tag_name)<EOL><DEDENT>name, value = match.groups()<EOL>if name:<EOL><INDENT>name = name.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>kwargs[name] = parser.compile_filter(value)<EOL><DEDENT>else:<EOL><INDENT>args.append(parser.compile_filter(value))<EOL><DEDENT><DEDENT><DEDENT>return SocialWidgetNode(args, kwargs)<EOL>

Renders the selected social widget. You can specify optional settings
    that will be passed  to widget template.

    Sample usage:
    {% social_widget_render widget_template ke1=val1 key2=val2 %}

    For example to render Twitter follow button you can use code like this:
    {% social_widget_render 'twitter/follow_button.html' username="ev" %}


if locale is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return normalize(locale).split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>

Normalize the locale string and split the value needed for the api url


def _subscribe_mock(self, signal_name, weak):

callback = mock.Mock()<EOL>decorator = self.model.subscribe(signal_name, weak)<EOL>return decorator(callback)<EOL>

Create a mock callback function and subscribe it to the specific
        signal on ``self.model``.


cmd = "<STR_LIT>".format(port)<EOL>if daemon:<EOL><INDENT>cmd += "<STR_LIT>"<EOL><DEDENT>run(cmd)<EOL>


version = '<STR_LIT>'<EOL>with open(fname, '<STR_LIT:r>') as fp:<EOL><INDENT>reg = re.compile(r'<STR_LIT>')<EOL>for line in fp:<EOL><INDENT>m = reg.match(line)<EOL>if m:<EOL><INDENT>version = m.group(<NUM_LIT:1>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if not version:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return version<EOL>

Attempts to find the version number in the file names fname.
    Raises RuntimeError if not found.


if isinstance(value, list):<EOL><INDENT>return FrozenList(*value)<EOL><DEDENT>if isinstance(value, dict):<EOL><INDENT>return FrozenDict(**value)<EOL><DEDENT>return value<EOL>


if len(keys) == <NUM_LIT:1>:<EOL><INDENT>data[keys[<NUM_LIT:0>]] = value<EOL><DEDENT>else:<EOL><INDENT>if keys[<NUM_LIT:0>] not in data:<EOL><INDENT>data[keys[<NUM_LIT:0>]] = {}<EOL><DEDENT>set_nested(data[keys[<NUM_LIT:0>]], value, *keys[<NUM_LIT:1>:])<EOL><DEDENT>

Assign to a nested dictionary.

    :param dict data: Dictionary to mutate
    :param value: Value to set
    :param list *keys: List of nested keys

    >>> data = {}
    >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
    >>> data
    {'k0': {'k1': {'k2': 'hi'}}}


def proxy_factory(BaseSchema, label, ProxiedClass, get_key):

def local():<EOL><INDENT>key = get_key()<EOL>try:<EOL><INDENT>return proxies[BaseSchema][label][key]<EOL><DEDENT>except KeyError:<EOL><INDENT>proxies[BaseSchema][label][key] = ProxiedClass()<EOL>return proxies[BaseSchema][label][key]<EOL><DEDENT><DEDENT>return LocalProxy(local)<EOL>

Create a proxy to a class instance stored in ``proxies``.

    :param class BaseSchema: Base schema (e.g. ``StoredObject``)
    :param str label: Name of class variable to set
    :param class ProxiedClass: Class to get or create
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


def wrapper(cls):<EOL><INDENT>for label, ProxiedClass in six.iteritems(proxy_map):<EOL><INDENT>proxy = proxy_factory(cls, label, ProxiedClass, get_key)<EOL>setattr(cls, label, proxy)<EOL><DEDENT>return cls<EOL><DEDENT>return wrapper<EOL>

Class decorator factory; adds proxy class variables to target class.

    :param dict proxy_map: Mapping between class variable labels and proxied
        classes
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


if value is None:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(value, self.base_class):<EOL><INDENT>if not value._is_loaded:<EOL><INDENT>raise exceptions.DatabaseError('<STR_LIT>')<EOL><DEDENT>return value._primary_key<EOL><DEDENT>return self.base_class._to_primary_key(value)<EOL>

Return primary key; if value is StoredObject, verify
that it is loaded.


self._touch(instance)<EOL>return self.data.get(instance, None)<EOL>

Return data from raw data store, rather than overridden
        __get__ methods. Should NOT be overwritten.


@wraps(func)<EOL>def wrapped(this, *args, **kwargs):<EOL><INDENT>if '<STR_LIT>' in this.__dict__ and this._detached:<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL><DEDENT>return func(this, *args, **kwargs)<EOL><DEDENT>return wrapped<EOL>


@wraps(func)<EOL>def wrapped(*args, **kwargs):<EOL><INDENT>me = args[<NUM_LIT:0>]<EOL>if not hasattr(me, '<STR_LIT>') ornot me._storage:<EOL><INDENT>raise exceptions.ImproperConfigurationError(<EOL>'<STR_LIT>'<EOL>.format(me._name.upper())<EOL>)<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>return wrapped<EOL>

Ensure that self/cls contains a Storage backend.


for stack, key in obj._backrefs_flat:<EOL><INDENT>backref_key, parent_schema_name, parent_field_name = stack<EOL>parent_schema = obj._collections[parent_schema_name]<EOL>parent_key_store = parent_schema._pk_to_storage(key)<EOL>parent_object = parent_schema.load(parent_key_store)<EOL>if parent_object is None:<EOL><INDENT>continue<EOL><DEDENT>if parent_object._fields[parent_field_name]._list:<EOL><INDENT>getattr(parent_object, parent_field_name).remove(obj)<EOL><DEDENT>else:<EOL><INDENT>parent_field_object = parent_object._fields[parent_field_name]<EOL>setattr(parent_object, parent_field_name, parent_field_object._gen_default())<EOL><DEDENT>parent_object.save()<EOL><DEDENT>

When removing an object, other objects with references to the current
    object should remove those references. This function identifies objects
    with forward references to the current object, then removes those
    references.

    :param obj: Object to which forward references should be removed


for ref in _collect_refs(obj):<EOL><INDENT>ref['<STR_LIT:value>']._remove_backref(<EOL>ref['<STR_LIT>']._backref_field_name,<EOL>obj,<EOL>ref['<STR_LIT>'],<EOL>strict=False<EOL>)<EOL><DEDENT>

When removing an object with foreign fields, back-references from
    other objects to the current object should be deleted. This function
    identifies foreign fields of the specified object whose values are not
    None and which specify back-reference keys, then removes back-references
    from linked objects to the specified object.

    :param obj: Object for which back-references should be removed


for ref in _collect_refs(obj, fields):<EOL><INDENT>updated = ref['<STR_LIT:value>']._update_backref(<EOL>ref['<STR_LIT>']._backref_field_name,<EOL>obj,<EOL>ref['<STR_LIT>'],<EOL>)<EOL>if updated:<EOL><INDENT>logging.debug('<STR_LIT>'.format(<EOL>obj._name, obj._primary_key, ref['<STR_LIT>'],<EOL>ref['<STR_LIT:value>']._name, ref['<STR_LIT:value>']._primary_key,<EOL>))<EOL><DEDENT><DEDENT>

Ensure that all forward references on the provided object have the
    appropriate backreferences.

    :param StoredObject obj: Database record
    :param list fields: Optional list of field names to check


return self._pk_to_storage(self._primary_key)<EOL>


def get_changed_fields(self, cached_data, storage_data):

if not self._is_loaded or cached_data is None:<EOL><INDENT>return []<EOL><DEDENT>return [<EOL>field<EOL>for field in self._fields<EOL>if cached_data.get(field) != storage_data.get(field)<EOL>]<EOL>

Get fields that differ between the cache_sandbox and the current object.
        Validation and after_save methods should only be run on diffed
        fields.

        :param cached_data: Storage-formatted data from cache_sandbox
        :param storage_data: Storage-formatted data from object
        :return: List of diffed fields


@classmethod<EOL><INDENT>@has_storage<EOL>@log_storage<EOL>def load(cls, key=None, data=None, _is_loaded=True):<DEDENT>

<EOL>signals.load.send(<EOL>cls,<EOL>key=key,<EOL>data=data,<EOL>)<EOL>if key is not None:<EOL><INDENT>key = cls._check_pk_type(key)<EOL>cached_object = cls._load_from_cache(key)<EOL>if cached_object is not None:<EOL><INDENT>return cached_object<EOL><DEDENT><DEDENT>if data is None:<EOL><INDENT>data = cls._storage[<NUM_LIT:0>].get(cls._primary_name, cls._pk_to_storage(key))<EOL><DEDENT>if data is None:<EOL><INDENT>return None<EOL><DEDENT>data = cls.from_storage(data)<EOL>if cls._version_of and '<STR_LIT>' in data and data['<STR_LIT>'] != cls._version:<EOL><INDENT>old_object = cls._version_of.load(data=data)<EOL>new_object = cls(_is_loaded=_is_loaded)<EOL>cls.migrate(old_object, new_object)<EOL>new_object._stored_key = new_object._primary_key<EOL>return new_object<EOL><DEDENT>ret = cls(_is_loaded=_is_loaded, **data)<EOL>ret._stored_key = ret._primary_key<EOL>return ret<EOL>


for record in cls.find():<EOL><INDENT>record.save()<EOL><DEDENT>


@classmethod<EOL><INDENT>def migrate(cls, old, new, verbose=True, dry_run=False, rm_refs=True):<DEDENT>

if verbose:<EOL><INDENT>logging.basicConfig(format='<STR_LIT>',<EOL>level=logging.DEBUG)<EOL><DEDENT>deleted_fields = [field for field in old._fields if field not in new._fields]<EOL>added_fields = [field for field in new._fields if field not in old._fields]<EOL>logging.info('<STR_LIT>'.format(deleted_fields))<EOL>logging.info('<STR_LIT>'.format(added_fields))<EOL>if old._primary_name != new._primary_name:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(old_name=old._primary_name,<EOL>old_field=old._fields[old._primary_name],<EOL>new_name=new._primary_name,<EOL>new_field=new._fields[new._primary_name]))<EOL><DEDENT>for field in old._fields:<EOL><INDENT>if field not in cls._fields:<EOL><INDENT>if rm_refs:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>field=old._fields[field]))<EOL>if not dry_run:<EOL><INDENT>rm_fwd_refs(old)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>field=old._fields[field]))<EOL><DEDENT>continue<EOL><DEDENT>old_field_obj = old._fields[field]<EOL>new_field_obj = new._fields[field]<EOL>if old_field_obj != new_field_obj:<EOL><INDENT>if not old_field_obj._required and new_field_obj._required:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(name=field))<EOL><DEDENT>else:<EOL><INDENT>logging.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>old_field=old_field_obj,<EOL>new_field=new_field_obj)<EOL>)<EOL><DEDENT>continue<EOL><DEDENT>if not dry_run:<EOL><INDENT>field_object = cls._fields[field]<EOL>field_object.__set__(<EOL>new,<EOL>getattr(old, field),<EOL>safe=True<EOL>)<EOL><DEDENT><DEDENT>if not dry_run:<EOL><INDENT>new.__backrefs = old.__backrefs<EOL><DEDENT>if not dry_run:<EOL><INDENT>cls._migrate(old, new)<EOL><DEDENT>

Migrate record to new schema.

        :param old: Record from original schema
        :param new: Record from new schema
        :param verbose: Print detailed info
        :param dry_run: Dry run; make no changes if true
        :param rm_refs: Remove references on deleted fields


@classmethod<EOL><INDENT>def _migrate(cls, old, new):<DEDENT>

return new<EOL>

Subclasses can override this class to perform a custom migration.
        This is run after the migrate() method.

        Example:
        ::

            class NewSchema(StoredObject):
                _id = fields.StringField(primary=True, index=True)
                my_string = fields.StringField()

                @classmethod
                def _migrate(cls, old, new):
                    new.my_string = old.my_string + 'yo'

                _meta = {
                    'version_of': OldSchema,
                    'version': 2,
                    'optimistic': True
                }

        :param old: Record from original schema
        :param new: Record from new schema


for validator in self._record_validators:<EOL><INDENT>validator(self)<EOL><DEDENT>

Apply record-level validation. Run on `save`.


if self._detached:<EOL><INDENT>raise exceptions.DatabaseError('<STR_LIT>')<EOL><DEDENT>for field_name, field_object in self._fields.items():<EOL><INDENT>if hasattr(field_object, '<STR_LIT>'):<EOL><INDENT>field_object.on_before_save(self)<EOL><DEDENT><DEDENT>signals.before_save.send(<EOL>self.__class__,<EOL>instance=self<EOL>)<EOL>cached_data = self._get_cached_data(self._stored_key)<EOL>storage_data = self.to_storage()<EOL>if self._primary_key is not None and cached_data is not None:<EOL><INDENT>fields_changed = set(<EOL>self.get_changed_fields(cached_data, storage_data)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>fields_changed = set(self._fields.keys())<EOL><DEDENT>if not fields_changed and not force:<EOL><INDENT>return []<EOL><DEDENT>for field_name in fields_changed:<EOL><INDENT>field_object = self._fields[field_name]<EOL>field_object.do_validate(getattr(self, field_name), self)<EOL><DEDENT>self.validate_record()<EOL>primary_changed = (<EOL>self._primary_key != self._stored_key<EOL>and<EOL>self._primary_name in fields_changed<EOL>)<EOL>if self._is_loaded:<EOL><INDENT>if primary_changed and not getattr(self, '<STR_LIT>', False):<EOL><INDENT>self.delegate(<EOL>self._storage[<NUM_LIT:0>].remove,<EOL>False,<EOL>RawQuery(self._primary_name, '<STR_LIT>', self._stored_key)<EOL>)<EOL>self._clear_caches(self._stored_key)<EOL>self.insert(self._primary_key, storage_data)<EOL><DEDENT>else:<EOL><INDENT>self.update_one(self, storage_data=storage_data, saved=True, inmem=True)<EOL><DEDENT><DEDENT>elif self._is_optimistic and self._primary_key is None:<EOL><INDENT>self._optimistic_insert()<EOL><DEDENT>else:<EOL><INDENT>self.insert(self._primary_key, storage_data)<EOL><DEDENT>if self._is_loaded and primary_changed:<EOL><INDENT>if not getattr(self, '<STR_LIT>', False):<EOL><INDENT>self._updating_key = True<EOL>update_backref_keys(self)<EOL>self._stored_key = self._primary_key<EOL>self._updating_key = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._stored_key = self._primary_key<EOL><DEDENT>self._is_loaded = True<EOL>signals.save.send(<EOL>self.__class__,<EOL>instance=self,<EOL>fields_changed=fields_changed,<EOL>cached_data=cached_data or {},<EOL>)<EOL>storage_data[self._primary_name] = self._storage_key<EOL>self._set_cache(self._primary_key, self, storage_data)<EOL>return fields_changed<EOL>

Save a record.

        :param bool force: Save even if no fields have changed; used to update
            back-references
        :returns: List of changed fields


for key, value in kwargs.items():<EOL><INDENT>self._fields[key].__set__(self, value, safe=True)<EOL><DEDENT>

Update multiple fields, specified by keyword arguments.

        Example::

            person.update(given_name='Fred', family_name='Mercury')

        ... is equivalent to ... ::

            person.given_name = 'Fred'
            person.family_name = 'Mercury'

        :param **kwargs: field names and the values to set


@classmethod<EOL><INDENT>@has_storage<EOL>@log_storage<EOL>def find(cls, query=None, **kwargs):<DEDENT>

cls._process_query(query)<EOL>return cls._storage[<NUM_LIT:0>].QuerySet(<EOL>cls,<EOL>cls._storage[<NUM_LIT:0>].find(query, **kwargs)<EOL>)<EOL>

:param query:
:param kwargs:
:return: an iterable of :class:`StoredObject` instances


@classmethod<EOL><INDENT>def delegate(cls, method, conflict=None, *args, **kwargs):<DEDENT>

if cls.queue.active:<EOL><INDENT>action = WriteAction(method, *args, **kwargs)<EOL>if conflict:<EOL><INDENT>logger.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(action))<EOL><DEDENT>cls.queue.push(action)<EOL><DEDENT>else:<EOL><INDENT>method(*args, **kwargs)<EOL><DEDENT>

Execute or queue a database action. Variable positional and keyword
        arguments are passed to the provided method.

        :param function method: Method to execute or queue
        :param bool conflict: Potential conflict between cache_sandbox and backend,
            e.g., in the event of bulk updates or removes that bypass the
            cache_sandbox


cls.queue.start()<EOL>

Start the queue. Between calling `start_queue` and `commit_queue`,
        all writes will be deferred to the queue.


cls.queue.clear()<EOL>


if cls.queue:<EOL><INDENT>cls._cache.clear()<EOL>cls._object_cache.clear()<EOL><DEDENT>cls.clear_queue()<EOL>

Cancel any pending actions. This method clears the queue and also
        clears caches if any actions are pending.


try:<EOL><INDENT>cls.queue.commit()<EOL>cls.clear_queue()<EOL><DEDENT>except:<EOL><INDENT>cls.cancel_queue()<EOL>raise<EOL><DEDENT>

Commit all queued actions. If any actions fail, clear caches. Note:
        the queue will be cleared whether an error is raised or not.


@classmethod<EOL><INDENT>def subscribe(cls, signal_name, weak=True):<DEDENT>

try:<EOL><INDENT>signal = getattr(signals, signal_name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(signal_name)<EOL>)<EOL><DEDENT>sender = None if cls._is_root else cls<EOL>return signal.connect_via(sender, weak)<EOL>

:param str signal_name: Name of signal to subscribe to; must be found
    in ``signals.py``.
:param bool weak: Create weak reference to callback
:returns: Decorator created by ``Signal::connect_via``
:raises: ValueError if signal is not found

Example usage: ::

    >>> @Schema.subscribe('before_save')
    ... def listener(cls, instance):
    ...     instance.value += 1


@classmethod<EOL><INDENT>@has_storage<EOL>def remove_one(cls, which, rm=True):<DEDENT>

<EOL>obj = cls._which_to_obj(which)<EOL>rm_fwd_refs(obj)<EOL>rm_back_refs(obj)<EOL>cls._clear_caches(obj._storage_key)<EOL>if rm:<EOL><INDENT>cls.delegate(<EOL>cls._storage[<NUM_LIT:0>].remove,<EOL>False,<EOL>RawQuery(obj._primary_name, '<STR_LIT>', obj._storage_key)<EOL>)<EOL><DEDENT>obj._detached = True<EOL>

Remove an object, along with its references and back-references.
        Remove the object from the cache_sandbox and sets its _detached flag to True.

        :param which: Object selector: Query, StoredObject, or primary key
        :param rm: Remove data from backend


objs = cls.find(query)<EOL>for obj in objs:<EOL><INDENT>cls.remove_one(obj, rm=False)<EOL><DEDENT>cls.delegate(<EOL>cls._storage[<NUM_LIT:0>].remove,<EOL>False,<EOL>query<EOL>)<EOL>

Remove objects by query.

        :param query: Query object


alphabet = '<STR_LIT>'<EOL>return '<STR_LIT>'.join(random.sample(alphabet, n))<EOL>

Generated random alphanumeric key.

        :param n: Number of characters in random key


def _optimistic_insert(self, primary_name, value, n=<NUM_LIT:5>):

while True:<EOL><INDENT>try:<EOL><INDENT>key = self._generate_random_id(n)<EOL>value[primary_name] = key<EOL>self.insert(primary_name, key, value)<EOL>break<EOL><DEDENT>except KeyExistsException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return key<EOL>

Attempt to insert with randomly generated key until insert
        is successful.

        :param str primary_name: The name of the primary key.
        :param dict value: The dictionary representation of the record.
        :param n: Number of characters in random key


@abc.abstractmethod<EOL><INDENT>def insert(self, primary_name, key, value):<DEDENT>

pass<EOL>

Insert a new record.

        :param str primary_name: Name of primary key
        :param key: The value of the primary key
        :param dict value: The dictionary of attribute:value pairs


@abc.abstractmethod<EOL><INDENT>def update(self, query, data):<DEDENT>

pass<EOL>

Update multiple records with new data.

        :param query: A query object.
        :param dict data: Dictionary of key:value pairs.


@abc.abstractmethod<EOL><INDENT>def get(self, primary_name, key):<DEDENT>

pass<EOL>

Get a single record.

        :param str primary_name: The name of the primary key.
        :param key: The value of the primary key.


pass<EOL>


@abc.abstractmethod<EOL><INDENT>def find_one(self, query=None, **kwargs):<DEDENT>

pass<EOL>

Gets a single object from the collection.

        If no matching documents are found, raises `NoResultsFound`.
        If >1 matching documents are found, raises `MultipleResultsFound`.

        :params: One or more `Query` or `QuerySet` objects may be passed

        :returns: The selected document


@abc.abstractmethod<EOL><INDENT>def find(self, query=None, **kwargs):<DEDENT>

pass<EOL>

Return a generator of query results. Takes optional `by_pk` keyword
argument; if true, return keys rather than
values.

:param query:

:return: a generator of :class:`~.storedobject.StoredObject` instances


self._sort = keys<EOL>return self<EOL>

Iteratively sort data by keys in reverse order.


def __init__(self, collection_name,  prefix='<STR_LIT>', ext='<STR_LIT>'):

<EOL>filename = collection_name + '<STR_LIT:.>' + ext<EOL>if prefix:<EOL><INDENT>self.filename = prefix + filename<EOL><DEDENT>else:<EOL><INDENT>self.filename = filename<EOL><DEDENT>self.store = {}<EOL>if os.path.exists(self.filename):<EOL><INDENT>with open(self.filename, '<STR_LIT:rb>') as fp:<EOL><INDENT>data = fp.read()<EOL>self.store = pickle.loads(data)<EOL><DEDENT><DEDENT>

Build pickle file name and load data if exists.

        :param collection_name: Collection name
        :param prefix: File prefix.
        :param ext: File extension.


def _remove_by_pk(self, key, flush=True):

try:<EOL><INDENT>del self.store[key]<EOL><DEDENT>except Exception as error:<EOL><INDENT>pass<EOL><DEDENT>if flush:<EOL><INDENT>self.flush()<EOL><DEDENT>

Retrieve value from store.

        :param key: Key


form = ContactForm(request.POST or None)<EOL>if form.is_valid():<EOL><INDENT>subject = form.cleaned_data['<STR_LIT>']<EOL>message = form.cleaned_data['<STR_LIT:message>']<EOL>sender = form.cleaned_data['<STR_LIT>']<EOL>cc_myself = form.cleaned_data['<STR_LIT>']<EOL>recipients = settings.CONTACTFORM_RECIPIENTS<EOL>if cc_myself:<EOL><INDENT>recipients.append(sender)<EOL><DEDENT>send_mail(getattr(settings, "<STR_LIT>", '<STR_LIT>') + subject, message, sender, recipients)<EOL>return render(request, '<STR_LIT>')<EOL><DEDENT>return render( request, '<STR_LIT>', {'<STR_LIT>': form})<EOL>

Displays the contact form and sends the email


def debug_log(message):<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.debug(message.encode('<STR_LIT>').decode())<EOL><DEDENT>@functools.wraps(wrapped_function)<EOL>def _wrapper(parser, match, **kwargs):<EOL><INDENT>func_name = wrapped_function.__name__<EOL>debug_log(u'<STR_LIT>'.format(<EOL>func_name=func_name,<EOL>matched_string=match.group(),<EOL>))<EOL>try:<EOL><INDENT>result = wrapped_function(parser, match, **kwargs)<EOL><DEDENT>except IgnoredMatchException:<EOL><INDENT>debug_log(u'<STR_LIT>'.format(func_name=func_name))<EOL>raise<EOL><DEDENT>debug_log(u'<STR_LIT>'.format(<EOL>func_name=func_name,<EOL>result=result,<EOL>))<EOL>return result<EOL><DEDENT>return _wrapper<EOL>

Decorator that produces DEBUG level log messages before and after
    calling a parser method.

    If a callback raises an IgnoredMatchException the log will show 'IGNORED'
    instead to indicate that the parser will not create any objects from
    the matched string.

    Example:
        DEBUG:poyo.parser:parse_simple <-     123: 456.789
        DEBUG:poyo.parser:parse_int <- 123
        DEBUG:poyo.parser:parse_int -> 123
        DEBUG:poyo.parser:parse_float <- 456.789
        DEBUG:poyo.parser:parse_float -> 456.789
        DEBUG:poyo.parser:parse_simple -> <Simple name: 123, value: 456.789>


raise IgnoredMatchException<EOL>


raise IgnoredMatchException<EOL>

Ignore lines that contain three dash symbols.


for pattern, callback in self.rules:<EOL><INDENT>match = pattern.match(self.source, pos=self.pos)<EOL>if not match:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>node = callback(match)<EOL><DEDENT>except IgnoredMatchException:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.seen.append(node)<EOL><DEDENT>return match<EOL><DEDENT>raise NoMatchException(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(self.source[self.pos:])<EOL>)<EOL>

Try to find a pattern that matches the source and calll a parser
        method to create Python objects.

        A callback that raises an IgnoredMatchException indicates that the
        given string data is ignored by the parser and no objects are created.

        If none of the pattern match a NoMatchException is raised.


while self.pos < self.max_pos:<EOL><INDENT>match = self.find_match()<EOL>self.pos = match.end()<EOL><DEDENT>return self.root()<EOL>

Parse the given string data and sequentually update the current
        cursor position until the end is reached.

        Return the Root object if successful.


if not isinstance(child, ChildMixin):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(type(child))<EOL>)<EOL><DEDENT>child.parent = self<EOL>self._children.append(child)<EOL>

If the given object is an instance of Child add it to self and
        register self as a parent.


cls.test_server = AdsTestServer(logging=True)<EOL>cls.test_server.start()<EOL>time.sleep(<NUM_LIT:1>)<EOL>


cls.test_server.stop()<EOL>time.sleep(<NUM_LIT:1>)<EOL>


self.test_server.request_history = []<EOL>self.plc = pyads.Connection(TEST_SERVER_AMS_NET_ID,<EOL>TEST_SERVER_AMS_PORT,<EOL>TEST_SERVER_IP_ADDRESS)<EOL>


def assert_command_id(self, request, target_id):<EOL>

<EOL>command_id = request.ams_header.command_id<EOL>command_id = struct.unpack('<STR_LIT>', command_id)[<NUM_LIT:0>]<EOL>self.assertEqual(command_id, target_id)<EOL>


self.start()<EOL>return self<EOL>


def __exit__(self, exc_type, exc_value, traceback):<EOL>

self.close()<EOL>


<EOL>for client in self.clients:<EOL><INDENT>client.close()<EOL><DEDENT>self.clients = []<EOL>if self._run:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self._run = False<EOL><DEDENT>self.server.close()<EOL>

Close client connections and stop main server loop.


self.stop()<EOL>


self._run = True<EOL>self.server.listen(<NUM_LIT:5>)<EOL>logger.info(<EOL>"<STR_LIT>".format(<EOL>self.ip_address or "<STR_LIT:localhost>", self.port<EOL>)<EOL>)<EOL>while self._run:<EOL><INDENT>ready, _, _ = select.select([self.server], [], [], <NUM_LIT:0.1>)<EOL>if ready:<EOL><INDENT>try:<EOL><INDENT>client, address = self.server.accept()<EOL><DEDENT>except:<EOL><INDENT>continue<EOL><DEDENT>logger.info("<STR_LIT>".format(*address))<EOL>client_thread = AdsClientConnection(<EOL>handler=self.handler, client=client, address=address, server=self<EOL>)<EOL>client_thread.daemon = True<EOL>client_thread.start()<EOL>self.clients.append(client_thread)<EOL><DEDENT><DEDENT>

Listen for incoming connections from clients.


if self._run:<EOL><INDENT>logger.info(<EOL>"<STR_LIT>".format(*self.client_address)<EOL>)<EOL>self._run = False<EOL><DEDENT>self.join()<EOL>


if self.is_alive():<EOL><INDENT>self.stop()<EOL><DEDENT>self.client.close()<EOL>


self._run = True<EOL>while self._run:<EOL><INDENT>ready, _, _ = select.select([self.client], [], [], <NUM_LIT:0.1>)<EOL>if not ready:<EOL><INDENT>continue<EOL><DEDENT>data, _ = self.client.recvfrom(<NUM_LIT>)<EOL>if not data:<EOL><INDENT>self.client.close()<EOL>self._run = False<EOL>continue<EOL><DEDENT>if len(data) < <NUM_LIT>:<EOL><INDENT>logger.warning(<EOL>"<STR_LIT>".format(<EOL>*self.client_address, data=data<EOL>)<EOL>)<EOL>continue<EOL><DEDENT>request_packet = self.construct_request(data)<EOL>self.server.request_history.append(request_packet)<EOL>response = self.handler.handle_request(request_packet)<EOL>if isinstance(response, (AmsResponseData,)):<EOL><INDENT>response_bytes = self.construct_response(response, request_packet)<EOL>self.client.send(response_bytes)<EOL>continue<EOL><DEDENT>logger.error("<STR_LIT>")<EOL><DEDENT>

Listen for data on client connection and delegate requests.


def construct_response(self, response_data, request):<EOL>

<EOL>target_net_id = request.ams_header.source_net_id<EOL>target_port = request.ams_header.source_port<EOL>source_net_id = request.ams_header.target_net_id<EOL>source_port = request.ams_header.target_port<EOL>command_id = request.ams_header.command_id<EOL>invoke_id = request.ams_header.invoke_id<EOL>state_flags = response_data.state_flags<EOL>ams_length = struct.pack("<STR_LIT>", len(response_data.data))<EOL>error_code = response_data.error_code<EOL>data = response_data.data<EOL>ams_header = "<STR_LIT>".encode("<STR_LIT:utf-8>").join(<EOL>(<EOL>target_net_id,<EOL>target_port,<EOL>source_net_id,<EOL>source_port,<EOL>command_id,<EOL>state_flags,<EOL>ams_length,<EOL>error_code,<EOL>invoke_id,<EOL>data,<EOL>)<EOL>)<EOL>ams_tcp_header = "<STR_LIT>".encode("<STR_LIT:utf-8>") + struct.pack("<STR_LIT>", len(ams_header))<EOL>return ams_tcp_header + ams_header<EOL>

Construct binary AMS response to return to the client.

        :param AmsResponseData response_data: Data to include in the response
        :param AmsPacket request: The originating request for the response


data = request_bytes  <EOL>tcp_header = AmsTcpHeader(data[<NUM_LIT:2>:<NUM_LIT:6>])<EOL>ams_header = AmsHeader(<EOL>data[<NUM_LIT:6>:<NUM_LIT:12>],<EOL>data[<NUM_LIT:12>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT:20>],<EOL>data[<NUM_LIT:20>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT:30>],<EOL>data[<NUM_LIT:30>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:],<EOL>)<EOL>return AmsPacket(tcp_header, ams_header)<EOL>

Unpack an AMS packet from binary data.

        :param bytes request_bytes: The raw request data
        :rtype AmsPacket:
        :return: AmsPacket with fields populated from the binary data


raise not NotImplementedError()<EOL>

Handle incoming requests.

        :param AmsPacket request: The request data received from the client
        :rtype: AmsResponseData
        :return: Data needed to construct the AMS response packet


<EOL>command_id_bytes = request.ams_header.command_id<EOL>command_id = struct.unpack("<STR_LIT>", command_id_bytes)[<NUM_LIT:0>]<EOL>state = struct.unpack("<STR_LIT>", request.ams_header.state_flags)[<NUM_LIT:0>]<EOL>state = state | <NUM_LIT>  <EOL>state = struct.pack("<STR_LIT>", state)<EOL>if command_id == constants.ADSCOMMAND_READDEVICEINFO:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>major_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>minor_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>version_build = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>device_name = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>response_content = (<EOL>major_version + minor_version + version_build + device_name<EOL>)<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_READ:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_length = struct.unpack("<STR_LIT>", request.ams_header.data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>response_value = (("<STR_LIT>" * (response_length - <NUM_LIT:1>)) + "<STR_LIT:\x00>").encode("<STR_LIT:utf-8>")<EOL>response_content = struct.pack("<STR_LIT>", len(response_value)) + response_value<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_WRITE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_content = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_READSTATE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>ads_state = struct.pack("<STR_LIT>", constants.ADSSTATE_RUN)<EOL>device_state = struct.pack("<STR_LIT>", <NUM_LIT:0>)<EOL>response_content = ads_state + device_state<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_WRITECTRL:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_content = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_ADDDEVICENOTE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>handle = ("<STR_LIT>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>response_content = handle<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_DELDEVICENOTE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_content = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_DEVICENOTE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_content = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL><DEDENT>elif command_id == constants.ADSCOMMAND_READWRITE:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>response_length = struct.unpack("<STR_LIT>", request.ams_header.data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>response_value = (("<STR_LIT>" * (response_length - <NUM_LIT:1>)) + "<STR_LIT:\x00>").encode("<STR_LIT:utf-8>")<EOL>response_content = struct.pack("<STR_LIT>", len(response_value)) + response_value<EOL><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>".format(hex(command_id)))<EOL>error_code = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>return AmsResponseData(state, error_code, "<STR_LIT>".encode("<STR_LIT:utf-8>"))<EOL><DEDENT>error_code = ("<STR_LIT:\x00>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>response_data = error_code + response_content<EOL>return AmsResponseData(state, request.ams_header.error_code, response_data)<EOL>

Handle incoming requests and send a response.


<EOL>command_id_bytes = request.ams_header.command_id<EOL>command_id = struct.unpack("<STR_LIT>", command_id_bytes)[<NUM_LIT:0>]<EOL>state = struct.unpack("<STR_LIT>", request.ams_header.state_flags)[<NUM_LIT:0>]<EOL>state = state | <NUM_LIT>  <EOL>state = struct.pack("<STR_LIT>", state)<EOL>def handle_read_device_info():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>major_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>minor_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>version_build = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>device_name = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>response_content = (<EOL>major_version + minor_version + version_build + device_name<EOL>)<EOL>return response_content<EOL><DEDENT>def handle_read():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>plc_datatype = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(index_group, index_offset, plc_datatype)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_VALBYHND:<EOL><INDENT>response_value = self._named_data[index_offset].value<EOL><DEDENT>else:<EOL><INDENT>response_value = self._data[(index_group, index_offset)][:plc_datatype]<EOL><DEDENT>return struct.pack("<STR_LIT>", len(response_value)) + response_value<EOL><DEDENT>def handle_write():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>plc_datatype = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>value = data[<NUM_LIT:12>:(<NUM_LIT:12> + plc_datatype)]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(index_group, index_offset, plc_datatype, value)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_RELEASEHND:<EOL><INDENT>return b"<STR_LIT>"<EOL><DEDENT>elif index_group == constants.ADSIGRP_SYM_VALBYHND:<EOL><INDENT>self._named_data[index_offset].value = value<EOL>return b"<STR_LIT>"<EOL><DEDENT>self._data[(index_group, index_offset)] = value<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_read_write():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>read_length = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>write_length = struct.unpack("<STR_LIT>", data[<NUM_LIT:12>:<NUM_LIT:16>])[<NUM_LIT:0>]<EOL>write_data = data[<NUM_LIT:16>:(<NUM_LIT:16> + write_length)]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(<EOL>index_group, index_offset, read_length, write_length, write_data<EOL>)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_HNDBYNAME:<EOL><INDENT>var_name = write_data.decode()<EOL>names = [x.name for x in self._named_data]<EOL>try:<EOL><INDENT>handle = names.index(var_name)<EOL><DEDENT>except ValueError:<EOL><INDENT>self._named_data.append(PLCVariable(name=var_name, value=bytes(<NUM_LIT:16>)))<EOL>handle = len(self._named_data) - <NUM_LIT:1><EOL><DEDENT>read_data = struct.pack("<STR_LIT>", handle)<EOL><DEDENT>else:<EOL><INDENT>read_data = self._data[(index_group, index_offset)][:read_length]<EOL>self._data[(index_group, index_offset)] = write_data<EOL><DEDENT>return struct.pack("<STR_LIT>", len(read_data)) + read_data<EOL><DEDENT>def handle_read_state():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>ads_state = struct.pack("<STR_LIT>", constants.ADSSTATE_RUN)<EOL>device_state = struct.pack("<STR_LIT>", <NUM_LIT:0>)<EOL>return ads_state + device_state<EOL><DEDENT>def handle_writectrl():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_add_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>handle = ("<STR_LIT>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>return handle<EOL><DEDENT>def handle_delete_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>function_map = {<EOL>constants.ADSCOMMAND_READDEVICEINFO: handle_read_device_info,<EOL>constants.ADSCOMMAND_READ: handle_read,<EOL>constants.ADSCOMMAND_WRITE: handle_write,<EOL>constants.ADSCOMMAND_READWRITE: handle_read_write,<EOL>constants.ADSCOMMAND_READSTATE: handle_read_state,<EOL>constants.ADSCOMMAND_WRITECTRL: handle_writectrl,<EOL>constants.ADSCOMMAND_ADDDEVICENOTE: handle_add_devicenote,<EOL>constants.ADSCOMMAND_DELDEVICENOTE: handle_delete_devicenote,<EOL>constants.ADSCOMMAND_DEVICENOTE: handle_devicenote,<EOL>}<EOL>try:<EOL><INDENT>response_content = function_map[command_id]()<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.info("<STR_LIT>".format(hex(command_id)))<EOL>error_code = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>return AmsResponseData(state, error_code, "<STR_LIT>".encode("<STR_LIT:utf-8>"))<EOL><DEDENT>error_code = ("<STR_LIT:\x00>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>response_data = error_code + response_content<EOL>return AmsResponseData(state, request.ams_header.error_code, response_data)<EOL>

Handle incoming requests and create a response.


return c_float * n<EOL>


return c_double * n<EOL>


return c_int16 * n<EOL>


return c_int32 * n<EOL>


return c_short * n<EOL>


try:<EOL><INDENT>id_numbers = list(map(int, ams_netid.split("<STR_LIT:.>")))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(id_numbers) != <NUM_LIT:6>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ams_netid_st = SAmsNetId()<EOL>ams_netid_st.b = (c_ubyte * <NUM_LIT:6>)(*id_numbers)<EOL>return ams_netid_st<EOL>

Parse an AmsNetId from *str* to *SAmsNetId*.

    :param str ams_netid: NetId as a string
    :rtype: SAmsNetId
    :return: NetId as a struct


global port<EOL>port = port or adsPortOpenEx()<EOL>return port<EOL>

Connect to the TwinCAT message router.

    :rtype: int
    :return: port number


global port<EOL>if port is not None:<EOL><INDENT>adsPortCloseEx(port)<EOL>port = None<EOL><DEDENT>

Close the connection to the TwinCAT message router.


if port is not None:<EOL><INDENT>return adsGetLocalAddressEx(port)<EOL><DEDENT>return None<EOL>

Return the local AMS-address and the port number.

    :rtype: AmsAddr


if isinstance(ams_netid, str):<EOL><INDENT>ams_netid_st = _parse_ams_netid(ams_netid)<EOL><DEDENT>else:<EOL><INDENT>ams_netid_st = ams_netid<EOL><DEDENT>assert isinstance(ams_netid_st, SAmsNetId)<EOL>if linux:<EOL><INDENT>return adsSetLocalAddress(ams_netid_st)<EOL><DEDENT>else:<EOL><INDENT>raise ADSError(<EOL>text="<STR_LIT>"<EOL>)<EOL><DEDENT>

Set the local NetID (**Linux only**).

    :param str: new AmsNetID
    :rtype: None

    **Usage:**

        >>> import pyads
        >>> pyads.open_port()
        >>> pyads.set_local_address('0.0.0.0.1.1')


if port is not None:<EOL><INDENT>return adsSyncReadStateReqEx(port, adr)<EOL><DEDENT>return None<EOL>

Read the current ADS-state and the machine-state.

    Read the current ADS-state and the machine-state from the
    ADS-server.

    :param AmsAddr adr: local or remote AmsAddr
    :rtype: (int, int)
    :return: adsState, deviceState


def write_control(adr, ads_state, device_state, data, plc_datatype):<EOL>

if port is not None:<EOL><INDENT>return adsSyncWriteControlReqEx(<EOL>port, adr, ads_state, device_state, data, plc_datatype<EOL>)<EOL><DEDENT>

Change the ADS state and the machine-state of the ADS-server.

    :param AmsAddr adr: local or remote AmsAddr
    :param int ads_state: new ADS-state, according to ADSTATE constants
    :param int device_state: new machine-state
    :param data: additional data
    :param int plc_datatype: datatype, according to PLCTYPE constants

    :note: Despite changing the ADS-state and the machine-state it is possible
           to send additional data to the ADS-server. For current ADS-devices
           additional data is not progressed.
           Every ADS-device is able to communicate its current state to other
           devices.
           There is a difference between the device-state and the state of the
           ADS-interface (AdsState). The possible states of an ADS-interface
           are defined in the ADS-specification.


if port is not None:<EOL><INDENT>return adsSyncReadDeviceInfoReqEx(port, adr)<EOL><DEDENT>return None<EOL>

Read the name and the version number of the ADS-server.

    :param AmsAddr adr: local or remote AmsAddr
    :rtype: string, AdsVersion
    :return: device name, version


def write(adr, index_group, index_offset, value, plc_datatype):<EOL>

if port is not None:<EOL><INDENT>return adsSyncWriteReqEx(<EOL>port, adr, index_group, index_offset, value, plc_datatype<EOL>)<EOL><DEDENT>

Send data synchronous to an ADS-device.

    :param AmsAddr adr: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param Type plc_datatype: type of the data given to the PLC,
        according to PLCTYPE constants


if port is not None:<EOL><INDENT>return adsSyncReadWriteReqEx2(<EOL>port,<EOL>adr,<EOL>index_group,<EOL>index_offset,<EOL>plc_read_datatype,<EOL>value,<EOL>plc_write_datatype,<EOL>return_ctypes,<EOL>)<EOL><DEDENT>return None<EOL>

Read and write data synchronous from/to an ADS-device.

    :param AmsAddr adr: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type plc_read_datatype: type of the data given to the PLC to respond
            to, according to PLCTYPE constants
        :param value: value to write to the storage address of the PLC
    :param Type plc_write_datatype: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: PLCTYPE
    :return: value: **value**


def read(adr, index_group, index_offset, plc_datatype, return_ctypes=False):<EOL>

if port is not None:<EOL><INDENT>return adsSyncReadReqEx2(<EOL>port, adr, index_group, index_offset, plc_datatype, return_ctypes<EOL>)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device.

        :param AmsAddr adr: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param int plc_datatype: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :return: value: **value**


def read_by_name(adr, data_name, plc_datatype, return_ctypes=False):<EOL>

if port is not None:<EOL><INDENT>return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device from data name.

    :param AmsAddr adr: local or remote AmsAddr
    :param string data_name: data name
    :param int plc_datatype: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :return: value: **value**


def write_by_name(adr, data_name, value, plc_datatype):<EOL>

if port is not None:<EOL><INDENT>return adsSyncWriteByNameEx(port, adr, data_name, value, plc_datatype)<EOL><DEDENT>

Send data synchronous to an ADS-device from data name.

    :param AmsAddr adr: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param int plc_datatype: type of the data given to the PLC,
        according to PLCTYPE constants


return adsAddRoute(adr.netIdStruct(), ip_address)<EOL>

Establish a new route in the AMS Router (linux Only).

    :param pyads.structs.AmsAddr adr: AMS Address of routing endpoint
    :param str ip_address: ip address of the routing endpoint


return adsDelRoute(adr.netIdStruct())<EOL>

Remove existing route from the AMS Router (Linux Only).

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.


def add_device_notification(adr, data_name, attr, callback, user_handle=None):<EOL>

if port is not None:<EOL><INDENT>return adsSyncAddDeviceNotificationReqEx(<EOL>port, adr, data_name, attr, callback, user_handle<EOL>)<EOL><DEDENT>return None<EOL>

Add a device notification.

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.
    :param str data_name: PLC storage address
    :param pyads.structs.NotificationAttrib attr: object that contains
        all the attributes for the definition of a notification
    :param callback: callback function that gets executed on in the event
        of a notification

    :rtype: (int, int)
    :returns: notification handle, user handle

    Save the notification handle and the user handle on creating a
    notification if you want to be able to remove the notification
    later in your code.


def del_device_notification(adr, notification_handle, user_handle):<EOL>

if port is not None:<EOL><INDENT>return adsSyncDelDeviceNotificationReqEx(<EOL>port, adr, notification_handle, user_handle<EOL>)<EOL><DEDENT>

Remove a device notification.

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.
    :param notification_handle: address of the variable that contains
        the handle of the notification
    :param user_handle: user handle


if port is not None:<EOL><INDENT>return adsSyncSetTimeoutEx(port, ms)<EOL><DEDENT>


self.open()<EOL>return self<EOL>


def __exit__(self, _type, _val, _traceback):<EOL>

self.close()<EOL>


if self._open:<EOL><INDENT>return<EOL><DEDENT>self._port = adsPortOpenEx()<EOL>if linux:<EOL><INDENT>adsAddRoute(self._adr.netIdStruct(), self.ip_address)<EOL><DEDENT>self._open = True<EOL>


if not self._open:<EOL><INDENT>return<EOL><DEDENT>if linux:<EOL><INDENT>adsDelRoute(self._adr.netIdStruct())<EOL><DEDENT>if self._port is not None:<EOL><INDENT>adsPortCloseEx(self._port)<EOL>self._port = None<EOL><DEDENT>self._open = False<EOL>

:summary: Close the connection to the TwinCAT message router.


if self._port is not None:<EOL><INDENT>return adsGetLocalAddressEx(self._port)<EOL><DEDENT>return None<EOL>

Return the local AMS-address and the port number.

        :rtype: AmsAddr


if self._port is not None:<EOL><INDENT>return adsSyncReadStateReqEx(self._port, self._adr)<EOL><DEDENT>return None<EOL>

Read the current ADS-state and the machine-state.

        Read the current ADS-state and the machine-state from the ADS-server.

        :rtype: (int, int)
        :return: adsState, deviceState


def write_control(self, ads_state, device_state, data, plc_datatype):<EOL>

if self._port is not None:<EOL><INDENT>return adsSyncWriteControlReqEx(<EOL>self._port, self._adr, ads_state, device_state, data, plc_datatype<EOL>)<EOL><DEDENT>

Change the ADS state and the machine-state of the ADS-server.

        :param int ads_state: new ADS-state, according to ADSTATE constants
        :param int device_state: new machine-state
        :param data: additional data
        :param int plc_datatype: datatype, according to PLCTYPE constants

        :note: Despite changing the ADS-state and the machine-state it is
            possible to send additional data to the ADS-server. For current
            ADS-devices additional data is not progressed.
            Every ADS-device is able to communicate its current state to other
            devices. There is a difference between the device-state and the
            state of the ADS-interface (AdsState). The possible states of an
            ADS-interface are defined in the ADS-specification.


if self._port is not None:<EOL><INDENT>return adsSyncReadDeviceInfoReqEx(self._port, self._adr)<EOL><DEDENT>return None<EOL>

Read the name and the version number of the ADS-server.

        :rtype: string, AdsVersion
        :return: device name, version


def write(self, index_group, index_offset, value, plc_datatype):<EOL>

if self._port is not None:<EOL><INDENT>return adsSyncWriteReqEx(<EOL>self._port, self._adr, index_group, index_offset, value, plc_datatype<EOL>)<EOL><DEDENT>

Send data synchronous to an ADS-device.

        :param int index_group: PLC storage area, according to the INDEXGROUP
            constants
        :param int index_offset: PLC storage address
        :param value: value to write to the storage address of the PLC
        :param int plc_datatype: type of the data given to the PLC,
            according to PLCTYPE constants


if self._port is not None:<EOL><INDENT>return adsSyncReadWriteReqEx2(<EOL>self._port,<EOL>self._adr,<EOL>index_group,<EOL>index_offset,<EOL>plc_read_datatype,<EOL>value,<EOL>plc_write_datatype,<EOL>return_ctypes,<EOL>)<EOL><DEDENT>return None<EOL>

Read and write data synchronous from/to an ADS-device.

        :param int index_group: PLC storage area, according to the INDEXGROUP
            constants
        :param int index_offset: PLC storage address
        :param int plc_read_datatype: type of the data given to the PLC to
            respond to, according to PLCTYPE constants
        :param value: value to write to the storage address of the PLC
        :param plc_write_datatype: type of the data given to the PLC,
            according to PLCTYPE constants
            :rtype: PLCTYPE
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
        :return: value: **value**


def read(self, index_group, index_offset, plc_datatype, return_ctypes=False):<EOL>

if self._port is not None:<EOL><INDENT>return adsSyncReadReqEx2(<EOL>self._port, self._adr, index_group, index_offset, plc_datatype, return_ctypes<EOL>)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device.

        :param int index_group: PLC storage area, according to the INDEXGROUP
            constants
        :param int index_offset: PLC storage address
        :param int plc_datatype: type of the data given to the PLC, according
            to PLCTYPE constants
            :return: value: **value**
        :param bool return_ctypes: return ctypes instead of python types if True
            (default: False)


def read_by_name(self, data_name, plc_datatype, return_ctypes=False):<EOL>

if self._port:<EOL><INDENT>return adsSyncReadByNameEx(self._port, self._adr, data_name, plc_datatype, return_ctypes)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device from data name.

        :param string data_name: data name
        :param int plc_datatype: type of the data given to the PLC, according
            to PLCTYPE constants
            :return: value: **value**
        :param bool return_ctypes: return ctypes instead of python types if True
            (default: False)


def write_by_name(self, data_name, value, plc_datatype):<EOL>

if self._port:<EOL><INDENT>return adsSyncWriteByNameEx(<EOL>self._port, self._adr, data_name, value, plc_datatype<EOL>)<EOL><DEDENT>

Send data synchronous to an ADS-device from data name.

        :param string data_name: PLC storage address
        :param value: value to write to the storage address of the PLC
        :param int plc_datatype: type of the data given to the PLC,
            according to PLCTYPE constants


def add_device_notification(self, data_name, attr, callback, user_handle=None):<EOL>

if self._port is not None:<EOL><INDENT>notification_handle, user_handle = adsSyncAddDeviceNotificationReqEx(<EOL>self._port, self._adr, data_name, attr, callback, user_handle<EOL>)<EOL>return notification_handle, user_handle<EOL><DEDENT>return None<EOL>

Add a device notification.

        :param str data_name: PLC storage address
        :param pyads.structs.NotificationAttrib attr: object that contains
            all the attributes for the definition of a notification
        :param callback: callback function that gets executed on in the event
            of a notification

        :rtype: (int, int)
        :returns: notification handle, user handle

        Save the notification handle and the user handle on creating a
        notification if you want to be able to remove the notification
        later in your code.

        **Usage**:

            >>> import pyads
            >>> from ctypes import size_of
            >>>
            >>> # Connect to the local TwinCAT PLC
            >>> plc = pyads.Connection('127.0.0.1.1.1', 851)
            >>>
            >>> # Create callback function that prints the value
            >>> def mycallback(adr, notification, user):
            >>>     contents = notification.contents
            >>>     value = next(
            >>>         map(int,
            >>>             bytearray(contents.data)[0:contents.cbSampleSize])
            >>>     )
            >>>     print(value)
            >>>
            >>> with plc:
            >>>     # Add notification with default settings
            >>>     attr = pyads.NotificationAttrib(size_of(pyads.PLCTYPE_INT))
            >>>
            >>>     hnotification, huser = plc.add_device_notification(
            >>>         adr, attr, mycallback)
            >>>
            >>>     # Remove notification
            >>>     plc.del_device_notification(hnotification, huser)


def del_device_notification(self, notification_handle, user_handle):<EOL>

if self._port is not None:<EOL><INDENT>adsSyncDelDeviceNotificationReqEx(<EOL>self._port, self._adr, notification_handle, user_handle<EOL>)<EOL><DEDENT>

Remove a device notification.

        :param notification_handle: address of the variable that contains
            the handle of the notification
        :param user_handle: user handle


return self._open<EOL>

Show the current connection state.

        :return: True if connection is open


if self._port is not None:<EOL><INDENT>adsSyncSetTimeoutEx(self._port, ms)<EOL><DEDENT>


def notification_decorator(func):<EOL><INDENT>def func_wrapper(notification, data_name):<EOL><INDENT>contents = notification.contents<EOL>data = contents.data<EOL>data_size = contents.cbSampleSize<EOL>datatype_map = {<EOL>PLCTYPE_BOOL: "<STR_LIT>",<EOL>PLCTYPE_BYTE: "<STR_LIT>",<EOL>PLCTYPE_DINT: "<STR_LIT>",<EOL>PLCTYPE_DWORD: "<STR_LIT>",<EOL>PLCTYPE_INT: "<STR_LIT>",<EOL>PLCTYPE_LREAL: "<STR_LIT>",<EOL>PLCTYPE_REAL: "<STR_LIT>",<EOL>PLCTYPE_SINT: "<STR_LIT>",<EOL>PLCTYPE_UDINT: "<STR_LIT>",<EOL>PLCTYPE_UINT: "<STR_LIT>",<EOL>PLCTYPE_USINT: "<STR_LIT>",<EOL>PLCTYPE_WORD: "<STR_LIT>",<EOL>}  <EOL>if plc_datatype == PLCTYPE_STRING:<EOL><INDENT>dest = (c_ubyte * data_size)()<EOL>memmove(addressof(dest), addressof(data), data_size)<EOL>value = bytearray(dest).split(b"<STR_LIT>", <NUM_LIT:1>)[<NUM_LIT:0>].decode("<STR_LIT:utf-8>")<EOL><DEDENT>elif issubclass(plc_datatype, Structure):<EOL><INDENT>value = plc_datatype()<EOL>fit_size = min(data_size, sizeof(value))<EOL>memmove(addressof(value), addressof(data), fit_size)<EOL><DEDENT>elif plc_datatype not in datatype_map:<EOL><INDENT>value = data<EOL><DEDENT>else:<EOL><INDENT>value = struct.unpack(<EOL>datatype_map[plc_datatype], bytearray(data)[:data_size]<EOL>)[<NUM_LIT:0>]<EOL><DEDENT>dt = filetime_to_dt(contents.nTimeStamp)<EOL>return func(contents.hNotification, data_name, dt, value)<EOL><DEDENT>return func_wrapper<EOL><DEDENT>return notification_decorator<EOL>

Decorate a callback function.

        **Decorator**.

        A decorator that can be used for callback functions in order to
        convert the data of the NotificationHeader into the fitting
        Python type.

        :param plc_datatype: The PLC datatype that needs to be converted. This can
        be any basic PLC datatype or a `ctypes.Structure`.

        The callback functions need to be of the following type:

        >>> def callback(handle, name, timestamp, value)

        * `handle`: the notification handle
        * `name`: the variable name
        * `timestamp`: the timestamp as datetime value
        * `value`: the converted value of the variable

        **Usage**:

            >>> import pyads
            >>>
            >>> plc = pyads.Connection('172.18.3.25.1.1', 851)
            >>>
            >>>
            >>> @plc.notification(pyads.PLCTYPE_STRING)
            >>> def callback(handle, name, timestamp, value):
            >>>     print(handle, name, timestamp, value)
            >>>
            >>>
            >>> with plc:
            >>>    attr = pyads.NotificationAttrib(20,
            >>>                                    pyads.ADSTRANS_SERVERCYCLE)
            >>>    handles = plc.add_device_notification('GVL.test', attr,
            >>>                                          callback)
            >>>    while True:
            >>>        pass


self.version = stAdsVersion.version<EOL>self.revision = stAdsVersion.revision<EOL>self.build = stAdsVersion.build<EOL>

Create new AdsVersion object.

        :param pyads.constants.SAdsVersion stAdsVersion: ctypes structure
            with the version info


def __init__(self, netid=None, port=None):<EOL>

self._ams_addr = SAmsAddr()<EOL>if netid is not None:<EOL><INDENT>self.netid = netid<EOL><DEDENT>if port is not None:<EOL><INDENT>self.port = port<EOL><DEDENT>

Create a new AmsAddr object by a given netid and port.

        :param netid: NetId of an ADS device
        :param port: port of an ADS device


return self.netid + "<STR_LIT>" + str(self._ams_addr.port)<EOL>

Textual representation of the AMS address.

        :rtype: string
        :return:  textual representation of the AMS adress


return '<STR_LIT:.>'.join(map(str, self._ams_addr.netId.b))<EOL>

Netid of the AmsAddress.

        The Netid is always returned as a String. If the NetId is set
        it can be passed as a String or as a SAmsNetId struct.


return self._ams_addr.port<EOL>


return self._ams_addr<EOL>


return self._ams_addr.netId<EOL>


self.netid = adrString<EOL>

Set the AMS-adress according to the given IP-address.

        :type adrString: string
        :param adrString: ip-address of an ADS device


return '<STR_LIT>'.format(self.netid, self.port)<EOL>


def __init__(self, length, trans_mode=ADSTRANS_SERVERONCHA,<EOL>max_delay=<NUM_LIT>, cycle_time=<NUM_LIT>):<EOL>

self._attrib = SAdsNotificationAttrib()<EOL>if length:<EOL><INDENT>self._attrib.cbLength = length<EOL><DEDENT>if trans_mode:<EOL><INDENT>self._attrib.nTransMode = trans_mode<EOL><DEDENT>if max_delay:<EOL><INDENT>self._attrib.nMaxDelay = int(max_delay * <NUM_LIT>)<EOL><DEDENT>if cycle_time:<EOL><INDENT>self._attrib.nCycleTime = int(cycle_time * <NUM_LIT>)<EOL><DEDENT>

Create a new NotificationAttrib object.

        :param int length: length of the data
        :param int trans_mode: transmission mode
        :param float max_delay: maximum delay in ms
        :param float cycle_time: cycle time in ms


return self._attrib<EOL>


return self._attrib.cbLength<EOL>


return self._attrib.nTransMode<EOL>

Mode of transmission.

        This can be one of the following:

        * ADSTRANS_NOTRANS
        * ADSTRANS_CLIENTCYCLE
        * ADSTRANS_CLIENT1REQ
        * ADSTRANS_SERVERCYCLE
        * ADSTRANS_SERVERONCHA


return self._attrib.nMaxDelay<EOL>

Maximum allowed delay between notifications in ms.


return self._attrib.nCycleTime<EOL>

Notification cycle time in ms for cycle transmission mode.


return ('<STR_LIT>'<EOL>.format(self.length, self.trans_mode, self.max_delay,<EOL>self.cycle_time))<EOL>


@wraps(fn)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>if platform_is_windows():  <EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>

Raise a runtime error if on Win32 systems.

    Decorator.

    Decorator for functions that interact with the router for the Linux
    implementation of the ADS library.

    Unlike the Windows implementation which uses a separate router daemon,
    the Linux library manages AMS routing in-process. As such, routing must be
    configured programatically via. the provided API. These endpoints are
    invalid on Win32 systems, so an exception will be raised.


add_route = _adsDLL.AdsAddRoute<EOL>add_route.restype = ctypes.c_long<EOL>ip_address_p = ctypes.c_char_p(ip_address.encode("<STR_LIT:utf-8>"))<EOL>error_code = add_route(net_id, ip_address_p)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Establish a new route in the AMS Router.

    :param pyads.structs.SAmsNetId net_id: net id of routing endpoint
    :param str ip_address: ip address of the routing endpoint


delete_route = _adsDLL.AdsDelRoute<EOL>delete_route(net_id)<EOL>

Remove existing route from the AMS Router.

    :param pyads.structs.SAmsNetId net_id: net id associated with the routing
        entry which is to be removed from the router.


port_open_ex = _adsDLL.AdsPortOpenEx<EOL>port_open_ex.restype = ctypes.c_long<EOL>port = port_open_ex()<EOL>if port == <NUM_LIT:0>:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>return port<EOL>

Connect to the TwinCAT message router.

    :rtype: int
    :return: port number


port_close_ex = _adsDLL.AdsPortCloseEx<EOL>port_close_ex.restype = ctypes.c_long<EOL>error_code = port_close_ex(port)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Close the connection to the TwinCAT message router.


get_local_address_ex = _adsDLL.AdsGetLocalAddressEx<EOL>ams_address_struct = SAmsAddr()<EOL>error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>local_ams_address = AmsAddr()<EOL>local_ams_address._ams_addr = ams_address_struct<EOL>return local_ams_address<EOL>

Return the local AMS-address and the port number.

    :rtype: pyads.structs.AmsAddr
    :return: AMS-address


set_local_address = _adsDLL.AdsSetLocalAddress<EOL>set_local_address(ams_netid)<EOL>

Change the local NetId.

    :param pyads.structs.SAmsNetId ams_netid: new AmsNetID
    :rtype: None


sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>ads_state = ctypes.c_int()<EOL>ads_state_pointer = ctypes.pointer(ads_state)<EOL>device_state = ctypes.c_int()<EOL>device_state_pointer = ctypes.pointer(device_state)<EOL>error_code = sync_read_state_request(<EOL>port, ams_address_pointer, ads_state_pointer, device_state_pointer<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>return (ads_state.value, device_state.value)<EOL>

Read the current ADS-state and the machine-state.

    Read the current ADS-state and the machine-state from the
    ADS-server.

    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :rtype: (int, int)
    :return: ads_state, device_state


sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>device_name_buffer = ctypes.create_string_buffer(<NUM_LIT:20>)<EOL>device_name_pointer = ctypes.pointer(device_name_buffer)<EOL>ads_version = SAdsVersion()<EOL>ads_version_pointer = ctypes.pointer(ads_version)<EOL>error_code = sync_read_device_info_request(<EOL>port, ams_address_pointer, device_name_pointer, ads_version_pointer<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>return (device_name_buffer.value.decode(), AdsVersion(ads_version))<EOL>

Read the name and the version number of the ADS-server.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :rtype: string, AdsVersion
    :return: device name, version


def adsSyncWriteControlReqEx(<EOL>port, address, ads_state, device_state, data, plc_data_type<EOL>):<EOL>

sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>ads_state_c = ctypes.c_ulong(ads_state)<EOL>device_state_c = ctypes.c_ulong(device_state)<EOL>if plc_data_type == PLCTYPE_STRING:<EOL><INDENT>data = ctypes.c_char_p(data.encode("<STR_LIT:utf-8>"))<EOL>data_pointer = data<EOL>data_length = len(data_pointer.value) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>data = plc_data_type(data)<EOL>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.sizeof(data)<EOL><DEDENT>error_code = sync_write_control_request(<EOL>port,<EOL>ams_address_pointer,<EOL>ads_state_c,<EOL>device_state_c,<EOL>data_length,<EOL>data_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Change the ADS state and the machine-state of the ADS-server.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param int ads_state: new ADS-state, according to ADSTATE constants
    :param int device_state: new machine-state
    :param data: additional data
    :param int plc_data_type: plc datatype, according to PLCTYPE constants


def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):<EOL>

sync_write_request = _adsDLL.AdsSyncWriteReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>index_group_c = ctypes.c_ulong(index_group)<EOL>index_offset_c = ctypes.c_ulong(index_offset)<EOL>if plc_data_type == PLCTYPE_STRING:<EOL><INDENT>data = ctypes.c_char_p(value.encode("<STR_LIT:utf-8>"))<EOL>data_pointer = data  <EOL>data_length = len(data_pointer.value) + <NUM_LIT:1>  <EOL><DEDENT>else:<EOL><INDENT>if type(plc_data_type).__name__ == "<STR_LIT>":<EOL><INDENT>data = plc_data_type(*value)<EOL><DEDENT>else:<EOL><INDENT>data = plc_data_type(value)<EOL><DEDENT>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.sizeof(data)<EOL><DEDENT>error_code = sync_write_request(<EOL>port,<EOL>ams_address_pointer,<EOL>index_group_c,<EOL>index_offset_c,<EOL>data_length,<EOL>data_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Send data synchronous to an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int indexGroup: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param int plc_data_type: type of the data given to the PLC,
        according to PLCTYPE constants


sync_read_write_request = _adsDLL.AdsSyncReadWriteReqEx2<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>index_group_c = ctypes.c_ulong(index_group)<EOL>index_offset_c = ctypes.c_ulong(index_offset)<EOL>if read_data_type == PLCTYPE_STRING:<EOL><INDENT>read_data = (STRING_BUFFER * PLCTYPE_STRING)()<EOL><DEDENT>else:<EOL><INDENT>read_data = read_data_type()<EOL><DEDENT>read_data_pointer = ctypes.pointer(read_data)<EOL>read_length = ctypes.c_ulong(ctypes.sizeof(read_data))<EOL>bytes_read = ctypes.c_ulong()<EOL>bytes_read_pointer = ctypes.pointer(bytes_read)<EOL>if write_data_type == PLCTYPE_STRING:<EOL><INDENT>write_data_pointer = ctypes.c_char_p(<EOL>value.encode("<STR_LIT:utf-8>")<EOL>)  <EOL>write_length = len(value) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if type(write_data_type).__name__ == "<STR_LIT>":<EOL><INDENT>write_data = write_data_type(*value)<EOL><DEDENT>else:<EOL><INDENT>write_data = write_data_type(value)<EOL><DEDENT>write_data_pointer = ctypes.pointer(write_data)<EOL>write_length = ctypes.sizeof(write_data)<EOL><DEDENT>err_code = sync_read_write_request(<EOL>port,<EOL>ams_address_pointer,<EOL>index_group_c,<EOL>index_offset_c,<EOL>read_length,<EOL>read_data_pointer,<EOL>write_length,<EOL>write_data_pointer,<EOL>bytes_read_pointer,<EOL>)<EOL>if err_code:<EOL><INDENT>raise ADSError(err_code)<EOL><DEDENT>if read_data_type != PLCTYPE_STRING and bytes_read.value != read_length.value:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(<EOL>read_length.value, bytes_read.value<EOL>)<EOL>)<EOL><DEDENT>if return_ctypes:<EOL><INDENT>return read_data<EOL><DEDENT>if read_data_type == PLCTYPE_STRING:<EOL><INDENT>return read_data.value.decode("<STR_LIT:utf-8>")<EOL><DEDENT>if type(read_data_type).__name__ == "<STR_LIT>":<EOL><INDENT>return [i for i in read_data]<EOL><DEDENT>if hasattr(read_data, "<STR_LIT:value>"):<EOL><INDENT>return read_data.value<EOL><DEDENT>return read_data<EOL>

Read and write data synchronous from/to an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type read_data_type: type of the data given to the PLC to respond to,
        according to PLCTYPE constants
    :param value: value to write to the storage address of the PLC
    :param Type write_data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: read_data_type
    :return: value: value read from PLC


def adsSyncReadReqEx2(<EOL>port, address, index_group, index_offset, data_type, return_ctypes=False<EOL>):<EOL>

sync_read_request = _adsDLL.AdsSyncReadReqEx2<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>index_group_c = ctypes.c_ulong(index_group)<EOL>index_offset_c = ctypes.c_ulong(index_offset)<EOL>if data_type == PLCTYPE_STRING:<EOL><INDENT>data = (STRING_BUFFER * PLCTYPE_STRING)()<EOL><DEDENT>else:<EOL><INDENT>data = data_type()<EOL><DEDENT>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.c_ulong(ctypes.sizeof(data))<EOL>bytes_read = ctypes.c_ulong()<EOL>bytes_read_pointer = ctypes.pointer(bytes_read)<EOL>error_code = sync_read_request(<EOL>port,<EOL>ams_address_pointer,<EOL>index_group_c,<EOL>index_offset_c,<EOL>data_length,<EOL>data_pointer,<EOL>bytes_read_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(<EOL>data_length.value, bytes_read.value<EOL>)<EOL>)<EOL><DEDENT>if return_ctypes:<EOL><INDENT>return data<EOL><DEDENT>if data_type == PLCTYPE_STRING:<EOL><INDENT>return data.value.decode("<STR_LIT:utf-8>")<EOL><DEDENT>if type(data_type).__name__ == "<STR_LIT>":<EOL><INDENT>return [i for i in data]<EOL><DEDENT>if hasattr(data, "<STR_LIT:value>"):<EOL><INDENT>return data.value<EOL><DEDENT>return data<EOL>

Read data synchronous from an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: data_type
    :return: value: **value**


def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):<EOL>

<EOL>handle = adsSyncReadWriteReqEx2(<EOL>port,<EOL>address,<EOL>ADSIGRP_SYM_HNDBYNAME,<EOL><NUM_LIT>,<EOL>PLCTYPE_UDINT,<EOL>data_name,<EOL>PLCTYPE_STRING,<EOL>)<EOL>value = adsSyncReadReqEx2(<EOL>port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes<EOL>)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, <NUM_LIT:0>, handle, PLCTYPE_UDINT)<EOL>return value<EOL>

Read data synchronous from an ADS-device from data name.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param string data_name: data name
    :param Type data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: data_type
    :return: value: **value**


def adsSyncWriteByNameEx(port, address, data_name, value, data_type):<EOL>

<EOL>handle = adsSyncReadWriteReqEx2(<EOL>port,<EOL>address,<EOL>ADSIGRP_SYM_HNDBYNAME,<EOL><NUM_LIT>,<EOL>PLCTYPE_UDINT,<EOL>data_name,<EOL>PLCTYPE_STRING,<EOL>)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, <NUM_LIT:0>, handle, PLCTYPE_UDINT)<EOL>

Send data synchronous to an ADS-device from data name.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param Type data_type: type of the data given to the PLC,
        according to PLCTYPE constants


def adsSyncAddDeviceNotificationReqEx(<EOL>port, adr, data_name, pNoteAttrib, callback, user_handle=None<EOL>):<EOL>

global callback_store<EOL>if NOTEFUNC is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx<EOL>pAmsAddr = ctypes.pointer(adr.amsAddrStruct())<EOL>hnl = adsSyncReadWriteReqEx2(<EOL>port, adr, ADSIGRP_SYM_HNDBYNAME, <NUM_LIT>, PLCTYPE_UDINT, data_name, PLCTYPE_STRING<EOL>)<EOL>nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)<EOL>nIndexOffset = ctypes.c_ulong(hnl)<EOL>attrib = pNoteAttrib.notificationAttribStruct()<EOL>pNotification = ctypes.c_ulong()<EOL>nHUser = ctypes.c_ulong(hnl)<EOL>if user_handle is not None:<EOL><INDENT>nHUser = ctypes.c_ulong(user_handle)<EOL><DEDENT>adsSyncAddDeviceNotificationReqFct.argtypes = [<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(SAmsAddr),<EOL>ctypes.c_ulong,<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(SAdsNotificationAttrib),<EOL>NOTEFUNC,<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(ctypes.c_ulong),<EOL>]<EOL>adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long<EOL>def wrapper(addr, notification, user):<EOL><INDENT>return callback(notification, data_name)<EOL><DEDENT>c_callback = NOTEFUNC(wrapper)<EOL>err_code = adsSyncAddDeviceNotificationReqFct(<EOL>port,<EOL>pAmsAddr,<EOL>nIndexGroup,<EOL>nIndexOffset,<EOL>ctypes.byref(attrib),<EOL>c_callback,<EOL>nHUser,<EOL>ctypes.byref(pNotification),<EOL>)<EOL>if err_code:<EOL><INDENT>raise ADSError(err_code)<EOL><DEDENT>callback_store[pNotification.value] = c_callback<EOL>return (pNotification.value, hnl)<EOL>

Add a device notification.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
    :param callback: Callback function to handle notification
    :param user_handle: User Handle
    :rtype: (int, int)
    :returns: notification handle, user handle


def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):<EOL>

adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx<EOL>pAmsAddr = ctypes.pointer(adr.amsAddrStruct())<EOL>nHNotification = ctypes.c_ulong(notification_handle)<EOL>err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)<EOL>callback_store.pop(notification_handle, None)<EOL>if err_code:<EOL><INDENT>raise ADSError(err_code)<EOL><DEDENT>adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, <NUM_LIT:0>, user_handle, PLCTYPE_UDINT)<EOL>

Remove a device notification.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param int notification_handle: Notification Handle
    :param int user_handle: User Handle


adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx<EOL>cms = ctypes.c_long(nMs)<EOL>err_code = adsSyncSetTimeoutFct(port, cms)<EOL>if err_code:<EOL><INDENT>raise ADSError(err_code)<EOL><DEDENT>

Set Timeout.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param int nMs: timeout in ms


return "<STR_LIT>" + self.msg<EOL>

Return text representation of the object.


if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None):<EOL><INDENT>dt = dt.replace(tzinfo=utc)<EOL><DEDENT>return EPOCH_AS_FILETIME + (timegm(dt.timetuple()) *<EOL>HUNDREDS_OF_NANOSECONDS)<EOL>

Convert a datetime to Microsoft filetime format.

    If the object is time zone-naive, it is forced to UTC before conversion.

    >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0))
    '128930364000000000'
    >>> dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
    116444736000000000L
    >>> dt_to_filetime(datetime(1970, 1, 1, 0, 0))
    116444736000000000L


return datetime.utcfromtimestamp((ft - EPOCH_AS_FILETIME) /<EOL>HUNDREDS_OF_NANOSECONDS)<EOL>

Convert a Microsoft filetime number to a Python datetime.

    The new datetime object is time zone-naive but is equivalent to tzinfo=utc.

    >>> filetime_to_dt(116444736000000000)
    datetime.datetime(1970, 1, 1, 0, 0)
    >>> filetime_to_dt(128930364000000000)
    datetime.datetime(2009, 7, 25, 23, 0)


return ZERO<EOL>

Return offset of localtime from UTC time.


return "<STR_LIT>"<EOL>


return ZERO<EOL>


return sys.platform.startswith('<STR_LIT>') orsys.platform.startswith('<STR_LIT>')<EOL>

Return True if current platform is Linux or Mac OS.


return sys.platform == '<STR_LIT:win32>'<EOL>

Return True if current platform is Windows.


patterns = (<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):<EOL><INDENT>os.remove(f)<EOL><DEDENT>

Remove all binary files in the adslib directory.


child_models = []<EOL>for related_object in get_all_related_objects(self.base_model._meta):<EOL><INDENT>model = getattr(<EOL>related_object, '<STR_LIT>', related_object.model)<EOL>if issubclass(model, self.base_model):<EOL><INDENT>class SettingValueAdmin(self.base_admin_class):<EOL><INDENT>pass<EOL><DEDENT>child_models.append((model, SettingValueAdmin))<EOL><DEDENT><DEDENT>return child_models<EOL>

Returns a list of ``(Model, ModelAdmin)`` tuples for ``base_model``
subclasses.


<EOL>return obj.value<EOL>

Returns the ``value`` field from the child model.


if default is None:<EOL><INDENT>settings = self.setting_model.objects.as_dict()<EOL><DEDENT>else:<EOL><INDENT>settings = self.setting_model.objects.as_dict(default=default)<EOL><DEDENT>return settings<EOL>


def get_value(self, context, name, default):

settings = self.setting_model.objects.filter(name=name)<EOL>if default is None:<EOL><INDENT>settings = settings.as_dict()<EOL><DEDENT>else:<EOL><INDENT>settings = settings.as_dict(default=default)<EOL><DEDENT>value = settings[name]<EOL>return value<EOL>


def render_tag(self, context, name, nodelist):

<EOL>settings = self.setting_model.objects.filter(name=name).as_dict()<EOL>try:<EOL><INDENT>value = settings[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>value = settings[name] = nodelist.render(context)<EOL><DEDENT>return value<EOL>


settings = Setting.objects.all().as_dict(default='<STR_LIT>')<EOL>context = {<EOL>'<STR_LIT>': settings,<EOL>}<EOL>return context<EOL>

Adds a ``SettingDict`` object for the ``Setting`` model to the context as
``SETTINGS``. Automatically creates non-existent settings with an empty
string as the default value.


def __init__(self, model=None, queryset=None, default=None):

if model:<EOL><INDENT>self.model = model<EOL>self.queryset = model.objects.all()<EOL><DEDENT>elif queryset is not None: <EOL><INDENT>if model:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>self.model = queryset.model<EOL>self.queryset = queryset<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>self.default = default<EOL>self.empty_cache = True<EOL>super(SettingDict, self).__init__()<EOL>

All setting values for the given model or queryset will be lazily
loaded into the cache on first access.

If ``default`` is not ``None``, non-existent settings will be created
on access.


<EOL>if self.empty_cache:<EOL><INDENT>self.refresh()<EOL><DEDENT>deleted = self.model.objects.filter(name=key).delete()<EOL>try:<EOL><INDENT>super(SettingDict, self).__delitem__(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>if not deleted:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>

Deletes a setting from the dict and the database.


<EOL>if self.empty_cache:<EOL><INDENT>self.refresh()<EOL><DEDENT>try:<EOL><INDENT>value = super(SettingDict, self).__getitem__(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>value = self.model.objects.get(name=key).value<EOL><DEDENT>except self.model.DoesNotExist:<EOL><INDENT>if self.default is None:<EOL><INDENT>raise KeyError(key)<EOL><DEDENT>value = self.default<EOL>self.model.objects.create(name=key, value=value)<EOL><DEDENT>super(SettingDict, self).__setitem__(key, value)<EOL><DEDENT>return value<EOL>

Returns the setting value for ``key`` from the cache if possible,
otherwise from the database. Adds values that are fetched from the
database to the cache.


<EOL>if self.empty_cache:<EOL><INDENT>self.refresh()<EOL><DEDENT>with transaction.atomic():<EOL><INDENT>self.model.objects.filter(name=key).delete()<EOL>self.model.objects.create(name=key, value=value)<EOL><DEDENT>super(SettingDict, self).__setitem__(key, value)<EOL>

Tries to delete and then creates a setting, in case the value type has
changed. Otherwise, we would need to get, update (if same type), or
delete and create (if not same type).


<EOL>args = [(obj.name, obj.value) for obj in self.queryset.all()]<EOL>super(SettingDict, self).update(args)<EOL>self.empty_cache = False<EOL>

Updates the cache with setting values from the database.


settings = SettingDict(queryset=self, default=default)<EOL>return settings<EOL>

Returns a ``SettingDict`` object for this queryset.


if value is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>model = Setting.get_model_for_value(value)<EOL>obj = super(SettingQuerySet, model.objects.all()).create(name=name, value=value)<EOL>return obj<EOL>

Creates and returns an object of the appropriate type for ``value``.


for related_object in get_all_related_objects(cls._meta):<EOL><INDENT>model = getattr(related_object, '<STR_LIT>', related_object.model)<EOL>if issubclass(model, cls):<EOL><INDENT>if model.is_compatible(value):<EOL><INDENT>return model<EOL><DEDENT><DEDENT><DEDENT>raise ValueError(<EOL>'<STR_LIT>' % value)<EOL>

Iterates through setting value subclasses, returning one that is
compatible with the type of ``value``. Calls ``is_compatible()`` on
each subclass.


if not hasattr(cls, '<STR_LIT>'):<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return isinstance(value, cls.value_type)<EOL>

Returns ``True`` if this model should be used to store ``value``.

Checks if ``value`` is an instance of ``value_type``. Override this
method if you need more advanced behaviour. For example, to distinguish
between single and multi-line text.


async def trigger(self, event, data=None, socket_id=None):

json_data = json.dumps(data, cls=self.pusher.encoder)<EOL>query_string = self.signed_query(event, json_data, socket_id)<EOL>signed_path = "<STR_LIT>" % (self.path, query_string)<EOL>pusher = self.pusher<EOL>absolute_url = pusher.get_absolute_path(signed_path)<EOL>response = await pusher.http.post(<EOL>absolute_url, data=json_data,<EOL>headers=[('<STR_LIT:Content-Type>', '<STR_LIT:application/json>')])<EOL>response.raise_for_status()<EOL>return response.status_code == <NUM_LIT><EOL>


self._registered_callbacks[event] = callback<EOL>return True<EOL>

Bind to an ``event`` in this channel. The ``callback`` function is
        executed every time the event is triggered.


if not self._consumer:<EOL><INDENT>waiter = self._waiter = asyncio.Future()<EOL>try:<EOL><INDENT>address = self._websocket_host()<EOL>self.logger.info('<STR_LIT>', address)<EOL>self._consumer = await self.http.get(address)<EOL>if self._consumer.status_code != <NUM_LIT>:<EOL><INDENT>raise PusherError("<STR_LIT>")<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>waiter.set_exception(exc)<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>await waiter<EOL><DEDENT><DEDENT>return self._consumer<EOL>


def on_message(self, websocket, message):

waiter = self._waiter<EOL>self._waiter = None<EOL>encoded = json.loads(message)<EOL>event = encoded.get('<STR_LIT>')<EOL>channel = encoded.get('<STR_LIT>')<EOL>data = json.loads(encoded.get('<STR_LIT:data>'))<EOL>try:<EOL><INDENT>if event == PUSHER_ERROR:<EOL><INDENT>raise PusherError(data['<STR_LIT:message>'], data['<STR_LIT:code>'])<EOL><DEDENT>elif event == PUSHER_CONNECTION:<EOL><INDENT>self.socket_id = data.get('<STR_LIT>')<EOL>self.logger.info('<STR_LIT>',<EOL>self.socket_id)<EOL>waiter.set_result(self.socket_id)<EOL><DEDENT>elif event == PUSHER_SUBSCRIBED:<EOL><INDENT>self.logger.info('<STR_LIT>',<EOL>encoded.get('<STR_LIT>'))<EOL><DEDENT>elif channel:<EOL><INDENT>self[channel]._event(event, data)<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>if waiter:<EOL><INDENT>waiter.set_exception(exc)<EOL><DEDENT>else:<EOL><INDENT>self.logger.exception('<STR_LIT>')<EOL><DEDENT><DEDENT>


return self.endpoint.http_session<EOL>


return self.client.http_session<EOL>


dirname = os.path.dirname(filename or __file__)<EOL>git_show = sh('<STR_LIT>',<EOL>cwd=dirname)<EOL>timestamp = git_show.partition('<STR_LIT:\n>')[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>return timestamp.strftime('<STR_LIT>')<EOL>

Returns a numeric identifier of the latest git changeset.

    The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
    This value isn't guaranteed to be unique, but collisions are very unlikely,
    so it's sufficient for generating the development version numbers.


async def upload_file(self, bucket, file, uploadpath=None, key=None,<EOL>ContentType=None, **kw):

is_filename = False<EOL>if hasattr(file, '<STR_LIT>'):<EOL><INDENT>if hasattr(file, '<STR_LIT>'):<EOL><INDENT>file.seek(<NUM_LIT:0>)<EOL><DEDENT>file = file.read()<EOL>size = len(file)<EOL><DEDENT>elif key:<EOL><INDENT>size = len(file)<EOL><DEDENT>else:<EOL><INDENT>is_filename = True<EOL>size = os.stat(file).st_size<EOL>key = os.path.basename(file)<EOL><DEDENT>assert key, '<STR_LIT>'<EOL>if not ContentType:<EOL><INDENT>ContentType, _ = mimetypes.guess_type(key)<EOL><DEDENT>if uploadpath:<EOL><INDENT>if not uploadpath.endswith('<STR_LIT:/>'):<EOL><INDENT>uploadpath = '<STR_LIT>' % uploadpath<EOL><DEDENT>key = '<STR_LIT>' % (uploadpath, key)<EOL><DEDENT>params = dict(Bucket=bucket, Key=key)<EOL>if not ContentType:<EOL><INDENT>ContentType = '<STR_LIT>'<EOL><DEDENT>params['<STR_LIT>'] = ContentType<EOL>if size > MULTI_PART_SIZE and is_filename:<EOL><INDENT>resp = await _multipart(self, file, params)<EOL><DEDENT>elif is_filename:<EOL><INDENT>with open(file, '<STR_LIT:rb>') as fp:<EOL><INDENT>params['<STR_LIT>'] = fp.read()<EOL><DEDENT>resp = await self.put_object(**params)<EOL><DEDENT>else:<EOL><INDENT>params['<STR_LIT>'] = file<EOL>resp = await self.put_object(**params)<EOL><DEDENT>if '<STR_LIT>' not in resp:<EOL><INDENT>resp['<STR_LIT>'] = key<EOL><DEDENT>if '<STR_LIT>' not in resp:<EOL><INDENT>resp['<STR_LIT>'] = bucket<EOL><DEDENT>return resp<EOL>

Upload a file to S3 possibly using the multi-part uploader
        Return the key uploaded


async def copy_storage_object(self, source_bucket, source_key,<EOL>bucket, key):

info = await self.head_object(Bucket=source_bucket, Key=source_key)<EOL>size = info['<STR_LIT>']<EOL>if size > MULTI_PART_SIZE:<EOL><INDENT>result = await _multipart_copy(self, source_bucket, source_key,<EOL>bucket, key, size)<EOL><DEDENT>else:<EOL><INDENT>result = await self.copy_object(<EOL>Bucket=bucket, Key=key,<EOL>CopySource=_source_string(source_bucket, source_key)<EOL>)<EOL><DEDENT>return result<EOL>

Copy a file from one bucket into another


def upload_folder(self, bucket, folder, key=None, skip=None,<EOL>content_types=None):

uploader = FolderUploader(self, bucket, folder, key, skip,<EOL>content_types)<EOL>return uploader.start()<EOL>

Recursively upload a ``folder`` into a backet.

        :param bucket: bucket where to upload the folder to
        :param folder: the folder location in the local file system
        :param key: Optional key where the folder is uploaded
        :param skip: Optional list of files to skip
        :param content_types: Optional dictionary mapping suffixes to
            content types
        :return: a coroutine


async def _upload_file(self, full_path):

rel_path = os.path.relpath(full_path, self.folder)<EOL>key = s3_key(os.path.join(self.key, rel_path))<EOL>ct = self.content_types.get(key.split('<STR_LIT:.>')[-<NUM_LIT:1>])<EOL>with open(full_path, '<STR_LIT:rb>') as fp:<EOL><INDENT>file = fp.read()<EOL><DEDENT>try:<EOL><INDENT>await self.botocore.upload_file(self.bucket, file, key=key,<EOL>ContentType=ct)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>LOGGER.error('<STR_LIT>', key, exc)<EOL>self.failures[key] = self.all.pop(full_path)<EOL>return<EOL><DEDENT>size = self.all.pop(full_path)<EOL>self.success[key] = size<EOL>self.total_size += size<EOL>percentage = <NUM_LIT:100>*(<NUM_LIT:1> - len(self.all)/self.total_files)<EOL>message = '<STR_LIT>'.format(<EOL>percentage, key, convert_bytes(size))<EOL>LOGGER.info(message)<EOL>


if not self.can_paginate(operation_name):<EOL><INDENT>raise OperationNotPageableError(operation_name=operation_name)<EOL><DEDENT>else:<EOL><INDENT>actual_operation_name = self._PY_TO_OP_NAME[operation_name]<EOL>Paginator.PAGE_ITERATOR_CLS = AsyncPageIterator<EOL>paginator = Paginator(<EOL>getattr(self, operation_name),<EOL>self._cache['<STR_LIT>'][actual_operation_name])<EOL>return paginator<EOL><DEDENT>

Create a paginator for an operation.
        :type operation_name: string
        :param operation_name: The operation name.  This is the same name
            as the method name on the client.  For example, if the
            method name is ``create_foo``, and you'd normally invoke the
            operation as ``client.create_foo(**kwargs)``, if the
            ``create_foo`` operation can be paginated, you can use the
            call ``client.get_paginator("create_foo")``.
        :raise OperationNotPageableError: Raised if the operation is not
            pageable.  You can use the ``client.can_paginate`` method to
            check if an operation is pageable.
        :rtype: L{botocore.paginate.Paginator}
        :return: A paginator object.


return AsyncSession(session_vars=env_vars)<EOL>


def get_cache_key(user_or_username, size, prefix):

if isinstance(user_or_username, get_user_model()):<EOL><INDENT>user_or_username = user_or_username.username<EOL><DEDENT>return '<STR_LIT>' % (prefix, user_or_username, size)<EOL>

Returns a cache key consisten of a username and image size.


def cache_set(key, value):<EOL><INDENT>cache.set(key, value, AVATAR_CACHE_TIMEOUT)<EOL>return value<EOL><DEDENT>def cached_func(user, size):<EOL><INDENT>prefix = func.__name__<EOL>cached_funcs.add(prefix)<EOL>key = get_cache_key(user, size, prefix=prefix)<EOL>return cache.get(key) or cache_set(key, func(user, size))<EOL><DEDENT>return cached_func<EOL>

Decorator to cache the result of functions that take a ``user`` and a
``size`` value.


sizes = set(AUTO_GENERATE_AVATAR_SIZES)<EOL>if size is not None:<EOL><INDENT>sizes.add(size)<EOL><DEDENT>for prefix in cached_funcs:<EOL><INDENT>for size in sizes:<EOL><INDENT>cache.delete(get_cache_key(user, size, prefix))<EOL><DEDENT><DEDENT>

Function to be called when saving or changing an user's avatars.


alt = unicode(user)<EOL>url = reverse('<STR_LIT>', kwargs={'<STR_LIT:user>' : user, '<STR_LIT:size>' : size})<EOL>return """<STR_LIT>""" % (url, alt,<EOL>)<EOL>

This tag tries to get the default avatar for a user without doing any db
requests. It achieve this by linking to a special view that will do all the
work for us. If that special view is then cached by a CDN for instance,
we will avoid many db calls.


next = request.POST.get('<STR_LIT>', request.GET.get('<STR_LIT>',<EOL>request.META.get('<STR_LIT>', None)))<EOL>if not next:<EOL><INDENT>next = request.path<EOL><DEDENT>return next<EOL>

The part that's the least straightforward about views in this module is how they
determine their redirects after they have finished computation.

In short, they will try and determine the next place to go in the following order:

1. If there is a variable named ``next`` in the *POST* parameters, the view will
redirect to that variable's value.
2. If there is a variable named ``next`` in the *GET* parameters, the view will
redirect to that variable's value.
3. If Django can determine the previous page from the HTTP headers, the view will
redirect to that previous page.


if self.receiver != None:<EOL><INDENT>self.receiver.join()<EOL><DEDENT>for s in self.senders.values():<EOL><INDENT>s.join()<EOL><DEDENT>


if not hasattr(callback, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>self.send_callback = callback<EOL>

Sets the send callback function.

If the HDLC controller has already been started, the new
callback function will be taken into account for the next
data frames to be sent.


if not hasattr(callback, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>self.receive_callback = callback<EOL>

Sets the receive callback function.

This method has to be called before starting the
HDLC controller.


if sending_timeout >= HDLController.MIN_SENDING_TIMEOUT:<EOL><INDENT>self.sending_timeout = sending_timeout<EOL><DEDENT>


return len(self.senders)<EOL>


while len(self.senders) >= self.window:<EOL><INDENT>pass<EOL><DEDENT>self.senders[self.new_seq_no] = self.Sender(<EOL>self.write,<EOL>self.send_lock,<EOL>data,<EOL>self.new_seq_no,<EOL>timeout=self.sending_timeout,<EOL>callback=self.send_callback,<EOL>)<EOL>self.senders[self.new_seq_no].start()<EOL>self.new_seq_no = (self.new_seq_no + <NUM_LIT:1>) % HDLController.MAX_SEQ_NO<EOL>

Sends a new data frame.

This method will block until a new room is available for
a new sender. This limit is determined by the size of the window.


return self.frames_received.get()<EOL>

Gets the next frame received.

This method will block until a new data frame is available.


def make_request(self, url, method='<STR_LIT>', headers=None,<EOL>data=None, callback=None, errors=STRICT,<EOL>verify=False, timeout=None, **params):

if '<STR_LIT>' not in url.lower():<EOL><INDENT>params.update({<EOL>'<STR_LIT>': self.api_key<EOL>})<EOL><DEDENT>return super(Flights, self).make_request(url, method, headers,<EOL>data, callback, errors,<EOL>verify, **params)<EOL>

Call the `make_request` method from apiwrapper.
So we can inject the apikey when it's not available.


service_url = self.PRICING_SESSION_URL<EOL>return self.make_request(service_url,<EOL>method='<STR_LIT>',<EOL>headers=self._headers(),<EOL>callback=lambda resp: resp.headers[<EOL>'<STR_LIT:location>'],<EOL>data=params)<EOL>

Create the session
date format: YYYY-mm-dd
location: ISO code.
After creating the session,
this method will return the poll_url.


def get_result(self, errors=STRICT, **params):

service_url = self.create_session(**params)<EOL>return self.poll(service_url, errors=errors)<EOL>

Get all results, no filtering,
etc. by creating and polling the session.


def make_request(self, url, method='<STR_LIT>', headers=None, data=None,<EOL>callback=None, errors=STRICT, verify=False, timeout=None, **params):

error_modes = (STRICT, GRACEFUL, IGNORE)<EOL>error_mode = errors or GRACEFUL<EOL>if error_mode.lower() not in error_modes:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>% '<STR_LIT:U+002C>'.join(error_modes))<EOL><DEDENT>if callback is None:<EOL><INDENT>callback = self._default_resp_callback<EOL><DEDENT>request = getattr(requests, method.lower())<EOL>log.debug('<STR_LIT>' % url)<EOL>log.debug('<STR_LIT>' % method)<EOL>log.debug('<STR_LIT>' % params)<EOL>log.debug('<STR_LIT>' % headers)<EOL>log.debug('<STR_LIT>' % timeout)<EOL>r = request(<EOL>url, headers=headers, data=data, verify=verify, timeout=timeout, params=params)<EOL>log.debug('<STR_LIT>' % r.url)<EOL>try:<EOL><INDENT>r.raise_for_status()<EOL>return callback(r)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return self._with_error_handling(r, e,<EOL>error_mode, self.response_format)<EOL><DEDENT>

Reusable method for performing requests.
:param url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
                  default callback will parse response as json object.
:param errors - specifies communication errors handling mode, possible
                values are:
                 * strict (default) - throw an error as soon as one
                    occurred
                 * graceful - ignore certain errors, e.g. EmptyResponse
                 * ignore - ignore all errors and return a result in
                            any case.
                            NOTE that it DOES NOT mean that no
                            exceptions can be
                            raised from this method, it mostly ignores
                            communication
                            related errors.
                 * None or empty string equals to default
:param verify - whether or not to verify SSL cert, default to False
:param timeout - the timeout of the request in second, default to None
:param params - additional query parameters for request