@classmethod
def decode_conjure_bean_type(cls, obj, conjure_type):
    """Decodes json into a conjure bean type (a plain bean, not enum
        or union).

        Args:
            obj: the json object to decode
            conjure_type: a class object which is the bean type
                we're decoding into
        Returns:
            A instance of a bean of type conjure_type.
        """
    deserialized = {}
    for python_arg_name, field_definition in conjure_type._fields().items():
        field_identifier = field_definition.identifier
        if field_identifier not in obj or obj[field_identifier] is None:
            cls.check_null_field(obj, deserialized, python_arg_name,
                field_definition)
        else:
            value = obj[field_identifier]
            field_type = field_definition.field_type
            deserialized[python_arg_name] = cls.do_decode(value, field_type)
    return conjure_type(**deserialized)


@classmethod
def get_common_names(cls, other):
    """Returns array member names common to both classes."""
    return list(set(cls._get_array_member_names()) & set(other.
        _get_array_member_names()))


def fullstop(sentence: str, punct: str='.') ->str:
    """adds a fullstop to the end of a sentence if needed"""
    sentence = sentence.rstrip()
    if sentence.endswith(('!', '?', '.', ';', ':', '-', '=')):
        return sentence
    return sentence + punct


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


@classmethod
def shared_content_remove_member_details(cls, val):
    """
        Create an instance of this class set to the
        ``shared_content_remove_member_details`` tag with value ``val``.

        :param SharedContentRemoveMemberDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_remove_member_details', val)


def get_occurrence_times_for_event(event):
    """
    Return a tuple with two sets containing the (start, end) datetimes of an
    Event's Occurrences, or the original start datetime if an Occurrence's
    start was modified by a user.
    """
    occurrences_starts = set()
    occurrences_ends = set()
    for start, original_start, end, original_end in event.occurrences.all(
        ).values_list('start', 'original_start', 'end', 'original_end'):
        occurrences_starts.add(original_start or start)
        occurrences_ends.add(original_end or end)
    return occurrences_starts, occurrences_ends


def send_warnings_and_remove():
    """Send warnings to disabled users and remove them if needed.

        All users, that have their delivery disabled, get warnings about being
        un-subscribed until Mailinglist's maximum configured numbered of
        warnings are sent and then remove the user.
        """


def false():
    """
    Returns the logical value FALSE
    """
    return False


def _format_spectrogram(ax, qspecgram, colormap='viridis'):
    """Helper tool to format a `~gwpy.spectrogram.Spectrogram` plot axis
    """
    ax.imshow(qspecgram)
    ax.colorbar(cmap=colormap, norm='linear', clim=(0, 25), label=
        'Normalized energy')
    ax.set_yscale('linear')
    ax.set_ylabel('Frequency [Hz]')
    ax.grid(True, axis='y', which='both')


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def is_int(i):
    """Check if a variable is an `int` type.

    Args:
        i: The object to check.

    Returns:
        :obj:`bool`: If the object can be converted to an :obj:`int`.
    """
    if not i:
        return False
    try:
        int(i)
        return True
    except ValueError:
        return False


def sun_rise_set():
    """
    @api {post} /map/weather/sun_rise_set 日出日落
    @apiVersion 1.0.0
    @apiGroup Weather
    @apiDescription 日出日落

    @apiParam (Headers) {String} token 令牌
    @apiParam (Headers) {String} device_token 设备令牌
    @apiParam (Headers) {String} content_type 内容类型
    @apiParam (Headers) {String} timestamp 时间戳
    @apiParam (Headers) {String} location 经纬度

    @apiSuccess (Success) {Object} basic 基础信息
    @apiSuccess (Success) {String} basic.location 地区／城市名称
    @apiSuccess (Success) {String} basic.cid 地区／城市ID
    @apiSuccess (Success) {String} basic.lat 地区／城市纬度
    @apiSuccess (Success) {String} basic.lon 地区／城市经度
    @apiSuccess (Success) {String} basic.parent_city 该地区／城市的上级城市
    @apiSuccess (Success) {String} basic.admin_area 该地区／城市所属行政区域
    @apiSuccess (Success) {String} basic.cnty 该地区／城市所属国家名称
    @apiSuccess (Success) {String} basic.tz 该地区／城市所在时区
    @apiSuccess (Success) {Object} update 接口更新时间
    @apiSuccess (Success) {String} update.loc 当地时间，24小时制，格式yyyy-MM-dd HH:mm
    @apiSuccess (Success) {String} update.utc UTC时间，24小时制，格式yyyy-MM-dd HH:mm
    @apiSuccess (Success) {String} status 接口状态
    @apiSuccess (Success) {Object} SunriseSunset 日出日落
    @apiSuccess (Success) {String} SunriseSunset.date 预报日期
    @apiSuccess (Success) {String} SunriseSunset.sr 日出时间
    @apiSuccess (Success) {String} SunriseSunset.ss 日落时间
    @apiSuccess (Success) {String} SunriseSunset.mr 月升时间
    @apiSuccess (Success) {String} SunriseSunset.ms 月落时间

    @apiSuccessExample {json} Success-Response:
    {
        "data": [
            {
                "basic": {
                    "cid": "CN101020500",
                    "location": "嘉定",
                    "parent_city": "上海",
                    "admin_area": "上海",
                    "cnty": "中国",
                    "lat": "31.38352394",
                    "lon": "121.25033569",
                    "tz": "+8.00"
                },
                "update": {
                    "loc": "2018-07-17 14:48",
                    "utc": "2018-07-17 06:48"
                },
                "status": "ok",
                "sunrise_sunset": [
                    {
                        "date": "2018-07-17",
                        "mr": "09:24",
                        "ms": "22:20",
                        "sr": "05:02",
                        "ss": "18:59"
                    }
                ]
            }
        ]
    }
    """


@staticmethod
def get_not_implemented():
    """Not implemented warning."""
    return [{'title': 'not implemented'}]


def capture_screen():
    """
    Captures the screen to a Pillow Image object
    """
    from PIL import Image
    import mss
    with mss.mss() as sct:
        for monitor in sct.monitors:
            if monitor['left'] == 0 and monitor['top'] == 0:
                break
        sct_img = sct.grab(monitor)
    img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')
    return img


def stash_and_create():
    """Store this action in the NLA stack as a non-contributing strip for later use, and create a new action

    """
    pass


@staticmethod
def delete(playlist_id):
    """Build a playlist delete event.

		Parameters:
			playlist_id (str): A playlist ID.

		Returns:
			dict: A mutation dict.
		"""
    return {'delete': playlist_id}


@staticmethod
def add_polygon_coordinates(coordinates: list, point: list):
    """Add given point to given coordinates list if is not the equal to the last coordinates."""
    if coordinates:
        last_point = coordinates[-1]
        if last_point[0] == point[0] and last_point[1] == point[1]:
            return
    coordinates.append(point)


def get_campaign(ApplicationId=None, CampaignId=None):
    """
    Returns information about a campaign.

    :example: response = client.get_campaign(
        ApplicationId='string',
        CampaignId='string'
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :type CampaignId: string
    :param CampaignId: [REQUIRED]

    :rtype: dict
    :return: {
        'CampaignResponse': {
            'AdditionalTreatments': [
                {
                    'Id': 'string',
                    'MessageConfiguration': {
                        'APNSMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'DefaultMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'GCMMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        }
                    },
                    'Schedule': {
                        'EndTime': 'string',
                        'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                        'IsLocalTime': True|False,
                        'QuietTime': {
                            'End': 'string',
                            'Start': 'string'
                        },
                        'StartTime': 'string',
                        'Timezone': 'string'
                    },
                    'SizePercent': 123,
                    'State': {
                        'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
                    },
                    'TreatmentDescription': 'string',
                    'TreatmentName': 'string'
                },
            ],
            'ApplicationId': 'string',
            'CreationDate': 'string',
            'DefaultState': {
                'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
            },
            'Description': 'string',
            'HoldoutPercent': 123,
            'Id': 'string',
            'IsPaused': True|False,
            'LastModifiedDate': 'string',
            'Limits': {
                'Daily': 123,
                'Total': 123
            },
            'MessageConfiguration': {
                'APNSMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'DefaultMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'GCMMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                }
            },
            'Name': 'string',
            'Schedule': {
                'EndTime': 'string',
                'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                'IsLocalTime': True|False,
                'QuietTime': {
                    'End': 'string',
                    'Start': 'string'
                },
                'StartTime': 'string',
                'Timezone': 'string'
            },
            'SegmentId': 'string',
            'SegmentVersion': 123,
            'State': {
                'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
            },
            'TreatmentDescription': 'string',
            'TreatmentName': 'string',
            'Version': 123
        }
    }

    :returns:
    (dict) -- 200 response
    CampaignResponse (dict) -- Campaign definition
    AdditionalTreatments (list) -- Treatments that are defined in addition to the default treatment.
    (dict) -- Treatment resource
    Id (string) -- The unique treatment ID.
    MessageConfiguration (dict) -- The message configuration settings.
    APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    DefaultMessage (dict) -- The default message for all channels.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    Schedule (dict) -- The campaign schedule.
    EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
    Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
    IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
    QuietTime (dict) -- The time during which the campaign sends no messages.
    End (string) -- The default end time for quiet time in ISO 8601 format.
    Start (string) -- The default start time for quiet time in ISO 8601 format.

    StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
    Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11

    SizePercent (integer) -- The allocated percentage of users for this treatment.
    State (dict) -- The treatment status.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    TreatmentDescription (string) -- A custom description for the treatment.
    TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.

    ApplicationId (string) -- The ID of the application to which the campaign applies.
    CreationDate (string) -- The date the campaign was created in ISO 8601 format.
    DefaultState (dict) -- The status of the campaign's default treatment. Only present for A/B test campaigns.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    Description (string) -- A description of the campaign.
    HoldoutPercent (integer) -- The allocated percentage of end users who will not receive messages from this campaign.
    Id (string) -- The unique campaign ID.
    IsPaused (boolean) -- Indicates whether the campaign is paused. A paused campaign does not send messages unless you resume it by setting IsPaused to false.
    LastModifiedDate (string) -- The date the campaign was last updated in ISO 8601 format.
    Limits (dict) -- The campaign limits settings.
    Daily (integer) -- The maximum number of messages that the campaign can send daily.
    Total (integer) -- The maximum total number of messages that the campaign can send.

    MessageConfiguration (dict) -- The message configuration settings.
    APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    DefaultMessage (dict) -- The default message for all channels.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    Name (string) -- The custom name of the campaign.
    Schedule (dict) -- The campaign schedule.
    EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
    Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
    IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
    QuietTime (dict) -- The time during which the campaign sends no messages.
    End (string) -- The default end time for quiet time in ISO 8601 format.
    Start (string) -- The default start time for quiet time in ISO 8601 format.

    StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
    Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11

    SegmentId (string) -- The ID of the segment to which the campaign sends messages.
    SegmentVersion (integer) -- The version of the segment to which the campaign sends messages.
    State (dict) -- The campaign status. An A/B test campaign will have a status of COMPLETED only when all treatments have a status of COMPLETED.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    TreatmentDescription (string) -- A custom description for the treatment.
    TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.
    Version (integer) -- The campaign version number.

    """
    pass


def is_mono_repeat(kmer):
    """
    Return true if kmer represents a mono-nucleotide repeat (e.g. AAAA).
    """
    return bool(len(set(kmer)) == 1)


def deserialize_datetime(string):
    """
    Deserializes string to datetime.

    The string should be in iso8601 datetime format.

    :param string: str.
    :type string: str
    :return: datetime.
    :rtype: datetime
    """
    try:
        from dateutil.parser import parse
        return parse(string)
    except ImportError:
        return string


def isindexed(spot_index, indexed_spots_dict):
    """
    return grain index if spot is indexed, otherwise return None
    """
    c = -1
    cg = -2
    if indexed_spots_dict[spot_index][c] == 1:
        return indexed_spots_dict[spot_index][cg]
    else:
        return None


def match_replace_regex(regex, src_namespace, dest_namespace):
    """Return the new mapped namespace if the src_namespace matches the
    regex."""
    match = regex.match(src_namespace)
    if match:
        return dest_namespace.replace('*', match.group(1))
    return None


def first_item(a):
    """
    Return the first item of an iterable.

    Parameters
    ----------
    a : object
        Iterable to get the first item from.

    Returns
    -------
    object

    Raises
    ------
    StopIteration
        If the iterable is empty.

    Examples
    --------
    >>> a = range(10)
    >>> first_item(a)
    0
    """
    return next(iter(a))


def get_evaluation_metrics(targets, predictions):
    """Compute the f1, precision, accuracy and summary report from sklearn."""
    from sklearn import metrics
    report = metrics.classification_report(targets, predictions)
    precision = metrics.precision_score(targets, predictions, average=
        'weighted')
    f1 = metrics.f1_score(targets, predictions, average='weighted')
    accuracy = metrics.accuracy_score(targets, predictions)
    return report, precision, f1, accuracy


def remove_latex_chars_from_arrow(direction):
    """Remove non-filename friendly characters from LaTeX format of direction"""
    return direction.strip('$\\')


def get_merge_direction(cell1, cell2):
    """
    Determine the side of cell1 that can be merged with cell2.

    This is based on the location of the two cells in the table as well
    as the compatability of their height and width.

    For example these cells can merge::

         cell1    cell2      merge "RIGHT"

        +-----+  +------+   +-----+------+
        | foo |  | dog  |   | foo | dog  |
        |     |  +------+   |     +------+
        |     |  | cat  |   |     | cat  |
        |     |  +------+   |     +------+
        |     |  | bird |   |     | bird |
        +-----+  +------+   +-----+------+

    But these cells cannot merge::

        +-----+  +------+
        | foo |  | dog  |
        |     |  +------+
        |     |  | cat  |
        |     |  +------+
        |     |
        +-----+

    Parameters
    ----------
    cell1 : dashtable.data2rst.Cell
    cell2 : dashtable.data2rst.Cell

    Returns
    -------
    str
        The side onto which cell2 can be merged. Will be one of
        ["LEFT", "RIGHT", "BOTTOM", "TOP", "NONE"]
    """
    cell1_left = cell1.column
    cell1_right = cell1.column + cell1.column_count
    cell1_top = cell1.row
    cell1_bottom = cell1.row + cell1.row_count
    cell2_left = cell2.column
    cell2_right = cell2.column + cell2.column_count
    cell2_top = cell2.row
    cell2_bottom = cell2.row + cell2.row_count
    if (cell1_right == cell2_left and cell1_top == cell2_top and
        cell1_bottom == cell2_bottom and cell1.right_sections >= cell2.
        left_sections):
        return 'RIGHT'
    elif cell1_left == cell2_left and cell1_right == cell2_right and cell1_top == cell2_bottom and cell1.top_sections >= cell2.bottom_sections:
        return 'TOP'
    elif cell1_left == cell2_left and cell1_right == cell2_right and cell1_bottom == cell2_top and cell1.bottom_sections >= cell2.top_sections:
        return 'BOTTOM'
    elif cell1_left == cell2_right and cell1_top == cell2_top and cell1_bottom == cell2_bottom and cell1.left_sections >= cell2.right_sections:
        return 'LEFT'
    else:
        return 'NONE'


def select_more():
    """Select more spline points connected to initial selection

    """
    pass


def __contains__(key):
    """Tell if a key exists in the mapping."""


def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1,
    length=100, fill='█'):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ('{0:.' + str(decimals) + 'f}').format(100 * (iteration /
        float(total)))
    print(percent)
    if iteration == total:
        print('')


def state_dict(monitor):
    """
        pytorch-like API. Alias for __getstate__
        """
    return monitor.__getstate__()


def cross_vectors_xy(u, v):
    """Compute the cross product of two vectors, assuming they lie in the XY-plane.

    Parameters
    ----------
    u : sequence of float
        XY(Z) coordinates of the first vector.
    v : sequence of float
        XY(Z) coordinates of the second vector.

    Returns
    -------
    list
        The cross product of the two vectors.
        This vector will be perpendicular to the XY plane.

    Examples
    --------
    >>> cross_vectors_xy([1.0, 0.0], [0.0, 1.0])
    [0.0, 0.0, 1.0]

    >>> cross_vectors_xy([1.0, 0.0, 0.0], [0.0, 1.0, 0.0])
    [0.0, 0.0, 1.0]

    >>> cross_vectors_xy([1.0, 0.0, 1.0], [0.0, 1.0, 1.0])
    [0.0, 0.0, 1.0]

    """
    return [0.0, 0.0, u[0] * v[1] - u[1] * v[0]]


def get_instance_state(instanceName=None):
    """
    Returns the state of a specific instance. Works on one instance at a time.
    See also: AWS API Documentation

    :example: response = client.get_instance_state(
        instanceName='string'
    )

    :type instanceName: string
    :param instanceName: [REQUIRED]
            The name of the instance to get state information about.

    :rtype: dict
    :return: {
        'state': {
            'code': 123,
            'name': 'string'
        }
    }

    """
    pass


def select_mirror(only_active: bool=False, extend: bool=False):
    """Mirror the bone selection

    :param only_active: Active Only, Only operate on the active bone
    :type only_active: bool
    :param extend: Extend, Extend the selection
    :type extend: bool
    """
    pass


def _issubclass(cls, classinfo):
    """
    issubclass() variant that doesn't raise an exception if cls isn't a
    class.
    """
    try:
        return issubclass(cls, classinfo)
    except TypeError:
        return False


def software(software):
    """Method called at `slapos node software` phase.

    :param software: slapos.grid.SlapObject.Software, currently processed software
    """


def circular_indices(vector, start, length, num):
    """docstring for circular_indices"""
    if start > length:
        start = start - length
    if start + num < length:
        return vector[start:start + num]
    return vector[start:] + vector[:start + num - length]


def get_style(document, elem):
    """Get the style for this node element.

    :Args:
      - document (:class:`ooxml.doc.Document`): Document object
      - elem (:class:`ooxml.doc.Element`): Node element

    :Returns:
      Returns :class:`ooxml.doc.Style` object or None if it is not found.
    """
    try:
        return document.styles.get_by_id(elem.style_id)
    except AttributeError:
        return None


def negative(attrs, inputs, proto_obj):
    """Negation of every element in a tensor"""
    return 'negative', attrs, inputs


def train_2d(trainer):
    """Optimize the objective function of 2d variables with a customized trainer."""
    x1, x2 = -5, -2
    s_x1, s_x2 = 0, 0
    res = [(x1, x2)]
    for i in range(20):
        x1, x2, s_x1, s_x2 = trainer(x1, x2, s_x1, s_x2)
        res.append((x1, x2))
    print('epoch %d, x1 %f, x2 %f' % (i + 1, x1, x2))
    return res


@classmethod
def get_business_non_required_fields(cls):
    """
        Get ``set`` of ``non required fields`` for :attr:`.BUSINESS_TYPE`

        Returns:
            ``set`` of fields
        """
    fields = cls.get_non_required_fields()
    return fields.union(super().get_business_non_required_fields(), {
        'business_description', 'business_facebook', 'business_twitter'})


def ipython_profile_name():
    """
    return the name of the current ipython profile or `None`

    Example (add to default RunEngine metadata)::

        RE.md['ipython_profile'] = str(ipython_profile_name())
        print("using profile: " + RE.md['ipython_profile'])

    """
    from IPython import get_ipython
    return get_ipython().profile


def kmeans_missing(xx_, no_clusters, max_iter=30):
    """Perform K-Means clustering on data with missing values.
    Found it in stackoverflow
    Argumentss:
      xx_:            An [n_samples, n_features] array of data to cluster.
      n_clusters:   Number of clusters to form.
      max_iter:     Maximum number of EM iterations to perform.

    Returns:
      labels:       An [n_samples] vector of integer labels.
      centroids:    An [n_clusters, n_features] array of cluster centroids.
      x_hat:        Copy of xx_ with the missing values filled in.
    """
    from sklearn.cluster import KMeans
    import numpy as np
    prev_centroids = []
    prev_labels = []
    missing = ~np.isfinite(xx_)
    mu_ = np.nanmean(xx_, 0, keepdims=1)
    x_hat = np.where(missing, mu_, xx_)
    for cc_ in np.arange(max_iter):
        if cc_ > 0:
            cls = KMeans(no_clusters, init=prev_centroids)
        else:
            cls = KMeans(no_clusters, n_jobs=-1)
        labels = cls.fit_predict(x_hat)
        centroids = cls.cluster_centers_
        x_hat[missing] = centroids[labels][missing]
        if cc_ > 0 and np.all(labels == prev_labels):
            break
        prev_labels = labels
        prev_centroids = cls.cluster_centers_
    return labels, centroids, x_hat


def __get_tile_dataset(_query_uri):
    """This function identifies the appropriate tile dataset."""
    if 'categories' in _query_uri:
        _dataset = 'tile_category'
    else:
        _dataset = 'tile'
    return _dataset


def fpAdd(_rm, a, b):
    """
    Returns the addition of two floating point numbers, `a` and `b`.
    """
    return a + b


def nato(phonetic_dict, in_str):
    """
	This function can be used to convert a sentence into its NATO equivalent
	The sentence can contain alphanumeric characters or symbols, but the output will ignore the symbols
	except the space which is used for sparsing

	Returns -- A response string which spells the sentence and a list which consists of translations of
	each word
	"""
    in_str = in_str.upper()
    words = in_str.split()
    out_str = ''
    out_list = []
    for word in words:
        word_list = []
        for ch in word:
            if ch.isnumeric() or ch.isalpha():
                if out_str == '':
                    out_str += phonetic_dict[ch]
                else:
                    out_str += ' ' + phonetic_dict[ch]
                word_list.append(phonetic_dict[ch])
        out_list.append(word_list)
    return out_str, out_list


def openBlob(blob, mode='r'):
    """ open a blob taking into consideration that it might need to be
        invalidated in order to be fetch again via zeo;  please see
        http://dev.plone.org/plone/changeset/32170/ for more info """
    try:
        return blob.open(mode)
    except IOError:
        blob._p_deactivate()
        return blob.open(mode)


def groupname(gid=None):
    """Return the name of the group with the given gid.

    If gid is None, return the name of the current group."""
    return None


def to_yaml(dumper, data):
    """Convert AttrDict to dictionary, preserving order"""
    return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items())


def check_network_exists(conn, networkname, logger):
    """ check if the network exists, may or may not be active """
    network_names = conn.listNetworks()
    network_names += conn.listDefinedNetworks()
    if networkname not in network_names:
        logger.error("%s doesn't exist" % networkname)
        return False
    else:
        return True


def getInstanceVarNames(obj):
    """Return a list the names of all (potential) instance variables."""
    slots = {}
    if hasattr(obj, '__dict__'):
        slots.update(obj.__dict__)
    if hasattr(obj, '__class__'):
        slots['__class__'] = 1
    cls = getattr(obj, '__class__', type(obj))
    if hasattr(cls, '__mro__'):
        for base in cls.__mro__:
            for name, value in base.__dict__.items():
                if hasattr(value, '__get__') and not callable(value
                    ) and hasattr(obj, name):
                    slots[name] = 1
    if '__dict__' in slots:
        del slots['__dict__']
    slots = sorted(slots.keys())
    return slots


@classmethod
def user_exists(cls, *args, **kwargs):
    """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        """
    if 'username' in kwargs:
        kwargs[cls.username_field()] = kwargs.pop('username')
    return cls.user_model().objects.filter(*args, **kwargs).count() > 0


def _compute_fixture_value(fixturedef, session):
    """ Computes the fixturedef evaluated in the scope of the first item in the
    list of collected items. """
    request = session.items[0]._request
    request._compute_fixture_value(fixturedef)
    res = fixturedef.cached_result[0]
    request._fixture_defs[fixturedef.argname] = fixturedef
    return res


@classmethod
def check_obj(cls, obj):
    """Return True if obj is a list or tuple."""
    return isinstance(obj, (list, tuple))


def default_export_aggregated_timers(aggregated_report):
    """Default implementation of aggregated timer logging"""
    pass


def dec_to_hex(decimal_number):
    """
    Accepts a decimal integer.
    Returns a hexadecimal number in a string.
    """
    hex_char = {(10): 'A', (11): 'B', (12): 'C', (13): 'D', (14): 'E', (15):
        'F'}
    hex_number = ''
    while decimal_number > 0:
        hex = decimal_number % 16
        decimal_number = (decimal_number - hex) // 16
        if hex >= 10:
            hex_number = hex_char[hex] + hex_number
            continue
        hex_number = str(hex) + hex_number
    return hex_number


def _PerModeSmall36(x):
    """Takes Numeric Code and returns String API code

    Input Values: 1:"Totals", 2:"PerGame", 3:"Per36"

    Used in:

    """
    measure = {(1): 'Totals', (2): 'PerGame', (3): 'Per36'}
    try:
        return measure[x]
    except:
        raise ValueError('Please enter a number between 1 and ' + str(len(
            measure)))


@classmethod
def group_join_policy_updated_details(cls, val):
    """
        Create an instance of this class set to the
        ``group_join_policy_updated_details`` tag with value ``val``.

        :param GroupJoinPolicyUpdatedDetails val:
        :rtype: EventDetails
        """
    return cls('group_join_policy_updated_details', val)


def tocreset(I, Ipickup, TD, curve='U1', CTR=1):
    """
    Time OverCurrent Reset Time Function

    Function to calculate the time to reset for a TOC
    (Time-OverCurrent, 51) element.

    Parameters
    ----------
    I:          float
                Measured Current in Amps
    Ipickup:    float
                Fault Current Pickup Setting (in Amps)
    TD:         float
                Time Dial Setting
    curve:      string, optional
                Name of specified TOC curve, may be entry from set:
                {U1,U2,U3,U4,U5,C1,C2,C3,C4,C5}, default=U1
    CTR:        float, optional
                Current Transformer Ratio, default=1

    Returns
    -------
    tr:         float
                Time-to-Reset for characterized element.
    """
    curve = curve.upper()
    C = {'U1': 1.08, 'U2': 5.95, 'U3': 3.88, 'U4': 5.67, 'U5': 0.323, 'C1':
        13.5, 'C2': 47.3, 'C3': 80.0, 'C4': 120.0, 'C5': 4.85}
    M = I / (CTR * Ipickup)
    tr = TD * (C[curve] / (1 - M ** 2))
    return tr


def configure(conf):
    """
	Detects the program dbus-binding-tool and sets ``conf.env.DBUS_BINDING_TOOL``
	"""
    conf.find_program('dbus-binding-tool', var='DBUS_BINDING_TOOL')


def _add_gaussian(sig, noise1, noise2):
    """
    Helper function to add_noise

    This one simply adds one of the Gaussians to the sig and ignores the other
    one.
    """
    return sig + noise1


def interpret_stats(results):
    """Generates the string to be shown as updates after the execution of a
    Cypher query

    :param results: ``ResultSet`` with the raw results of the execution of
                    the Cypher query
    """
    stats = results.stats
    contains_updates = stats.pop('contains_updates', False) if stats else False
    if not contains_updates:
        result = '{} rows affected.'.format(len(results))
    else:
        result = ''
        for stat, value in stats.items():
            if value:
                result = '{}\n{} {}.'.format(result, value, stat.replace(
                    '_', ' '))
    return result.strip()


def transport_new(_, __, *args, **kwargs):
    """Monkey patch Transport.__new__() to create a TracingTransport object"""
    from elasticsearch_opentracing import TracingTransport
    return TracingTransport.__new__(TracingTransport, *args, **kwargs)


def _resolve(name):
    """Resolve a dotted name to a global object."""
    name = name.split('.')
    used = name.pop(0)
    found = __import__(used)
    for n in name:
        used = used + '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            __import__(used)
            found = getattr(found, n)
    return found


@staticmethod
def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):
    """Given a code and list of locations, convert to snippet lines.

        return will include line number, a separator (``sep``), then
        line contents.

        At most ``context`` lines are shown before each location line.

        After each location line, the column is marked using
        ``colmark``. The first character is repeated up to column, the
        second character is used only once.

        :return: list of lines of sources or column markups.
        :rtype: list
        """
    if not locations:
        return []
    lines = code.split('\n')
    offset = int(len(lines) / 10) + 1
    linenofmt = '%{}d'.format(offset)
    s = []
    for loc in locations:
        line = max(0, loc.get('line', 1) - 1)
        column = max(0, loc.get('column', 1) - 1)
        start_line = max(0, line - context)
        for i, ln in enumerate(lines[start_line:line + 1], start_line):
            s.append('{}{}{}'.format(linenofmt % i, sep, ln))
        s.append('{}{}{}'.format(' ' * (offset + len(sep)), colmark[0] *
            column, colmark[1]))
    return s


def get(isamAppliance, check_mode=False, force=False):
    """
    Get information on existing snapshots
    """
    return isamAppliance.invoke_get('Retrieving snapshots', '/snapshots')


def __call__(allow_cached=True):
    """
        Resolve the reference, as with :meth:`IWeakRef.call`; however, allows
        control of caching.

        :keyword allow_cached: If `True` (the default) a cached value can be used. If
                set to `False`, this will not return a cached value. Note, however, that,
                in a cluster, this may still return an object that other nodes might consider
                gone.
        """


def is_valid_file(filepath):
    """Return True if filepath exists

    Args:
        filepath (str): path to file

    Returns:
        bool: True if path exists, False otherwise
    """
    try:
        open(filepath, 'r').close()
        return True
    except OSError:
        return False


def getL3BridgeConfig(update):
    """
    Creates configuration sections for layer 3 bridging.
    """
    interfaces = update.cache_get('networkInterfaces')
    parprouted = list()
    for iface in interfaces:
        l3bridge = iface.get('l3bridge', None)
        if l3bridge is None:
            continue
        config = {'type': 'bridge'}
        options = {'interfaces': [iface['externalIntf'], l3bridge]}
        parprouted.append((config, options))
    update.cache_set('parproutedConfig', parprouted)


@classmethod
def detwingle(cls, in_bytes, main_encoding='utf8', embedded_encoding=
    'windows-1252'):
    """Fix characters from one encoding embedded in some other encoding.

        Currently the only situation supported is Windows-1252 (or its
        subset ISO-8859-1), embedded in UTF-8.

        :param in_bytes: A bytestring that you suspect contains
            characters from multiple encodings. Note that this _must_
            be a bytestring. If you've already converted the document
            to Unicode, you're too late.
        :param main_encoding: The primary encoding of `in_bytes`.
        :param embedded_encoding: The encoding that was used to embed characters
            in the main document.
        :return: A bytestring in which `embedded_encoding`
          characters have been converted to their `main_encoding`
          equivalents.
        """
    if embedded_encoding.replace('_', '-').lower() not in ('windows-1252',
        'windows_1252'):
        raise NotImplementedError(
            'Windows-1252 and ISO-8859-1 are the only currently supported embedded encodings.'
            )
    if main_encoding.lower() not in ('utf8', 'utf-8'):
        raise NotImplementedError(
            'UTF-8 is the only currently supported main encoding.')
    byte_chunks = []
    chunk_start = 0
    pos = 0
    while pos < len(in_bytes):
        byte = in_bytes[pos]
        if not isinstance(byte, int):
            byte = ord(byte)
        if (byte >= cls.FIRST_MULTIBYTE_MARKER and byte <= cls.
            LAST_MULTIBYTE_MARKER):
            for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES:
                if byte >= start and byte <= end:
                    pos += size
                    break
        elif byte >= 128 and byte in cls.WINDOWS_1252_TO_UTF8:
            byte_chunks.append(in_bytes[chunk_start:pos])
            byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte])
            pos += 1
            chunk_start = pos
        else:
            pos += 1
    if chunk_start == 0:
        return in_bytes
    else:
        byte_chunks.append(in_bytes[chunk_start:])
    return b''.join(byte_chunks)


def _get_shading(idf):
    """Get the shading surfaces from the IDF."""
    shading_types = ['SHADING:ZONE:DETAILED', 'SHADING:SITE:DETAILED']
    shading = []
    for shading_type in shading_types:
        shading.extend(idf.idfobjects[shading_type])
    return shading


def los_id_4(df):
    """Line-of-sight id 4

    Helper predicate for sample validation

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing the measurements for this window

    Returns
    -------
    bool
        True if `df` contains los_ids 0, 1, 2, and 3
    """
    return set(df.los_id) == set([0, 1, 2, 3])


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def history_before(date):
    """ Returns an IEstimatedExecution containing the information of the last history entry before the given date
            or None if no entry was found
        """


def t_network_record_type_ip6(val):
    """
    Convert/validate: Network record type.

    :param any val: Value to be converted/validated
    :return: network record type.
    :rtype: str
    :raises ValueError: if the value is not valid network record type
    """
    if str(val) == 'ipv6':
        return str(val)
    raise ValueError("Invalid type '{:s}' for network record".format(val))


@classmethod
def _load(cls, parser, configuration_groups):
    """ Load the argparse definition and parse them

        :param description: description of configuration
        :param configuration_groups: list configuration groupe to load
        :param useseparator: boolean(default False)
        """
    if configuration_groups is None:
        return
    for group in cls.groups:
        if group not in configuration_groups:
            continue
        label = cls.labels.get(group)
        if label:
            g = parser.add_argument_group(label)
        else:
            g = parser
        for function in cls.groups[group]:
            function(g)


def create_user_crumbs(request, crumbs):
    """Creates the base-list of breadcrumbs, depending on the current
    users authorisation level.
    """
    if request.current_user.has_permission('admin.users.view'):
        crumbs.insert(0, {'title': 'Users', 'url': request.route_url('users')})
    if request.current_user.has_permission('admin'):
        try:
            crumbs.insert(0, {'title': 'Administration', 'url': request.
                route_url('admin')})
        except:
            pass
    crumbs[-1]['current'] = True
    return crumbs


@classmethod
def prev_text_version(cls, version):
    """Method which returns previous number from the string.

        From string ``build10s`` it returns 9.

        :param str text: Line to search in.
        :return: Next number
        :rtype: int
        """
    return max(0, cls.parse_text_version(version) - 1)


def print_usage():
    """Print a help message."""
    print(
        """query_pubmed.py [-h] [-c] [-d delay] query

This script sends a query to PubMed (via the NCBI Entrez webservice*)
and prints the MEDLINE formatted results to the screen.

Arguments:
    -h           Print out this help message.
    -c           Count the hits, and don't print them out.

* http://www.ncbi.nlm.nih.gov/Entrez/
"""
        )


def callable_bool(value):
    """ A compatibility wrapper for pre Django 1.10 User model API that used
    is_authenticated() and is_anonymous() methods instead of attributes
    """
    if callable(value):
        return value()
    else:
        return value


def fil_remove_remote(branchs):
    """Remove branchs with remote"""
    for branch in branchs:
        if not 'remotes/' in branch:
            yield branch


def does_not_compose(left, right):
    """ Composition error. """
    return '{} does not compose with {}.'.format(left, right)


def pytest_saltfactories_minion_verify_configuration(request, minion_config,
    username):
    """
    This hook is called to vefiry the provided minion configuration
    """


def suffix_join(array: list, sep: str='', suffix_sep: str=None):
    """Returns similarly to str.join() however allows you to specify a different final join separator

    Example:
        ', '.join(["One", "Two", "Three"])  # => 'One, Two, Three'
        suffix_join(["One", "Two", "Three"], sep=', ', suffix_sep=" or ")  # => 'One, Two or Three'
    """
    if suffix_sep is None:
        suffix_sep = sep
    if len(array) >= 2:
        return sep.join(array[:-1]) + suffix_sep + array[-1]
    return sep.join(array)


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def timestamp_to_date_str(dt):
    """ Serialize a date/time value into YYYY-MM-DD date string. """
    return str(dt.date())


def match(path):
    """
        If the ``path`` passed to this function can be matched by the
        ``pattern`` of this route, return a dictionary (the
        'matchdict'), which will contain keys representing the dynamic
        segment markers in the pattern mapped to values extracted from
        the provided ``path``.

        If the ``path`` passed to this function cannot be matched by
        the ``pattern`` of this route, return ``None``.
        """


def list_set_bits(r, expected_length):
    """Return list of positions of bits set to one in given data.

    This method is used to read e.g. violated zones. They are marked by ones
    on respective bit positions - as per Satel manual.
    """
    set_bit_numbers = []
    bit_index = 1
    assert len(r) == expected_length + 1
    for b in r[1:]:
        for i in range(8):
            if b >> i & 1 == 1:
                set_bit_numbers.append(bit_index)
            bit_index += 1
    return set_bit_numbers


@classmethod
def dump_forest(cls, root_node, token_dicts=None):
    """ Return a string with a multi-line text representation of the parse tree """
    dumper = cls(token_dicts)
    dumper.go(root_node)
    dumper._result.append('Q0')
    return '\n'.join(dumper._result)


def use_shading_nodes():
    """Enable nodes on a material, world or lamp

    """
    pass


@staticmethod
def _maybe_cast(item, caster):
    """Given a casting function, attempt to cast to that type while masking common cast
        exceptions.

        N.B. This is mostly suitable for casting string types to numeric types - e.g. a port number
        read from disk into an int.

        :param func caster: A casting callable (e.g. `int`).
        :returns: The result of caster(item) or item if TypeError or ValueError are raised during cast.
        """
    try:
        return caster(item)
    except (TypeError, ValueError):
        return item


def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


def get_filename_suffix(filename, suffixes):
    """Ensure that the given file has a suffix that is in the given set of
    allowed suffixes. Returns the matched suffix or None.

    Parameters
    ----------
    filename : string
        Name of file
    suffixes : Iterable(string)

    Returns
    -------
    string
        Matched suffix from list of suffixes or None.
    """
    for s in suffixes:
        if filename.endswith(s):
            return s


@staticmethod
def metadata_updated_on(item):
    """Extracts and coverts the update time from a Meetup item.

        The timestamp is extracted from 'updated' field and converted
        to a UNIX timestamp.

        :param item: item generated by the backend

        :returns: a UNIX timestamp
        """
    ts = item['updated']
    ts = ts / 1000.0
    return ts


@classmethod
def validate_enum_field(cls, value, enum_list, null=True):
    """
        Validate enum field value

        :type value: object
        :param value:

        :type enum_list: list
        :param enum_list: list of allow value

        :type null: bool
        :param null: is allow None value

        :rtype: dict
        :return: {'is_valid':bool, 'error_msg':str}
        """
    is_valid = True
    error_msg = None
    if null is False and value is None:
        is_valid = False
        error_msg = 'Data should not be None'
    if value is not None:
        if value in enum_list is False:
            is_valid = False
            error_msg = 'Data value should be from list: {}'.format(enum_list)
    return {'is_valid': is_valid, 'error_msg': error_msg}


def __replace_repeat(_sentence):
    """
    Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences.

    :param _sentence:
    """
    _repeat_dict = {}
    if _sentence is not None:
        while _sentence.find('#DEFINE_REPEAT') != -1:
            _begin_index = _sentence.find('#DEFINE_REPEAT')
            _start_index = _begin_index + 15
            _end_index = _sentence.find(']')
            if _sentence.find('#DEFINE_REPEAT') is not None:
                _sub_list = _sentence[_start_index:_end_index].split(',')
                _choice = _sub_list[0]
                _repeat_text = _sub_list[1]
                _repeat_dict[_choice] = _repeat_text
                _sentence = _sentence.replace(_sentence[_begin_index:
                    _end_index + 1], '', 1)
        while _sentence.find('#REPEAT') != -1:
            if _sentence.find('#REPEAT') is not None:
                _repeat_begin_index = _sentence.find('#REPEAT')
                _repeat_start_index = _repeat_begin_index + 8
                _repeat_end_index = _sentence.find(']', _repeat_start_index)
                _repeat_index = _sentence[_repeat_start_index:_repeat_end_index
                    ]
                if _repeat_index in _repeat_dict:
                    _sentence = _sentence.replace(_sentence[
                        _repeat_begin_index:_repeat_end_index + 1], str(
                        _repeat_dict[_repeat_index]))
        if _sentence.find('#REPEAT') == -1:
            return _sentence
        return _sentence
    else:
        return _sentence


def nlg_request_format_spec():
    """Expected request schema for requests sent to an NLG endpoint."""
    return {'type': 'object', 'properties': {'template': {'type': 'string'},
        'arguments': {'type': 'object'}, 'tracker': {'type': 'object',
        'properties': {'sender_id': {'type': 'string'}, 'slots': {'type':
        'object'}, 'latest_message': {'type': 'object'},
        'latest_event_time': {'type': 'number'}, 'paused': {'type':
        'boolean'}, 'events': {'type': 'array'}}}, 'channel': {'type':
        'object', 'properties': {'name': {'type': 'string'}}}}}


def format_dt(dt):
    """
    Format datetime object for human friendly representation.
    """
    value = dt.strftime('%a, %d %b %Y %H:%M:%S %Z')
    return value


@staticmethod
def key_to_index(key):
    """Maps internal name to group index.

        Maps the internal name of a feature to the index of the corresponding
        feature grouping. For example for a feature vector consisting of the
        x-y-z position of the left and the right arm, the features for the left
        and the right arm can be extracted separately as a group, effectively
        splitting the feature vector into two vectors with x, y, and z at the
        positions specified by the the mapping of this function.

        Parameters
        ----------
        key : str
            The key into the mapping

        Returns
        -------
        int :
            The index in the feature array.

        Raises
        ------
        NotImplementedError
            If the child class does not implement this function.

        Notes
        -----
        Optionally this method can be overwritten at runtime.

        Examples
        --------
        >>> def my_key_to_index(key)
        ...     return {
        ...         "x": 0,
        ...         "y": 1,
        ...         "z": 2
        ...     }[key]
        ...
        >>> State.description = {'LArm': {'x': 0, 'y': 1, 'z': 2}
        ...                      'RArm': {'x': 3, 'y': 4, 'z': 5}}
        >>> State.key_to_index = staticmethod(my_key_to_index)

        This specifies the mapping in both direction.

        >>> state = [0.1, 0.4, 0.3. 4.6. 2.5. 0.9]
        >>>
        >>> mapping = State.description['LArm']
        >>>
        >>> larm = np.zeros[len(mapping.keys())]
        >>> for key, axis in mapping.iteritems():
        ...     larm[State.key_to_index(key)] = state[axis]
        ...
        >>> print larm
        [0.1, 0.4, 0.3]

        This extracts the features for the left arm from the `state` vector.

        """
    raise NotImplementedError


def _get_endpoint(client, **kwargs):
    """Get an endpoint using the provided keystone client."""
    return client.service_catalog.url_for(service_type=kwargs.get(
        'service_type') or 'sip', endpoint_type=kwargs.get('endpoint_type') or
        'publicURL')


def reverse_complement(seq: str):
    """
    Inputs a sequence of DNA and returns the reverse complement se$
    Outputs a reversed string of the input where A>T, T>A, G>C, an$
    """
    conversion = str.maketrans('ACGTacgt', 'TGCAtgca')
    comp = seq.translate(conversion)
    rev_comp = comp[::-1]
    return rev_comp


def default_engine_has_exhausted_gas_recirculation(fuel_type):
    """
    Returns the default engine has exhaust gas recirculation value [-].

    :param fuel_type:
        Fuel type (diesel, gasoline, LPG, NG, ethanol, methanol, biodiesel,
        propane).
    :type fuel_type: str

    :return:
        Does the engine have exhaust gas recirculation technology?
    :rtype: bool
    """
    return fuel_type in ('diesel', 'biodiesel')


def read_release_version():
    """Read version information from VERSION file"""
    try:
        from ._version_cache import version
        if len(version) == 0:
            version = None
        return version
    except ImportError:
        return 'unknown'


@classmethod
def __digit(cls, s_code: str) ->str:
    """
        add the digit check bit
        :return:
        """
    i = 1
    tmp_sum = 0
    for num in s_code:
        if 0 == i % 2:
            tmp = int(ord(num)) * 2 % 10
        else:
            tmp = int(ord(num)) * 3 % 10
        tmp_sum += tmp
        i += 2
    if 0 == tmp_sum % 10:
        bit = 0
    elif tmp_sum > 100:
        bit = 10 - tmp_sum % 100 % 10
    else:
        bit = 10 - tmp_sum % 10
    return str(bit)


def p_ordinary_symbols(p):
    """expression : PLUS
                  | MINUS
                  | DIVIDE
                  | TIMES
                  | DTIMES
                  | ID
                  | NUMBER
                  | COMMA
                  | EXCL
                  | MOD
                  | EQ
                  | UP LBRACE expression RBRACE
                  """
    translate = {'\\infty': 'infty', '\\times': '*'}
    if p[1] == '\\%':
        p[0] = '% '
    elif p[1] == '^':
        p[0] = '^(%s) ' % p[3]
    else:
        p[0] = '%s ' % translate.get(p[1], p[1])


def is_bool(value):
    """ Checks if the value is a bool """
    return value.lower() in ['true', 'false', 'yes', 'no', 'on', 'off']


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def image_from_view(filepath: str=''):
    """Make an image from the current 3D view for re-projection

    :param filepath: File Path, Name of the file
    :type filepath: str
    """
    pass


def proc(request):
    """
    Place the ProctorGroups 'proc' object in every template context.

    This makes using Proctor test groups in templates very convenient.

    Dependent on the Proctor middleware.

        {{ proc.buttoncolortst.payload|default_if_none:"..." }}

        {% if proc.buttoncolortst.group == 'green' %}
    """
    return {'proc': request.proc} if hasattr(request, 'proc') else {}


def get_value(x):
    """
    This is for when using the 'autograd' backend and you want to detach an
    ArrayBox and just convert it to a numpy array.
    """
    if str(type(x)) == "<class 'autograd.numpy.numpy_boxes.ArrayBox'>":
        return x._value
    else:
        return x


def chlorophyll_a():
    """Chlorophyll-A legend for MERIS"""
    raise NotImplementedError('This palette is not implemented - ' +
        'it was earlier though...')


def tweakmode_exit(isolate_action: bool=False):
    """Exit tweaking mode for the action referenced by the active strip

    :param isolate_action: Isolate Action, Disable ‘solo’ on any of the NLA Tracks after exiting tweak mode to get things back to normal
    :type isolate_action: bool
    """
    pass


@classmethod
def comment(cls, comment, drop_incompat_keys=False):
    """Patch a comment object"""
    comment['created_time'] = str(int(comment.get('created_at')))
    from_user = {'username': comment['user']['username'], 'profile_picture':
        comment['user']['profile_pic_url'], 'id': str(comment['user']['pk']
        ), 'full_name': comment['user']['full_name']}
    comment['from'] = from_user
    comment['id'] = str(comment['pk'])
    if drop_incompat_keys:
        cls._drop_keys(comment, ['bit_flags', 'content_type', 'created_at',
            'created_at_utc', 'media_id', 'pk', 'status', 'type', 'user',
            'user_id'])
    return comment


def get(obj, default=None):
    """For obj, return active IToken or default.

        Token must be active (not ended), or else return default.
        """


@classmethod
def class_key(cls):
    """Nice order of classes."""
    return 1, 0, 'Number'


def _set_argument(args, option_pair, hist=None):
    """
    If the value isn't set in the args namespace, check history if a
    record exists of it and ask user if most recent use or new value should
    be used.

    :param args:
    :param option_pair:
    :param hist:
    :return:
    """
    hist = hist or {}
    while not getattr(args, option_pair[0]):
        histlist = hist.get(option_pair[0], None)
        if histlist is None:
            last = ''
        else:
            last = histlist[-1]
        print(option_pair[1])
        print('[{}]'.format(last))
        attr = input()
        if attr or last:
            setattr(args, option_pair[0], attr or last)
            break


@staticmethod
def p_compu_vtab_range_in_val_out_val(p):
    """compu_vtab_range_in_val_out_val : number_number_string_value_list"""
    p[0] = p[1]


def config_check(args, config, key):
    """ Take in the args, config, and returns the proper key.

    :param args:
    :param config:
    :param key:
    :return: value
    """
    value = args.get(key)
    if value is None:
        value = config.get(key)
    return value


def switch_direction():
    """Change the direction that a chain of bones points in (head <-> tail swap)

    """
    pass


def theta_K_MgOH_HMW84(T, P):
    """c-c': potassium magnesium-hydroxide [HMW84]."""
    theta = 0.0
    valid = T == 298.15
    return theta, valid


def deenhance(sent):
    """
    Reinstate Basic Dependencies deprels.
    """
    for tok in sent['toks']:
        if 'bhead' in tok:
            tok['head'] = tok['bhead']
            tok['deprel'] = tok['bdeprel']
            del tok['bhead']
            del tok['bdeprel']


def get_paginator(operation_name=None):
    """
    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').

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


def list_string_to_dict(string):
    """Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``."""
    dictionary = {}
    for idx, c in enumerate(string):
        dictionary.update({c: idx})
    return dictionary


@classmethod
def _largest_nonfractional_unit(cls, amount):
    """
        Return largest unit such that `amount` is larger than 1 when
        expressed in that unit.
        """
    units = sorted(cls._UNITS.values())
    prev = units[0].base
    for unit in units:
        if prev.amount(unit.base) <= amount < unit.amount(unit.base):
            return prev
        prev = unit
    return unit


def trim_prefix(name):
    """Trim off the name space prefix."""
    names = name.split(':')
    if len(names) == 1:
        return names[0]
    if len(names) == 2:
        return names[1]
    return None


def get_stage(restApiId=None, stageName=None):
    """
    Gets information about a  Stage resource.
    See also: AWS API Documentation

    :example: response = client.get_stage(
        restApiId='string',
        stageName='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The identifier of the RestApi resource for the Stage resource to get information about.

    :type stageName: string
    :param stageName: [REQUIRED]
            The name of the Stage resource to get information about.

    :rtype: dict
    :return: {
        'deploymentId': 'string',
        'clientCertificateId': 'string',
        'stageName': 'string',
        'description': 'string',
        'cacheClusterEnabled': True|False,
        'cacheClusterSize': '0.5'|'1.6'|'6.1'|'13.5'|'28.4'|'58.2'|'118'|'237',
        'cacheClusterStatus': 'CREATE_IN_PROGRESS'|'AVAILABLE'|'DELETE_IN_PROGRESS'|'NOT_AVAILABLE'|'FLUSH_IN_PROGRESS',
        'methodSettings': {
            'string': {
                'metricsEnabled': True|False,
                'loggingLevel': 'string',
                'dataTraceEnabled': True|False,
                'throttlingBurstLimit': 123,
                'throttlingRateLimit': 123.0,
                'cachingEnabled': True|False,
                'cacheTtlInSeconds': 123,
                'cacheDataEncrypted': True|False,
                'requireAuthorizationForCacheControl': True|False,
                'unauthorizedCacheControlHeaderStrategy': 'FAIL_WITH_403'|'SUCCEED_WITH_RESPONSE_HEADER'|'SUCCEED_WITHOUT_RESPONSE_HEADER'
            }
        },
        'variables': {
            'string': 'string'
        },
        'documentationVersion': 'string',
        'createdDate': datetime(2015, 1, 1),
        'lastUpdatedDate': datetime(2015, 1, 1)
    }

    :returns:
    (string) --
    (string) --

    """
    pass


@classmethod
def cursor_up(cls, no_of_chars):
    """ moves the cursor up"""
    print(u'\x1b[' + str(no_of_chars) + 'A')


def hello_world(name=None, *, no_capitalize=False):
    """Greets the world or the given name.

    :param name: If specified, only greet this person.
    :param no_capitalize: Don't capitalize the given name.
    """
    if name:
        if not no_capitalize:
            name = name.title()
        return 'Hello {0}!'.format(name)
    return 'Hello world!'


def pgettext(msgid: str, msgctxt: str):
    """Try to translate the given msgid (with optional msgctxt).

    :param msgid: The string to translate.
    :type msgid: str
    :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).
    :type msgctxt: str
    :return:  The translated string (or msgid if no translation was found).
    """
    pass


@classmethod
def get(cls, session, parent=None):
    """Gets all of the System controllers from the APIC.
        This information comes from
        the APIC 'eqptBoard' class.

        If parent is specified, it will only get system
        controllers that are children of the the parent.
        The system controlles will also be added as children
        to the parent Node.

        :param session: APIC session
        :param parent: parent Node

        :returns: list of Systemcontrollers
        """
    return cls.get_obj(session, cls._get_apic_classes(), parent)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a SearchStatus object from a json dictionary."""
    args = {}
    if 'scope' in _dict:
        args['scope'] = _dict.get('scope')
    if 'status' in _dict:
        args['status'] = _dict.get('status')
    if 'status_description' in _dict:
        args['status_description'] = _dict.get('status_description')
    if 'last_trained' in _dict:
        args['last_trained'] = _dict.get('last_trained')
    return cls(**args)


def print_bold(msg, end='\n'):
    """Convenience function to print a message in bold style

    Optionally you can also specify how the bold text should end. By default
    it ends with a new line character.

    :arg msg: Message to be converted to bold style
    :arg end: Tell how the printed string should end (newline, space etc)
    """
    print('\x1b[1m' + msg + '\x1b[0m', end=end)


def mongo_load(database, collection_key, id_key):
    """Load data from MongoDB database.

    Args:
        database (:class:`pymongo.database.Database`): MongoDB database to save
            results to.
        collection_key (str): name of collection.
        id_key (str): id key to look up data.

    Returns:
        retrieved data (returns None if no data with :attr:`id_key` is found).
    """
    return database[collection_key].find_one({'_id': id_key})


def _is_float(s):
    """Check if a value is a float."""
    try:
        float(s)
        return True
    except ValueError:
        return False


def sequenceOfFloats(string):
    """
    A custom type for the argparse commandline parser.
    Accepts only colon-separated lists of valid float values.

    Examples
    --------

    >>> parser.add_argument('argname', type=sequenceOfFloats, help='help')

    """
    value = list(map(float, string.split(',')))
    return value


def convert_to_cmd_options(args=None, options=None):
    """
    Converts the given list of args and dict of options to a string expected for
    standard Unix-like command line options
    e.g. [arg, ...] [--kwarg=val, --kwarg-arg=val2, ...]

    :param args:
    :param options:
    """
    args = args or []
    options = options or {}
    cmd_parts = []
    cmd_parts.extend(args)
    for key, value in options.iteritems():
        cmd_parts.append('--%s' % key.replace('_', '-'))
        cmd_parts.append(value)
    return ' '.join(cmd_parts)


def command_selendroid(args, logger):
    """Command with selendroid+plugin standalone jar file"""
    logger.error(
        """server_driver not developed yet,
        open issue on github if you got this"""
        )


def _is_section_key(key):
    """Is a Config key a section name (does it start with a capital)?"""
    if key and key[0].upper() == key[0] and not key.startswith('_'):
        return True
    else:
        return False


@classmethod
def index(cls, action):
    """
        Return action index in the action space.

        :param action: action representation
        :type action: OrderedDict
        :rtype: int
        """
    for index, fluent in enumerate(action):
        if action[fluent] == 1:
            return index


@classmethod
def get_software_package(cls, calc, **kwargs):
    """Return the package or program name that was used to produce the structure.

        Only package or program name should be used, e.g. 'VASP', 'psi3', 'Abinit', etc.
        """
    return 'Quantum ESPRESSO'


def data_for_idx(face_idx, dem, grid, data):
    """get data for cell with face_idx face_idx"""
    face = grid['face_coordinates'][face_idx]
    affine = dem['affine']
    idx = (face - (affine.xoff, affine.yoff)) / (affine.a, affine.e)
    i_min, i_max = int(idx[:, (0)].min()), int(idx[:, (0)].max())
    j_min, j_max = int(idx[:, (1)].min()), int(idx[:, (1)].max())
    dem_i = dem['band'][j_min:j_max, i_min:i_max]
    vol_i = data['vol1'][face_idx]
    data = dict(face=face, dem=dem_i, vol=vol_i)
    return data


def read_text(filename):
    """Read a ``utf-8`` encoded text file and returns the text as ``string``.

    This is just a utily function, that is not recommended to use if the text
    file does not fit your available RAM. Mostly used for small text files.

    :param filename: File from which is the text to be read
    :type filename: string
    :return: Text in the file
    :rtype: string
    """
    with open(filename, 'r', encoding='utf8') as fp:
        text = fp.read()
    return text


@staticmethod
def to_newton(romer):
    """ Convert romer to newton """
    return (romer - 7.5) * 22 / 35


def __getitem__(selector):
    """Returns the selected version of a content.

        Returns a ``IVersionData`` object.
        """


def loading():
    """CLI loading marker.

    Warnings
    --------
    not implemented
    """
    pass


def p_l_value_placeholder_record(p):
    """l_value : PLACEHOLDER fields"""
    p[0] = 'record', ('placeholder', p[1]), p[2]


def filter_int(item):
    """Tests and outputs int.

    >>> filter_int(3):
    3
    """
    if isinstance(item, int):
        return item
    else:
        return ''


@classmethod
def user_error(cls, val):
    """
        Create an instance of this class set to the ``user_error`` tag with
        value ``val``.

        :param SharingUserError val:
        :rtype: ListFileMembersError
        """
    return cls('user_error', val)


def int_to_poly(integer: int, modulus: int=2) ->object:
    """
    Encodes an integer as a polynomial.

    Parameters:
        integer (int): Integer to encode.
        modulus (int): Modulus to reduce the integer over.

    Returns:
        object: Polynomial representation.

    Examples:
        >>> from samson.math.general import int_to_poly
        >>> int_to_poly(100)
        <Polynomial: x**6 + x**5 + x**2, coeff_ring=ZZ/ZZ(2)>

        >>> int_to_poly(128, 3)
        <Polynomial: x**4 + x**3 + ZZ(2)*x**2 + ZZ(2), coeff_ring=ZZ/ZZ(3)>

    """
    from samson.math.all import ZZ, Polynomial
    base_coeffs = []
    while integer != 0 and integer != -1:
        integer, r = divmod(integer, modulus)
        base_coeffs.append(r)
    return Polynomial(base_coeffs, ZZ / ZZ(modulus))


def next_power_of_2(n):
    """ Return next power of 2 greater than or equal to n """
    n -= 1
    shift = 1
    while n + 1 & n:
        n |= n >> shift
        shift *= 2
    return max(4, n + 1)


def finish():
    """
        Callback called when the request is closing.

        @return: If necessary, the pending data accumulated from previous
            C{encode} calls.
        @rtype: C{str}
        """


def config_matcher(segments):
    """A matcher for a mailing list's configuration resource.

    e.g. /config
    e.g. /config/description
    """
    if len(segments) < 1 or segments[0] != 'config':
        return None
    if len(segments) == 1:
        return (), {}, ()
    if len(segments) == 2:
        return (), dict(attribute=segments[1]), ()
    return None


@classmethod
def canRead(cls, *args, **kwargs):
    """
        Check if we can read the input.  This takes the same parameters as
        __init__.

        :returns: True if this class can read the input.  False if it cannot.
        """
    return False


def all_methods(obj):
    """
    Return a list of names of methods of `obj`
    """
    temp = []
    for name in dir(obj):
        func = getattr(obj, name)
        if hasattr(func, '__call__'):
            temp.append(name)
    return temp


def bytes_to_short(higher_byte, lower_byte):
    """
    Transforms two bytes into a short (Using Big-Endian!)

    :param higher_byte: The byte at position 0 (Higher byte)
    :param lower_byte: The byte at position 1 (Lower byte)
    :return: The two bytes transformed into a short
    """
    return higher_byte << 8 | lower_byte


def objects_remove_all():
    """Remove selected objects from all groups

    """
    pass


@classmethod
def adapt_emulated_to_native(cls, impl, **kw):
    """Produce a Postgresql native :class:`.postgresql.ENUM` from plain
        :class:`.Enum`.

        """
    kw.setdefault('validate_strings', impl.validate_strings)
    kw.setdefault('name', impl.name)
    kw.setdefault('schema', impl.schema)
    kw.setdefault('inherit_schema', impl.inherit_schema)
    kw.setdefault('metadata', impl.metadata)
    kw.setdefault('_create_events', False)
    kw.setdefault('values_callable', impl.values_callable)
    return cls(**kw)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a TokenDictRule object from a json dictionary."""
    args = {}
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    else:
        raise ValueError(
            "Required property 'text' not present in TokenDictRule JSON")
    if 'tokens' in _dict:
        args['tokens'] = _dict.get('tokens')
    else:
        raise ValueError(
            "Required property 'tokens' not present in TokenDictRule JSON")
    if 'readings' in _dict:
        args['readings'] = _dict.get('readings')
    if 'part_of_speech' in _dict:
        args['part_of_speech'] = _dict.get('part_of_speech')
    else:
        raise ValueError(
            "Required property 'part_of_speech' not present in TokenDictRule JSON"
            )
    return cls(**args)


def plot_residual_error(ax, x, y, y_hat, n_bins=50, alpha=0.7, s=2):
    """ Plots all the residuals from y and 'y_hat' across x
        INPUT:
            dataframe:
                dataframe of floats or invts
            x:
                a dataframe,list or array of ints or floats
            y
                a dataframe,list or array of ints or floats
            y_hat:
                a array of y values you predicted from x to be compared with
                the values of y
        OUTPUT:
            A plot showing the residuals across x (error)
    """
    residuals = y - y_hat
    ax.axhline(0, color='black', linestyle='--')
    ax.scatter(x, residuals, color='red', alpha=alpha, s=s)
    ax.set_ylabel('Residuals ($y - \\hat y$)')


@classmethod
def splay_pheromone_by_ant_k(cls, add_pheromone, path):
    """アリkが分泌したフェロモンをパスに添付する

        calc_path_scoresで計算したフェロモンを
        通ったpathのエッジに加算する

        Args:
            add_pheromone(float): 一つあたりのエッジに加算するフェロモン
            path: アリが通ったパス

        Returns:

        """
    with cls.DRIVER.session() as session:
        for i in range(len(path) - 1):
            query = (
                f'MATCH (n1:Node{{url: "{path[i]}"}}) MATCH (n2:Node{{url: "{path[i + 1]}"}}) MATCH (n1)-[r:Link]->(n2) SET r.pheromone = r.pheromone + {add_pheromone}'
                )
            session.run(query)


def parse_sources(sourcedef):
    """parse a source definition such as 'src1:1.0,src2' into a sequence of
    tuples (src_id, weight)"""
    sources = []
    for srcdef in sourcedef.strip().split(','):
        srcval = srcdef.strip().split(':')
        src_id = srcval[0]
        if len(srcval) > 1:
            weight = float(srcval[1])
        else:
            weight = 1.0
        sources.append((src_id, weight))
    return sources


def _difference(data, names):
    """Data condition x subject"""
    data_differences = []
    diffnames = []
    diffnames_2lines = []
    for i, (name1, data1) in enumerate(zip(names, data)):
        for name2, data2 in zip(names[i + 1:], data[i + 1:]):
            data_differences.append(data1 - data2)
            diffnames.append('-'.join([name1, name2]))
            diffnames_2lines.append('-\n'.join([name1, name2]))
    return data_differences, diffnames, diffnames_2lines


def setproctitle(text):
    """
    This is a wrapper for setproctitle.setproctitle().  The call sets
    'text' as the new process title and returns the previous value.

    The module is commonly not installed.  If missing, nothing is changed,
    and the call returns None.

    The module is described here: https://pypi.python.org/pypi/setproctitle
"""
    try:
        import setproctitle
    except Exception as e:
        return None
    else:
        prev = setproctitle.getproctitle()
        setproctitle.setproctitle(text)
        return prev


def checkjointures(myserie, possiblevalues):
    """
    Check the list of categories in a column against a provided standard list
    :param myserie: pandas.Series to be checked
    :param possiblevalues: list of standard values
    :return: None
    print:
    - if all values are matching, a simple message indicating evrything is correct
     - the percentage of rows and the percentage of unique values matching standard values
     - the number of rows and the number of unique values that are unknown in the standard values
     - example of non-matching values and the number of occurences
    """
    matchingvalues = myserie[myserie.isin(possiblevalues)]
    unknownvalues = myserie[myserie.isin(possiblevalues) == False]
    if unknownvalues.shape[0] == 0:
        print('100% of values match')
    else:
        percentrowmatching = matchingvalues.shape[0] / myserie.shape[0]
        percentvaluematching = matchingvalues.unique().shape[0
            ] / myserie.unique().shape[0]
        print('{:.0%}'.format(percentrowmatching), 'of rows matching for ',
            '{:.0%}'.format(percentvaluematching), 'of values matching.')
        print(unknownvalues.shape[0], 'rows unknowns for ', unknownvalues.
            unique().shape[0], ' unknown unique values')
        print('Example unknowns:')
        print(unknownvalues.value_counts().iloc[:10])


def _floyd_warshall(graph):
    """
    Calculate the shortest path between two tokens using the Floyd Warshall
    algorithm where the graph is the dependency graph
    """
    dist = {}
    pred = {}
    for u in graph:
        dist[u] = {}
        pred[u] = {}
        for v in graph:
            dist[u][v] = float('inf')
            pred[u][v] = -1
        dist[u][u] = 0
        for neighbor in graph[u]:
            dist[u][neighbor] = graph[u][neighbor]
            pred[u][neighbor] = u
    for t in graph:
        for u in graph:
            for v in graph:
                newdist = dist[u][t] + dist[t][v]
                if newdist < dist[u][v]:
                    dist[u][v] = newdist
                    pred[u][v] = pred[t][v]
    return dist, pred


@classmethod
def from_iso(cls, iso):
    """Retrieve the first datacenter id associated to an ISO."""
    result = cls.list({'sort_by': 'id ASC'})
    dc_isos = {}
    for dc in result:
        if dc['iso'] not in dc_isos:
            dc_isos[dc['iso']] = dc['id']
    return dc_isos.get(iso)


def iso2gr(date):
    """Transform iso date string to greek formatted date string

    :param date: Iso formatted date string (yyyy-mm-dd)
    :return: Greek formatted date string (dd/mm/yyyy)
    """
    strdate = str(date)
    try:
        year, month, day = strdate.split('-')
        return '%s/%s/%s' % (day, month, year)
    except ValueError:
        return '01/01/1000'


def int_to_unknown_bytes(num, byteorder='big'):
    """Converts an int to the least number of bytes as possible."""
    return num.to_bytes((num.bit_length() + 7) // 8 or 1, byteorder)


def strip_spaces_and_quotes(value):
    """Remove invalid whitespace and/or single pair of dquotes and return None
    for empty strings.

    Used to prepare cookie values, path, and domain attributes in a way which
    tolerates simple formatting mistakes and standards variations.
    """
    value = value.strip() if value else ''
    if value and len(value) > 1 and value[0] == value[-1] == '"':
        value = value[1:-1]
    if not value:
        value = ''
    return value


def double(value, name):
    """casts to an float value"""
    if isinstance(value, float):
        return value
    fvalue = float(value)
    return fvalue


def _get_nexus_subject_param(vicon, name, param):
    """Wrapper to get subject parameter from Nexus."""
    value = vicon.GetSubjectParam(name, param)
    if type(value) == tuple:
        value = value[0] if value[1] else None
    return value


def _convert_ddb_list_to_list(conversion_list):
    """Given a dynamodb list, it will return a python list without the dynamodb
        datatypes

    Args:
        conversion_list (dict): a dynamodb list which includes the
            datatypes

    Returns:
        list: Returns a sanitized list without the dynamodb datatypes
    """
    ret_list = []
    for v in conversion_list:
        for v1 in v:
            ret_list.append(v[v1])
    return ret_list


def _outputItem(item, status):
    """
    Output the formatted information to the console.
    """
    print('{0:<9} {1}'.format(status, item))


def mat311mod(a, b):
    """
    Compute moduli of a 3x1 matrix.

    Parameters
    ----------
    a : tuple of float
        3x1 matrix
    b : float
        modulus

    Returns
    -------
    res : tuple of float
        3x1 matrix
    """
    res = [0, 0, 0]
    r3 = range(3)
    for i in r3:
        res[i] = int(a[i] - int(a[i] / b) * b)
    return res


def attach():
    """Attach active node to a frame

    """
    pass


def get_session_from_response_assertion(assertion):
    u"""
    Получение ID сессии из ответа (утверждения) на запрос

    :param assertion: Утверждение (Assertion, xml)
    :type assertion: etree.ElementTree
    :return: идентификатор сессии
    :rtype: basestring
    """
    session_id = None
    statement = assertion.xpath(
        '//saml2p:Response//saml2:Assertion//saml2:AuthnStatement',
        namespaces={'saml2p': 'urn:oasis:names:tc:SAML:2.0:protocol',
        'saml2': 'urn:oasis:names:tc:SAML:2.0:assertion'})
    if len(statement) > 0 and 'SessionIndex' in statement[0].attrib:
        session_id = statement[0].attrib['SessionIndex']
    return session_id


def load_pywintypes(finder, module):
    """the pywintypes module is actually contained in a DLL but since those
       cannot be loaded directly in Python 2.5 and higher a special module is
       used to perform that task; simply use that technique directly to
       determine the name of the DLL and ensure it is included as a normal
       extension."""
    import pywintypes
    module.file = pywintypes.__file__
    module.code = None


def frame_as_object(frame):
    """
    Return a pandas DataFrame as NumPy `dtype` ``object``.
    Useful for casting from a categorical frame.
    """
    return frame.apply(lambda x: x.astype('object'))


def populate_display_title(apps, schema_editor):
    """
    Populates display_title on both StacksFeaturedLink and
    StacksFeaturedLinkList.
    """
    StacksFeaturedLink = apps.get_model('stacks_featuredlink',
        'StacksFeaturedLink')
    for link in StacksFeaturedLink.objects.all():
        link.display_title = link.name
        link.save()
    StacksFeaturedLinkList = apps.get_model('stacks_featuredlink',
        'StacksFeaturedLinkList')
    for link_list in StacksFeaturedLinkList.objects.all():
        link_list.name = link_list.list_name
        link_list.display_title = link_list.list_name
        link_list.save()


@classmethod
def paper_doc_untrashed_details(cls, val):
    """
        Create an instance of this class set to the
        ``paper_doc_untrashed_details`` tag with value ``val``.

        :param PaperDocUntrashedDetails val:
        :rtype: EventDetails
        """
    return cls('paper_doc_untrashed_details', val)


@staticmethod
def format_place_list(places):
    """Format a list of places as an English phrase."""
    if len(places) < 3:
        return ' and '.join(places)
    else:
        most_places = ', '.join(places[0:-1])
        return '{}, and {}'.format(most_places, places[-1])


@staticmethod
def _trim_text_middle(val, maxw):
    """ Trim data by removing middle characters, so hello world' for 8 will become hel..rld.
            This kind of trimming seems to be better than tail trimming for user and database names.
        """
    half = int((maxw - 2) / 2)
    return val[:half] + '..' + val[-half:]


def remove_small_ns(taus, devs, deverrs, ns):
    """ Remove results with small number of samples.
        If n is small (==1), reject the result

    Parameters
    ----------
    taus: array
        List of tau values for which deviation were computed
    devs: array
        List of deviations
    deverrs: array or list of arrays
        List of estimated errors (possibly a list containing two arrays :
        upper and lower values)
    ns: array
        Number of samples for each point

    Returns
    -------
    (taus, devs, deverrs, ns): tuple
        Identical to input, except that values with low ns have been removed.

    """
    ns_big_enough = ns > 1
    o_taus = taus[ns_big_enough]
    o_devs = devs[ns_big_enough]
    o_ns = ns[ns_big_enough]
    if isinstance(deverrs, list):
        assert len(deverrs) < 3
        o_deverrs = [deverrs[0][ns_big_enough], deverrs[1][ns_big_enough]]
    else:
        o_deverrs = deverrs[ns_big_enough]
    if len(o_devs) == 0:
        print('remove_small_ns() nothing remains!?')
        raise UserWarning
    return o_taus, o_devs, o_deverrs, o_ns


def asciibytes(data):
    """For Python 2/3 compatibility:
    If it is 'bytes' already, do nothing, otherwise convert to ASCII Bytes"""
    if isinstance(data, bytes):
        return data
    else:
        return data.encode('ASCII')


def parents(node):
    """Returns a 2-tuple of parent nodes for a revision.

        Values will be ``nullid`` if the parent is empty.
        """


def method_overridden(method_name, klass, instance):
    """
    Determine if a method has been overridden.
    """
    method = getattr(klass, method_name)
    default_method = getattr(method, '__func__', method)
    return default_method is not getattr(instance, method_name).__func__


def str_query_param(value: 'PrimitiveData') ->str:
    """
    Coerce a primitive data type into a string value for query params.

    Note that we prefer JSON-style 'true'/'false' for boolean values here.
    """
    if value is True:
        return 'true'
    elif value is False:
        return 'false'
    elif value is None:
        return ''
    return str(value)


def set_stack_policy(StackName=None, StackPolicyBody=None, StackPolicyURL=None
    ):
    """
    Sets a stack policy for a specified stack.
    See also: AWS API Documentation

    :example: response = client.set_stack_policy(
        StackName='string',
        StackPolicyBody='string',
        StackPolicyURL='string'
    )

    :type StackName: string
    :param StackName: [REQUIRED]
            The name or unique stack ID that you want to associate a policy with.

    :type StackPolicyBody: string
    :param StackPolicyBody: Structure containing the stack policy body. For more information, go to Prevent Updates to Stack Resources in the AWS CloudFormation User Guide. You can specify either the StackPolicyBody or the StackPolicyURL parameter, but not both.

    :type StackPolicyURL: string
    :param StackPolicyURL: Location of a file containing the stack policy. The URL must point to a policy (maximum size: 16 KB) located in an S3 bucket in the same region as the stack. You can specify either the StackPolicyBody or the StackPolicyURL parameter, but not both.

    """
    pass


def _create_depend_tag(dep_type, name, version_eq=None, version_lt=None,
    version_lte=None, version_gt=None, version_gte=None):
    """Create xml snippet for package.xml."""
    version_string = []
    for key, var in {'version_eq': version_eq, 'version_lt': version_lt,
        'version_lte': version_lte, 'version_gt': version_gt, 'version_gte':
        version_gte}.items():
        if var is not None:
            version_string.append(' %s="%s"' % (key, var))
    result = '  <%s%s>%s</%s>\n' % (dep_type, ''.join(version_string), name,
        dep_type)
    return result