<commit_before># -*- coding: utf-8 -*-
'''
The Salt Cloud Runner
=====================

This runner wraps the functionality of salt cloud making salt cloud routines
available to all internal apis via the runner system
'''

# Import python libs
import os

# Import Salt libs
import salt.cloud

def _get_client():
    '''
    Return a cloud client
    '''
    client = salt.cloud.CloudClient(
            os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud')
            )
    return client

def list_sizes(provider='all'):
    '''
    List cloud provider sizes for the given providers
    '''
    client = _get_client()
    sizes = client.list_sizes(provider)
    return sizes

def list_images(provider='all'):
    '''
    List cloud provider images for the given providers
    '''
    client = _get_client()
    images = client.list_images(provider)
    return images

def list_locations(provider='all'):
    '''
    List cloud provider sizes for the given providers
    '''
    client = _get_client()
    locations = client.list_locations(provider)
    return locations

def query(query_type='list_nodes'):
    '''
    List cloud provider data for all providers
    '''
    client = _get_client()
    info = client.query(query_type)
    return info

def full_query(query_type='list_nodes_full'):
    '''
    List all available cloud provider data
    '''
    client = _get_client()
    info = client.full_query(query_type)
    return info

def select_query(query_type='list_nodes_select'):
    '''
    List selected nodes
    '''
    client = _get_client()
    info = client.select_query(query_type)
    return info

def profile(prof=None, instances=None, **kwargs):
    '''
    Create a cloud vm with the given profile and instances, instances can be a
    list or comma-delimited string

    CLI Example:

    .. code-block:: bash

        salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
    '''
    if prof is None and 'profile' in kwargs:
        prof = kwargs['profile']

    if prof is None:
        return {'Error': 'A profile (or prof) must be defined'}

    if instances is None and 'names' in kwargs:
        instances = kwargs['names']

    if instances is None:
        return {'Error': 'One or more instances (comma-delimited) must be set'}

    client = _get_client()
    info = client.profile(prof, instances, **kwargs)
    return info

def map_run(path, **kwargs):
    '''
    Execute a salt cloud map file
    '''
    client = _get_client()
    info = client.map_run(path, **kwargs)
    return info

def destroy(instances):
    '''
    Destroy the named vm(s)
    '''
    client = _get_client()
    info = client.destroy(instances)
    return info

def action(
        fun=None,
        cloudmap=None,
        instances=None,
        provider=None,
        instance=None,
        **kwargs):
    '''
    Execute a single action on the given map/provider/instance
    '''
    client = _get_client()
    info = client.action(fun, cloudmap, instances, provider, instance, kwargs)
    return info

def create(provider, instances, **kwargs):
    '''
    Create an instance using Salt Cloud

    CLI Example:

    .. code-block:: bash

        salt-run cloud.create my-ec2-config myinstance \
            image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
            securitygroup=default delvol_on_destroy=True
    '''
    create_kwargs = {}
    for kwarg in kwargs:
        if not kwarg.startswith('__'):
            create_kwargs[kwarg] = kwargs[kwarg]
    client = _get_client()
    info = client.create(provider, instances, **create_kwargs)
    return info
<commit_msg>Making salt.runners.cloud python3 compatible<commit_after># -*- coding: utf-8 -*-
'''
The Salt Cloud Runner
=====================

This runner wraps the functionality of salt cloud making salt cloud routines
available to all internal apis via the runner system
'''
from __future__ import absolute_import

# Import python libs
import os

# Import Salt libs
import salt.cloud

def _get_client():
    '''
    Return a cloud client
    '''
    client = salt.cloud.CloudClient(
            os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud')
            )
    return client

def list_sizes(provider='all'):
    '''
    List cloud provider sizes for the given providers
    '''
    client = _get_client()
    sizes = client.list_sizes(provider)
    return sizes

def list_images(provider='all'):
    '''
    List cloud provider images for the given providers
    '''
    client = _get_client()
    images = client.list_images(provider)
    return images

def list_locations(provider='all'):
    '''
    List cloud provider sizes for the given providers
    '''
    client = _get_client()
    locations = client.list_locations(provider)
    return locations

def query(query_type='list_nodes'):
    '''
    List cloud provider data for all providers
    '''
    client = _get_client()
    info = client.query(query_type)
    return info

def full_query(query_type='list_nodes_full'):
    '''
    List all available cloud provider data
    '''
    client = _get_client()
    info = client.full_query(query_type)
    return info

def select_query(query_type='list_nodes_select'):
    '''
    List selected nodes
    '''
    client = _get_client()
    info = client.select_query(query_type)
    return info

def profile(prof=None, instances=None, **kwargs):
    '''
    Create a cloud vm with the given profile and instances, instances can be a
    list or comma-delimited string

    CLI Example:

    .. code-block:: bash

        salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
    '''
    if prof is None and 'profile' in kwargs:
        prof = kwargs['profile']

    if prof is None:
        return {'Error': 'A profile (or prof) must be defined'}

    if instances is None and 'names' in kwargs:
        instances = kwargs['names']

    if instances is None:
        return {'Error': 'One or more instances (comma-delimited) must be set'}

    client = _get_client()
    info = client.profile(prof, instances, **kwargs)
    return info

def map_run(path, **kwargs):
    '''
    Execute a salt cloud map file
    '''
    client = _get_client()
    info = client.map_run(path, **kwargs)
    return info

def destroy(instances):
    '''
    Destroy the named vm(s)
    '''
    client = _get_client()
    info = client.destroy(instances)
    return info

def action(
        fun=None,
        cloudmap=None,
        instances=None,
        provider=None,
        instance=None,
        **kwargs):
    '''
    Execute a single action on the given map/provider/instance
    '''
    client = _get_client()
    info = client.action(fun, cloudmap, instances, provider, instance, kwargs)
    return info

def create(provider, instances, **kwargs):
    '''
    Create an instance using Salt Cloud

    CLI Example:

    .. code-block:: bash

        salt-run cloud.create my-ec2-config myinstance \
            image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
            securitygroup=default delvol_on_destroy=True
    '''
    create_kwargs = {}
    for kwarg in kwargs:
        if not kwarg.startswith('__'):
            create_kwargs[kwarg] = kwargs[kwarg]
    client = _get_client()
    info = client.create(provider, instances, **create_kwargs)
    return info
<|endoftext|>


<commit_before>'''
Configuration management using Augeas
=====================================

:strong:`NOTE:` This state requires the ``augeas`` Python module.

.. _Augeas: http://augeas.net/

Augeas_ can be used to manage configuration files. Currently only the ``set``
command is supported via this state. The :mod:`augeas
<salt.modules.augeas_cfg>` module also has support for get, match, remove, etc.

Examples:

Set the first entry in ``/etc/hosts`` to ``localhost``:

.. code-block:: yaml

    hosts:
      augeas.setvalue:
        - changes:
          - /files/etc/hosts/1/canonical: localhost

Add a new host to ``/etc/hosts`` with the IP address ``192.168.1.1`` and
hostname ``test``:

.. code-block:: yaml

    hosts:
      augeas.setvalue:
        - changes:
          - /files/etc/hosts/2/ipaddr: 192.168.1.1
          - /files/etc/hosts/2/canonical: foo.bar.com
          - /files/etc/hosts/2/alias[1]: foosite
          - /files/etc/hosts/2/alias[2]: foo

You can also set a prefix if you want to avoid redundancy:

.. code-block:: yaml

    nginx-conf:
      augeas.setvalue:
        - prefix: /files/etc/nginx/nginx.conf
        - changes:
          - user: www-data
          - worker_processes: 2
          - http/server_tokens: off
          - http/keepalive_timeout: 65

'''

def __virtual__():
    return 'augeas' if 'augeas.setvalue' in __salt__ else False

def setvalue(name, prefix=None, changes=[], **kwargs):
    '''
    Set a value for a specific augeas path
    '''
    ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}

    args = []
    if not changes:
        ret['comment'] = '\'changes\' must be specified and not empty'
        return ret
    else:
        if not isinstance(changes, list):
            ret['comment'] = '\'changes\' must be formatted as a list'
            return ret
        for change in changes:
            if not isinstance(change, dict) or len(change) > 1:
                ret['comment'] = 'Invalidly-formatted change'
                return ret
            key = next(iter(change))
            args.extend([key, change[key]])

    if prefix is not None:
        args.insert(0, 'prefix={0}'.format(prefix))

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Calling setvalue with {0}'.format(args)
        return ret

    call = __salt__['augeas.setvalue'](*args)

    ret['result'] = call['retval']

    if ret['result'] is False:
        ret['comment'] = 'Error: {0}'.format(call['error'])
        return ret

    ret['comment'] = 'Success'
    for change in changes:
        ret['changes'].update(change)
    return ret
<commit_msg>Fix pylint<commit_after>'''
Configuration management using Augeas
=====================================

:strong:`NOTE:` This state requires the ``augeas`` Python module.

.. _Augeas: http://augeas.net/

Augeas_ can be used to manage configuration files. Currently only the ``set``
command is supported via this state. The :mod:`augeas
<salt.modules.augeas_cfg>` module also has support for get, match, remove, etc.

Examples:

Set the first entry in ``/etc/hosts`` to ``localhost``:

.. code-block:: yaml

    hosts:
      augeas.setvalue:
        - changes:
          - /files/etc/hosts/1/canonical: localhost

Add a new host to ``/etc/hosts`` with the IP address ``192.168.1.1`` and
hostname ``test``:

.. code-block:: yaml

    hosts:
      augeas.setvalue:
        - changes:
          - /files/etc/hosts/2/ipaddr: 192.168.1.1
          - /files/etc/hosts/2/canonical: foo.bar.com
          - /files/etc/hosts/2/alias[1]: foosite
          - /files/etc/hosts/2/alias[2]: foo

You can also set a prefix if you want to avoid redundancy:

.. code-block:: yaml

    nginx-conf:
      augeas.setvalue:
        - prefix: /files/etc/nginx/nginx.conf
        - changes:
          - user: www-data
          - worker_processes: 2
          - http/server_tokens: off
          - http/keepalive_timeout: 65

'''

def __virtual__():
    return 'augeas' if 'augeas.setvalue' in __salt__ else False

def setvalue(name, prefix=None, changes=None, **kwargs):
    '''
    Set a value for a specific augeas path
    '''
    ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}

    args = []
    if not changes:
        ret['comment'] = '\'changes\' must be specified'
        return ret
    else:
        if not isinstance(changes, list):
            ret['comment'] = '\'changes\' must be formatted as a list'
            return ret
        for change in changes:
            if not isinstance(change, dict) or len(change) > 1:
                ret['comment'] = 'Invalidly-formatted change'
                return ret
            key = next(iter(change))
            args.extend([key, change[key]])

    if prefix is not None:
        args.insert(0, 'prefix={0}'.format(prefix))

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Calling setvalue with {0}'.format(args)
        return ret

    call = __salt__['augeas.setvalue'](*args)

    ret['result'] = call['retval']

    if ret['result'] is False:
        ret['comment'] = 'Error: {0}'.format(call['error'])
        return ret

    ret['comment'] = 'Success'
    for change in changes:
        ret['changes'].update(change)
    return ret
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
Managing Images in OpenStack Glance
===================================
'''
# Import python libs
import logging

log = logging.getLogger(__name__)

def image_present(name, visibility=None, protected=None, checksum=None):
    '''
    Checks if given image is present with properties
    set as specified.

    Supported properties:
      - visibility ('public' or 'private')
      - protected (bool)
      - checksum (string, md5sum)
    '''
    ret = {'name': name,
            'changes': {},
            'result': True,
            'comment': '',
            }

    images_dict = __salt__['glance.image_list'](name=name)
    log.debug('Got images_dict: {0}'.format(images_dict))
    if len(images_dict) == 1 and 'images' in images_dict:
        images_dict = images_dict['images']

    if len(images_dict) == 0:
        ret['result'] = False
        ret['comment'] = 'No image with name "{0}"'.format(name)
    elif len(images_dict) == 1:
        if len(images_dict) == 1:
            image = images_dict[images_dict.keys()[0]]
        else:
            image = images_dict[0]
        if visibility and image['visibility'] != visibility:
            ret['result'] = False
            ret['comment'] += '"visibility" is {0}, should be {1}'.format(
                image['visibility'], visibility)
        if protected is not None and image['protected'] ^ protected:
            ret['result'] = False
            ret['comment'] += '"protected" is {0}, should be {1}'.format(
                image['protected'], protected)
        if checksum and image['checksum'] != checksum:
            ret['result'] = False
            ret['comment'] += '"checksum" is {0}, should be {1}'.format(
                image['checksum'], checksum)
    else:
        raise NotImplementedError
    return ret
<commit_msg>also comment correct values<commit_after># -*- coding: utf-8 -*-
'''
Managing Images in OpenStack Glance
===================================
'''
# Import python libs
import logging

log = logging.getLogger(__name__)

def image_present(name, visibility=None, protected=None, checksum=None):
    '''
    Checks if given image is present with properties
    set as specified.

    Supported properties:
      - visibility ('public' or 'private')
      - protected (bool)
      - checksum (string, md5sum)
    '''
    ret = {'name': name,
            'changes': {},
            'result': True,
            'comment': '',
            }

    images_dict = __salt__['glance.image_list'](name=name)
    log.debug('Got images_dict: {0}'.format(images_dict))
    if len(images_dict) == 1 and 'images' in images_dict:
        images_dict = images_dict['images']

    if len(images_dict) == 0:
        ret['result'] = False
        ret['comment'] = 'No image with name "{0}"'.format(name)
    elif len(images_dict) == 1:
        if len(images_dict) == 1:
            image = images_dict[images_dict.keys()[0]]
        else:
            image = images_dict[0]
        if visibility:
            if image['visibility'] != visibility:
                ret['result'] = False
                ret['comment'] += '"visibility" is {0}, should be {1}.\n'.format(
                    image['visibility'], visibility)
            else:
                ret['comment'] += '"visibility" is correct ({0}).\n'.format(
                    visibility)
        if protected is not None:
            if not isinstance(protected, bool) or image['protected'] ^ protected:
                ret['result'] = False
                ret['comment'] += '"protected" is {0}, should be {1}.\n'.format(
                    image['protected'], protected)
            else:
                ret['comment'] += '"protected" is correct ({0}).\n'.format(
                    protected)
        if checksum:
            if image['checksum'] != checksum:
                ret['result'] = False
                ret['comment'] += '"checksum" is {0}, should be {1}.\n'.format(
                    image['checksum'], checksum)
            else:
                ret['comment'] += '"checksum" is correct ({0}).\n'.format(
                    checksum)
    else:
        raise NotImplementedError
    return ret
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import

def gt(name, value):
    '''
    Only succeed if the value in the given register location is greater than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] > value:
        ret['result'] = True
    return ret

def gte(name, value):
    '''
    Only succeed if the value in the given register location is greater or equal
    than the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] >= value:
        ret['result'] = True
    return ret

def lt(name, value):
    '''
    Only succeed if the value in the given register location is less than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] < value:
        ret['result'] = True
    return ret

def lte(name, value):
    '''
    Only succeed if the value in the given register location is less than
    or equal the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] <= value:
        ret['result'] = True
    return ret

def eq(name, value):
    '''
    Only succeed if the value in the given register location is equal to
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] == value:
        ret['result'] = True
    return ret

def ne(name, value):
    '''
    Only succeed if the value in the given register location is not equal to
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] != value:
        ret['result'] = True
    return ret

def contains(name, value):
    '''
    Only succeed if the value in the given register location is greater than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = None
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    try:
        if value in __reg__[name]['val']:
            ret['result'] = True
    except TypeError:
        pass
    return ret
<commit_msg>Fix error where this fires if the value is not present<commit_after># -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import

def gt(name, value):
    '''
    Only succeed if the value in the given register location is greater than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] > value:
        ret['result'] = True
    return ret

def gte(name, value):
    '''
    Only succeed if the value in the given register location is greater or equal
    than the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] >= value:
        ret['result'] = True
    return ret

def lt(name, value):
    '''
    Only succeed if the value in the given register location is less than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] < value:
        ret['result'] = True
    return ret

def lte(name, value):
    '''
    Only succeed if the value in the given register location is less than
    or equal the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] <= value:
        ret['result'] = True
    return ret

def eq(name, value):
    '''
    Only succeed if the value in the given register location is equal to
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] == value:
        ret['result'] = True
    return ret

def ne(name, value):
    '''
    Only succeed if the value in the given register location is not equal to
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    if __reg__[name]['val'] != value:
        ret['result'] = True
    return ret

def contains(name, value):
    '''
    Only succeed if the value in the given register location is greater than
    the given value
    '''
    ret = {'name': name,
           'result': False,
           'comment': '',
           'changes': {}}
    if name not in __reg__:
        ret['result'] = False
        ret['comment'] = 'Value {0} not in register'.format(name)
        return ret
    try:
        if value in __reg__[name]['val']:
            ret['result'] = True
    except TypeError:
        pass
    return ret
<|endoftext|>


<commit_before>import pandas as pd
import numpy
import math
from bioinput import Bioinput
import sys

class Biomeasure:
    """ This is the main calling class

    __init__ sets the __hr_rawdata

    """

    def __init__(self, threshold=0.9):
        self.__hr_rawdata = pd.DataFrame(numpy.empty((10, 2))*numpy.nan, columns=['voltage', 'time'])
        self.__threshold = threshold
        inputfile = Bioinput()
        self.ecg_file = inputfile.file

    def thresholdhr(self):
        """ Will return a list of thresholds, as well as the number of chunks and data_chunk size

        :return: dataframe with column threshold_hr, and data chunk size and number of chunks for data
        """

        self.__hr_rawdata['voltage'] = list(range(0, 100, 10))
        self.__hr_rawdata['time'] = list(range(0, 50, 5))
        time_step = self.__hr_rawdata['time'][2] - self.__hr_rawdata['time'][1]
        data_chunk = int(math.floor((5 / time_step)))
        number_chunks = int(math.floor((len(self.__hr_rawdata) / data_chunk)))

        threshold_hr = [None] * number_chunks

        for j in range(0, number_chunks):
            maxhr_data = max(self.__hr_rawdata['voltage'][(j * data_chunk):(j * data_chunk) + data_chunk])
            threshold_hr[j] = self.__threshold * maxhr_data
        threshold_hr = pd.DataFrame(numpy.array(threshold_hr), columns=['Threshold'])
        print(threshold_hr)
        return [threshold_hr, data_chunk, number_chunks]

    def hrdetector(self):
        """Use threshold detection to specify a heart beat (QRS height) and estimate both instanteous and hr over delta_t

        :param
        """
        # delta_t = input('Enter how long you would like to average your heart rate over (in s): ')
        # Use delta_t, average the HR over that time
        # for i in hr_rawdata[1], find minimum and max locally, threshold on that (using a timing fxn)
        # Calls thresholdhr every so often
        [thresholds, data_chunk, number_chunks] = self.thresholdhr()
        # DataFrame, thresholds, data_chunk (# of points per 5 seconds), number_chunks
        columns = ['HeartRate', 'B/T', 'time']
        # index = [None] * len(thresholds)
        hr = pd.DataFrame(numpy.empty(((len(thresholds)), 3)), columns=columns)
        hr['HeartRate'] = None
        hr['B/T'] = 'Healthy... for now'
        hr['time'] = list(range(0, number_chunks * 5, 5))

        hb_count = [0] * len(thresholds)

        # time_step = hr_rawdata['time'][2]-hr_rawdata['time'][1]  # find time step
        for j in range(0, len(thresholds)):
            for i in range(1, data_chunk):
                if (self.__hr_rawdata['voltage'][i * (j + 1)] > thresholds['Threshold'][j]) and \
                        (self.__hr_rawdata['voltage'][(i * (j + 1)) - 1] < thresholds['Threshold'][j]):
                    hb_count[j] = hb_count[j] + 1
            hr.at[j, 'HeartRate'] = (hb_count[j] / 5) * 60
        return hr

    def change_threshold(self, threshold):
        self.__init__(threshold)

def main(threshold):
    hr_measure = Biomeasure(threshold)
    # hr_rawdata_new = Bioinput().read_input()
    hr_measure.change_threshold(0.5)
    hr_measure.hrdetector()

if __name__ == "__main__":
    main(sys.argv)
<commit_msg>Some small changes to implement workability with bioinput.py class, seems to be on it's dang way<commit_after>import pandas as pd
import numpy
import math
from bioinput import Bioinput
import sys

class Biomeasure:
    """ This is the main calling class

    __init__ sets the __hr_rawdata

    """

    def __init__(self, threshold=0.9):
        self.__threshold = threshold
        inputfile = Bioinput()
        self.ecg_file = inputfile.file
        self.__hr_rawdata = inputfile.read_input()

    def thresholdhr(self):
        """ Will return a list of thresholds, as well as the number of chunks and data_chunk size

        :return: dataframe with column threshold_hr, and data chunk size and number of chunks for data
        """

        #self.__hr_rawdata['voltage'] = list(range(0, 100, 10))
        #self.__hr_rawdata['time'] = list(range(0, 50, 5))
        time_step = self.__hr_rawdata['time'][2] - self.__hr_rawdata['time'][1]
        data_chunk = int(math.floor((5 / time_step)))
        number_chunks = int(math.floor((len(self.__hr_rawdata) / data_chunk)))

        threshold_hr = [None] * number_chunks

        for j in range(0, number_chunks):
            maxhr_data = max(self.__hr_rawdata['voltage'][(j * data_chunk):(j * data_chunk) + data_chunk])
            threshold_hr[j] = self.__threshold * maxhr_data
        threshold_hr = pd.DataFrame(numpy.array(threshold_hr), columns=['Threshold'])
        print(threshold_hr)
        return [threshold_hr, data_chunk, number_chunks]

    def hrdetector(self):
        """Use threshold detection to specify a heart beat (QRS height) and estimate both instanteous and hr over delta_t

        :param
        """
        # delta_t = input('Enter how long you would like to average your heart rate over (in s): ')
        # Use delta_t, average the HR over that time
        # for i in hr_rawdata[1], find minimum and max locally, threshold on that (using a timing fxn)
        # Calls thresholdhr every so often
        [thresholds, data_chunk, number_chunks] = self.thresholdhr()
        # DataFrame, thresholds, data_chunk (# of points per 5 seconds), number_chunks
        columns = ['HeartRate', 'B/T', 'time']
        # index = [None] * len(thresholds)
        hr = pd.DataFrame(numpy.empty(((len(thresholds)), 3)), columns=columns)
        hr['HeartRate'] = None
        hr['B/T'] = 'Healthy... for now'
        hr['time'] = list(range(0, number_chunks * 5, 5))

        hb_count = [0] * len(thresholds)

        # time_step = hr_rawdata['time'][2]-hr_rawdata['time'][1]  # find time step
        for j in range(0, len(thresholds)):
            for i in range(1, data_chunk):
                if (self.__hr_rawdata['voltage'][i * (j + 1)] > thresholds['Threshold'][j]) and \
                        (self.__hr_rawdata['voltage'][(i * (j + 1)) - 1] < thresholds['Threshold'][j]):
                    hb_count[j] = hb_count[j] + 1
            hr.at[j, 'HeartRate'] = (hb_count[j] / 5) * 60
        return hr

    def change_threshold(self, threshold):
        self.__init__(threshold)

def main(threshold):
    hr_measure = Biomeasure(threshold)
    # hr_rawdata_new = Bioinput().read_input()
    hr_measure.change_threshold(0.5)
    hr_measure.hrdetector()

if __name__ == "__main__":
    main(sys.argv)
<|endoftext|>


<commit_before>"""
S3 Storage object.
"""
import os
import tempfile

import boto
from boto.s3.key import Key
from django.conf import settings

from .base import BaseStorage, StorageError

################################
#  S3 Storage Object
################################

class Storage(BaseStorage):
    """ S3 API Storage. """
    S3_BUCKET = getattr(settings, 'DBBACKUP_S3_BUCKET', None)
    S3_ACCESS_KEY = getattr(settings, 'DBBACKUP_S3_ACCESS_KEY', None)
    S3_SECRET_KEY = getattr(settings, 'DBBACKUP_S3_SECRET_KEY', None)
    S3_DOMAIN = getattr(settings, 'DBBACKUP_S3_DOMAIN', 'https://s3.amazonaws.com/')
    S3_DIRECTORY = getattr(settings, 'DBBACKUP_S3_DIRECTORY', "django-dbbackups/")
    S3_DIRECTORY = '%s/' % S3_DIRECTORY.strip('/')

    def __init__(self, server_name=None):
        self._check_filesystem_errors()
        self.name = 'AmazonS3'
        self.conn = boto.connect_s3(self.S3_ACCESS_KEY, self.S3_SECRET_KEY)
        self.bucket = self.conn.get_bucket(self.S3_BUCKET)
        BaseStorage.__init__(self)

    def _check_filesystem_errors(self):
        """ Check we have all the required settings defined. """
        if not self.S3_BUCKET:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_BUCKET to be defined in settings.')
        if not self.S3_ACCESS_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_ACCESS_KEY to be defined in settings.')
        if not self.S3_SECRET_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_SECRET_KEY to be defined in settings.')

    ###################################
    #  DBBackup Storage Methods
    ###################################

    @property
    def bucket(self):
        return self.bucket

    def backup_dir(self):
        return self.S3_DIRECTORY

    def delete_file(self, filepath):
        """ Delete the specified filepath. """
        self.bucket.delete_key(filepath)

    def list_directory(self):
        """ List all stored backups for the specified. """
        return [k.name for k in
                self.bucket.get_all_keys(prefix=self.S3_DIRECTORY)]

    def write_file(self, filehandle):
        """ Write the specified file. """
        filepath = os.path.join(self.S3_DIRECTORY, filehandle.name)
        key = Key(self.bucket)
        key.key = filepath
        filehandle.seek(0)
        key.set_contents_from_file(filehandle)

    def read_file(self, filepath):
        """ Read the specified file and return it's handle. """
        key = Key(self.bucket)
        key.key = filepath
        filehandle = tempfile.SpooledTemporaryFile(max_size=10 * 1024 * 1024)
        key.get_contents_to_file(filehandle)
        return filehandle
<commit_msg>Upload to s3 using multipart to avoid 5 GB maximum<commit_after>"""
S3 Storage object.
"""
import os
import tempfile
from cStringIO import StringIO

import boto
from boto.s3.key import Key
from django.conf import settings

from .base import BaseStorage, StorageError

################################
#  S3 Storage Object
################################

class Storage(BaseStorage):
    """ S3 API Storage. """
    S3_BUCKET = getattr(settings, 'DBBACKUP_S3_BUCKET', None)
    S3_ACCESS_KEY = getattr(settings, 'DBBACKUP_S3_ACCESS_KEY', None)
    S3_SECRET_KEY = getattr(settings, 'DBBACKUP_S3_SECRET_KEY', None)
    S3_DOMAIN = getattr(settings, 'DBBACKUP_S3_DOMAIN', 'https://s3.amazonaws.com/')
    S3_DIRECTORY = getattr(settings, 'DBBACKUP_S3_DIRECTORY', "django-dbbackups/")
    S3_DIRECTORY = '%s/' % S3_DIRECTORY.strip('/')

    def __init__(self, server_name=None):
        self._check_filesystem_errors()
        self.name = 'AmazonS3'
        self.conn = boto.connect_s3(self.S3_ACCESS_KEY, self.S3_SECRET_KEY)
        self.bucket = self.conn.get_bucket(self.S3_BUCKET)
        BaseStorage.__init__(self)

    def _check_filesystem_errors(self):
        """ Check we have all the required settings defined. """
        if not self.S3_BUCKET:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_BUCKET to be defined in settings.')
        if not self.S3_ACCESS_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_ACCESS_KEY to be defined in settings.')
        if not self.S3_SECRET_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_SECRET_KEY to be defined in settings.')

    ###################################
    #  DBBackup Storage Methods
    ###################################

    @property
    def bucket(self):
        return self.bucket

    def backup_dir(self):
        return self.S3_DIRECTORY

    def delete_file(self, filepath):
        """ Delete the specified filepath. """
        self.bucket.delete_key(filepath)

    def list_directory(self):
        """ List all stored backups for the specified. """
        return [k.name for k in
                self.bucket.get_all_keys(prefix=self.S3_DIRECTORY)]

    def write_file(self, filehandle):
        """ Write the specified file.
            Use multipart upload because normal upload maximum is 5 GB.
        """
        filepath = os.path.join(self.S3_DIRECTORY, filehandle.name)

        filehandle.seek(0)

        mp = self.bucket.initiate_multipart_upload(filepath)

        try:
            part_index = 1
            while True:
                buffer = filehandle.read(5 * 1024 * 1024)

                if not buffer:
                    break
                else:
                    string_file = StringIO(buffer)
                    try:
                        string_file.seek(0)
                        mp.upload_part_from_file(string_file, part_index)
                    finally:
                        string_file.close()

                    part_index += 1

            mp.complete_upload()
        except:
            mp.cancel_upload()
            raise

    def read_file(self, filepath):
        """ Read the specified file and return it's handle. """
        key = Key(self.bucket)
        key.key = filepath
        filehandle = tempfile.SpooledTemporaryFile(max_size=10 * 1024 * 1024)
        key.get_contents_to_file(filehandle)
        return filehandle
<|endoftext|>


<commit_before># coding:utf8

import os
import imp
import time
import types
import random
import traceback

from .. import utils

def default_plugin__accept_request(self, msg, rsp, utils, *args, **kwargs):
    if msg.was_appeal and msg.args[0].lower() in self.keywords:
        return True

    return False

class Pluginmanager(object):
    def __init__(self, bot, vkr):
        self.plugins = {}
        self.plugin_list = []
        self.builtin_plugin_list = []
        self.custom_plugin_list = []
        self.log = lambda *x, **y: None
        self.bot = bot
        self.utils = PluginUtils(self, self.bot, vkr, self.log)

    def plugin_respond(self, msg, rsp):
        for name in self.plugin_list:
            if not self.plugins[name]._accept_request(msg, rsp, self.utils):
                continue

            user_access_level = self.utils.get_user_access_level(msg)

            if user_access_level < self.plugins[name].protection:
                rsp.text = (
                    u'Для использования команды необходим уровень доступа %d.\n'
                    u'Ваш уровень доступа: %d'
                        % (self.plugins[name].protection, user_access_level)
                )
                break

            if self.plugins[name].argument_required:
                if len(msg.args) < 2:
                    rsp.text = \
                        u'Эту команду можно использовать только с аргументом'
                    break

            rsp = self.plugins[name].respond(msg, rsp, self.utils)
            break

        return rsp

    def load_plugins(self):
        self.plugins = {}
        self.plugin_list = []
        self.builtin_plugin_list = []
        self.custom_plugin_list = []

        if not os.path.exists(utils.CUSTOM_PLUGIN_DIR):
            self.log(
                u'Создание директории для пользовательских плагинов: %s ...'
                    % utils.CUSTOM_PLUGIN_DIR, 1
            )
            os.mkdir(utils.CUSTOM_PLUGIN_DIR)

        self.log(u'Чтение встроенных плагинов ...', 0)
        self._load_plugins_from(utils.PLUGIN_DIR)

        for p in self.plugins:
            self.builtin_plugin_list.append(p)

        self.log(u'Чтение пользовательских плагинов ...', 1)
        self._load_plugins_from(utils.CUSTOM_PLUGIN_DIR)

        for p in sorted(self.plugins, key=lambda x: self.plugins[x].priority,
                        reverse=True):
            self.plugin_list.append(p)

        self.builtin_plugin_list = set(self.builtin_plugin_list)

        self.custom_plugin_list = \
            set(set(self.plugin_list) - self.builtin_plugin_list)

        self.log(
            u'Загружены плагины: [b]%s[/b]' % ', '.join(self.plugin_list), 0)

    def _load_plugins_from(self, path):
        files = sorted(os.listdir(path))  # sorting to ensure that .py goes first
        included = []

        for f in files:
            if f.startswith('plugin_'):
                try:
                    if f.endswith('.py'):
                        if f + 'o' in files:
                            if os.path.getmtime(os.path.join(path, f + 'c')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyc newer
                                continue

                            elif os.path.getmtime(os.path.join(path, f + 'o')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyo newer
                                continue

                        self._add_plugin(
                            imp.load_source('', os.path.join(path, f)), f, f[7:-3])

                        included.append(f)

                    elif f.endswith('.pyc') or f.endswith('.pyo'):
                        if f[:-1] in included:
                            continue

                        if f.endswith('c'):
                            if os.path.getmtime(os.path.join(path, f[:-1] + 'o')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyo newer
                                continue
                        else:
                            if os.path.getmtime(os.path.join(path, f[:-1] + 'c')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyc newer
                                continue

                        self._add_plugin(
                            imp.load_compiled('', os.path.join(path, f)), f, f[7:-4])

                        included.append(f[:-1])

                except Exception:
                    self.log(u'[b]Ошибка при загрузке плагина %s[/b]' % f, 2)
                    self.log(traceback.format_exc().decode('utf8'), 2)

    def _add_plugin(self, plugin, f, name):
        p = plugin.Plugin()

        if getattr(p, 'disabled', False):
            return

        if getattr(p, 'name', None) is None:
            self.log(
                u'[b]Предупреждение: отсутствует имя модуля %s. Использую %s[/b]'
                    % (f, name), 1
            )
            p.name = name

        if len(getattr(p, 'keywords', ())) == 0:
            self.log(u'[b]Ошибка: Нет ключевых слов для модуля %s[/b]' % f, 1)
            return

        if getattr(p, '__doc__', None) is None:
            self.log(
                u'[b]Предупреждение: модуль %s не имеет документации[/b]' % f, 1
            )
            p.__doc__ = ''

        if not hasattr(p, 'protection'):
            self.log(
                u'[b]Предупреждение: модуль %s не имеет информации о защите. '
                u'Использую 0[/b]' % f, 1
            )
            p.protection = 0

        if not hasattr(p, 'argument_required'):
            self.log(
                u'[b]Предупреждение: модуль %s не имеет информации о '
                u'необходимости аргумента. Использую False[/b]' % f, 1
            )
            p.argument_required = False

        if not hasattr(p, 'priority'):
            p.priority = 0

        if not hasattr(p, '_accept_request'):
            p._accept_request = \
                types.MethodType(default_plugin__accept_request, p)

        if p.name in self.plugins:
            self.log(
                u'Предупреждение: модуль [b]%s[/b] будет переназначен ...' %
                p.name, 1)

            if p.name in self.builtin_plugin_list:
                self.builtin_plugin_list.remove(p.name)

            if p.name in self.custom_plugin_list:
                self.custom_plugin_list.remove(p.name)

        self.plugins[name] = p

    def set_logging_function(self, logging_function):
        self.log = logging_function
        self.utils.log = logging_function
        self.log(u'Подключена функция логгирования для менеджера плагинов', 0)

class PluginUtils(object):
    """This class contains all nesessary utils for plugins
    """

    def __init__(self, pm, bot, vkr, log):
        self.__pm = pm
        self.__bot = bot
        self.vkr = vkr
        self.log = log

    def get_settings(self):
        return self.__bot.settings

    def get_blacklist(self):
        return self.__bot.blacklist

    def get_whitelist(self):
        return self.__bot.whitelist

    def get_custom_commands(self):
        return self.__bot.custom_commands

    def get_settings(self, key, section='Plugins'):
        return utils.get_settings(key, section=section)

    def save_setting(self, key, val, section='Plugins'):
        self.log(u'Обновляю настройки: %s=%s' % (key, val), 0)
        utils.save_setting(key, val, section=section)

        if key in self.__bot.settings:
            self.__bot.settings[key] = val

        self.__bot.is_settings_changed = True

    def save_blacklist(self, blacklist):
        utils.save_blacklist(blacklist)
        self.__bot.blacklist = blacklist

    def save_whitelist(self, whitelist):
        utils.save_whitelist(whitelist)
        self.__bot.whitelist = whitelist

    def save_custom_commands(self, custom_commands):
        utils.save_custom_commands(custom_commands)
        self.__bot.custom_commands = custom_commands

    def clear_message_queue(self):
        self.__bot.mlpd = None

    def get_user_access_level(self, msg):
        whitelist = self.get_whitelist()

        if msg.out:
            user_access_level = 4
        elif msg.real_user_id in whitelist:
            user_access_level = whitelist[msg.real_user_id]
        else:
            user_access_level = 0

        return user_access_level

    def safe_format(self, *args, **kwargs):
        return utils.safe_format(*args, **kwargs)

    def get_plugin_list(self):
        return self.__pm.plugin_list

    def get_builtin_plugin_list(self):
        return self.__pm.builtin_plugin_list

    def get_custom_plugin_list(self):
        return self.__pm.custom_plugin_list

    def get_plugin(self, name):
        return self.__pm.plugins[name] if name in self.__pm.plugin_list else None

    def stop_bot(self):
        self.log(u'Вызов функции остановки', 0)
        self.__bot.runtime_error = 0

    def set_startup_response(self, response):
        self.__bot.startup_response = response

    def restart_bot(self):
        self.log(u'Вызов функции перезагрузки', 0)
        self.__bot.runtime_error = 1<commit_msg>Fixed errors if .pyo or .pyc plugin files missing<commit_after># coding:utf8

import os
import imp
import time
import types
import random
import traceback

from .. import utils

def default_plugin__accept_request(self, msg, rsp, utils, *args, **kwargs):
    if msg.was_appeal and msg.args[0].lower() in self.keywords:
        return True

    return False

class Pluginmanager(object):
    def __init__(self, bot, vkr):
        self.plugins = {}
        self.plugin_list = []
        self.builtin_plugin_list = []
        self.custom_plugin_list = []
        self.log = lambda *x, **y: None
        self.bot = bot
        self.utils = PluginUtils(self, self.bot, vkr, self.log)

    def plugin_respond(self, msg, rsp):
        for name in self.plugin_list:
            if not self.plugins[name]._accept_request(msg, rsp, self.utils):
                continue

            user_access_level = self.utils.get_user_access_level(msg)

            if user_access_level < self.plugins[name].protection:
                rsp.text = (
                    u'Для использования команды необходим уровень доступа %d.\n'
                    u'Ваш уровень доступа: %d'
                        % (self.plugins[name].protection, user_access_level)
                )
                break

            if self.plugins[name].argument_required:
                if len(msg.args) < 2:
                    rsp.text = \
                        u'Эту команду можно использовать только с аргументом'
                    break

            rsp = self.plugins[name].respond(msg, rsp, self.utils)
            break

        return rsp

    def load_plugins(self):
        self.plugins = {}
        self.plugin_list = []
        self.builtin_plugin_list = []
        self.custom_plugin_list = []

        if not os.path.exists(utils.CUSTOM_PLUGIN_DIR):
            self.log(
                u'Создание директории для пользовательских плагинов: %s ...'
                    % utils.CUSTOM_PLUGIN_DIR, 1
            )
            os.mkdir(utils.CUSTOM_PLUGIN_DIR)

        self.log(u'Чтение встроенных плагинов ...', 0)
        self._load_plugins_from(utils.PLUGIN_DIR)

        for p in self.plugins:
            self.builtin_plugin_list.append(p)

        self.log(u'Чтение пользовательских плагинов ...', 1)
        self._load_plugins_from(utils.CUSTOM_PLUGIN_DIR)

        for p in sorted(self.plugins, key=lambda x: self.plugins[x].priority,
                        reverse=True):
            self.plugin_list.append(p)

        self.builtin_plugin_list = set(self.builtin_plugin_list)

        self.custom_plugin_list = \
            set(set(self.plugin_list) - self.builtin_plugin_list)

        self.log(
            u'Загружены плагины: [b]%s[/b]' % ', '.join(self.plugin_list), 0)

    def _load_plugins_from(self, path):
        files = sorted(os.listdir(path))  # sorting to ensure that .py goes first
        included = []

        for f in files:
            if f.startswith('plugin_'):
                try:
                    if f.endswith('.py'):
                        if f + 'c' in files:
                            if os.path.getmtime(os.path.join(path, f + 'c')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyc newer
                                continue

                        elif f + 'o' in files:
                            if os.path.getmtime(os.path.join(path, f + 'o')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyo newer
                                continue

                        self._add_plugin(
                            imp.load_source('', os.path.join(path, f)), f, f[7:-3])

                        included.append(f)

                    elif f.endswith('.pyc') or f.endswith('.pyo'):
                        if f[:-1] in included:
                            continue

                        if f.endswith('c') and f[:-1] + 'o' in files:
                            if os.path.getmtime(os.path.join(path, f[:-1] + 'o')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyo newer
                                continue
                        elif f[:-1] + 'c' in files:
                            if os.path.getmtime(os.path.join(path, f[:-1] + 'c')) > os.path.getmtime(os.path.join(path, f)):
                                # .pyc newer
                                continue

                        self._add_plugin(
                            imp.load_compiled('', os.path.join(path, f)), f, f[7:-4])

                        included.append(f[:-1])

                except Exception:
                    self.log(u'[b]Ошибка при загрузке плагина %s[/b]' % f, 2)
                    self.log(traceback.format_exc().decode('utf8'), 2)

    def _add_plugin(self, plugin, f, name):
        p = plugin.Plugin()

        if getattr(p, 'disabled', False):
            return

        if getattr(p, 'name', None) is None:
            self.log(
                u'[b]Предупреждение: отсутствует имя модуля %s. Использую %s[/b]'
                    % (f, name), 1
            )
            p.name = name

        if len(getattr(p, 'keywords', ())) == 0:
            self.log(u'[b]Ошибка: Нет ключевых слов для модуля %s[/b]' % f, 1)
            return

        if getattr(p, '__doc__', None) is None:
            self.log(
                u'[b]Предупреждение: модуль %s не имеет документации[/b]' % f, 1
            )
            p.__doc__ = ''

        if not hasattr(p, 'protection'):
            self.log(
                u'[b]Предупреждение: модуль %s не имеет информации о защите. '
                u'Использую 0[/b]' % f, 1
            )
            p.protection = 0

        if not hasattr(p, 'argument_required'):
            self.log(
                u'[b]Предупреждение: модуль %s не имеет информации о '
                u'необходимости аргумента. Использую False[/b]' % f, 1
            )
            p.argument_required = False

        if not hasattr(p, 'priority'):
            p.priority = 0

        if not hasattr(p, '_accept_request'):
            p._accept_request = \
                types.MethodType(default_plugin__accept_request, p)

        if p.name in self.plugins:
            self.log(
                u'Предупреждение: модуль [b]%s[/b] будет переназначен ...' %
                p.name, 1)

            if p.name in self.builtin_plugin_list:
                self.builtin_plugin_list.remove(p.name)

            if p.name in self.custom_plugin_list:
                self.custom_plugin_list.remove(p.name)

        self.plugins[name] = p

    def set_logging_function(self, logging_function):
        self.log = logging_function
        self.utils.log = logging_function
        self.log(u'Подключена функция логгирования для менеджера плагинов', 0)

class PluginUtils(object):
    """This class contains all nesessary utils for plugins
    """

    def __init__(self, pm, bot, vkr, log):
        self.__pm = pm
        self.__bot = bot
        self.vkr = vkr
        self.log = log

    def get_settings(self):
        return self.__bot.settings

    def get_blacklist(self):
        return self.__bot.blacklist

    def get_whitelist(self):
        return self.__bot.whitelist

    def get_custom_commands(self):
        return self.__bot.custom_commands

    def get_settings(self, key, section='Plugins'):
        return utils.get_settings(key, section=section)

    def save_setting(self, key, val, section='Plugins'):
        self.log(u'Обновляю настройки: %s=%s' % (key, val), 0)
        utils.save_setting(key, val, section=section)

        if key in self.__bot.settings:
            self.__bot.settings[key] = val

        self.__bot.is_settings_changed = True

    def save_blacklist(self, blacklist):
        utils.save_blacklist(blacklist)
        self.__bot.blacklist = blacklist

    def save_whitelist(self, whitelist):
        utils.save_whitelist(whitelist)
        self.__bot.whitelist = whitelist

    def save_custom_commands(self, custom_commands):
        utils.save_custom_commands(custom_commands)
        self.__bot.custom_commands = custom_commands

    def clear_message_queue(self):
        self.__bot.mlpd = None

    def get_user_access_level(self, msg):
        whitelist = self.get_whitelist()

        if msg.out:
            user_access_level = 4
        elif msg.real_user_id in whitelist:
            user_access_level = whitelist[msg.real_user_id]
        else:
            user_access_level = 0

        return user_access_level

    def safe_format(self, *args, **kwargs):
        return utils.safe_format(*args, **kwargs)

    def get_plugin_list(self):
        return self.__pm.plugin_list

    def get_builtin_plugin_list(self):
        return self.__pm.builtin_plugin_list

    def get_custom_plugin_list(self):
        return self.__pm.custom_plugin_list

    def get_plugin(self, name):
        return self.__pm.plugins[name] if name in self.__pm.plugin_list else None

    def stop_bot(self):
        self.log(u'Вызов функции остановки', 0)
        self.__bot.runtime_error = 0

    def set_startup_response(self, response):
        self.__bot.startup_response = response

    def restart_bot(self):
        self.log(u'Вызов функции перезагрузки', 0)
        self.__bot.runtime_error = 1<|endoftext|>


<commit_before>import regex

from globalvars import GlobalVars
from helpers import log

def load_blacklists():
    with open("bad_keywords.txt", "r", encoding="utf-8") as f:
        GlobalVars.bad_keywords = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("blacklisted_websites.txt", "r", encoding="utf-8") as f:
        GlobalVars.blacklisted_websites = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("blacklisted_usernames.txt", "r", encoding="utf-8") as f:
        GlobalVars.blacklisted_usernames = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("watched_keywords.txt", "r", encoding="utf-8") as f:
        GlobalVars.watched_keywords = dict()
        for lineno, line in enumerate(f, 1):
            if regex.compile('^\s*(?:#|$)').match(line):
                continue
            try:
                when, by_whom, what = line.rstrip().split('\t')
            except ValueError as err:
                log('error', '{0}:{1}:{2}'.format(
                    'watched_keywords.txt', lineno, err))
                continue
            GlobalVars.watched_keywords[what] = {'when': when, 'by': by_whom}
<commit_msg>put watched keywords in an OrderedDict<commit_after>from collections import OrderedDict
import regex

from globalvars import GlobalVars
from helpers import log

def load_blacklists():
    with open("bad_keywords.txt", "r", encoding="utf-8") as f:
        GlobalVars.bad_keywords = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("blacklisted_websites.txt", "r", encoding="utf-8") as f:
        GlobalVars.blacklisted_websites = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("blacklisted_usernames.txt", "r", encoding="utf-8") as f:
        GlobalVars.blacklisted_usernames = [line.rstrip() for line in f if len(line.rstrip()) > 0]
    with open("watched_keywords.txt", "r", encoding="utf-8") as f:
        GlobalVars.watched_keywords = OrderedDict()
        for lineno, line in enumerate(f, 1):
            if regex.compile('^\s*(?:#|$)').match(line):
                continue
            try:
                when, by_whom, what = line.rstrip().split('\t')
            except ValueError as err:
                log('error', '{0}:{1}:{2}'.format(
                    'watched_keywords.txt', lineno, err))
                continue
            GlobalVars.watched_keywords[what] = {'when': when, 'by': by_whom}
<|endoftext|>


<commit_before>"""
Utility functions used for url download, file extract, data parsing, etc.
"""

from __future__ import print_function
from .string_ascii import str_to_ascii, ascii_to_str, convert_str_to_ascii, convert_ascii_to_str
from .file_extraction import extract_file
from .file_load import load_matlab, load_json, load_pickle
from .md5hash import check_file_integrity_md5, get_hash_value
from .os_funs import *
from .download_url import download_file

def download_extract_all(urls, md5sum, dir_save, clean_cache=False, verbose=True):
    """Download urls + extract files to disk.

    Download + extract all url files to disk. If clean_cache is
    True, it removes the download files.

    Parameters
    ----------
    urls : list
        List of URL paths.
    md5sum : list
        List of md5 checksum strings for each url.
    dir_save : str
        Directory path to store the data.
    clean_cache : bool
        Remove downloaded files and keep only the extracted data.
    verbose : bool
        Display messages on screen.

    Returns
    -------
        None

    Raises
    ------
        None
    """
    # Check if urls is a str
    if isinstance(urls, str):
        urls = [urls]

    # check if the save directory exists
    if not os.path.exists(dir_save):
        create_dir(dir_save)

    # download + extract data and remove temporary files
    for i, url in enumerate(urls):
        if verbose:
            print('({}/{}) Download url: {}'.format(i+1, len(urls), url))

        # get download save filename
        fname_save = os.path.join(dir_save, os.path.basename(url))

        # download file
        if download_file(url, dir_save, fname_save, verbose) and verbose:
            print('File already exists, skip downloading this url.')
            continue

        # check md5 sum (if available)
        if any(md5sum):
            if not check_file_integrity_md5(fname_save, md5sum):
                print('**WARNING**: md5 checksum does not match for file: {}'.format(fname_save))
                print('MD5 checksum(File/reference): {} - {}'.format(get_hash_value(fname_save), md5sum))

        # extract file
        extract_file(fname_save, dir_save, verbose)

        # remove downloaded file (if triggered by the user)
        if clean_cache:
            delete_file(fname_save)
<commit_msg>add xml file load option<commit_after>"""
Utility functions used for url download, file extract, data parsing, etc.
"""

from __future__ import print_function
from .string_ascii import str_to_ascii, ascii_to_str, convert_str_to_ascii, convert_ascii_to_str
from .file_extraction import extract_file
from .file_load import load_matlab, load_json, load_pickle, load_xml
from .md5hash import check_file_integrity_md5, get_hash_value
from .os_funs import *
from .download_url import download_file

def download_extract_all(urls, md5sum, dir_save, clean_cache=False, verbose=True):
    """Download urls + extract files to disk.

    Download + extract all url files to disk. If clean_cache is
    True, it removes the download files.

    Parameters
    ----------
    urls : list
        List of URL paths.
    md5sum : list
        List of md5 checksum strings for each url.
    dir_save : str
        Directory path to store the data.
    clean_cache : bool
        Remove downloaded files and keep only the extracted data.
    verbose : bool
        Display messages on screen.

    Returns
    -------
        None

    Raises
    ------
        None
    """
    # Check if urls is a str
    if isinstance(urls, str):
        urls = [urls]

    # check if the save directory exists
    if not os.path.exists(dir_save):
        create_dir(dir_save)

    # download + extract data and remove temporary files
    for i, url in enumerate(urls):
        if verbose:
            print('({}/{}) Download url: {}'.format(i+1, len(urls), url))

        # get download save filename
        fname_save = os.path.join(dir_save, os.path.basename(url))

        # download file
        if download_file(url, dir_save, fname_save, verbose) and verbose:
            print('File already exists, skip downloading this url.')
            continue

        # check md5 sum (if available)
        if any(md5sum):
            if not check_file_integrity_md5(fname_save, md5sum):
                print('**WARNING**: md5 checksum does not match for file: {}'.format(fname_save))
                print('MD5 checksum(File/reference): {} - {}'.format(get_hash_value(fname_save), md5sum))

        # extract file
        extract_file(fname_save, dir_save, verbose)

        # remove downloaded file (if triggered by the user)
        if clean_cache:
            delete_file(fname_save)
<|endoftext|>


<commit_before>"""
Split a video file into chapters by detecting fade/cut to black

Script file should look like this. Note that as long as the INPUT
directive is found, everything else can be ignored.

# Path to input file (note that comments are ignored)
INPUT=/path/to/inputfile.mkv
# Optional blackness threshold (a pixel is black if darker than this)
# pixel_black_th=0.10
# Optional picture blackness threshold (a frame is black if this many
# of its pixels are considered black)
# picture_black_ratio_th=0.98
# Optional blackness duration to define a segment. Once we have this much
# blackness, we count a new segment. The default (2.0) is usually too long.
black_min_duration=0.25
# Rather than reprobe the file repeatedly, save the ffprobe result to a file.
# If any of the blackdetect parameters change, the cache will be discarded.
# Note that the cache file can store data from multiple input files and/or
# multiple blackness detection schemes independently.
cache_file=some_file.json
# Create output file names with a pattern for convenience. Use {n} for the
# file name (numbered from 1 with the first output that isn't "--"), and
# the description given on the output line is {desc}.
# output_format={n:02d} - {desc}
# Numbering for the output file names starts at this index:
# first_track=1

# After this are all the chapter definitions.

# Write a single chapter to this file
OUTPUT=1,chapter1.mkv
# Skip one chapter
OUTPUT=1,--
# There's a black moment inside this logical chapter, so write out two
# consecutive chapters as a single file.
OUTPUT=2,chapter2.mkv
# Etc. If blacksplit.py is run with the --append parameter, it will
# add null entries to this file, annotated with timing marker comments,
# and specifying no output; all you have to do is edit the file names
# (and possibly merge some if necessary).
"""
import json
import os
import subprocess

# Abuse of __doc__ :)
class BadScriptFile(Exception): "Unknown error (shouldn't happen)"
class UnknownDirective(BadScriptFile): "Unrecognized directive %r on line %d"
class MissingInput(BadScriptFile): "No INPUT=filename found"
class BadInput(BadScriptFile): "Input file not found - %r on line %d"
class BadOutput(BadScriptFile): "Invalid OUTPUT directive %r on line %d"

def human_time(s):
	"""Convert floating-point seconds into human-readable time"""
	if s < 60.0: return "%.3f" % s
	m = int(s) / 60
	if m < 60: return "%d:%06.3f" % (m, s % 60)
	return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60)

def black_split(script, append_unknowns):
	cfg = {
		"pixel_black_th": "0.10", # Same defaults as ffmpeg uses
		"picture_black_ratio_th": "0.98",
		"black_min_duration": "2.0",
		"cache_file": None,
		"first_track": "1",
		"output_format": "{n:02d} - {desc}",
	}
	inputs, outputs = [], []

	with open(script) as f:
		for pos, line in enumerate(f, 1):
			line = line.split("#")[0].strip() # yeah it's naive, no quoting of hashes
			if not line: continue
			if "=" in line:
				key, val = line.split("=", 1)
				if key in cfg: cfg[key] = val
				elif key == "INPUT":
					try: os.stat(val)
					except FileNotFoundError: raise BadInput(val, pos) from None
					inputs.append(val)
				elif key == "OUTPUT":
					if "," not in val: raise BadOutput(line, pos)
					count, fn = val.split(",", 1)
					try: count = int(count)
					except ValueError: raise BadOutput(line, pos)
					if count < 1: raise BadOutput(line, pos)
					# If count is 3, add two Ellipsis entries and then the file name
					outputs.extend([...] * (count - 1))
					outputs.append(fn)
				else: raise UnknownDirective(line, pos)
	if not inputs: raise MissingInput
	min_black = float(cfg["black_min_duration"]) # ValueError if bad duration format
	bdparams = ":".join(f"{k}={cfg[k]}" for k in "pixel_black_th picture_black_ratio_th black_min_duration".split())
	cache = { }
	if cfg["cache_file"]:
		try:
			with open(cfg["cache_file"]) as f:
				cache = json.load(f)
			if not isinstance(cache, dict): cache = { }
		except FileNotFoundError:
			pass
	file_no = int(cfg["first_track"])
	for inputfile in inputs:
		cache_key = "%r-%r" % (inputfile, bdparams)
		if cache_key not in cache:
			print("Finding blackness...") # Hello, blackness, my old... friend??
			with subprocess.Popen([
				"ffprobe", "-f", "lavfi",
				"-i", f"movie={inputfile},blackdetect={bdparams}[out0]",
				"-show_entries", "tags=lavfi.black_start,lavfi.black_end",
				"-of", "default=nw=1", "-hide_banner",
			], stdout=subprocess.PIPE, text=True) as proc:
				cache[cache_key] = []
				for line in proc.stdout:
					# TODO: Provide some sort of progress indication?
					# It'd be jerky (emitting only when a blackness is
					# found), but better than nothing.
					cache[cache_key].append(line.rstrip("\n"))
			if cfg["cache_file"]:
				with open(cfg["cache_file"], "w") as f:
					json.dump(cache, f, sort_keys=True, indent=4)
				print("Saved to cache for next time.")
		last_start = last_end = None
		last_end = 0.0
		output_idx = 0
		for line in cache[cache_key]:
			if "=" not in line: continue
			key, val = line.split("=", 1)
			# NOTE: The lines sometimes appear to be duplicated. Don't get thrown off by this.
			if key == "TAG:lavfi.black_start": last_start = float(val)
			if key == "TAG:lavfi.black_end" and last_start is not None:
				start, end, last_start = last_start, float(val), None
				if end - start < min_black: continue
				output_idx += 1 # Using 1-based indexing for human convenience
				# NOTE: The "start" and "end" are of the blackness. A chapter runs from
				# last_end to start, spanning the time of non-blackness between the black.
				if output_idx > len(outputs):
					fr, to, dur = human_time(last_end), human_time(start), human_time(start - last_end)
					if append_unknowns:
						with open(script, "a") as f:
							print("# Chapter %d: from %s to %s ==> %s" % (output_idx, fr, to, dur), file=f)
							print("OUTPUT=1,--", file=f)
					print("New chapter: from %s to %s, %s" % (fr, to, dur))
					last_end = end
					continue
				output = outputs[output_idx - 1]
				if output is ...:
					# Continue this into the next one.
					# That's actually quite simple; we just don't change last_end,
					# meaning that the start of the next block will include this.
					continue
				if output != "--": # An output of "--" means no file to create
					output = cfg["output_format"].format(n=file_no, desc=output)
					print("Creating:", output)
					file_no += 1
					subprocess.run([
						"ffmpeg", "-i", inputfile,
						"-ss", str(last_end), "-t", str(start - last_end),
						"-c", "copy", output,
						"-y", "-loglevel", "quiet", "-stats",
					], check=True)
				last_end = end
	print("To chain another file:")
	print("first_track=%d" % file_no)

if __name__ == "__main__":
	import sys
	append = "--append" in sys.argv
	args = [a for a in sys.argv[1:] if not a.startswith("--")]
	if "--help" in sys.argv or not args:
		print("USAGE: python3 %s scriptfile" % sys.argv[0])
		print("For scriptfile format, see docstring")
		sys.exit(0)
	for fn in args:
		try:
			black_split(fn, append)
		except BadScriptFile as e:
			print(e.__doc__ % e.args)
			break
<commit_msg>blacksplit: Prefix any appended blocks<commit_after>"""
Split a video file into chapters by detecting fade/cut to black

Script file should look like this. Note that as long as the INPUT
directive is found, everything else can be ignored.

# Path to input file (note that comments are ignored)
INPUT=/path/to/inputfile.mkv
# Optional blackness threshold (a pixel is black if darker than this)
# pixel_black_th=0.10
# Optional picture blackness threshold (a frame is black if this many
# of its pixels are considered black)
# picture_black_ratio_th=0.98
# Optional blackness duration to define a segment. Once we have this much
# blackness, we count a new segment. The default (2.0) is usually too long.
black_min_duration=0.25
# Rather than reprobe the file repeatedly, save the ffprobe result to a file.
# If any of the blackdetect parameters change, the cache will be discarded.
# Note that the cache file can store data from multiple input files and/or
# multiple blackness detection schemes independently.
cache_file=some_file.json
# Create output file names with a pattern for convenience. Use {n} for the
# file name (numbered from 1 with the first output that isn't "--"), and
# the description given on the output line is {desc}.
# output_format={n:02d} - {desc}
# Numbering for the output file names starts at this index:
# first_track=1

# After this are all the chapter definitions.

# Write a single chapter to this file
OUTPUT=1,chapter1.mkv
# Skip one chapter
OUTPUT=1,--
# There's a black moment inside this logical chapter, so write out two
# consecutive chapters as a single file.
OUTPUT=2,chapter2.mkv
# Etc. If blacksplit.py is run with the --append parameter, it will
# add null entries to this file, annotated with timing marker comments,
# and specifying no output; all you have to do is edit the file names
# (and possibly merge some if necessary).
"""
import json
import os
import subprocess

# Abuse of __doc__ :)
class BadScriptFile(Exception): "Unknown error (shouldn't happen)"
class UnknownDirective(BadScriptFile): "Unrecognized directive %r on line %d"
class MissingInput(BadScriptFile): "No INPUT=filename found"
class BadInput(BadScriptFile): "Input file not found - %r on line %d"
class BadOutput(BadScriptFile): "Invalid OUTPUT directive %r on line %d"

def human_time(s):
	"""Convert floating-point seconds into human-readable time"""
	if s < 60.0: return "%.3f" % s
	m = int(s) / 60
	if m < 60: return "%d:%06.3f" % (m, s % 60)
	return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60)

def black_split(script, append_unknowns):
	cfg = {
		"pixel_black_th": "0.10", # Same defaults as ffmpeg uses
		"picture_black_ratio_th": "0.98",
		"black_min_duration": "2.0",
		"cache_file": None,
		"first_track": "1",
		"output_format": "{n:02d} - {desc}",
	}
	inputs, outputs = [], []

	with open(script) as f:
		for pos, line in enumerate(f, 1):
			line = line.split("#")[0].strip() # yeah it's naive, no quoting of hashes
			if not line: continue
			if "=" in line:
				key, val = line.split("=", 1)
				if key in cfg: cfg[key] = val
				elif key == "INPUT":
					try: os.stat(val)
					except FileNotFoundError: raise BadInput(val, pos) from None
					inputs.append(val)
				elif key == "OUTPUT":
					if "," not in val: raise BadOutput(line, pos)
					count, fn = val.split(",", 1)
					try: count = int(count)
					except ValueError: raise BadOutput(line, pos)
					if count < 1: raise BadOutput(line, pos)
					# If count is 3, add two Ellipsis entries and then the file name
					outputs.extend([...] * (count - 1))
					outputs.append(fn)
				else: raise UnknownDirective(line, pos)
	if not inputs: raise MissingInput
	min_black = float(cfg["black_min_duration"]) # ValueError if bad duration format
	bdparams = ":".join(f"{k}={cfg[k]}" for k in "pixel_black_th picture_black_ratio_th black_min_duration".split())
	cache = { }
	if cfg["cache_file"]:
		try:
			with open(cfg["cache_file"]) as f:
				cache = json.load(f)
			if not isinstance(cache, dict): cache = { }
		except FileNotFoundError:
			pass
	file_no = int(cfg["first_track"])
	for inputfile in inputs:
		cache_key = "%r-%r" % (inputfile, bdparams)
		if cache_key not in cache:
			print("Finding blackness...") # Hello, blackness, my old... friend??
			with subprocess.Popen([
				"ffprobe", "-f", "lavfi",
				"-i", f"movie={inputfile},blackdetect={bdparams}[out0]",
				"-show_entries", "tags=lavfi.black_start,lavfi.black_end",
				"-of", "default=nw=1", "-hide_banner",
			], stdout=subprocess.PIPE, text=True) as proc:
				cache[cache_key] = []
				for line in proc.stdout:
					# TODO: Provide some sort of progress indication?
					# It'd be jerky (emitting only when a blackness is
					# found), but better than nothing.
					cache[cache_key].append(line.rstrip("\n"))
			if cfg["cache_file"]:
				with open(cfg["cache_file"], "w") as f:
					json.dump(cache, f, sort_keys=True, indent=4)
				print("Saved to cache for next time.")
		last_start = last_end = None
		last_end = 0.0
		output_idx = 0
		append_desc = "# %s:\n" % inputfile
		for line in cache[cache_key]:
			if "=" not in line: continue
			key, val = line.split("=", 1)
			# NOTE: The lines sometimes appear to be duplicated. Don't get thrown off by this.
			if key == "TAG:lavfi.black_start": last_start = float(val)
			if key == "TAG:lavfi.black_end" and last_start is not None:
				start, end, last_start = last_start, float(val), None
				if end - start < min_black: continue
				output_idx += 1 # Using 1-based indexing for human convenience
				# NOTE: The "start" and "end" are of the blackness. A chapter runs from
				# last_end to start, spanning the time of non-blackness between the black.
				if output_idx > len(outputs):
					fr, to, dur = human_time(last_end), human_time(start), human_time(start - last_end)
					if append_unknowns:
						with open(script, "a") as f:
							print("%s# Chapter %d: from %s to %s ==> %s" %
								(append_desc, output_idx, fr, to, dur), file=f)
							print("OUTPUT=1,--", file=f)
							append_desc = ""
					print("New chapter: from %s to %s, %s" % (fr, to, dur))
					last_end = end
					continue
				output = outputs[output_idx - 1]
				if output is ...:
					# Continue this into the next one.
					# That's actually quite simple; we just don't change last_end,
					# meaning that the start of the next block will include this.
					continue
				if output != "--": # An output of "--" means no file to create
					output = cfg["output_format"].format(n=file_no, desc=output)
					print("Creating:", output)
					file_no += 1
					subprocess.run([
						"ffmpeg", "-i", inputfile,
						"-ss", str(last_end), "-t", str(start - last_end),
						"-c", "copy", output,
						"-y", "-loglevel", "quiet", "-stats",
					], check=True)
				last_end = end
	print("To chain another file:")
	print("first_track=%d" % file_no)

if __name__ == "__main__":
	import sys
	append = "--append" in sys.argv
	args = [a for a in sys.argv[1:] if not a.startswith("--")]
	if "--help" in sys.argv or not args:
		print("USAGE: python3 %s scriptfile" % sys.argv[0])
		print("For scriptfile format, see docstring")
		sys.exit(0)
	for fn in args:
		try:
			black_split(fn, append)
		except BadScriptFile as e:
			print(e.__doc__ % e.args)
			break
<|endoftext|>


<commit_before>try:
    import keystone
    import capstone
    KEYSTONE = True
except ImportError:
    KEYSTONE = False

from .__base__ import AsmBase

class DeenPluginAsmArm(AsmBase):
    name = 'assembly_arm'
    display_name = 'ARM'
    aliases = ['asm_arm',
               'asmarm',
               'assemble_arm',
               'assemblearm',
               'arm']
    cmd_name = 'assembly_arm'
    cmd_help='Assemble/Disassemble for the ARM architecture'
    keystone_arch = keystone.KS_ARCH_ARM
    keystone_mode = keystone.KS_MODE_ARM
    capstone_arch = capstone.CS_ARCH_ARM
    capstone_mode = capstone.CS_MODE_ARM

    def __init__(self):
        super(DeenPluginAsmArm, self).__init__()
        # Initialize keystone and capstone as soon as an instance
        # of this plugin will be created.
        self.ks = keystone.Ks(self.keystone_arch, self.keystone_mode)
        self.cs = capstone.Cs(self.capstone_arch, self.capstone_mode)

class DeenPluginAsmArmThumb(AsmBase):
    name = 'assembly_armthumb'
    display_name = 'ARM Thumb'
    aliases = ['asm_armthumb',
               'thumb']
    cmd_name = 'assembly_armthumb'
    cmd_help='Assemble/Disassemble for the ARM architecture with Thumb instructions'
    keystone_arch = keystone.KS_ARCH_ARM
    keystone_mode = keystone.KS_MODE_THUMB
    capstone_arch = capstone.CS_ARCH_ARM
    capstone_mode = capstone.CS_MODE_THUMB

    def __init__(self):
        super(DeenPluginAsmArmThumb, self).__init__()
        # Initialize keystone and capstone as soon as an instance
        # of this plugin will be created.
        self.ks = keystone.Ks(self.keystone_arch, self.keystone_mode)
        self.cs = capstone.Cs(self.capstone_arch, self.capstone_mode)
<commit_msg>Reimplemented ARM assemblies with new base class<commit_after>try:
    import keystone
    import capstone
    KEYSTONE = True
except ImportError:
    KEYSTONE = False

from .__base__ import AsmBase

class DeenPluginAsmArm(AsmBase):
    name = 'assembly_arm'
    display_name = 'ARM'
    aliases = ['asm_arm',
               'asmarm',
               'assemble_arm',
               'assemblearm',
               'arm']
    cmd_name = 'assembly_arm'
    cmd_help='Assemble/Disassemble for the ARM architecture'
    keystone_arch = keystone.KS_ARCH_ARM
    keystone_mode = keystone.KS_MODE_ARM
    capstone_arch = capstone.CS_ARCH_ARM
    capstone_mode = capstone.CS_MODE_ARM

    @staticmethod
    def add_argparser(argparser, cmd_name, cmd_help, cmd_aliases=None):
        # Add an additional argument for big endian mode.
        parser = AsmBase.add_argparser(argparser, cmd_name,
                                       cmd_help, cmd_aliases=cmd_aliases)
        parser.add_argument('-b', '--big-endian', dest='bigendian',
                            default=False, help='use big endian',
                            action='store_true')

class DeenPluginAsmArmThumb(AsmBase):
    name = 'assembly_armthumb'
    display_name = 'ARM Thumb'
    aliases = ['asm_armthumb',
               'thumb']
    cmd_name = 'assembly_armthumb'
    cmd_help='Assemble/Disassemble for the ARM architecture with Thumb instructions'
    keystone_arch = keystone.KS_ARCH_ARM
    keystone_mode = keystone.KS_MODE_THUMB
    capstone_arch = capstone.CS_ARCH_ARM
    capstone_mode = capstone.CS_MODE_THUMB

    @staticmethod
    def add_argparser(argparser, cmd_name, cmd_help, cmd_aliases=None):
        # Add an additional argument for big endian mode.
        parser = AsmBase.add_argparser(argparser, cmd_name,
                                       cmd_help, cmd_aliases=cmd_aliases)
        parser.add_argument('-b', '--big-endian', dest='bigendian',
                            default=False, help='use big endian',
                            action='store_true')
<|endoftext|>