"""
This module intends to be a delegate for writing emails.

Its clients should only instantiate their writer of choice &
provide it with some basic data to include in the email.
They then get an email that's ready-to-send via taskcluster.Notify service.
"""

from dataclasses import dataclass, asdict
from abc import ABC, abstractmethod

from typing import List, Tuple, Union

from django.conf import settings
from treeherder.model.models import Push
from treeherder.perf.models import BackfillRecord, PerformanceSignature

FXPERF_TEST_ENG_EMAIL = "perftest-alerts@mozilla.com"  # team' s email

@dataclass
class Email:
    address: str = None
    content: str = None
    subject: str = None

    def as_payload(self) -> dict:
        return asdict(self)

class EmailWriter(ABC):
    def __init__(self):
        self._email = Email()

    def prepare_new_email(self, must_mention: Union[List[object], object]) -> dict:
        """
        Template method
        """
        must_mention = self.__ensure_its_list(must_mention)

        self._write_address()
        self._write_subject()
        self._write_content(must_mention)
        return self.email

    @property
    def email(self):
        return self._email.as_payload()

    @abstractmethod
    def _write_address(self):
        pass  # pragma: no cover

    @abstractmethod
    def _write_subject(self):
        pass  # pragma: no cover

    @abstractmethod
    def _write_content(self, must_mention: List[object]):
        pass  # pragma: no cover

    @staticmethod
    def __ensure_its_list(must_mention) -> List[object]:
        if not isinstance(must_mention, List):
            must_mention = [must_mention]
        return must_mention

# For automatically backfilling performance data
class BackfillReportContent:
    DESCRIPTION = """Perfherder automatically backfills performance jobs originating from Linux platforms.
     It does this every hour, as long as it doesn't exceed the daily limit.
    > __Here's a summary of latest backfills:__
    ---
        """

    TABLE_HEADERS = """
    | Alert summary | Alert | Job symbol | Total backfills (aprox.) | Push range |
    | :---: | :---: | :---: | :---: | :---: |
        """

    def __init__(self):
        self._raw_content = None

    def include_records(self, records: List[BackfillRecord]):
        self._initialize_report_intro()

        for record in records:
            self._include_in_report(record)

    def _initialize_report_intro(self):
        if self._raw_content is None:
            self._raw_content = self.DESCRIPTION + self.TABLE_HEADERS

    def _include_in_report(self, record: BackfillRecord):
        new_table_row = self._build_table_row(record)
        self._raw_content += f"{new_table_row}\n"

    def _build_table_row(self, record: BackfillRecord) -> str:
        alert_summary = record.alert.summary
        alert = record.alert
        job_type = record.job_type
        total_backfills = record.total_backfills_triggered
        push_range = self.__build_push_range(record.get_context())

        # some fields require adjustments
        summary_id = alert_summary.id
        alert_id = alert.id
        job_symbol = str(job_type)

        return f"| {summary_id} | {alert_id} | {job_symbol} | {total_backfills} | {push_range} |"

    def __build_push_range(self, backfill_context: List[dict]) -> str:
        """
        Provides link to Treeherder' s Job view
        """
        from_push, to_push = self.__fetch_border_pushes(backfill_context)  # suspect range as tuple

        # TODO: repository should be provided by upstream (AKA backfill context)
        #  to save some database calls
        repository = from_push.repository.name
        from_change = from_push.revision
        to_change = to_push.revision

        return f"{settings.SITE_URL}/jobs?repo={repository}&fromchange={from_change}&tochange={to_change}"

    def __fetch_border_pushes(self, backfill_context) -> Tuple[Push, Push]:
        from_datapoint = backfill_context[0]
        to_datapoint = backfill_context[-1]

        from_push = from_datapoint['push_id']
        to_push = to_datapoint['push_id']

        from_push = Push.objects.get(id=from_push)
        to_push = Push.objects.get(id=to_push)
        return from_push, to_push

    def __str__(self):
        if self._raw_content is None:
            raise ValueError("No content set")
        return self._raw_content

class BackfillNotificationWriter(EmailWriter):
    def _write_address(self):
        self._email.address = FXPERF_TEST_ENG_EMAIL

    def _write_subject(self):
        self._email.subject = "Automatic Backfilling Report"

    def _write_content(self, must_mention: List[BackfillRecord]):
        content = BackfillReportContent()
        content.include_records(must_mention)

        self._email.content = str(content)

# For performance data cycling
class DeletionReportContent:
    DESCRIPTION = """Perfherder removes performance data that is older than one year and in some cases even sooner, leaving behind performance signatures that aren't associated to any data point. These as well need to be removed.
    > __Here's a summary of recently deleted performance signatures:__
    ---
        """

    TABLE_HEADERS = """
    | Repository | Framework | Platform | Suite | Application |
    | :---: | :---: | :---: | :---: | :---: |
        """

    def __init__(self):
        self._raw_content = None

    def include_signatures(self, signatures: List[PerformanceSignature]):
        self._initialize_report_intro()

        for signature in signatures:
            self._include_in_report(signature)

    def _initialize_report_intro(self):
        if self._raw_content is None:
            self._raw_content = self.DESCRIPTION + self.TABLE_HEADERS

    def _include_in_report(self, signature: PerformanceSignature):
        new_table_row = self._build_table_row(signature)
        self._raw_content += f"{new_table_row}\n"

    def _build_table_row(self, signature: PerformanceSignature) -> str:
        props = self.__extract_properties(signature)

        return '| {repository} | {framework} | {platform} | {suite} | {application} |'.format(
            repository=props["repository"],
            framework=props["framework"],
            platform=props["platform"],
            suite=props["suite"],
            application=props["application"],
        )

    def __extract_properties(self, signature: PerformanceSignature) -> dict:
        return {
            "repository": signature.repository.name,
            "framework": signature.framework.name,
            "platform": signature.platform.platform,
            "suite": signature.suite,
            "application": signature.application,
        }

    def __str__(self):
        if self._raw_content is None:
            raise ValueError("No content set")
        return self._raw_content

class DeletionNotificationWriter(EmailWriter):
    def _write_address(self):
        self._email.address = FXPERF_TEST_ENG_EMAIL

    def _write_subject(self):
        self._email.subject = "Summary of deleted Performance Signatures"

    def _write_content(self, must_mention: List[PerformanceSignature]):
        content = DeletionReportContent()
        content.include_signatures(must_mention)

        self._email.content = str(content)


import sys

from elixir.statements import STATEMENTS
from elixir import Entity
from elixir import has_field, belongs_to, has_many
from elixir import Integer, String, CHAR, Integer

from sqlalchemy import func, select

from cartography import geometry

from byCycle.util import gis, joinAttrs
from byCycle.model.entities.util import cascade_args
from byCycle.model.data.sqltypes import POINT, LINESTRING

__all__ = ['Node', 'Edge', 'StreetName', 'City', 'State', 'Place']

def base_statements(base_entity_name):
    """Pseudo-statement to import the statements from a "base" entity.

    When this pseudo-statement is added as the first statement in an
    ``Entity`` class definition, it effectively copies the statements from the
    "base" ``Entity`` identified by ``base_entity_name`` to the "child"
    ``Entity`` that executes the statement.

    """
    entity = globals()[base_entity_name]
    class_locals = sys._getframe(1).f_locals
    statements = class_locals[STATEMENTS] = getattr(entity, STATEMENTS)[:]

class Node(Entity):
    has_field('geom', POINT(4326))
    has_many('edges_f', of_kind='Edge', inverse='node_f')
    has_many('edges_t', of_kind='Edge', inverse='node_t')

    @property
    def edges(self):
        return list(self.edges_f) + list(self.edges_t)

class Edge(Entity):
    has_field('addr_f_l', Integer)
    has_field('addr_f_r', Integer)
    has_field('addr_t_l', Integer)
    has_field('addr_t_r', Integer)
    has_field('even_side', CHAR(1)),
    has_field('one_way', Integer)
    has_field('permanent_id', Integer)
    has_field('geom', LINESTRING(4326))
    belongs_to('node_f', of_kind='Node', **cascade_args)
    belongs_to('node_t', of_kind='Node', **cascade_args)
    belongs_to('street_name', of_kind='StreetName', **cascade_args)
    belongs_to('place_l', of_kind='Place', **cascade_args)
    belongs_to('place_r', of_kind='Place', **cascade_args)

    def to_feet(self):
        return self.to_miles() * 5280.0

    def to_miles(self):
        return gis.getLengthOfLineString([self.geom.pointN(n) for n in
                                          range(self.geom.numPoints())])

    def to_kilometers(self):
        return self.to_miles() * 1.609344

    def to_meters(self):
        return self.to_kilometers() / 1000.0

    def getSideNumberIsOn(self, num):
        """Determine which side of the edge, "l" or "r", ``num`` is on."""
        # Determine odd side of edge, l or r, for convenience
        odd_side = ('l', 'r')[self.even_side == 'l']
        # Is ``num`` on the even or odd side of this edge?
        # FIXME: What if there's no address range on the side ``num`` is on?
        #        Right now, we return the odd side by default
        return (odd_side, self.even_side)[int(num) % 2 == 0]

    def getPlaceOnSideNumberIsOn(self, num):
        """Get `Place` on side ``num`` is on."""
        side = self.getSideNumberIsOn(num)
        if side == 'l':
            return self.place_l
        else:
            return self.place_r

    def __len__(self):
        """Get the length of this `Edge`, using cached value if available."""
        try:
            self._length
        except AttributeError:
            self._length = self.geom.length()
        return self._length

    length = __len__

    def getPointAndLocationOfNumber(self, num):
        """

        ``num``
            A number that should be in the this edge's address range

        return
            ``Point``
                The coordinate of ``num`` within this edge
            Location
                The location, in range [0, 1], of ``num`` within this edge

        """
        # Sanity check; num should always be an `int`
        num = int(num or 0)

        # Determine location in [0, 1] of num along edge
        # Note: addrs might be NULL/None
        addrs = (self.addr_f_l, self.addr_f_r, self.addr_t_l, self.addr_t_r)
        min_addr = min(addrs)
        max_addr = max(addrs)
        if not num or None in (min_addr, max_addr):
            location = .5
        else:
            if min_addr == max_addr:
                location = .5
            else:
                edge_len = max_addr - min_addr
                dist_from_min_addr = num - min_addr
                location = float(dist_from_min_addr) / edge_len

        c = self.c

        # Function to get interpolated point
        f = func.line_interpolate_point(c.geom, location)
        # Function to get WKB version of lat/long point
        f = func.asbinary(f)

        # Query DB and get WKB POINT
        select_ = select([f.label('wkb_point')], c.id == self.id)
        result = select_.execute()
        wkb_point = result.fetchone().wkb_point

        point = geometry.Geometry.fromWKB(wkb_point)
        return point, location

    def splitAtGeocode(self, geocode, node_id=-1, edge_f_id=-1, edge_t_id=-2):
        """Split this edge at ``geocode`` and return two new edges.

        ``geocode`` `Geocode` -- The geocode to split the edge at.

        See `splitAtLocation` for further details

        """
        edge_f, edge_t = self.splitAtLocation(
            geocode.xy, geocode.location, node_id, edge_f_id, edge_t_id
        )
        # address range
        num = geocode.address.number
        edge_f.addr_t_l, edge_f.addr_t_r = num, num
        edge_t.addr_f_l, edge_t.addr_f_r = num, num
        return edge_f, edge_t

    def splitAtNumber(self, num, node_id=-1, edge_f_id=-1, edge_t_id=-2):
        """Split this edge at ``num`` and return two new edges.

        ``num`` `int` -- The address number to split the edge at.

        See `splitAtLocation` for further details

        """
        point, location = self.getPointAndLocationOfNumber(num)
        return self.splitAtLocation(
            point, location, node_id, edge_f_id, edge_t_id
        )

    def splitAtLocation(self, point, location,
                        node_id=-1, edge_f_id=-1, edge_t_id=-2):
        """Split this edge at ``location`` and return two new edges.

        The first edge is `node_f`=>``num``; the second is ``num``=>`node_t`.
        Distribute attributes of original edge to the two new edges.

        ``location`` `float` -- Location in range [0, 1] to split at
        ``node_id`` -- Node ID to assign the node at the split
        ``edge_f_id`` -- Edge ID to assign the `node_f`=>``num`` edge
        ``edge_t_id`` -- Edge ID to assign the ``num``=>`node_t` edge

        return `Edge`, `Edge` -- `node_f`=>``num``, ``num``=>`node_t` edges

        Recipe:
        - Determine location of num along edge; use .5 as default
        - Get XY at location
        - Get line geometry on either side of XY
        - Transfer geometry and attributes to two new edges
        - Return the  two new edges

        """
        num_points = self.geom.numPoints()
        points = [self.geom.pointN(i) for i in range(num_points)]
        N = int(num_points * location) or 1
        if N == num_points:
            N -= 1
        edge_f_points = points[:N] + [point]
        edge_t_points = [point] + points[N:]
        srs = self.geom.srs
        edge_f_geom = geometry.LineString(points=edge_f_points, srs=srs)
        edge_t_geom = geometry.LineString(points=edge_t_points, srs=srs)

        RegionEdge = self.__class__
        edge_f = RegionEdge(id=edge_f_id,
                            node_f_id=self.node_f_id, node_t_id=node_id,
                            street_name=self.street_name,
                            geom=edge_f_geom)
        edge_t = RegionEdge(id=edge_t_id,
                            node_f_id=node_id, node_t_id=self.node_t_id,
                            street_name=self.street_name,
                            geom=edge_t_geom)

        RegionNode = self.node_f.__class__
        geom = self.geom
        shared_node = RegionNode(id=node_id, geom=geom.pointN(N))
        edge_f.node_f = RegionNode(id=self.node_f_id, geom=geom.startPoint())
        edge_f.node_t = shared_node
        edge_t.node_f = shared_node
        edge_t.node_t = RegionNode(id=self.node_t_id, geom=geom.endPoint())

        return edge_f, edge_t

    def __str__(self):
        stuff = [
            joinAttrs(('Address Range:',
                       self.addr_f_l, ', ', self.addr_f_r,
                       'to',
                       self.addr_t_l, ', ', self.addr_t_r)),
            (self.street_name or '[No Street Name]'),
            self.place_l, self.place_r,
        ]
        return joinAttrs(stuff, join_string='\n')

    def to_builtin(self):
        return super(Edge, self).to_builtin()

class StreetName(Entity):
    has_field('prefix', String(2))
    has_field('name', String)
    has_field('sttype', String(4))
    has_field('suffix', String(2))

    def __str__(self):
        attrs = (
            (self.prefix or '').upper(),
            self._name_for_str(),
            (self.sttype or '').title(),
            (self.suffix or '').upper()
        )
        return joinAttrs(attrs)

    def to_builtin(self):
        return {
            'prefix': (self.prefix or '').upper(),
            'name': self._name_for_str(),
            'sttype': (self.sttype or '').title(),
            'suffix': (self.suffix or '').upper()
        }

    def _name_for_str(self):
        """Return lower case name if name starts with int, else title case."""
        name = self.name
        no_name = '[No Street Name]'
        try:
            int(name[0])
        except ValueError:
            name = name.title()
        except TypeError:
            # Street name not set (`None`)
            if name is None:
                name = name = no_name
            else:
                name = str(name)
        except IndexError:
            # Empty street name ('')
            name = no_name
        else:
            name = name.lower()
        return name

    def __nonzero__(self):
        """A `StreetName` must have at least a `name`."""
        return bool(self.name)

    def __eq__(self, other):
        self_attrs = (self.prefix, self.name, self.sttype, self.suffix)
        try:
            other_attrs = (other.prefix, other.name, other.sttype, other.suffix)
        except AttributeError:
            return False
        return (self_attrs == other_attrs)

    def almostEqual(self, other):
        self_attrs = (self.name, self.sttype)
        try:
            other_attrs = (other.name, other.sttype)
        except AttributeError:
            return False
        return (self_attrs == other_attrs)

class City(Entity):
    has_field('city', String)

    def __str__(self):
        if self.city:
            return self.city.title()
        else:
            return '[No City]'

    def to_builtin(self):
        return {
            'id': self.id,
            'city': str(self)
        }

    def __nonzero__(self):
        return bool(self.city)

class State(Entity):
    has_field('code', CHAR(2))  # Two-letter state code
    has_field('state', String)

    def __str__(self):
        if self.code:
            return self.code.upper()
        else:
            return '[No State]'

    def to_builtin(self):
        return {
            'id': self.id,
            'code': str(self),
            'state': str(self.state or '[No State]').title()
        }

    def __nonzero__(self):
        return bool(self.code or self.state)

class Place(Entity):
    has_field('zip_code', Integer)
    belongs_to('city', of_kind='City', **cascade_args)
    belongs_to('state', of_kind='State', **cascade_args)

    def _get_city_name(self):
        return (self.city.city if self.city is not None else None)
    def _set_city_name(self, name):
        if self.city is None:
            self.city = City()
        self.city.city = name
    city_name = property(_get_city_name, _set_city_name)

    def _get_state_code(self):
        return (self.state.code if self.state is not None else None)
    def _set_state_code(self, code):
        if self.state is None:
            self.state = State()
        self.state.code = code
    state_code = property(_get_state_code, _set_state_code)

    def _get_state_name(self):
        return (self.state.state if self.state is not None else None)
    def _set_state_name(self, name):
        if self.state is None:
            self.state = State()
        self.state.state = name
    state_name = property(_get_state_name, _set_state_name)

    def __str__(self):
        city_state = joinAttrs([self.city, self.state], ', ')
        return joinAttrs([city_state, str(self.zip_code or '')])

    def to_builtin(self):
        return {
            'city': (self.city.to_builtin() if self.city is not None else None),
            'state': (self.state.to_builtin() if self.state is not None else None),
            'zip_code': str(self.zip_code or None)
        }

    def __nonzero__(self):
        return bool(self.city or self.state or (self.zip_code is not None))


import pandas as pd
import re
import nltk
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
from pickle import load

import os
current_directory = os.getcwd()
print(current_directory)

df = pd.read_csv('data/dataset/suspicious-tweets.csv')
model_to_load_path = 'data/modelSave/nb_model.sav'

def load_model(path):
    model = load(open(path, 'rb'))
    return model

def preprocess_text(sen):
    sentence = re.sub('(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)', ' ', sen)  # Removing html tags
    sentence = re.sub('[^a-zA-Z]', ' ', sentence)  # Remove punctuations and numbers
    sentence = re.sub(r"\s+[a-zA-Z]\s+", ' ', sentence)  # Single character removal
    sentence = re.sub(r'\s+', ' ', sentence)  # Removing multiple spaces
    sentence = sentence.replace("ain't", "am not").replace("aren't", "are not")
    sentence = ' '.join(text.lower() for text in sentence.split(' '))  # Lowering cases
    sw = stopwords.words('english')
    sentence = ' '.join(text for text in sentence.split() if text not in sw)  # removing stopwords
    return sentence

stemmer = PorterStemmer()
count_vect = CountVectorizer()

df['message'] = df.message.apply(preprocess_text)
df['message'] = df['message'].apply(nltk.word_tokenize)
df['message'] = df['message'].apply(lambda x: [stemmer.stem(y) for y in x])
df['message'] = df['message'].apply(lambda x: ' '.join(x))

counts = count_vect.fit_transform(df['message'])
transformer = TfidfTransformer().fit(counts)
counts = transformer.fit_transform(counts)
print("End modelPrediction computation")

def prediction(stringa):
    model = load_model(model_to_load_path)
    stringa = preprocess_text(stringa)
    stringa = nltk.word_tokenize(stringa)
    stringa = ' '.join(stringa)
    stringa = count_vect.transform([stringa])
    stringa = transformer.transform(stringa)
    prediction = model.predict(stringa)
    return prediction

#MAKE PREDICTION
print(prediction("I am going to kill"))

print(prediction("Negro Under Sentence To Hang At Tallahassee."))
print(prediction("Unbelievable murder by an African community in New York"))
print(prediction("LGBQT rights parade attacked by white supremacists"))
print(prediction("Governor Brough Fired Upon By Negroes At Elaine"))
print(prediction("In a Turbulent Time for China, Xi Projects Unity at an Ex-Leader’s Funeral"))
print(prediction("Drone Attacks Hit Russia for 2nd Straight Day"))
print(prediction("pain Is Locked in a Stalemate With Morocco in the Second Half"))
print(prediction("Inside the Saudi Strategy to Keep the World Hooked on Oil"))
print(prediction("Biden Administration Expands Protections for Haitian Migrants"))
print(prediction("vegetarian mushroom shawarma pitas"))
print(prediction("Lebanese Stuffed Eggplant"))
print(prediction("Rosquillas maize biscuits from Nicaragua"))
print(prediction("Typical Polish dish - Zurek"))
print(prediction("Is This Elephant Bothering You?"))


from random import randint

sum = 20000
bet = 500
loss = 0
profit = 0
chance = 0

sleact = int(input("Enter your Dice sleaction"))

while(sum >= 0):
    profit = 0
    chance += 1
    x = randint(2, 12)
    print("Bet = ", bet)
    if x == sleact:
        sum = sum + (bet * 3)
        profit = profit + (bet*3)
        bet = 500

    else:
        loss = loss + bet
        sum = sum - bet
        bet = bet + 500

    print("Chances = ", chance)
    print("Dice = ", x)
    print("Total = ", sum)
    print("Loss = ", loss)
    print("Profit = ", profit)
    print("Total profit = ", profit - loss)

    input()


from datetime import datetime

import boto3
from botocore.exceptions import ClientError

from stream_alert_cli.logger import LOGGER_CLI

class LambdaVersion(object):
    """Publish new versions of the StreamAlert Lambda functions.

    Each Lambda function is configured with a production alias.
    This alias points to the latest published version of the
    Lambda function.

    After a Lambda package is versioned, the StreamAlert config
    is updated, and then Terraform runs to update the alias with
    the new version number.

    All StreamAlert setups should start with "$LATEST".
    """

    def __init__(self, **kwargs):
        """Initialize the version publishing

        Keyword Args:
            config (CLIConfig): Loaded StreamAlert CLI Config
            package (LambdaPackage): The created Lambda Package
            clustered_deploy (bool): Identifies cluster based Lambdas
        """
        self.config = kwargs['config']
        self.package = kwargs['package']
        self.clustered_deploy = kwargs.get('clustered_deploy', True)

    @staticmethod
    def _version_helper(**kwargs):
        """Make the API call to publish the Lambda function

        Keyword Arguments:
            client (boto3.client): Lambda boto3 client
            function_name (str): Lambda function name to publish
            code_sha_256 (str): The SHA256 of the current $LATEST package
            date (datetime): Current time

        Returns:
            int: Version OR False if the publish fails
        """
        client = kwargs.get('client')
        if not client:
            LOGGER_CLI.error('No AWS client provided')
            return False

        try:
            version = client.publish_version(
                FunctionName=kwargs['function_name'],
                CodeSha256=kwargs['code_sha_256'],
                Description='Publish Lambda {} on {}'.format(kwargs['function_name'],
                                                             kwargs['date'])
            )['Version']
        except ClientError as err:
            LOGGER_CLI.error(err)
            return False

        return int(version)

    def _publish_helper(self, **kwargs):
        """Handle clustered or single Lambda function publishing

        Keyword Arguments:
            cluster (str): The cluster to deploy to, this is optional

        Returns:
            bool: Result of the function publishes
        """
        cluster = kwargs.get('cluster')
        # Clustered Lambda functions have a different naming pattern
        if cluster:
            region = self.config['clusters'][cluster]['region']
            function_name = '{}_{}_streamalert_{}'.format(
                self.config['global']['account']['prefix'],
                cluster,
                self.package.package_name
            )
        else:
            region = self.config['global']['account']['region']
            function_name = '{}_streamalert_{}'.format(
                self.config['global']['account']['prefix'],
                self.package.package_name
            )

        # Configure the Lambda client
        client = boto3.client('lambda', region_name=region)
        code_sha_256 = self.config['lambda'][self.package.config_key]['source_current_hash']

        # Publish the function(s)
        # TODO: move the extra logic into the LambdaPackage subclasses instead of this
        if self.package.package_name == 'stream_alert_app':
            if not 'stream_alert_apps' in self.config['clusters'][cluster]['modules']:
                return True # nothing to publish for this cluster

            for app_name, app_info in self.config['clusters'][cluster]['modules'] \
                ['stream_alert_apps'].iteritems():
                # Name follows format: '<prefix>_<cluster>_<service>_<app_name>_app'
                function_name = '_'.join([self.config['global']['account']['prefix'], cluster,
                                          app_info['type'], app_name, 'app'])
                new_version = self._publish(client, function_name, code_sha_256)
                if not new_version:
                    continue

                LOGGER_CLI.info('Published version %s for %s:%s',
                                new_version, cluster, function_name)

                app_info['current_version'] = new_version

        else:

            new_version = self._publish(client, function_name, code_sha_256)
            if not new_version:
                return False

            # Update the config
            if cluster:
                LOGGER_CLI.info('Published version %s for %s:%s',
                                new_version, cluster, function_name)
                self.config['clusters'][cluster]['modules']['stream_alert'] \
                    [self.package.package_name]['current_version'] = new_version
            else:
                LOGGER_CLI.info('Published version %s for %s',
                                new_version, function_name)
                self.config['lambda'][self.package.config_key]['current_version'] = new_version
        self.config.write()

        return True

    def _publish(self, client, function_name, code_sha_256):
        """Publish the function"""
        date = datetime.utcnow().strftime("%Y%m%d_T%H%M%S")
        LOGGER_CLI.debug('Publishing %s', function_name)
        new_version = self._version_helper(
            client=client,
            function_name=function_name,
            code_sha_256=code_sha_256,
            date=date)

        return new_version

    def publish_function(self):
        """Main Publish Function method"""
        if self.clustered_deploy:
            for cluster in self.config.clusters():
                if not self._publish_helper(cluster=cluster):
                    return False
        else:
            if not self._publish_helper():
                return False

        return True


arq = open("cod.txt", "r")
names = arq.readlines()
arq.close()

arqName = "stringsCod.txt"

file = open(arqName,"w")

file.write("c(")

k = 1

for i in names:
	file.write('"' + i.rstrip() + '" = ' + str(k) + ',')
	k+=1

file.write(")")
file.close()


import codecs
import json
from Netflix import netflix
from JLPT import jlpt
from WaniKani import wanikani
from Dialect import dialect

frequencyFileNumber = int(input("""
After execution, there will be a text file generated with the corresponding name of the frequency file(s)
with all the words that weren't in your known words list.

Which frequency file would you like to use to compare with your known words?
1. Narou
2. Netflix
3. Novel 5k
4. Slice of Life
5. Shonen
6. Visual Novel
7. JLPT
8. Wanikani
9. Dialect
"""))

stars = 0
level = 0
if frequencyFileNumber < 7:
    stars = int(input("Up to how many stars do you want to analyze? (e.g. \"4\") "))
elif frequencyFileNumber == 7 or frequencyFileNumber == 8:
    level = int(input("Up to which level do you want to analyze? (e.g. \"3\") "))
elif frequencyFileNumber == 9:
    pass
else:
    raise Exception("Choose a better number for the stars or levels!")

if frequencyFileNumber == 1:
    fileNameFrequency = "Narou.json"
elif frequencyFileNumber == 2:
    fileNameFrequency = "Netflix.json"
elif frequencyFileNumber == 3:
    fileNameFrequency = "Novel 5k.json"
elif frequencyFileNumber == 4:
    fileNameFrequency = "Slice of Life.json"
elif frequencyFileNumber == 5:
    fileNameFrequency = "Shonen.json"
elif frequencyFileNumber == 6:
    fileNameFrequency = "Visual Novel.json"
elif frequencyFileNumber == 7:
    fileNameFrequency = "JLPT.json"
elif frequencyFileNumber == 8:
    fileNameFrequency = "Wanikani.json"
elif frequencyFileNumber == 9:
    fileNameFrequency = "Dialect.json"
else:
    raise Exception("Choose an actual number that is displayed in the help menu!")

fileNameWords = "Words.json"

dataFrequency = json.load(codecs.open(fileNameFrequency, 'r', 'utf-8-sig'))

with open(fileNameWords, 'r', encoding='UTF-8') as file:
    dataWords = json.load(file)

if frequencyFileNumber < 7:
    netflix(dataWords, dataFrequency, stars)
if frequencyFileNumber == 7:
    jlpt(dataWords, dataFrequency, level)
if frequencyFileNumber == 8:
    wanikani(dataWords, dataFrequency, level)
if frequencyFileNumber == 9:
    dialect(dataWords, dataFrequency)


# imports
from flask import Flask
from flask_restful import Api
from resources.items import Items
import temp_db

# initialization

app = Flask(__name__)
app.config["PROPOGATE_EXCEPTIONS"] = True
api = Api(app)

# endpoints
api.add_resource(Items, "/items")

# database initialization
temp_db.create_table()
if not temp_db.check_records():
    temp_db.insert_into_table()

temp_db.show_all()

# execution
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)


from picamera import PiCamera
from os import system
from time import sleep
import sys
import argparse

parser = argparse.ArgumentParser(description='Este programa permite tomar timelapses con una rPI Cam')
parser.add_argument('-tt','--totaltime', help='Tiempo total del timelapse en segundos', required=False, type=int)
parser.add_argument('-l','--lapse',help='Tiempo entre fotos en segndos', required=True, type=int)
parser.add_argument('-c', '--cantidad', help='Cantidad de imagenes', required=True, type=int)

args = parser.parse_args()

camera = PiCamera()
camera.resolution = (1024,768)
camera.vflip = True
camera.hflip = True

totaltime = args.totaltime
lapse = args.lapse
cantidad = args.cantidad

for i in range(cantidad):
    name = 'image{0:04d}.jpg'.format(i)
    camera.capture(name)
    print('photo %s taken'%(name))
    sleep(lapse)

print('done')


from kivy.clock import Clock
from kivy.base import EventLoop
from kivy.uix.button import Button

from src.monitor import kivy_timing

from src.common import (
    GRID_HINT,
    DEFAULT_ATLAS,
    get,
    generate_grid_id
)

from src.save import (
    GRID,
    load_level,
    save_level,
    validate_character
)

# All the grid custom widget ids will be store here. This is because the ids
# are not stored in kivy layout ids because there were dynamically updated so
# we manually store the id reference of all the word button object
grid_ptr: list = []

# The custom widget which will use to construct grids for the cross word
# levels. This is actually a button widget with some custom logic for the game
class WordButton(Button):
    # To prevent mulitple selection we use a static variable to lock the grid
    lock: bool = False

    # @kivy_timing -> Slow
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        grid_ptr.append(self)
        self.opacity: float = 0.0
        self.id: str = generate_grid_id()
        self.next_auto_selection_id = self.id
        self.disabled: bool = True
        self.text: str = str(GRID.popleft()) if len(GRID) >= 0 else 'X'
        self.level_logic()
        self.bind(on_press=self.on_click)
        self.fade_effect_ptr = Clock.schedule_interval(self.fade_effect, 0.001)
        EventLoop.window.bind(on_keyboard=self.event_keyboard)

    # @kivy_timing -> Slow
    def level_logic(self) -> None:
        if self.text == "0":
            self.text = ""
        else:
            self.disabled = False
            if self.text.islower():
                self.text = ""

    @kivy_timing
    def on_click(self, *_) -> None:
        if self.text == "" and not self.disabled and not WordButton.lock:
            self.text = "?"
            WordButton.lock = True
            self.background_normal = ""
            self.background_color = 0, 1, 1, 1
        if self.text == "" and not self.disabled and WordButton.lock:
            self.text = "?"
            # remove previous selection
            for widget in grid_ptr:
                if widget.text == "?" and widget != self:
                    widget.background_normal = DEFAULT_ATLAS
                    widget.background_color = 1, 1, 1, 1
                    widget.text = ""
            self.background_normal = ""
            self.background_color = 0, 1, 1, 1

    # @kivy_timing ->
    def event_keyboard(self, __, key: int, *_):
        if self.text == "?":
            # NOTE: Reload the level data again to check validation This needs
            # to be done because while building the grid all the elements are
            # popped out. Thus the GRID deque was empty.
            load_level(get(level_number=True))
            WordButton.lock = False

            # set the grid block to it's original form
            def set_grid_block_to_default(*_):
                self.background_normal = DEFAULT_ATLAS
                self.background_color = 1, 1, 1, 1
                try:
                    selection = GRID_HINT[int(self.id)].split()[1]
                except IndexError:
                    selection = '0'
                if selection == 'd':
                    self.next_auto_selection_id = str(int(self.id) + 14)
                if selection == 'dd':
                    self.next_auto_selection_id = str(int(self.id) + 28)

                elif selection == 'u':
                    self.next_auto_selection_id = str(int(self.id) - 14)
                if selection == 'uu':
                    self.next_auto_selection_id = str(int(self.id) - 28)

                elif selection == 'l':
                    self.next_auto_selection_id = str(int(self.id) - 1)
                elif selection == 'll':
                    self.next_auto_selection_id = str(int(self.id) - 2)

                elif selection == 'r':
                    self.next_auto_selection_id = str(int(self.id) + 1)
                elif selection == 'rr':
                    self.next_auto_selection_id = str(int(self.id) + 2)

                elif selection == 'dr':
                    x = str(int(self.id) + 14)
                    self.next_auto_selection_id = str(int(x) + 1)
                elif selection == 'ur':
                    x = str(int(self.id) - 14)
                    self.next_auto_selection_id = str(int(x) + 1)

                elif selection == 'dl':
                    x = str(int(self.id) + 14)
                    self.next_auto_selection_id = str(int(x) - 1)
                elif selection == 'ul':
                    x = str(int(self.id) - 14)
                    self.next_auto_selection_id = str(int(x) - 1)

                elif selection == '0':
                    self.next_auto_selection_id = '0'

                for widget in grid_ptr:
                    try:
                        if widget.id == self.next_auto_selection_id != self.id and not widget.text.upper() and self.text != "":
                            widget.background_normal = ""
                            widget.background_color = 0, 1, 1, 1
                            widget.text = '?'
                    except AttributeError:
                        pass
                WordButton.lock = True

            def not_correct_letter(*_):
                self.text = ""
                set_grid_block_to_default(None)

            # Android Back button or Esc key
            if key == 27:
                Clock.schedule_once(not_correct_letter, 1)

            # The key mush be the ascii value of the lowercase character as
            # the save file contains the lowercase chararcter to validate with
            if validate_character(chr(key).lower(), self.id):
                self.text = chr(key).upper()
                save_level(int(self.id), chr(key).upper())
                Clock.schedule_once(set_grid_block_to_default, 1)
            else:
                self.text = "X"
                self.background_normal = DEFAULT_ATLAS
                self.background_color = 1, 0, 0, 1
                Clock.schedule_once(not_correct_letter, 1)

    # @kivy_timing -> Slow
    def fade_effect(self, *_) -> None:
        if self.opacity < 1:
            self.opacity += 0.1
        # Unregister event after use
        elif self.opacity > 1:
            Clock.unschedule(self.fade_effect_ptr)


from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("new-listing", views.new_listing, name="new-listing"),
    path("listings/<slug>", views.listing, name="listing"),
    path("add-or-delete-watchlist/<slug>", views.add_or_delete_watchlist, name="add-or-delete-watchlist"),
    path("listings/<slug>/bid", views.bid, name="bid"),
    path("listings/<slug>/close", views.close_listing, name="close-listing"),
    path("listings/<slug>/comment", views.comment, name="comment"),
    path("watchlist", views.watchlist, name="watchlist"),
    path("categories", views.categories, name="categories"),
    path("categories/<slug>", views.category, name="category")
]


import numpy as np
from scipy.stats import entropy
import warnings

class MarkovChain:

    '''
    A MarkovChain
    '''

    def __init__(self, transition_matrix=None, state_vector=None):
        self.transition_matrix = transition_matrix
        self.state_vector = state_vector

    @property
    def transition_matrix(self):

        '''
        The Markov state transition probability matrix.
        Needs to be square.
        '''

        return self._transition_matrix

    @transition_matrix.setter
    def transition_matrix(self, transition_matrix):
        if transition_matrix is not None:
            transition_matrix = np.array(transition_matrix)
            assert transition_matrix.shape[0] == transition_matrix.shape[1], \
                'transition matrix needs to be square'
            assert all(transition_matrix.sum(axis=1).round(8) == 1), \
                'transition matrix rows need to sum to one'
            if hasattr(self, 'state_vector') and self.state_vector is not None:
                assert transition_matrix.shape[0] == self.state_vector.shape[1], \
                    'state vector dimension mismatch'
            self._transition_matrix = transition_matrix
        else:
            self._transition_matrix = None

    @property
    def state_vector(self):

        '''
        The current state vector.
        '''

        return self._state_vector

    @state_vector.setter
    def state_vector(self, state_vector):
        if state_vector is not None:
            state_vector = np.array(state_vector).reshape(1,-1)
            assert state_vector.sum(axis=1).round(8) == 1, \
                'state vector needs to sum to one'
            assert (state_vector>=0).all() and (state_vector<=1).all(), \
                'probabilites need to be bounded between zero and one'
            if hasattr(self, 'transition_matrix') and self.transition_matrix is not None:
                assert state_vector.shape[1] == self.transition_matrix.shape[0], \
                    'transition matrix dimension mismatch'
            self._state_vector = state_vector
        else:
            self._state_vector = None

    def steady_state(self, set_state=False):

        '''
        Returns the steady state probabilities of the Markov chain.
        If set_state=True, MarkovChain object is modified in place.
        '''

        dim = np.array(self.transition_matrix).shape[0]
        q = np.c_[(self.transition_matrix-np.eye(dim)),np.ones(dim)]
        QTQ = np.dot(q, q.T)
        steady_state = np.linalg.solve(QTQ,np.ones(dim))
        if set_state:
            self.state_vector = steady_state
        else:
            return steady_state

    def expected_durations(self):

        '''
        Returns the expected state durations of the MarkovChain object.
        '''

        expected_durations = (np.ones(self.n_states)-np.diag(self.transition_matrix))**-1
        return expected_durations

    @property
    def n_states(self):

        '''
        Returns the number of states of the MarkovChain object.
        '''

        if self.state_vector is not None:
            return self.state_vector.shape[1]
        elif self.transition_matrix is not None:
            return self.transition_matrix.shape[0]
        else:
            raise TypeError('MarkovChain object empty')

    def iterate(self, steps=1, set_state=False):

        '''
        Iterates the MarkovChain object the specified number of steps.
        steps should be a positive integer.
        (negative steps work, but tend to break when going before the initial state)
        If set_state=True, MarkovChain object is modified in place.
        '''

        new_state = np.dot(self.state_vector, np.linalg.matrix_power(self.transition_matrix, steps))

        # ensure total probability is 1
        # if new_state.sum() != 1:
        #     new_state = new_state.round(8)/new_state.round(8).sum()
        #     warnings.warn('state vector probabilities rounded to 8 digits')

        if set_state:
            self.state_vector = new_state
        else:
            new_mc = MarkovChain(transition_matrix=self.transition_matrix,
                                 state_vector=new_state)
            return new_mc

    def forecast(self, horizons=[1]):

        '''
        Returns forecasted state probabilities for a set of horizons.
        horizons needs to be an iterable.
        '''

        horizons_states = np.array([]).reshape(0, self.n_states)
        for horizon in horizons:
            pi_ = np.dot(self.state_vector, np.linalg.matrix_power(self.transition_matrix, horizon))
            horizons_states = np.concatenate([horizons_states, pi_.reshape(1, self.n_states)], axis=0)
        return horizons_states

    def rvs(self, size=0, random_state=1):

        '''
        Draws a random sample sequence from the MarkovChain object.
        t_steps is the number of time steps forward to be drawn.
        If t_steps is zero, only the current state is drawn.
        '''

        sample = np.random.choice(self.n_states, size=1, p=self.state_vector.squeeze())
        for t in range(1, size+1):
            sample = np.concatenate([sample, \
                        np.random.choice(self.n_states, size=1, p=self.transition_matrix[sample[-1]])])
        return sample

    def entropy(self, horizons=None):

        '''
        Calculate Shannon's entropy of the n state probabilities based on logarithms with base n.
        '''

        if horizons is None:
            state_entropy = entropy(self.state_vector.squeeze(), base=self.n_states)

        else:
            horizon_states = self.forecast(horizons)
            state_entropy = []
            for horizon in horizon_states:
                state_entropy += [entropy(horizon.squeeze(), base=self.n_states)]

        return np.array(state_entropy)

    def __repr__(self):
        return str(self)

    def __str__(self):
        '''
        Returns a summarizing string
        '''

        string = 'MarkovChain(\n'
        string += 'P=\n{},\n'.format(self.transition_matrix.__str__())
        string += 'pi=\n{}\n)'.format(self.state_vector.__str__())
        return string


from flask import jsonify, make_response, request
from flask_restful import Resource
from ..models.sale_model import *

class Sales(Resource):
    def __init__(self):
        self.sale = Sale()

    def post(self):
        data = request.get_json()
        user_id = data['user_id']
        product_id = data['product_id']
        quantity = data['quantity']
        unit_price = data['unit_price']
        total_cost = int(data['quantity']) * int(data['unit_price'])

        sale = self.sale.create_sale(user_id, product_id, quantity, unit_price)
        return make_response(jsonify({
            "message": "success",
            "sale": sale,
            "total_cost": total_cost
        }), 201)

    def get(self):
        sales = self.sale.get_all_sales()
        return make_response(jsonify({
            "status": "OK",
            "message": "success",
            "products": sales
        }), 200)

class FilterRecordsByAttendant(Resource):
    def __init__(self):
        self.sales = Sale()

    def get(self, user_id):
        sale_records = self.sales.filter_sales_records_by_attendant(user_id)
        return make_response(jsonify({
            "status": "OK",
            "message": "success",
            "product": sale_records
        }), 200)


#!/usr/bin/env python3
import argparse
import sql_metadata
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='hoge')
    parser.add_argument('filename', type=str)
    args = parser.parse_args()
    with open(args.filename) as f:
        read_data = f.read()
    f.close()
    for name in sql_metadata.get_query_tables(read_data):
        print(name)


import random
import shutil
import os
from func import *

tf.set_random_seed(777)  # for reproducibility

BATCH_SIZE = 32
LEARNING_RATE = 0.0001
HIDDEN_LAYER_NUM = 8
ONE_HIDDEN_LAYER_INPUT = 20
HIDDEN_LAYER_INPUTS = [ONE_HIDDEN_LAYER_INPUT] * (HIDDEN_LAYER_NUM + 1)
OPT_NAME = "r00001_hl" + str(HIDDEN_LAYER_NUM) + "_" + str(ONE_HIDDEN_LAYER_INPUT) + "_adam_leaky"
MAX_STEP = 30001
PROJECT_FOLDER = "../"
DATASET_NUM = 3

tf.reset_default_graph()

for index in range(0, DATASET_NUM):
    if index != 2:
        continue
    training_file_name = PROJECT_FOLDER + "data/problem1/training_" + str(index) + ".csv"
    test_file_name = PROJECT_FOLDER + "data/problem1/test_" + str(index) + ".csv"

    xy = np.loadtxt(training_file_name, delimiter=',', dtype=np.float32, skiprows=1)
    x_data = xy[:, 0:-1]
    y_data = xy[:, [-1]]
    feature_num = x_data.shape[1]

    X = tf.placeholder(tf.float32, [None, feature_num], name='x-input')
    Y = tf.placeholder(tf.float32, [None, 1], name='y-input')

    layer_parameters = []
    with tf.name_scope("inputlayer") as scope:
        W_input, b_input, layer_input = make_layer_simple(X, feature_num, HIDDEN_LAYER_INPUTS[0], "_input")
        layer_parameters.append([W_input, b_input, layer_input])
        w_input_hist, b_input_hist, layer_input_hist = make_summary(W_input, b_input, layer_input, "_input")

    # Hidden Layer
    for hd_index in range(0, HIDDEN_LAYER_NUM):
        with tf.name_scope("layer" + str(hd_index)) as scope:
            W, b, layer = make_layer_simple(layer_parameters[-1][2], HIDDEN_LAYER_INPUTS[hd_index],
                                          HIDDEN_LAYER_INPUTS[hd_index+1], str(hd_index))
            W_hist, b_hist, layer_hist = make_summary(W, b, layer, str(hd_index))

    with tf.name_scope("hypothesis") as scope:
        W_hypo, b_hypo, hypothesis = make_layer_sigmoid(layer_parameters[-1][2], HIDDEN_LAYER_INPUTS[-1], 1, "_hypo")
        w_hypo_hist, b_hypo_hist, hypothesis_hist = make_summary(W_hypo, b_hypo, hypothesis, "_hypo")

    with tf.name_scope("cost") as scope:
        cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
        tf.summary.scalar("cost", cost)

    with tf.name_scope("train") as scope:
        optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(cost)

    # Calculate accuracy
    predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))
    accuracy_summ = tf.summary.scalar("accuracy", accuracy)

    with tf.Session() as sess:
        # tensorboard --logdir=./logs/xor_logs
        merged_summary = tf.summary.merge_all()
        log_file_path = PROJECT_FOLDER + "logs/problem1/data_" + str(index) + "/" + OPT_NAME
        if os.path.exists(log_file_path):
            shutil.rmtree(log_file_path)
        writer = tf.summary.FileWriter(log_file_path)
        writer.add_graph(sess.graph)  # Show the graph

        # Initialize TensorFlow variables
        sess.run(tf.global_variables_initializer())

        last_cost = -1.0

        for step in range(MAX_STEP):
            summary, _ = sess.run([merged_summary, optimizer], feed_dict={X: x_data, Y: y_data})
            writer.add_summary(summary, global_step=step)

            if step % 1000 == 0:
                curr_cost = sess.run(cost, feed_dict={X: x_data, Y: y_data});
                print(step, curr_cost)
                # cost convergence
                # if abs(last_cost - curr_cost) < 0.005:
                    # break
                # result with train data has 99% accuracy
                if sess.run(accuracy, feed_dict={X: x_data, Y: y_data}) > 0.99:
                    break
                last_cost = curr_cost

        print("%d, Learning finished\n" % step)
        tf.summary.FileWriterCache.clear()

        # Accuracy report
        # for test
        test_xy = np.loadtxt(test_file_name, delimiter=',', dtype=np.float32, skiprows=1)
        test_x_data = test_xy[:, 0:-1]
        test_y_data = test_xy[:, [-1]]

        h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X: test_x_data, Y: test_y_data})
        # print('\nHypothesis: %d', h)
        # print("\nCorrect (Y): ", c)
        print("\nAccuracy: ", a)

        result_filename = PROJECT_FOLDER + "/result/problem1/data_" + str(index) + "/" + OPT_NAME + '.txt'
        os.makedirs(os.path.dirname(result_filename), exist_ok=True)
        result = open(result_filename, 'w')
        result.write("%f\n" % a)
        for item1, item2 in zip(h, c):
            result.write("%s %s\n" % (item1[0], item2[0]))

    print(str(index) + " : Done")
    tf.reset_default_graph()


from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
from config import TOKEN_API
import hashlib

bot = Bot(TOKEN_API)
dp = Dispatcher(bot)

@dp.inline_handler()
async def inline_cmd(inline_query: types.InlineQuery):
    text = inline_query.query or 'Empty'
    result_bold = hashlib.md5(text.encode()).hexdigest()
    text_italic = text + '1'
    result_italic = hashlib.md5(text_italic.encode()).hexdigest()

    item_bold = InlineQueryResultArticle(
        id=result_bold,
        input_message_content= InputTextMessageContent(f'{text}',parse_mode='HTML'),
        title = 'Bold',
        description='Empty',
        thumb_height=150,
        thumb_width=150,
        thumb_url = 'https://illustratorhow.com/wp-content/uploads/bold-text-illustrator7.png',
    )

    item_italic = InlineQueryResultArticle(
        id=result_italic,
        input_message_content=InputTextMessageContent(f'{text}',
                                                      parse_mode='HTML'),
        title = 'Italic',
        description='Empty',
        thumb_height=150,
        thumb_width=150,
        thumb_url = 'https://cdn-icons-png.flaticon.com/512/59/59377.png',
    )

    await bot.answer_inline_query(inline_query_id=inline_query.id,
                                  results=[item_bold, item_italic],
                                  cache_time=1)

if __name__ == "__main__":
    executor.start_polling(dispatcher=dp,
                           skip_updates=True)


# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 08:39:32 2018

@author: Anit Aggarwal
"""

import numpy as np
import pandas as pd
import math
import random

M = int(input("Enter the size of population"))
N = int(input("Enter the length of each memeber"))

population = np.random.randint(2,size=(M,N))
print(population)

G = int(input("Enter the number of generations to be passed "))

def fitness_func(X):
    return (sum(X)*sum(X))

fitness_values= np.ndarray(shape=(M,1))
for g in range(G):
    for i in range(M):
        fitness_values[i]=fitness_func(population[i])

    combined_array = np.hstack((population,fitness_values))

    normalized_fitness_values = fitness_values/sum(fitness_values)

    previous_probability = 0.0
    probability_of_selection= np.ndarray(shape=(M,1))

    for i in range(M):
        probability_of_selection[i,0] = previous_probability+ normalized_fitness_values[i]
        previous_probability = probability_of_selection[i,0]

    random_value1 = np.random.ranf()

    for i in range(M):
        if random_value1 < probability_of_selection[i]:
            idx1 = i
            break

    random_value2 = np.random.ranf()

    for i in range(M):
        if i == idx1:
            continue
        if random_value2<probability_of_selection[i]:
            idx2 = i
            break

    print(probability_of_selection[idx])
    print(idx1)

    print(probability_of_selection[idx])
    print(idx2)

    parent1 = population[idx1, :]
    parent2 = population[idx2, :]

    print("Selected Parents for crossover")
    print(parent1)
    print(parent2)

    cpt1 = random.randint(1,len(parent1)-1)

    offspring1= np.concatenate((parent1[0  : cpt1], parent2[cpt1 :  ]),axis=0)
    offspring2= np.concatenate((parent2[0  : cpt1], parent1[cpt1 :  ]),axis=0)

    print("Offsprings produced after crossover")
    print(offspring1)
    print(offspring2)

    probablityOfMutation=np.random.ranf()
    mutationPoint=random.randint(0,N-1)
    R3=np.random.ranf()

    if R3>=probablityOfMutation:
        offspring1[mutationPoint]=(offspring1[mutationPoint] + 1)%2;
        print("Offspring 1 after undergoing mutation")
        print(offspring1)

    population[idx1, :] = offspring1
    population[idx2, :] = offspring2

print("Population after",G,"Generations")
print(population)


BASE32_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789'
EXCLUDE_CHARS = {'o', 'i', 'l', 'q'}
CHARSET = ''
for c in BASE32_CHARS:
    if c not in EXCLUDE_CHARS:
        CHARSET += c
CHECKSUM_SIZE = 8

def polymod(values):
    chk = 1
    generator = [
        (0x01, 0x98f2bc8e61),
        (0x02, 0x79b76d99e2),
        (0x04, 0xf33e5fb3c4),
        (0x08, 0xae2eabe2a8),
        (0x10, 0x1e4f43e470)]
    for value in values:
        top = chk >> 35
        chk = ((chk & 0x07ffffffff) << 5) ^ value
        for i in generator:
            if top & i[0] != 0:
                chk ^= i[1]
    return chk ^ 1

def prefix_expand(prefix):
    return [ord(x) & 0x1f for x in prefix] + [0]

def calculate_checksum(prefix, payload):
    poly = polymod(prefix_expand(prefix) + payload + [0, 0, 0, 0, 0, 0, 0, 0])
    out = list()
    for i in range(CHECKSUM_SIZE):
        out.append((poly >> 5 * (7 - i)) & 0x1f)
    return out

def verify_checksum(prefix, payload):
    return polymod(prefix_expand(prefix) + payload) == 0

def b32decode(inputs):
    out = list()
    for letter in inputs:
        out.append(CHARSET.find(letter))
    return out

def b32encode(inputs):
    out = ''
    for char_code in inputs:
        out += CHARSET[char_code]
    return out

def convertbits(data, frombits, tobits, pad=True):
    acc = 0
    bits = 0
    ret = []
    maxv = (1 << tobits) - 1
    max_acc = (1 << (frombits + tobits - 1)) - 1
    for value in data:
        if value < 0 or (value >> frombits):
            return None
        acc = ((acc << frombits) | value) & max_acc
        bits += frombits
        while bits >= tobits:
            bits -= tobits
            ret.append((acc >> bits) & maxv)
    if pad:
        if bits:
            ret.append((acc << (tobits - bits)) & maxv)
    elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
        return None
    return ret


from .broker import AlisteBroker
from .enums import DeviceType

class Device:
    def __init__(
        self,
        deviceId: str,
        switchId: int,
        name: str,
        type: DeviceType,
        switchState: float,
        dimmable: bool,
        wattage: int,
        roomName: str,
        broker: AlisteBroker,
    ):
        self.deviceId = deviceId
        self.switchId = switchId
        self.name = name
        self.type = type
        self.switchState = switchState
        self.dimmable = dimmable
        self.wattage = wattage
        self.roomName = roomName
        self.broker = broker

        self._callbacks = set()
        self.broker.register_callback(self.on_message)

    def on_message(self, message):
        if (
            message["deviceId"] == self.deviceId
            and message["switchId"] == self.switchId
        ):
            self.on_state_change(message["state"])

    def refresh(self):
        for callback in self._callbacks:
            callback()

    def register_callback(self, callback) -> None:
        """Register callback, called when Roller changes state."""
        self._callbacks.add(callback)

    def remove_callback(self, callback) -> None:
        """Remove previously registered callback."""
        self._callbacks.discard(callback)

    def on_state_change(self, state):
        self.switchState = float(state)
        self.refresh()

    def build_command(self, command: float):
        return {
            "deviceId": self.deviceId,
            "switchId": self.switchId,
            "command": command,
        }

    async def turn_on(self):
        await self.broker.send_command(self.build_command(1))

    async def turn_off(self):
        await self.broker.send_command(self.build_command(0))

    async def dim(self, value: float):
        await self.broker.send_command(self.build_command(value))


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

# solution 1:
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

# solution 2: Breath first search
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        depth = 0
        q = collections.deque([root])
        while q:
            for i in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            depth += 1
        return depth

# solution 3: Depth first search
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        st = [[root, 1]]
        max_depth = 1
        while st:
            node, depth = st.pop()
            if node:
                max_depth = max(max_depth, depth)
                st.append([node.left, depth+1])
                st.append([node.right, depth+1])
        return max_depth


from odoo import fields, models

class ResCompany(models.Model):
    _name = "res.company"
    _inherit = ["countinghouse.legal_id_number", "res.company"]

    mandate_url = fields.Char(
        string="Mandate URL",
        required=False,
        help="""Full URL to download ACH Mandate /
                              Authorization form. Useful to include in email
                              templates for customer to access and
                              complete the Mandate form.""",
    )


import cv2
import numpy as np

img = cv2.imread('./imagenes/Madotsuki.jpg',1)
cv2.imshow('imagenRGB',img)
cv2.waitKey(0)

gris = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('imagenGRAY',gris)
cv2.waitKey(0)

hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow('imagenHSV',hsv)
cv2.waitKey(0)

yuyv=cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
cv2.imshow('imagenYUV',yuyv)
cv2.waitKey(0)

Tcrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
cv2.imshow('imagenYCrCb',Tcrcb)
cv2.waitKey(0)

b, g, r = cv2.split(img)
cv2.imshow('blue',b)
cv2.imshow('green',g)
cv2.imshow('red',r)

#src = cv2.merge([r,g,b])
#src = cv2.merge([g,r,b])
#src = cv2.merge([b,g,r])
#src = cv2.merge([b,r,g])
src = cv2.merge([r,b,g])
cv2.imshow('Change Image',src)
cv2.waitKey(0)

cv2.destroyAllWindows(0)


# import numpy as np
""" Takes csv file and creates dictionary representation so that we can reference the columns as data fields.
This allows processing each row and filtering out extreme data that could be errors.
parse() is function to convert csv to disctionary
remove() is function to go through parsed file and produce output with bad values removed
"""
import csv

DATA_FILE = 'april2020_002.csv'  # this is source speed test data
OUTPUT_FILE = 'output2' + DATA_FILE   # this is the final file
print('Data file used is: ', DATA_FILE)
print('Output file used is:', OUTPUT_FILE)

def parse(raw_file, delimiter=','):
    """
    :param raw_file: probably csv file
    :param delimiter: specify delimiter
    :return: parsed data
    Parses a raw CSV file to a JSON-line object.
    """
    #  open csv file
    opened_file = open(raw_file)
    #  read csv file
    csv_data = csv.reader(
        opened_file,
        delimiter=delimiter)  # first delimiter is csv.reader variable name
    #  csv_data object is now an iterator meaning we can get each element one at a time
    #  build data structure to return parsed data
    parsed_data = []  # this list will store every row of data
    fields = csv_data.__next__(
    )  # this will be the column headers; we can use .next() because csv_data is an iterator
    for row in csv_data:
        if row[1] == "":  # there is no text in the field so no data to process
            pass
        else:
            parsed_data.append(dict(zip(fields, row)))
            # Creates a new dict item for each row with col header as key and stores in a list
        #  city_count += 1
    # close csv file
    opened_file.close()
    return parsed_data

def remove_extremes(data_file, output_file):

    with open(output_file, "w", newline='') as f:
        writer = csv.writer(f,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow([
            'Date', 'DL', 'UL', 'Ping',
            'TCPPing'
        ])

        for item in data_file:
            if item['TCPPingTime'] != 'NULL' and int(item['TCPPingTime']) <= 4000 :
                writer.writerow([
                    item['DateTimeStamp'], int(item['DownloadSpeed']) / 1000,
                    int(item['UploadSpeed']) / 1000, item['PingTime'], item['TCPPingTime']
                ])
    f.close()
    return

def main():

    raw_data_file = parse(DATA_FILE)

    remove_extremes(raw_data_file, OUTPUT_FILE)

if __name__ == "__main__":
    main()


# defining a function to count each character
def count_letters(lines):
    lst = {}        # creating a dictionary to count and store each character uniquely
    for letter in lines:    # checking each character
        if letter.isalpha():    # checking if the character is alphabet or not
            letter = letter.lower() # converting every character to lower case to count same alphabets
            if letter not in lst:       # condition for finding alphabet for first time
                lst[letter] = 1
            else:                       # condition for finding same alphabet again
                lst[letter] = lst[letter] + 1
    return list(lst.items())            # returning the dictionary in the form of list

f_name = input("Enter file name:")      # asking user input for file name
file = open(f_name, "r")            # opening the file in read mode
line = file.read()
file.close()
result = count_letters(line)        # calling the function
print(result)                       # printing the list


import pickle
from math import log10, sqrt

def length(vector):
    length_v = float(0)
    for num in vector:
        length_v += num*num
    return sqrt(length_v)

# Compute the idf for each term
def get_idf(index):
    idf_dict = {}
    N = len(index)
    for word, doclist in index.items():
        temp = log10(N / len(doclist))  # idf = log_10(N/df)
        idf_dict[word] = temp*temp

    f = open('idf_dict.dat', 'wb')
    pickle.dump(idf_dict, f)
    f.close()
    return idf_dict

# Compute the doc vectors
def get_vectors(index, file_number, idf_dict):
    vectors = [[] for i in range(file_number)]
    for word, doc_list in index.items():
        idf = idf_dict[word]
        for doc, freq in doc_list.items():
            vectors[doc].append(len(freq)*idf)
    return vectors

# Compute the vectors' length
def get_vectorlength(vectors):
    vector_length = []
    for docv in vectors:
        vector_length.append(length(docv))

    f = open('vector_length.dat', 'wb')
    pickle.dump(vector_length, f)
    f.close()
    return vector_length

# load structure
def read_index():
    with open("posting_list.dat", 'rb') as f:
        index = pickle.load(f)
    return index

# Compute the values that a vs_model need
def vs_model_pre(file_num):
    index = read_index()
    idf_dict = get_idf(index)
    get_vectorlength(get_vectors(index, file_num, idf_dict))


#!/usr/bin/python3

def f(a, b):
    return a + b

def dict_interdiff(d1, d2):
    intersect = {}
    difference = {}
    for key1 in d1:
        if key1 in d2:
            intersect[key1] = f(d1[key1], d2[key1])
            del d2[key1]
        else:
            difference[key1] = d1[key1]
    for key2 in d2:
        difference[key2] = d2[key2]

    return (intersect, difference)

d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}

print(dict_interdiff(d1, d2))


"""Unit tests for ``:mod:zarp.plugins.sample_processors.genomepy``."""

import logging
from pathlib import Path
import shutil
from unittest.mock import Mock

from genomepy.genome import Genome
import numpy as np
import pandas as pd

from zarp.config.models import Config, ConfigRun, ConfigSample, ConfigUser
from zarp.samples.sample_record_processor import SampleRecordProcessor as SRP
from zarp.plugins.sample_processors.genomepy import (
    SampleProcessorGenomePy as SPG,
)

LOGGER = logging.getLogger(__name__)

class TestSampleProcessorGenomePy:
    """Test ``cls:zarp.plugins.sample_processors.SampleProcessorGenomePy``."""

    config = Config(
        run=ConfigRun(
            zarp_directory=Path(__file__).parents[2] / "files" / "zarp",
            genome_assemblies_map=Path(__file__).parents[2]
            / "files"
            / "genome_assemblies.csv",
        ),
        sample=ConfigSample(fragment_length_distribution_mean=1000),
        user=ConfigUser(),
    )
    data = pd.DataFrame(
        data={
            "identifier": ["sample1", "sample2"],
            "type": ["LOCAL_LIB_SINGLE", "LOCAL_LIB_SINGLE"],
            "orientation": ["SF", "SF"],
            "source": ["Schizosaccharomyces pombe", 4932],
        }
    )
    assemblies = ["ASM294v2", "R64-1-1"]

    def test_init(self):
        """Test constructor."""
        config = self.config.copy(deep=True)
        df = self.data.copy(deep=True)
        srp = SRP()
        srp.append(df)
        spg = SPG(config=config, records=srp.records)
        assert hasattr(spg, "records")
        assert len(spg.records.index) == 2

    def test_process(self, monkeypatch, tmpdir):
        """Test `.process()` method."""
        config = self.config.copy(deep=True)
        df = self.data.copy(deep=True)
        srp = SRP()
        srp.append(df)
        spg = SPG(config=config, records=srp.records)
        genomes_dir_root = Path(tmpdir)
        return_data = []
        for assembly in self.assemblies:
            genomes_dir = genomes_dir_root / "latest" / assembly
            genomes_dir.mkdir(parents=True, exist_ok=False)
            shutil.copyfile(
                Path(__file__).parents[2] / "files" / "fasta",
                genomes_dir / f"{assembly}.fa",
            )
            shutil.copyfile(
                Path(__file__).parents[2] / "files" / "gtf",
                genomes_dir / f"{assembly}.annotation.gtf",
            )
            obj = Genome(assembly, genomes_dir=genomes_dir_root / "latest")
            obj.annotation_gtf_file = (
                genomes_dir / f"{assembly}.annotation.gtf"
            )
            return_data.append(obj)
        monkeypatch.setattr(
            "genomepy.install_genome",
            Mock(side_effect=return_data),
        )
        df_out = spg.process()
        assert len(df_out.index) == 2
        assert (
            df_out["reference_sequences"].iloc[0]
            == genomes_dir_root
            / "latest"
            / self.assemblies[0]
            / f"{self.assemblies[0]}.fa"
        )
        assert (
            df_out["annotations"].iloc[0]
            == genomes_dir_root
            / "latest"
            / self.assemblies[0]
            / f"{self.assemblies[0]}.annotation.gtf"
        )
        assert (
            df_out["reference_sequences"].iloc[1]
            == genomes_dir_root
            / "latest"
            / self.assemblies[1]
            / f"{self.assemblies[1]}.fa"
        )
        assert (
            df_out["annotations"].iloc[1]
            == genomes_dir_root
            / "latest"
            / self.assemblies[1]
            / f"{self.assemblies[1]}.annotation.gtf"
        )

    def test_process_empty(self, caplog):
        """Test `.process()` method with no records."""
        config = self.config.copy(deep=True)
        srp = SRP()
        srdd = SPG(config=config, records=srp.records)
        assert len(srdd.records.index) == 0
        with caplog.at_level(logging.DEBUG):
            df_out = srdd.process()
        assert len(df_out.index) == 0
        assert "No genome resources to fetch" in caplog.text

    def test_set_assemblies(self):
        """Test `.set_assemblies()` method."""
        config = self.config.copy(deep=True)
        df = self.data.copy(deep=True)
        srp = SRP()
        srp.append(df)
        spg = SPG(config=config, records=srp.records)
        spg.set_assemblies()
        assert "assembly" in spg.records.columns
        assert len(spg.records["assembly"]) == 2
        assert list(spg.records["assembly"]) == ["ASM294v2", "R64-1-1"]

    def test_fetch_resources(self, monkeypatch, tmpdir):
        """Test `.fetch_resources()` method."""
        config = self.config.copy(deep=True)
        config.run.resources_version = 50
        df = self.data.copy(deep=True)
        srp = SRP()
        srp.append(df)
        spg = SPG(config=config, records=srp.records)
        spg.set_assemblies()
        genomes_dir_root = Path(tmpdir)
        return_data = []
        for assembly in self.assemblies:
            genomes_dir = (
                genomes_dir_root / str(config.run.resources_version) / assembly
            )
            genomes_dir.mkdir(parents=True, exist_ok=False)
            shutil.copyfile(
                Path(__file__).parents[2] / "files" / "fasta",
                genomes_dir / f"{assembly}.fa",
            )
            shutil.copyfile(
                Path(__file__).parents[2] / "files" / "gtf",
                genomes_dir / f"{assembly}.annotation.gtf",
            )
            obj = Genome(
                assembly,
                genomes_dir=genomes_dir_root
                / str(config.run.resources_version),
            )
            obj.annotation_gtf_file = (
                genomes_dir / f"{assembly}.annotation.gtf"
            )
            return_data.append(obj)
        # test with genome files and annotation files available
        monkeypatch.setattr(
            "genomepy.install_genome",
            Mock(side_effect=return_data),
        )
        paths = spg.fetch_resources(genomes_dir_root=genomes_dir_root)
        assert len(paths) == 2
        # test with one genome file and one annotation file missing
        Path(paths[self.assemblies[0]][0]).unlink()
        Path(paths[self.assemblies[1]][1]).unlink()
        monkeypatch.setattr(
            "genomepy.install_genome",
            Mock(side_effect=return_data),
        )
        paths = spg.fetch_resources(genomes_dir_root=genomes_dir_root)
        assert len(paths) == 0

    def test_set_resource_paths(self):
        """Test `.set_resource_paths()` method."""
        config = self.config.copy(deep=True)
        df = self.data.copy(deep=True)
        srp = SRP()
        srp.append(df)
        spg = SPG(config=config, records=srp.records)
        spg.set_assemblies()
        resource_paths = dict(
            zip(self.assemblies, [(Path(), Path()), (Path(), Path())])
        )
        # test when for all records, assemblies are available
        spg.set_resource_paths(resource_paths=resource_paths)
        assert spg.records["reference_sequences"].iloc[0] == Path()
        assert spg.records["annotations"].iloc[0] == Path()
        assert spg.records["reference_sequences"].iloc[1] == Path()
        assert spg.records["annotations"].iloc[1] == Path()
        # test when for one record, assembly is not available
        spg.records["assembly"].iloc[0] = None
        spg.set_resource_paths(resource_paths=resource_paths)
        assert np.isnan(spg.records["reference_sequences"].iloc[0])
        assert np.isnan(spg.records["annotations"].iloc[0])
        assert spg.records["reference_sequences"].iloc[1] == Path()
        assert spg.records["annotations"].iloc[1] == Path()


# type: ignore

import time
import patch_ftp
import robomaster.config  # noqa
from robomaster import robot, logger, logging  # noqa
import robomaster.conn
import robomaster.camera
import cv2
import sys
# import threading
import patch_ftp  # noqa

# IP = "127.0.0.1" # Leave to None to scan for IPs on (0.0.0.0)
IP = ""

run_video = True

def _video(ep_robot):
    print('start video stream')
    ep_robot.camera.start_video_stream(display=False, resolution="720p")
    global run_video
    run_video = True
    while run_video:
        try:
            frame = ep_robot.camera.read_cv2_image()
        except:
            frame = None
        if frame is not None:
            cv2.imshow('image', frame)
            cv2.waitKey(1)
        else:
            time.sleep(0.01)
    ep_robot.camera.stop_video_stream()

def _action(ep_robot):
    global run_video
    print('start action')
    for i in range(12):
        if i % 2:
            r, g, b = 200, 0, 0
            ep_robot.set_robot_mode('free')
            ep_robot.blaster.set_led(effect='off')
        else:
            r, g, b = 0, 0, 200
            ep_robot.set_robot_mode('chassis_lead')
            ep_robot.blaster.set_led(brightness=100, effect='on')
        ep_robot.led.set_led(r=r, g=g, b=b, effect=robomaster.led.EFFECT_BREATH, freq=10)
        ep_robot.chassis.move(x=1, y=0, z=0, xy_speed=1.0, z_speed=90).wait_for_completed()
        ep_robot.chassis.move(x=0, y=0, z=90, xy_speed=1.0, z_speed=90).wait_for_completed()
        ep_robot.gimbal.moveto(yaw=-90, pitch=-20, yaw_speed=90, pitch_speed=30).wait_for_completed()
        ep_robot.gimbal.moveto(yaw=-45, pitch=0, yaw_speed=90, pitch_speed=30).wait_for_completed()
    run_video = False

def main():
    logger.setLevel(logging.WARN)

    if IP:
        robomaster.config.LOCAL_IP_STR = IP
        robomaster.config.ROBOT_IP_STR = IP

    if(len(sys.argv) > 1):
        protocol = sys.argv[-1]
        robomaster.config.ep_conf.video_stream_proto = protocol
    ep_robot = robot.Robot()
    ep_robot.initialize(conn_type="sta")
    # action = threading.Thread(target=_action, args=(ep_robot,))
    # action.start()
    # _video(ep_robot)
    _action(ep_robot)
    ep_robot.close()

if __name__ == '__main__':
    main()


while True:
    a, b, c, d = map(int, input().split())
    if (a, b, c, d) == (0, 0, 0, 0):
        break
    count = 0
    while True:
        if a==b==c==d:
            break
        a, b, c, d = map(abs, [a-b, b-c, c-d, d-a])
        count += 1
    print(count)


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 16:35:09 2021

@author: jkuhnsman
"""

import requests
import re
import boto3
import time
from datetime import datetime as dt
from datetime import timedelta

url = "http://155.138.239.20:7935/metrics"

def getMetrics(url):
    r = requests.get(url, verify=False)
    raw = r.text
    raw_split = raw.split('\n')

    metrics = []

    for m in raw_split:
        if (not '#' in m) & ('livepeer' in m):
            metrics.append(m)

    metrics_parsed = {}

    for m in metrics:
        l = re.split('{|}',m)
        metrics_parsed[l[0]] = float(str(l[-1]).strip())

    return metrics_parsed

#%%

if __name__ == "__main__":
    healthy = True

    while True:
        metrics = getMetrics(url)
        if 'livepeer_transcoders_capacity' in metrics.keys():
            print(metrics['livepeer_transcoders_capacity'])
            if int(metrics['livepeer_transcoders_capacity']) > 0:
                healthy = True
            else:
                healthy = False
        else:
            healthy=False

        f = open("/root/http/index.html", "w")
        if healthy:
            f.write("healthy - frankfurt orch")
        else:
            f.write("orch is down - frankfurt orch")
        f.close()

        time.sleep(5)


import random
from copy import copy
import cv2 as cv
from scripts.utils import draw_image_on_image

class Heart:
    all_hearts = []
    image = cv.imread('kindpng_5455794.png', -1)

    def __init__(self):
        self.x_location = random.randrange(-50, 1000)
        self.y_location = 1000
        self.size = random.random() / 3
        self.is_alive = True
        Heart.all_hearts.append(self)

    def update(self):
        self.x_location += random.randrange(-2, 3)
        self.y_location += random.randrange(-10, 0)

    def kill(self):
        Heart.all_hearts.remove(self)
        del self
        print("OUCH!!")

    def draw_on_image(self, photo):
        if not draw_image_on_image(photo, Heart.image, (self.x_location, self.y_location), self.size):
            self.is_alive = False

    @classmethod
    def display_all_hearts(cls, img):
        for heart in cls.all_hearts:
            if not heart.is_alive:
                heart.kill()
        for heart in cls.all_hearts:
            heart.draw_on_image(img)
            heart.update()

    @staticmethod
    def create_heart():
        return Heart()

image = cv.imread('maayan.jpg')
cv.putText(image, 'I Love', (100, 200), 5, 10, (0, 0, 255), 3)
cv.putText(image, 'Maayan!!', (100, 500), 5, 10, (0, 0, 255), 3)
while True:
    frame = copy(image)
    if random.randrange(0, 40) == 1:
        Heart.create_heart()
    Heart.display_all_hearts(frame)
    cv.imshow('image', frame)
    cv.waitKey(1)


# NAMESPACE AND SCOPE

# Python program processing global variable
count = 5

def some_method():
    global count
    count = count + 1
    print(count)

some_method()

# If we pass immutable objects like whole numbers,
# tuple or strings they are passed by value.

# Python code to demonstrate
# call by value
string = "Geeks"

def test(string):
    string = "GeeksforGeeks"
    print("Inside Function:", string)

# Driver's code
test(string)
print("Outside Function:", string)

# Whereas if we pass a mutable object to a function
# like a list, they are passed by reference

# Python code to demonstrate
# call by reference

def add_more(list):
    list.append(50)
    print("Inside Function", list)

# Driver's code
mylist = [10, 20, 30, 40]
add_more(mylist)
print("Outside Function:", mylist)


from admin_loader import dp, pay_bot
from aiogram import types
from aiogram.dispatcher.filters.builtin import Command
from aiogram.utils.markdown import hlink
from data.config import ADMINS
import datetime
from dateutil import relativedelta
import logging
from utils.db_api.db_commands import database

@dp.message_handler(Command("kickusers"), state="*")
async def bot_kickusers(message: types.Message = None):
    """
    /kickusers функция бота.
    """

    t1 = datetime.datetime.now()
    text = "Start kickChatMember method\n"
    if message is not None:
        await message.answer(text=text)

    data = await database.get_users_active_subscribes()
    time = datetime.datetime.now()
    N = 0
    for row in data:
        if row["paid_till"] < time:
            channel_id = int(row["subscribe_channel_id"])
            chat_id = int(row["chat_id"])
            await pay_bot.kick_chat_member(channel_id, chat_id)
            await pay_bot.unban_chat_member(channel_id, chat_id)
            await database.update_user_subscribe_status(
                subscribe_channel_id=channel_id,
                chat_id=chat_id,
                subscribe_status="Expired",
                subscribe_status_previous="Active")
            N += 1
        elif row["paid_till"] < time + relativedelta.relativedelta(
                days=+2) and row["last_notify_time"] < time - relativedelta.relativedelta(days=+1):
            channel_id = int(str(row["subscribe_channel_id"])[4:])
            chat_id = int(row["chat_id"])
            text = "У вас заканчивается подписка на канал!\n"
            text += "Канал "
            text += hlink(f"{row['subscribe_channel']}\n",
                          f"https://t.me/c/{channel_id}/1")
            text += f"Срок подписки до {row['paid_till']}\n"
            try:
                await pay_bot.send_message(chat_id, text)
                await database.update_user_subscribe_last_notify_time(
                    last_notify_time=time,
                    subscribe_id=row["id"])
            except Exception as err:
                logging.exception(err)

    t2 = datetime.datetime.now()
    text = "Finish kickChatMember method\n"
    text += f"Kick N={N} users\n"
    time = t2 - t1
    text += f"Time: {time}\n"
    if message is not None:
        await message.answer(text=text)
    elif N > 0:
        for admin in ADMINS:
            await pay_bot.send_message(admin, text)


from selenium import webdriver
import time

try:
    browser = webdriver.Chrome()
    # 需要安装chrome driver, 和浏览器版本保持一致
    # http://chromedriver.storage.googleapis.com/index.html

    browser.get('https://shimo.im')
    time.sleep(1)
    # browser.switch_to_frame(browser.find_elements_by_tag_name('iframe')[0])
    btm1 = browser.find_element_by_xpath('/html/body/div[1]/div[1]/header/nav/div[3]/a[2]/button')
    btm1.click()
    time.sleep(5)
    browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[1]/div/input').send_keys('15055495@qq.com')
    browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[2]/div/input').send_keys('test123test456')
    time.sleep(3)
    browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/button').click()

    cookies = browser.get_cookies() # 获取cookies
    print(cookies)
    time.sleep(3)

except Exception as e:
    print(e)
finally:
    time.sleep(10)
    browser.close()


import threading

from multiprocessing import Queue

class UpstreamThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self, daemon=True)
        self.queue = Queue()
        self.socket = None
        self.socket_lock = threading.RLock()
        self.running = True

    def set_socket(self, socket):
        self.clear()
        with self.socket_lock:
            self.socket = socket

    def connected(self):
        with self.socket_lock:
            return self.socket is not None

    def put(self, b):
        self.queue.put(b)

    def clear(self):
        while not self.queue.empty():
            self.queue.get()

    def stop(self):
        self.set_socket(None)
        self.running = False

    def run(self):
        while self.running:
            if not self.queue.empty():
                # Acquire the lock since socket can be None when set in another thread
                with self.socket_lock:
                    if self.socket:
                        while not self.queue.empty():
                            pkt = self.queue.get()
                            try:
                                self.socket.send(pkt)
                            except Exception as _:
                                pass # Keep on throwing exceptions until we get a new socket


import requests
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.views.generic import DetailView, ListView, TemplateView
from django.views.generic.edit import FormMixin
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt

from .models import Property, PropertyType

from inquiry.forms import InquiryForm

from search.models import SearchCriteria

from .provinces import provinces

# Create your views here.

class Home(ListView):
    queryset = Property.objects.filter(active=True, deal=False)
    model = Property
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)
        locations = list(Property.objects.filter(active=True, deal=False).values())
        context['locations'] = locations

        return context

class About(TemplateView):
    template_name = 'about.html'

def search_ajax(request):
    if 'term' in request.GET:
        q = request.GET.get('term', '').capitalize()
        ps = list()
        for p in provinces:
            if q in p:
                ps.append(p)

    return JsonResponse(ps, safe=False)

class PropertyListView(ListView):
    model = Property
    template_name = 'property/property_list.html'

    def get_context_data(self, **kwargs):
        context = super(PropertyListView, self).get_context_data(**kwargs)
        global properties
        properties =  Property.objects.filter(active=True, deal=False)
        context['properties'] = properties
        context['page_title'] = 'Properties'
        context['message'] = 'Nothing to show'
        return context

    def post(self, request, *args, **kwargs):
        global properties
        form = self.request.POST

        if 'search' in form:
            properties = Property.objects.filter(active=True, deal=False)
            if form['type'] != '':
                properties = properties.filter(type__title=form['type'])
            if form['city']:
                properties = properties.filter(city__icontains=form['city'])
            if form['price_from'] and form['price_to']:
                properties = properties.filter(price__range=(int(form['price_from']), int(form['price_to'])))
            if form['floors']:
                properties = properties.filter(floor=form['floors'])
            if form['bedrooms']:
                properties = properties.filter(bedroom=form['bedrooms'])
            if form['bathrooms']:
                properties = properties.filter(bathroom=form['bathrooms'])
            if form['parking']:
                properties = properties.filter(parking=form['parking'])

            if form.get('basement'):
                properties = properties.filter(basement=True)
            if request.user.is_authenticated:
                search = SearchCriteria.objects.filter(user=request.user).first()
                if not search:
                    search = SearchCriteria.objects.create(user=request.user)
                property_type = PropertyType.objects.filter(title=form['type']).first()
                if property_type:
                    search.type = property_type
                else:
                    search.type = None
                search.city = form['city']
                search.price_from = form['price_from']
                search.price_to = form['price_to']
                search.floors = form['floors']
                search.bedrooms = form['bedrooms']
                search.bathrooms = form['bathrooms']
                search.parking = form['parking']
                search.basement = True if form.get('basement') == 'on' else False
                search.save()
            context ={
                'properties': properties,
                'page_title': 'Search',
                'message': 'Nothing found'
            }
            return render(request, 'property/property_list.html', context)

        elif form['type'] == 'filter':
            properties = Property.objects.filter(active=True, deal=False).filter(type__title=form['filter'])
        else:
            properties = properties.order_by(form['sort'])

        context = {
            'properties': properties,
        }

        return render(request, 'property/property_list.html', context)

class PropertyDetailView(FormMixin, DetailView):
    model = Property
    template_name = 'property/property_detail.html'
    context_object_name = 'property'
    form_class = InquiryForm

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            inquiry = form.save(commit=False)
            inquiry.property = self.get_object()
            inquiry.save()
            messages.success(request, 'Your inquiry has been sent successfully')
        else: messages.warning(request, 'Your inquiry has not been sent successfully')
        return redirect('property:property_detail', pk=self.get_object().id)

class TypePropertyListView(ListView):
    model = Property
    template_name = 'property/property_list.html'
    context_object_name = 'properties'

    def get_queryset(self):
        global properties
        properties = super(TypePropertyListView, self).get_queryset()
        slug = self.kwargs.get('slug')
        properties = Property.objects.filter(type__slug=slug, active=True, deal=False)
        return properties

    def get_context_data(self, **kwargs):
        context = super(TypePropertyListView, self).get_context_data(**kwargs)
        global slug
        slug = self.kwargs.get('slug')
        context['page_title'] = slug.capitalize()
        return context

    def post(self, request, *args, **kwargs):
        global properties
        form = self.request.POST
        if form['type'] == 'filter':
            properties = Property.objects.filter(active=True, deal=False).filter(type__title=form['filter'])
        else:
            properties = properties.order_by(form['sort'])
        context = {
            'properties': properties,
            'page_title': slug.capitalize(),
        }
        return render(request, 'property/property_list.html', context)

@login_required
@csrf_exempt
def add_to_favorites(request):
    form = request.POST
    if not form.get('property_id'):
        print('something is not a valid form')
    else:
        property = Property.objects.filter(id=form.get('property_id')).first()
        if not property:
            print('property not found')
        else:
            request.user.favorites.add(property)
            request.user.save()
    return redirect('property:property_detail', pk=form.get('property_id'))


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  2 13:26:03 2021

@author: paritoshsingh1
"""

import sys
sys.path.append(r"..")
from day01.day01 import sliding_window

with open("input.txt") as f:
    contents = f.read().strip()

contents = """
3,4,3,1,2
""".strip()

# Part 1

# naive

fishes = list(map(int, contents.split(",")))
# fishes = [0]
for day in range(0, 80):
    new_fish = []
    for fish in fishes:
        if fish > 0:
            new_fish.append(fish - 1)
        else:
            new_fish.append(6)
            new_fish.append(8)
    fishes = new_fish

print(len(fishes))

# Part 2

fishes = [0]
results = {}
for day in range(0, 64):
    new_fish = []
    for fish in fishes:
        if fish > 0:
            new_fish.append(fish - 1)
        else:
            new_fish.append(6)
            new_fish.append(8)
    fishes = new_fish
    results[day] = fishes.copy()
count_fisher = {k: len(v) - 1 for k, v in results.items()} # because i want to count how many new fishes made, so -1

####

total_days = 256
remaining_days = total_days
look_forward = 0

fishes = list(map(int, contents.split(",")))

while remaining_days > 64:
    look_forward += 64
    remaining_days -= 64
    new_fish = []
    for fish in fishes:
        new_fish.extend(results[63 - fish])
    fishes = new_fish

current_fish_count = len(fishes)
for fish in fishes:
    try:
        current_fish_count += count_fisher[remaining_days -1 - fish]
    except KeyError:
        pass

print(current_fish_count)

### round 3, crazy logic
meta_result_dict = {}

for total_days in range(1, 256 + 1):
    remaining_days = total_days
    look_forward = 0

    fishes = [0]

    while remaining_days > 64:
        look_forward += 64
        remaining_days -= 64
        new_fish = []
        for fish in fishes:
            new_fish.extend(results[63 - fish])
        fishes = new_fish

    current_fish_count = len(fishes)
    for fish in fishes:
        try:
            current_fish_count += count_fisher[remaining_days -1 - fish]
        except KeyError:
            pass

    print(current_fish_count)
    meta_result_dict[total_days] = current_fish_count

fishes = list(map(int, contents.split(",")))
totals = 0
total_days = 256
for fish in fishes:
    totals += meta_result_dict[total_days - fish]

print(totals)

## part 2, actually effin good- credits https://github.com/spenpal2000/adventofcode/blob/main/2021/day6/day6.py
from collections import Counter
def part2(fishes):
    timers = Counter({timer: 0 for timer in range(10)})
    fishes = Counter(fishes)
    fishes.update(timers)

    for day in range(256):
        fishes[7] += fishes.get(0, 0)
        fishes[9] += fishes.get(0, 0)
        fishes = {fish: fishes.get(fish + 1, 0) for fish in fishes}

    return sum(fishes.values())

part2(list(map(int, contents.split(","))))


import os
import sys

sys.path.append(os.curdir)

from pelicanconf import *

SITEURL = 'https://blog.cuongtn.xyz'
RELATIVE_URLS = False

LOCAL_USER = 'cuongtn'
REMOTE_USER = 'cuongtn'
ROOT = 'root'
SERVER_IP = '138.197.130.199'

PROJECT_LOCAL_DIR = '/home/%s/working/blog' % LOCAL_USER
PROJECT_REMOTE_DIR = '/home/%s/blog' % REMOTE_USER
PROJECT_URL = 'https://github.com/cuongtnx/blog.git'

VIRTUALENV_REMOTE = '/home/%s/blog/env' % REMOTE_USER

NGINX_FROM = '%s/deployment/blog.conf' % PROJECT_REMOTE_DIR
NGINX_TO = '/etc/nginx/conf.d/blog.conf'


from django.db import models

# Create your models here.

class Employee(models.Model):
    CATEGORY = [
        ('Java', 'Java'),
        ('Python', 'Python'),
        ('.NET', '.NET'),
        ('Testing', 'Testing'),
        ('Salesforce', 'Salesforce'),
        ('Deployment', 'Deployment'),
        ('DevOps', 'DevOps'),
        ('Cybersecurity', 'Cybersecurity'),
        ('DataScience', 'DataScience')
    ]

    name = models.CharField(max_length=50)
    age = models.IntegerField()
    skills = models.CharField(max_length=20, choices=CATEGORY)

    def __str__(self):
        return self.name


#理论部分
"""
用数组实现一个顺序队列。
用数组实现一个循环队列。
用链表实现一个链式队列。
练习部分
1. 模拟银行服务完成程序代码。
目前，在以银行营业大厅为代表的窗口行业中大量使用排队（叫号）系统，该系统完全模拟了人群排队全过程，通过
取票进队、排队等待、叫号服务等功能，代替了人们站队的辛苦。
排队叫号软件的具体操作流程为：
顾客取服务序号
当顾客抵达服务大厅时，前往放置在入口处旁的取号机，并按一下其上的相应服务按钮，取号机会自动打印出一张服
务单。单上显示服务号及该服务号前面正在等待服务的人数。
服务员工呼叫顾客
服务员工只需按一下其柜台上呼叫器的相应按钮，则顾客的服务号就会按顺序的显示在显示屏上，并发出“叮咚”和
相关语音信息，提示顾客前往该窗口办事。当一位顾客办事完毕后，柜台服务员工只需按呼叫器相应键，即可自动呼
叫下一位顾客。
编写程序模拟上面的工作过程，主要要求如下：
程序运行后，当看到“请点击触摸屏获取号码：”的提示时，只要按回车键，即可显示“您的号码是：XXX，您前面有
YYY位”的提示，其中XXX是所获得的服务号码，YYY是在XXX之前来到的正在等待服务的人数。
用多线程技术模拟服务窗口（可模拟多个），具有服务员呼叫顾客的行为，假设每个顾客服务的时间是10000ms，时间
到后，显示“请XXX号到ZZZ号窗口！”的提示。其中ZZZ是即将为客户服务的窗口号。

"""
def getCallNumber(self):
    if self.is_empty() and self.callNumber == 0:
        self.callNumber = 1
    else:
        self.callNumber += 1
    return self.callNumber

def getLength(self):
    if self.is_empty():
        return 0
    else:
        cur = self._head
        len = 1
        while cur != self._tail:
            cur = cur.next
            len += 1
        return len

def service(self):
    self.lock.acquire()
    while True:
        time.sleep(20)
        try:
            if not self.bankQueue.is_empty():
                print('请 %d 号到 %s 号窗口' % (self.bankQueue._head.data, threading.current_thread().name))
                self.bankQueue.dequeue()
                # time.sleep(10)
            else:
                print('队列为空哦')
        finally:
            self.lock.release()