from PIL import Image
import os
import splitfolders

raw_data_path='data//raw_data//'
processed_data_path='data//processed_data//'

def Convert_to_RGB(path):
    for i,image in enumerate(os.listdir(path)):
        im = Image.open(path+image)
        if im.mode != 'RGB':
            print("image converted: ",image)
            im.convert("RGB").save(path + f"RGB_image{i}.jpg")
            os.remove(path+image)

if __name__ =='__main__':
    #Convert all images into RGB form
    Convert_to_RGB(raw_data_path + 'Class0//')
    Convert_to_RGB(raw_data_path + 'Class1//')
    #perform train,validation,test split
    splitfolders.fixed(input=raw_data_path,output=processed_data_path,fixed=(1500,250,250))


#!/usr/bin/env python

from __future__ import print_function
import yaml
import copy
import os
import json

def add_to_yaml(a, b, ignore_keys=set(("name", "description", "PIPELINE"))):
    '''
    If an object is in b but not a, add it to a.

    Fail if confilicting values are found
    '''
    if type(a) != type(b):
        raise ValueError("Incomptable yaml entries found")
    if type(a) is dict:
        for k in b.keys():
            if k in ignore_keys:
                continue
            if k in a:
                add_to_yaml(a[k], b[k])
            else:
                a[k] = b[k]
    elif type(a) is list:  # In this case, order is unimportant
        try:  # Only applicable with zones.
            a_set, b_set = set(a), set(b)
            intersection = list(a_set.intersection(b_set))
            for i in range(len(a) - 1, -1, -1):
                if a[i] not in intersection:
                    a.pop(i)
            if len(a) == 0:
                raise ValueError("No values left after intersection")
            return
        except TypeError:
            pass
        # item["name"] essentially acts as a key
        a_dict = dict([(x["name"], x) for x in a])
        b_dict = dict([(x["name"], x) for x in b])
        for k, v in b_dict.items():
            if k in ignore_keys:
                continue
            if k in a_dict:
                if v != a_dict[k]:
                    print("'{}' does not equal '{}'".format(v, a_dict[k]))
                    raise ValueError("Paramters are unequal")
            else:
                a.append(v)
    else:
        if a != b:
            print("'{}' does not equal '{}'".format(a, b))
            raise ValueError("Values are unequal")

script_dir = os.path.dirname(os.path.realpath(__file__))
germline = yaml.load(open(script_dir + "/germline.yaml"))
tn = None
try:
    tn = yaml.load(open(script_dir + "/somatic.yaml"))
except IOError:
    pass
output = script_dir + "/runner_default.json"

additional_input_params = {
        "ZONES": None,
        "DISK_SIZE": 300,
        "MIN_CPU": 64,
        "MIN_RAM_GB": 56,
        "PIPELINE": "DNA",
        "PROJECT_ID": None,
        "DOCKER_IMAGE": "sentieon/sentieon-google-cloud:0.2.0",
        "PREEMPTIBLE_TRIES": 0,
        "NONPREEMPTIBLE_TRY": True
}

out_yaml = copy.deepcopy(germline)
if tn:
    add_to_yaml(out_yaml, tn)
out_json = {}
for param in out_yaml["inputParameters"]:
    k = param["name"]
    if "defaultValue" not in param:
        v = None
    elif param["defaultValue"] == "None":
        v = None
    else:
        v = param["defaultValue"]
    out_json[k] = v
out_json.update(additional_input_params)

with open(output, 'w') as f:
    json.dump(out_json, f, indent=2)


import unittest

import numpy as np

from potion.streamlitapp.category.curve_cluster import CurveCluster, ClusteringMethod

class CurveClusterTestCase(unittest.TestCase):

    def test_init(self):

        clusterer = CurveCluster(5, ClusteringMethod.DBSCAN)

        self.assertEqual(clusterer.num_clusters, 5)
        self.assertEqual(clusterer.clustering_method, ClusteringMethod.DBSCAN)
        self.assertEqual(clusterer.curve_mapping, {})
        self.assertEqual(clusterer.curve_mapping_flat, [])
        self.assertIsNone(clusterer.curves_similarity)
        self.assertIsNone(clusterer.clustering)
        self.assertIsNone(clusterer.cluster_counts)

    def test_create_curve_mapping(self):

        clusterer = CurveCluster(5)

        self.assertEqual((12, 10), np.shape(clusterer.curve_mapping_flat))

    def test_perform_clustering(self):

        clusterer = CurveCluster(2)

        clusterer.perform_clustering()

        # print(clusterer.clustering)

        vals = clusterer.clustering.tolist()
        one = [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0]
        two = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]

        self.assertTrue(one == vals or two == vals)

    def test_calculate_cluster_counts(self):

        clusterer = CurveCluster(2)

        clusterer.perform_clustering()
        clusterer.calculate_cluster_counts()

        # print(clusterer.clustering)
        # print(clusterer.cluster_counts)

        one = [4.0, 8.0]
        two = [8.0, 4.0]
        vals = clusterer.cluster_counts.tolist()

        self.assertTrue(one == vals or two == vals)

if __name__ == '__main__':
    unittest.main()


try:
    from methods.regular.regular_api import *

except:
    from default.methods.regular.regular_api import *
from shared.utils.job_launch_utils import task_template_label_attach
from shared.database.source_control.working_dir import WorkingDirFileLink
from shared.database.task.job.job import Job
from shared.utils.task import task_file_observers
from shared.database.userscript.userscript import UserScript
from shared.database.tag.tag import Tag

job_new_spec_list = [
    {"name": {
        'default': str(time.time()),
        'kind': str
        }
    },
    {"default_userscript_id": {
        'default': None,
        'kind': int
        }
    },
    {"share": {
        'default': "project",
        'kind': str
    }
    },
    {"instance_type": {
        'default': "box",
        'kind': str
    }
    },
    {"permission": {
        'default': "all_secure_users",
        'kind': str
    }
    },
    {"label_mode": {
        'default': "closed_all_available",
        'kind': str
    }
    },
    {"passes_per_file": {
        'default': 1,
        'kind': int
    }
    },
    {"type": {
        'default': "Normal",
        'kind': str,
    }
    },
    {"review_by_human_freqeuncy": {
        'default': "None",
        'kind': str
    }
    },
    {"category": {
        'default': "visual",
        'kind': str
    }
    },
    {"ui_schema_id": {
        'default': None,
        'kind': int,
        "required": False
    }
    },
    {"label_schema_id": {
        'default': None,
        'kind': int,
        "required": False
    }
    },
    {"td_api_trainer_basic_training": {
        'default': False,
        'kind': bool,
    }
    },
    {"launch_datetime": {
        'default': None,
        'kind': "datetime"
    }
    },
    {"interface_connection_id": {
        'default': None,
        'kind': int
    }
    },
    {"file_count": {
        'default': None,
        'kind': int
    }
    },
    {"label_file_list": {
        'default': None,
        'kind': list,
        'allow_empty': True,
        }
    },
    {"file_handling": {
        'default': "use_existing",
        'valid_values_list': [None, "use_existing", "isolate"],
        'kind': str
        }
    },
    {"member_list_ids": {
        'default': None,
        'allow_empty': True,
        'kind': list,
        'required': False
        }
    },
    {"reviewer_list_ids": {
        'default': None,
        'allow_empty': True,
        'kind': list,
        'required': False
    }
    },
    {"pro_network": {
        'default': False,
        'kind': bool,
        'required': False
        }
    },
    {"attached_directories_dict": {
        'kind': dict,
        'required': False
    }},
    {"allow_reviews": {
        'kind': bool,
        'required': False
        }
    },
    {"review_chance": {
        'kind': int,
        'required': False
        }
    },
    {"tag_list": {
        'default': None,
        'allow_empty': True,
        'kind': list,
        'required': False
        }
    },
]

"""
We have strong defaults for a new job
but not for updating? So keep this seperate for not?

But we want to validate the kind
"""

update_job_spec_list = [
    {"job_id": {
        'kind': int
    }},
    {"attached_directories_dict": {
        'kind': dict
    }},
    {"completion_directory_id": {
        'kind': int
    }},
    {"output_dir_action": {
        'kind': str
    }},
    {"name": {
        'kind': str,
        'default': None
    }
    },
    {"default_userscript_id": {
        'kind': int
        }
    },
    {"share_type": {
        'kind': str,
        'default': None
    }
    },
    {"file_handling": {
        'kind': str,
        'default': None
    }
    },
    {"ui_schema_id": {
        'default': None,
        'kind': int,
        "required": False
    }
    },
    {"label_schema_id": {
        'default': None,
        'kind': int,
        "required": False
    }
    },
    {"instance_type": {
        'kind': str,
        'default': None
    }
    },
    {"permission": {
        'kind': str,
        'default': None
    }
    },
    {"label_mode": {
        'kind': str,
        'default': None
    }
    },
    {"passes_per_file": {
        'kind': int,
        'default': None
    }
    },
    {"type": {
        'kind': str,
        'default': None
    }
    },
    {"review_by_human_freqeuncy": {
        'kind': str,
        'default': None
    }
    },
    {"interface_connection_id": {
        'kind': int,
        'default': None
    }
    },
    {"category": {
        'kind': str,
        'default': None
    }
    },
    {"launch_datetime": {
        'kind': "datetime",
        'default': None,
    }
    },
    {"file_count": {
        'kind': int,
        'default': None
    }
    },
    {"label_file_list": {
        'default': None,
        'kind': list,
        'allow_empty': True
        }
    },
    {"member_list_ids": {
        'default': None,
        'kind': list,
        'allow_empty': True,
        'required': False
        }
    },
    {"reviewer_list_ids": {
        'default': None,
        'allow_empty': True,
        'kind': list,
        'required': False
    }
    },
    {"pro_network": {
        'kind': bool,
        'required': False
        }
    },
    {"allow_reviews": {
        'kind': bool,
        'required': False
        }
    },
    {"review_chance": {
        'kind': int,
        'required': False
        }
    }
]

# note this is just for "label" at time of writing

@routes.route('/api/v1/project/<string:project_string_id>' +
              '/job/update',
              methods=['POST'])
@Project_permissions.user_has_project(
    Roles=["admin", "Editor"],
    apis_user_list=["api_enabled_builder"])
def job_update_api(project_string_id):
    """
    Do we want a different spec list here...

    """
    log, input, untrusted_input = regular_input.master(
        request=request,
        spec_list=update_job_spec_list)

    if len(log["error"].keys()) >= 1:
        return jsonify(log=log), 400

    with sessionMaker.session_scope() as session:
        project = Project.get(session, project_string_id)

        job = Job.get_by_id(session, input['job_id'])

        if job is None:
            log['error']['job'] = "No job found"
            return jsonify(log=log), 400

        Job_permissions.check_job_after_project_already_valid(
            job=job,
            project=project)

        job, log = job_update_core(session, job, project, input, log)
        if regular_log.log_has_error(log):
            return jsonify(log=log), 400
        log['success'] = True
        out = jsonify(job=job.serialize_new(),
                      log=log)

        return out, 200

@routes.route('/api/v1/project/<string:project_string_id>' +
              '/job/set-output-dir',
              methods=['POST'])
@Project_permissions.user_has_project(
    Roles=["admin", "Editor"],
    apis_user_list=["api_enabled_builder"])
def job_output_dir_update(project_string_id):
    """
    """
    output_job_spec = [
        {"job_id": {
            'kind': int
        }
        },
        {"output_dir": {
            'kind': int,
            'default': None,
            'required': False
        }},
        {
            "output_dir_action": {
                'kind': str,
                'default': None

            }
        }
    ]
    log, input, untrusted_input = regular_input.master(
        request=request,
        spec_list=output_job_spec)

    if len(log["error"].keys()) >= 1:
        return jsonify(log=log), 400

    with sessionMaker.session_scope() as session:
        project = Project.get(session, project_string_id)

        job = Job.get_by_id(session, input['job_id'])

        if job is None:
            log['error']['job'] = "No job found"
            return jsonify(log=log), 400

        Job_permissions.check_job_after_project_already_valid(
            job=job,
            project=project)

        job, log = update_output_dir_actions(session, job, project, input, log)

        if regular_log.log_has_error(log):
            return jsonify(log=log), 400

        log['success'] = True
        out = jsonify(job=job.serialize_new(),
                      log=log)

        return out, 200

def update_output_dir_actions(session, job, project, input_data, log):

    if input_data['output_dir_action'] not in ['copy', 'move', 'nothing']:
        log['error']['output_dir'] = 'output_dir  must be "copy", "move" or "nothing".'
        return None, log

    if input_data['output_dir_action'] == 'nothing':
        job.output_dir_action = input_data['output_dir_action']
        job.completion_directory_id = None
        session.add(job)
        return job, log

    directory = WorkingDir.get(session=session, directory_id=input_data['output_dir'], project_id=project.id)

    if directory is None:
        log['error']['output_dir'] = "No directory found"
        return None, log

    job_observable = task_file_observers.JobObservable(session=session, log=log, job=job)
    job.output_dir_action = input_data['output_dir_action']
    directory_observer = task_file_observers.DirectoryJobObserver(session=session,
                                                                  log=log,
                                                                  directory=directory,
                                                                  job_observable=job_observable)
    job_observable.add_new_directory_observer(directory_observer)
    return job, log

"""
TODO consider an update class object here
"""

def job_update_core(session, job, project, input: dict, log: dict):
    """
    Assumptions
        Main one is that if there are no updates the value will be
        empty. For example update name and not label file list...

        Main distinction is between things that touch the
        *tasks* and things that just touch the *job*
    """
    if job.status == 'draft':
        job, log = new_or_update_core(
            session=session,
            log=log,
            member=job.member_created,
            project=project,
            name=input.get('name'),
            share=input.get('share_type'),
            permission=input.get('permission'),
            label_mode=input.get('label_mode'),
            passes_per_file=input.get('passes_per_file'),
            instance_type=input.get('instance_type'),
            launch_datetime=input.get('launch_datetime'),
            file_count=input.get('file_count'),
            label_file_list=input.get('label_file_list'),
            file_handling=input.get('file_handling'),
            attached_directories_dict=input.get('attached_directories_dict'),
            output_dir_action=input.get('output_dir_action'),
            completion_directory_id=input.get('completion_directory_id'),
            interface_connection_id=input.get('interface_connection_id'),
            job_type=input['type'],
            member_list_ids=input['member_list_ids'],
            reviewer_list_ids=input.get('reviewer_list_ids'),
            default_userscript_id=input.get('default_userscript_id'),
            ui_schema_id=input.get('ui_schema_id'),
            label_schema_id=input.get('label_schema_id'),
            allow_reviews=input.get('allow_reviews'),
            review_chance=input.get('review_chance'),
            job=job
        )
        return job, log
    else:
        # Trending towards anything touching the tasks
        if input['label_file_list']:
            job.label_dict['label_file_list'] = build_label_file_list(
                input['label_file_list'], session, project)

            """
            The build label file list just does the raw IDs
            job_label_attach does all the other magic
            ie color maps, and also in future expansion the
            label mode handling (like the "closed all availble")
            """
            task_template_label_attach(session, job)

            session.add(job)

            log = update_tasks(job, session, log)
        if input.get('label_schema_id'):
            job.label_schema_id =input['label_schema_id']
            session.add(job)
        if input.get('ui_schema_id'):
            job.ui_schema_id =input['ui_schema_id']
            session.add(job)
        else:
            job.ui_schema_id = None
            session.add(job)

        if input['name']:
            job.name = input['name']
            session.add(job)
            log['info']['name'] = "Updated Name"

    return job, log

def update_tasks(job, session, log):
    task_list = job.task_list(
        session=session)

    for task in task_list:
        task.label_dict = job.label_dict
        session.add(task)

    log['info']['task_count'] = f"Updated {str(len(task_list))} tasks."
    return log

@routes.route('/api/v1/project/<string:project_string_id>' +
              '/job/new',
              methods=['POST'])
@Project_permissions.user_has_project(
    Roles=["admin", "Editor"],
    apis_user_list=["api_enabled_builder"])
def new_web(project_string_id):
    """
    Create "partial" task so that it can be saved as draft?

    Returns job id if possible
    That way we can save the job as a draft

    """
    log, input, untrusted_input = regular_input.master(
        request=request,
        spec_list=job_new_spec_list)
    if len(log["error"].keys()) >= 1:
        return jsonify(log=log), 400

    # What defaults are we using here?
    category = None
    type = None

    with sessionMaker.session_scope() as session:

        ### MAIN

        is_live = True

        # TODO usew new generic member thing...generic method to get member
        # But this users the "is_live" thing so check that...

        # We can't use this yet since the "is_live" is coming from auth.
        # member = get_member(session)

        user = User.get(session)
        if user:
            member = user.member
        else:
            client_id = request.authorization.get('username', None)
            auth = Auth_api.get(session, client_id)
            member = auth.member
            is_live = auth.is_live

        # careful this users user stuff not member
        # TODO standard lower() method ie for Exam?
        input['share'] = input['share'].lower()

        if input['share'] == "market" and input['type'] == "exam_template":

            # We only want Diffgram admins to be able to create this type
            if not user or user.is_super_admin is not True:
                log['error']['job'] = "Invalid permission. Try share 'project' or 'org'."
                return jsonify(log=log), 400

        if input['td_api_trainer_basic_training'] is True:

            if not user or user.is_super_admin is not True:
                log['error']['job'] = "Invalid permission. Try share 'project' or 'org'."
                return jsonify(log=log), 400

        project = Project.get(session, project_string_id)

        job, log = new_or_update_core(
            session=session,
            log=log,
            member=member,
            project=project,
            name=input['name'],
            share=input['share'],
            permission=input['permission'],
            label_mode=input['label_mode'],
            passes_per_file=input['passes_per_file'],
            instance_type=input['instance_type'],
            launch_datetime=input['launch_datetime'],
            file_count=input['file_count'],
            label_schema_id = input['label_schema_id'],
            label_file_list=input['label_file_list'],
            file_handling=input['file_handling'],
            job_type=input['type'],
            interface_connection_id=input.get('interface_connection_id'),
            member_list_ids=input['member_list_ids'],
            reviewer_list_ids=input.get('reviewer_list_ids'),
            attached_directories_dict=input['attached_directories_dict'],
            pro_network=input['pro_network'],
            default_userscript_id=input['default_userscript_id'],
            allow_reviews=input.get('allow_reviews'),
            review_chance=input.get('review_chance'),
            tag_list=input.get('tag_list')
        )
        if len(log["error"].keys()) >= 1:
            return jsonify(log=log), 400

        # Not happy about core method thing yet
        job.is_live = is_live
        # TODO: might need to move this inside new_or_update_core
        job.review_by_human_freqeuncy = input['review_by_human_freqeuncy']
        job.category = input['category']
        job.td_api_trainer_basic_training = input['td_api_trainer_basic_training']

        log['success'] = True

        out = jsonify(job=job.serialize_new(),
                      log=log)
        logger.info('Created Job succesfully.')
        return out, 200

def build_label_file_list(label_file_list,
                          session,
                          project) -> list:
    """
    Expects label_file_list to be of the form where
    it's a list of dicts ie [{id: 1}, {id: 2}]

    CAUTION this is JUST the label file list
    (not the color map or serialized thing)

    The overal label dict may be of the form of
    label_file_colour_map: {722716: {a: 1, hex: "#1BFC8C", hex8: "#1BFC8CFF",…},…}
    label_file_list: [722716, 726664, 726665]
    label_file_list_serialized: [{ann_is_complete: nul ...

    Updates " label_file_list: [722716, 726664, 726665]  " only.
    See job_label_attach() for specifics there...

    """

    if label_file_list:
        return File.validate_file_list(
            session=session,
            project_id=project.id,
            file_list=label_file_list)

    # Defaults if no list is provided.
    file_list = WorkingDirFileLink.file_list(
        session=session,
        working_dir_id=project.directory_default_id,
        # prefer to use self. for project here once this is a class
        limit=25,
        type="label")

    return [file.id for file in file_list]

def new_or_update_core(session,
                       log,
                       member,
                       project,
                       name,
                       share,
                       permission,
                       label_mode,
                       passes_per_file,
                       instance_type,
                       launch_datetime,
                       file_count,
                       label_file_list,
                       file_handling,
                       attached_directories_dict=None,
                       output_dir_action='nothing',
                       completion_directory_id=None,
                       interface_connection_id=None,
                       ui_schema_id=None,
                       label_schema_id=None,
                       job_type=None,
                       job=None,
                       member_list_ids=None,
                       reviewer_list_ids=None,
                       pro_network=False,
                       default_userscript_id=None,
                       allow_reviews=False,
                       review_chance=0,
                       tag_list=None
                       ):

    is_updating = False
    if job is None:
        job = Job(member_created=member,
                  project=project)
        session.add(job)
    else:
        is_updating = True

    job.allow_reviews = allow_reviews
    job.review_chance = (0 if review_chance == None else review_chance) / 100

    if member_list_ids is not None:
        log = job.update_member_list(
            member_list_ids = member_list_ids,
            session = session,
            log = log)

    if reviewer_list_ids is not None:
        log = job.update_reviewer_list(
            session = session,
            reviewer_list_ids = reviewer_list_ids,
            log = log)

    if default_userscript_id:
        default_userscript = UserScript.get(
            session = session,
            id = default_userscript_id,
            project_id = project.id)

        if default_userscript is None:
            log['error']['default_userscript_id'] = "Not found. Check ID or Project combo."
            return None, log

        job.default_userscript_id = default_userscript.id
    if label_file_list:
        # First update fields with special concerns (i.e label_dict, share_type, launch_datetime,dir.)
        job.label_dict['label_file_list'] = build_label_file_list(label_file_list, session, project)
        if is_updating:
            # Recreate labels information dict an update all tasks accordingly
            """
            The build label file list just does the raw IDs
            job_label_attach does all the other magic
            ie color maps, and also in future expansion the
            label mode handling (like the "closed all availble")

            """
            # Not really sure if tasks can exist while in draft mode but might be good idea to update anyways.
            task_template_label_attach(session, job)
            log = update_tasks(job, session, log)

    if is_updating and job.share_type != share:
        job.share_type = share
        if not job.share_type: job.share_type = 'project'
        job.share_type = job.share_type.lower()
        log['info']['share_type'] = "Updated share_type"
    else:
        # TODO: need to finish implementation and consider cases like: when updating a job, what happens to the bid?
        job.share_type = share
        job.share_type = job.share_type.lower()

    if job.share_type not in ["market", "org", "project"]:
        log['error']['kind'] = "Invalid share_type, valid options are: ['market', 'org', 'project']"
        return False, log

    job.launch_datetime = launch_datetime
    # We expect this to be a valid datetime object,
    # but otherwise don't validate, ie a date in the past
    # just means "launch now"

    if job.launch_datetime is not None:
        job.waiting_to_be_launched = True

    if not is_updating:
        directory = WorkingDir.new_blank_directory(session=session)
        job.directory = directory

    job.type = job_type
    if job.type == "Exam":
        job.is_template = True
    else:
        job.is_template = False

    # Now update or add the rest of the fields
    fields_to_process = {
        'name': name,
        'file_count': file_count,
        'type': job_type,
        'permission': permission,
        'label_mode': label_mode,
        'passes_per_file': passes_per_file,
        'ui_schema_id': ui_schema_id,
        'instance_type': instance_type,
        'file_handling': file_handling,
        'output_dir_action': output_dir_action,
        'label_schema_id': label_schema_id,
        'interface_connection_id': interface_connection_id,
        'pro_network': pro_network,
    }

    for field_key, field_val in fields_to_process.items():
        if is_updating and getattr(job, field_key) != field_val:
            setattr(job, field_key, field_val)
            log['info'][field_key] = f"Updated {field_key}"
        else:
            setattr(job, field_key, field_val)

    if job.pro_network is True:
        try:
            email_about_new_pro_job(
                job = job,
                user = member.user)
        except:
            logger.info("Failed to email about new pro job")
    # Update sync dirs and completion directory ID
    if isinstance(attached_directories_dict, dict):
        job.update_attached_directories(session,
                                        attached_directories_dict.get('attached_directories_list'),
                                        delete_existing=True)
        job.set_cache_key_dirty(cache_key="attached_directories_dict")
    if completion_directory_id:
        job.completion_directory_id = completion_directory_id

    if tag_list:
        log = add_tags_to_job(
            tag_list,
            session = session,
            project = project,
            job = job,
            log = log)

    if is_updating:
        Event.new(
            kind="update_job",
            session=session,
            member=member,
            success=True
        )
    else:
        Event.new(
            kind="new_job",
            session=session,
            member=member,
            success=True
        )
    return job, log

def add_tags_to_job(tag_list,
                    session,
                    project,
                    job,
                    log):

    if len(tag_list) > 100:
        log['error']['tag_list_length'] = f"Over limit, tags sent: {len(tag_list)}"
        return log

    for name in tag_list:

        tag = Tag.get_or_new(
            name = name,
            project_id = project.id,
            session = session)

        if tag.id is None:
            session.add(tag)

        jobtag = tag.add_to_job(job_id = job.id)

        session.add(jobtag)

    return log

def email_about_new_pro_job(job, user):

    subject = f"New Draft Pro Job: {job.name}"

    message = []

    message.append(job.name)
    message.append("\n")
    message.append(f"ID: {str(job.id)}")
    message.append("\n")
    message.append(f"file_count_statistic {str(job.file_count_statistic)}")
    message.append("\n")

    if user:
        message.append("\n")
        message.append(f"User: {user.first_name} {user.last_name}")
        message.append("\n")
        message.append(f"Email:{str(user.email)}")
    else:
        message.append("\n No Member.user")

    communicate_via_email.send(
	    email = "",
	    subject = subject,
	    message = "".join(message)
		)


from tkinter import ttk
from tkinter import *

root = Tk()
content = ttk.Frame(root)
frame = ttk.Frame(content,borderwidth=5,relief="sunken",width=200,height=100)
namelabel = ttk.Label(content,text="name")
name= ttk.Entry(content)

onevariable = BooleanVar()
twovariable = BooleanVar()
threevariable = BooleanVar()
onevariable.set(True)
twovariable.set(False)
threevariable.set(True)
one = ttk.Checkbutton(content,text="One",variable=onevariable,onvalue=True)
two = ttk.Checkbutton(content,text="Two",variable=twovariable,onvalue=True)
three = ttk.Checkbutton(content,text="Three",variable=threevariable,onvalue=True)
ok = ttk.Button(content,text="okay")
cancel = ttk.Button(content, text="cancel")

content.grid(column=0,row=0)
frame.grid(column=0, row=0,columnspan=3, rowspan=2)
namelabel.grid(column=3, row=0,columnspan=2)
name.grid(column=3, row=1,columnspan=2)
one.grid(column=0,row=3)
two.grid(column=1,row=3)
three.grid(column=2,row=3)
ok.grid(column=3,row=3)
cancel.grid(column=4,row=3)
root.mainloop()


submit = True
from collections import Counter
from aocd import data
import u

img = [int(c) for c in data.strip()]

def a():
    w = 25
    h = 6
    best_zero = None
    res = None
    for layer in u.chunks(img, w * h):
        counts = Counter(layer)
        if best_zero is None or counts[0] < best_zero:
            res = counts[1] * counts[2]
            best_zero = counts[0]
    return res

def b():
    w = 25
    h = 6
    out = [None] * (w * h)
    layers = list(u.chunks(img, w * h))
    for i in range(w * h):
        for layer in layers:
            if layer[i] != 2:
                out[i] = layer[i]
                break
    m = {
        (x, y): row[x] for y, row in enumerate(list(u.chunks(out, w))) for x in range(w)
    }
    u.print_matrix(m, " #")

u.main(a, b, submit=globals().get("submit", False))


#!/usr/bin/env python3

import ast
import os
import pathlib
import re

import astor
import django.conf.global_settings
from django.utils.version import get_docs_version

settings_path = pathlib.Path(os.path.dirname(__file__)) / '..' / 'forsta_auth' / 'settings.py'
settings = settings_path.read_text()

readme_path = pathlib.Path(os.path.dirname(__file__)) / '..' / 'README.md'

vars = []

for match in re.finditer(r'((?P<target>[A-Z0-9_]+)\W=)?\W?(?P<env>env(?P<db>\.db)?\(.*\)),?([ \t]*#[ \t]*(?P<comment>.*))?$', settings, re.MULTILINE):
    var = match.groupdict()

    call = ast.parse(match['env']).body[0].value
    args, kwargs = call.args, call.keywords

    if var['db']:
        var['name'] = 'DATABASE_URL'
    else:
        var['name'] = args[0].s

    for kwarg in kwargs:
        value = astor.to_source(kwarg.value).strip()
        if value.startswith('(') and value.endswith(')'):
            value = value[1:-1]
        if value.startswith('"""') and value.endswith('"""'):
            value = value[2:-2]
        if value.startswith('"') and value.endswith('"') and "'" not in value:
            value = "'" + value[1:-1] + "'"
        if kwarg.arg in ('default', 'cast'):
            var[kwarg.arg] = '`' + value.replace('|', '\\|').replace('`', '\\`') + '`'

    vars.append(var)

new_readme = []

with readme_path.open() as readme:
    for line in readme:
        new_readme.append(line)
        if line == '## Environment variables\n':
            break

    new_readme.extend([
        "\n",
        "Name | Cast | Default | Description\n",
        "---- | ---- | ------- | -----------\n",
    ])

    for var in vars:
        name = var['name'].replace('|', '\|')
        if not var.get('default'):
            name = f'**{name}**'
        comment = (var.get('comment') or '').replace('|', '\|')
        if var['target'] and hasattr(django.conf.global_settings, var['target']):
            if comment:
                comment = comment.rstrip('.') + '. '
            comment += f" [See Django documentation](https://docs.djangoproject.com/en/{get_docs_version()}/ref/settings/#{var['target'].lower().replace('_', '-')})"
        new_readme.append("{} | {} | {} | {}".format(
            name,
            var.get('cast') or '',
            var.get('default') or '',
            comment,
        ).strip() + '\n')

    resume = False
    for line in readme:
        if line.startswith('## '):
            resume = True
        if resume:
            new_readme.append(line)

readme_path.write_text(''.join(new_readme))


import collections

participant = ["mislav", "stanko", "mislav", "ana"]
completion = ["stanko", "ana", "mislav"]

def solution(participant, completion):
    dic = {}

    for i in participant:
        if i in dic.keys():
            dic[i] += 1
        else:
            dic[i] = 1
    # {'mislav': 2, 'stanko': 1, 'ana': 1}

    for i in completion:
        if i in dic.keys():
            dic[i] -= 1
    # {'mislav': 1, 'stanko': 0, 'ana': 0}

    for key, value in dic.items():
        if value == 1:
            return key
    # mislav

print(solution(participant, completion))

# Counter 라이브러리 활용한 풀이
def solution2(participant, completion):
    answer = collections.Counter(participant) - collections.Counter(completion)
    return list(answer.keys())[0]

# hash 활용한 풀이
def solution3(participant, completion):
    answer = ''
    temp = 0
    dic = {}
    for part in participant:
        dic[hash(part)] = part
        temp += int(hash(part))
    for com in completion:
        temp -= hash(com)
    answer = dic[temp]

    return answer

# sort 후 비교하는 풀이

def solution4(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[len(participant)-1]


from ultralytics import YOLO
import streamlit as st
import os

#######################################################################################################################
## Ъј» The aim of this script is to create an Rock/Paper/Scissors application based on a trained model (from YOLOv8). ##
## ЪЈъ The uploaded snapshots are stored, by default, in /workspace/attendee/.                                        ##
## ЪДа The train model is stored, by default, in /workspace/attendee/                                                 ##
## Рё╣№ИЈ Note on the environments variables:                                                                            ##
##      - WORK_PATH (default value: '/workspace/attendee/') is the path where get the model and store de snapshots   ##
#######################################################################################################################

# ЪЏа Get configuration from environment variables
WORK_PATH = os.getenv('WORK_PATH', '/workspace/attendee/')

# Save uploaded photo
def save_photo(photo):

    photoAbsolutePath = WORK_PATH + photo.name

    with open(photoAbsolutePath,'wb') as f:
         f.write(photo.getbuffer())

    return photoAbsolutePath

# main
if __name__ == '__main__':

    st.write("## Welcome on the Ъфе ЪЊё Рюѓ№ИЈ game!")
    # ЪДа Load the model
    model = YOLO(WORK_PATH + "best.torchscript")

    # ЪЊИ Camera input
    img_file_buffer = st.camera_input("Take your picture in real time:")
    if img_file_buffer is not None:
      photoPath = save_photo(img_file_buffer)

      # Ъћј Prediction
      results = model.predict(photoPath, verbose=True, save=True, conf=0.5)

      # ЪЊѕ Display results
      for r in results:
        for c in r.boxes.cls:
          st.write(r.names[int(c)])
      #st.write(results)


#!/usr/bin/python36
pm18a = qtth = mm20a = 0
while True:
    idade = int(input('Digite a idade: '))
    if idade > 18:
        pm18a += 1
    sexo = ' '
    while sexo not in 'MF':
        sexo = str(input('Digite o sexo:[M/F] ')).upper().strip()[0]
    if sexo == 'M':
        qtth += 1
    if sexo == 'F' and idade < 20:
        mm20a += 1
    cont = ' '
    while cont not in 'SN':
        cont = str(input('Continua:[S/N] ')).upper().strip()[0]
    if cont == 'N':
        break
if pm18a > 0:
    print(f'Foram cadastradas {pm18a} pessoa(s) maiores de 18 anos.')
if qtth > 0:
    print(f'Foram cadastrados {qtth} homen(s).')
if mm20a > 0:
    print(f'Foram cadastradas {mm20a} mulher(es) com menos de 20 anos.')


radix_256 = 2**256
radix_128 = 2**128
radix_32 = 2**32
radix_16 = 2**16
radix_8  = 2**8

def Hex(n, radix=0):
    '''Converts n to a hex string.
       If radix is not 0, pads to the max number of characters for digits modulo the radix.
       Uses capital letters, and no trailing L.
    '''
    if n < 0:
        signum = "-"
    else:
        signum = ""

    nh = hex(abs(n))[2:]

    if nh.find("L") >= 0:
        nh = nh[:-1]

    pad = (len(bin(radix)))/4  # -3 for the 0b[01], but then +3 for the round up.

    if pad >= len(nh):
        pad -= len(nh)
    else:
        pad = 0

    return(signum + "0x" + int(pad)*"0" + nh.upper())

def int2lelist(n, radix, listlen=0):
    '''Converts n to a little-endian list of length at least listlen in the given radix.
    '''
    if n < 0:
        n = -n
    elif n == 0:
       nlist = [0]
    else:
       nlist = []

    while n:
        nlist.append(int(n % radix))
        n = n // radix

    while len(nlist) < listlen:
        nlist.append(0)

    return nlist[:]

def belist2int(nlist, radix):
    '''Converts n from a big-endian list in the given radix to an integer.
    '''
    n = 0
    for ndigit in nlist:
        n *= radix
        n += ndigit

    return n

def int2belist(n, radix, listlen=0):
    '''Converts n to a big-endian list of length at least listlen in the given radix.
    '''
    nlist = int2lelist(n, radix, listlen)
    nlist.reverse()

    return nlist[:]

def lelist2int(nlist, radix):
    '''Converts n from a little-endian list in the given radix to an integer.
    '''
    nlist_rev = nlist[:]
    nlist_rev.reverse()

    return belist2int(nlist_rev, radix)

def long2hexstr(n, bitlen):
    '''Converts n to a hex string, where n is of bitlength bitlen
    '''
    return "{0:0>{width}X}".format(n, width=((bitlen*2)+7)/8)


import numpy as np

import pystencils

def test_assignment_from_stencil():

    stencil = [
        [0, 0, 4, 1, 0, 0, 0],
        [0, 0, 0, 2, 0, 0, 0],
        [0, 0, 0, 3, 0, 0, 0]
    ]

    x, y = pystencils.fields('x, y: [2D]')

    assignment = pystencils.assignment.assignment_from_stencil(stencil, x, y)
    assert isinstance(assignment, pystencils.Assignment)
    assert assignment.rhs == x[0, 1] + 4 * x[-1, 1] + 2 * x[0, 0] + 3 * x[0, -1]

    assignment = pystencils.assignment.assignment_from_stencil(stencil, x, y, normalization_factor=1 / np.sum(stencil))
    assert isinstance(assignment, pystencils.Assignment)


import os
import pickle
import time

import numpy as np

class Dataset:
    NAME = ""
    SEQUENCE_LENGTH = int()
    INPUT_FEATURES_SIZE = int()
    OUTPUT_CLASSES_SIZE = int()
    LABELS = list()

    def __init__(self, verbose=True, one_hot=False):
        if verbose:
            print("Loading {} dataset...".format(Dataset.NAME))

        self.X_train = None  # [batch_size, sequence_length, features]
        self.X_test = None  # [batch_size], or if one_hot: [batch_size, output_classes_size]
        self.Y_train = None  # (batch_size, sequence_length, features)
        self.Y_test = None  # [batch_size], or if one_hot: [batch_size, output_classes_size]
        self.load_train_test()
        if one_hot:
            self.Y_train = self.one_hot(self.Y_train)
            self.Y_test = self.one_hot(self.Y_test)
        else:
            self.Y_train = np.squeeze(self.Y_train)
            self.Y_test = np.squeeze(self.Y_test)

        if verbose:
            print("Shapes for [self.X_train, self.Y_train, self.X_test, self.Y_test]:")
            for ds in [self.X_train, self.Y_train, self.X_test, self.Y_test]:
                print(
                    "  shape={}".format(ds.shape),
                    ", max-min={}".format(np.max(ds) - np.min(ds)),
                    ", mean={}".format(np.mean(ds)),
                    ", std={}".format(np.std(ds)))
            print("Dataset loaded.\n")

    def one_hot(self, Y_):
        """Function to encode output labels from number indexes.

        e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]
            argument:   Y_, a 2D np.ndarray containing features by index
            return:     Y_, a 2D np.ndarray containing one-hot features
        """
        Y_ = Y_.reshape(len(Y_))
        return np.eye(self.OUTPUT_CLASSES_SIZE)[np.array(Y_, dtype=np.int32)]  # Returns FLOATS

class UCIHARDataset(Dataset):
    NAME = "UCIHAR"
    SEQUENCE_LENGTH = 128
    INPUT_FEATURES_SIZE = 9
    OUTPUT_CLASSES_SIZE = 6
    LABELS = [
        "WALKING",
        "WALKING_UPSTAIRS",
        "WALKING_DOWNSTAIRS",
        "SITTING",
        "STANDING",
        "LAYING"
    ]

    def __init__(self, verbose=True):
        super().__init__(verbose)

    def load_train_test(self):
        # Those are separate normalised input features for the neural network
        INPUT_SIGNAL_TYPES = [
            "body_acc_x_",
            "body_acc_y_",
            "body_acc_z_",
            "body_gyro_x_",
            "body_gyro_y_",
            "body_gyro_z_",
            "total_acc_x_",
            "total_acc_y_",
            "total_acc_z_"
        ]
        DATA_PATH = "data/"
        DATASET_PATH = DATA_PATH + "UCI HAR Dataset/"

        TRAIN = "train/"
        TEST = "test/"

        X_train_signals_paths = [
            DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES
        ]
        X_test_signals_paths = [
            DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES
        ]
        Y_train_path = DATASET_PATH + TRAIN + "y_train.txt"
        Y_test_path = DATASET_PATH + TEST + "y_test.txt"

        self.X_train = self.load_X(X_train_signals_paths)
        self.X_test = self.load_X(X_test_signals_paths)
        self.Y_train = self.load_Y(Y_train_path)
        self.Y_test = self.load_Y(Y_test_path)

    def load_X(self, X_signals_paths):
        """Load "X" (the neural network's training and testing inputs).

        Given attribute (train or test) of feature, read all 9 features into an
        np ndarray of shape [sample_sequence_idx, time_step, feature_num]
            argument:   X_signals_paths str attribute of feature: 'train' or 'test'
            return:     np ndarray, tensor of features
        """
        X_signals = []

        for signal_type_path in X_signals_paths:
            file = open(signal_type_path, 'r')
            # Read dataset from disk, dealing with text files' syntax
            X_signals.append(
                [np.array(serie, dtype=np.float32) for serie in [
                    row.replace('  ', ' ').strip().split(' ') for row in file
                ]]
            )
            file.close()

        return np.transpose(np.array(X_signals), (1, 2, 0))

    def load_Y(self, y_path):
        """Load "Y" (the neural network's training and testing outputs).

        Read Y file of values to be predicted
            argument: y_path str attibute of Y: 'train' or 'test'
            return: Y ndarray / tensor of the 6 one_hot labels of each sample
        """
        file = open(y_path, 'r')
        # Read dataset from disk, dealing with text file's syntax
        Y_ = np.array(
            [elem for elem in [
                row.replace('  ', ' ').strip().split(' ') for row in file
            ]],
            dtype=np.int32
        )
        file.close()

        # Substract 1 to each output class for friendly 0-based indexing
        return Y_ - 1

class OpportunityDataset(Dataset):
    NAME = "Opportunity"
    SEQUENCE_LENGTH = 24
    INPUT_FEATURES_SIZE = 113
    OUTPUT_CLASSES_SIZE = 18

    def __init__(self, verbose=True):
        super().__init__(verbose)

    def load_train_test(self):
        raise NotImplementedError()

    def load_dataset(self, filename):
        raise NotImplementedError()


__all__ = ['NewsDetailView']

from django.core.cache import cache
from django.views.generic import DetailView

from mainapp.models import News

class NewsDetailView(DetailView):
    model = News
    template_name = "mainapp/news/news_detail.html"

    def get_context_data(self, **kwargs):
        cached_news = cache.get(f'news_object_{self.object.pk}')
        if cached_news is None:
            cache.set(f'news_object_{self.object.pk}', self.object)
            cached_news = cache.get(f'news_object_{self.object.pk}')
        context_obj_name = self.get_context_object_name(self.object)
        c = {'object': cached_news, context_obj_name: cached_news, 'view': self}

        # c = super().get_context_data(**kwargs)

        return c


import getopt
import sys

from cvalue import CValue

def c_value():
    """
    C-Value Method CLI Entrance
    :return: None
    """
    input_path = None
    output_path = None
    argv = sys.argv[1:]
    if not argv:
        raise ValueError
    opts, args = getopt.getopt(argv, "i:o:", ["input=", "output="])
    for opt, arg in opts:
        if opt in ["-i", "--input"]:
            input_path = arg
        if opt in ["-o", "--output"]:
            output_path = arg
    if not input_path or not output_path:
        raise ValueError
    CValue(input_path, output_path)

c_value()


import scrapy
from scrapy_splash import SplashRequest
from urllib.parse import quote_plus
from datetime import datetime

from scrap_articles.items import ArticleItem
from scrap_articles.spiders.utils import check_country

def get_page(keyword, current):
    return f'https://dl.acm.org/action/doSearch?AllField={quote_plus(keyword)}&pageSize={50}&startPage={current}'

class ACMSpider(scrapy.Spider):
    name = "acm_spider"
    current_page = 1

    def __init__(self, keyword='', **kwargs):
        self.keyword = keyword
        self.start_urls = [get_page(keyword, self.current_page)]
        super().__init__(**kwargs)

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'wait': 3})

    def parse(self, response):
        for item in response.css(".issue-item__title a::attr(href)").getall():
            yield SplashRequest(response.urljoin(item), self.parse_article, args={'wait': 3})

        if self.current_page < 10:
            self.current_page += 1
            yield SplashRequest(get_page(self.keyword, self.current_page), self.parse, args={'wait': 3})

    def parse_article(self, response):
        unis = response.css(".author-info__body p::text").getall()
        countries = [uni.split(",")[-1].strip() for uni in filter(lambda x: "," in x, unis)]
        countries = filter(lambda x: check_country(x), countries)
        date = response.css(".CitationCoverDate::text").get()
        item = ArticleItem()

        item['id'] = response.url.split("/")[-1]
        item['title'] = response.css('.citation__title::text').get()
        item['abstract'] = response.css('.abstractSection p::text').get()
        item['authors'] = response.css(".loa__author-name span::text").getall()
        try:
            item['citations'] = int(response.css(".tooltip__body .citation span::text").get())
        except:
            pass
        item['countries'] = countries
        item['universities'] = unis
        item['keywords'] = [self.keyword]
        item['date'] = datetime.strptime(date, '%d %B %Y') if date else None
        item['source'] = "acm"

        return item


from mrjob.job import MRJob
from mrjob.step import MRStep
import numpy as np
import pickle
from sklearn.neighbors import KNeighborsClassifier as KNC
import csv
import re

# Helper function to read SKLearn KNN model objects
def open_pickle(filename):
    f = open(filename, 'rb')
    ob = pickle.load(f)
    f.close()
    return ob

KNN = [("five", open_pickle("5_neighbors_model.obj")),
    ("ten", open_pickle("10_neighbors_model.obj")),
    ("fifteen", open_pickle("15_neighbors_model.obj")),
    ("twenty", open_pickle("20_neighbors_model.obj"))]

class KNNSuccesses(MRJob):

    def mapper(self, _, line):
        try:
            var_list = [float(x) for x in line.strip().split(',')][1:]
            true_val = var_list[-1]
            if (0 > true_val > -1): # Unstandardizes data
                true_val = 1
            elif (2 > true_val > 1):
                true_val = 2
            elif (4 > true_val > 3):
                true_val = 3
            elif (5 > true_val > 6):
                true_val = 4
            else:
                true_val = 1
            for model in KNN:
                yield model[0], model[1].score(np.array([var_list[0:-1]]), np.array([true_val]))
            yield "lines", 1
        except:
            yield 'h', 1

    def reducer(self, model, count):
        yield model, sum(count)

if __name__ == '__main__':
    KNNSuccesses.run()


"""
Diagonal traversal
"""
from typing import List
import collections

class Solution:
    def findDiagonalOrder_i(self, matrix: [List[List[int]]]) -> List[int]:
        entries = [(i + j, (j, i)[(i ^ j) & 1], val)
                   for i, row in enumerate(matrix)
                   for j, val in enumerate(row)]
        return [e[2] for e in sorted(entries)]

    def findDiagonalOrder(self, matrix: [List[List[int]]]) -> List[int]:
        def sorter(xy):
            x, y = xy
            return (x + y, x if (x + y) % 2 else y)

        m, n = len(matrix), len(matrix[0])
        indices = sorted(((i, j) for i in range(m) for j in range(n)),
                         key=sorter)
        return [matrix[i][j] for i, j in indices]

    def findDiagonalOrder_dd(self, matrix: [List[List[int]]]) -> List[int]:
        result = []
        dd = collections.defaultdict(list)
        for i, row in enumerate(matrix):
            for j, val in enumerate(row):
                dd[i + j].append(val)
        for k in sorted(dd.keys()):
            diag = dd[k] if k % 2 else reversed(dd[k])
            result.extend(diag)
        return result

def test():
    sol = Solution()
    cases = [
        [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    ]
    for case in cases:
        print(sol.findDiagonalOrder(case))

if __name__ == '__main__':
    test()


import asyncio
from dataclasses import dataclass
from typing import List

from clients.tg.api import TgClient
from clients.fapi.tg import TgClientWithFile
from clients.fapi.s3 import S3Client
from clients.tg.dcs import UpdateObj, File
from bot.utils import log_exceptions

@dataclass
class WorkerConfig:
    endpoint_url: str
    aws_secret_access_key: str
    aws_access_key_id: str
    bucket: str
    concurrent_workers: int = 1

class Worker:
    def __init__(self, token: str, queue: asyncio.Queue, config: WorkerConfig):
        self.queue = queue
        self.config = config
        self.run = True
        # обязательный параметр, в него нужно сохранить запущенные корутины воркера
        self._tasks: List[asyncio.Task] = []
        # обязательный параметр, выполнять работу с s3 нужно через объект класса self.s3
        # для загрузки файла нужно использовать функцию fetch_and_upload или stream_upload
        self.s3 = S3Client(
            endpoint_url=config.endpoint_url,
            aws_secret_access_key=config.aws_secret_access_key,
            aws_access_key_id=config.aws_access_key_id
        )
        self.tg = TgClient(token)
        self.ftg = TgClientWithFile(token)
        self.is_first_msg = True

    @log_exceptions
    async def handle_update(self, upd: UpdateObj):
        """
        в этом методе должна происходить обработка сообщений и реализация бизнес-логики
        бизнес-логика бота тестируется с помощью этого метода, файл с тестами tests.bot.test_worker::TestHandler
        """
        if self.is_first_msg:
            self.is_first_msg = False
            await self.tg.send_message(upd.message.chat.id, '[greeting]')
        else:
            if not upd.message.document:
                await self.tg.send_message(upd.message.chat.id, '[document is required]')
            else:
                await self.tg.send_message(upd.message.chat.id, '[document]')
                raise Exception('a;a;a')
                file: File = await self.ftg.get_file(upd.message.document.file_id)
                await self.ftg.download_file(file.file_path, file.file_unique_id)
                await self.s3.stream_file(self.config.bucket, upd.message.document.file_name, file.file_unique_id)

                await self.tg.send_message(upd.message.chat.id, '[document has been saved]')

    @log_exceptions
    async def _worker(self):
        """
        должен получать сообщения из очереди и вызывать handle_update
        """
        while self.run:
            msg = await self.queue.get()
            await self.handle_update(msg)

    def start(self):
        """
        должен запустить столько воркеров, сколько указано в config.concurrent_workers
        запущенные задачи нужно положить в _tasks
        """
        self.run = True
        self._tasks = [asyncio.create_task(self._worker()) for _ in range(self.config.concurrent_workers)]

    @log_exceptions
    async def stop(self):
        """
        нужно дождаться пока очередь не станет пустой (метод join у очереди), а потом отменить все воркеры
        """
        self.run = False
        if not self.queue.empty():
            await self.queue.join()

        for task in self._tasks:
            task.cancel()

        await asyncio.sleep(0.1)


# [BOJ] 3980. 선발 명단
# 풀이 시간: 40 분
# 실행 시간: 124 ms
# 메모리: 31256 KB

# player: 현재 몇 번째 선수인지
# score: 현재까지의 점수
def perm(player, score):
    global max_kepa

    # 종료 조건
    # 마지막 선수라면 종료
    if player == 11:
        # 최대 능력치 갱신
        max_kepa = max(max_kepa, score)
        return

    # 각각의 모든 포지션 탐색
    for i in range(11):
        # 가지 치기
        # 해당 포지션에 선수가 이미 배치되어 있거나, 현재 선수는 해당 포지션 능력치가 0이라면 패스
        if visited[i] or not kepa[player][i]:
            continue

        # 방문 체크
        visited[i] = 1

        # 재귀 호출
        perm(player + 1, score + kepa[player][i])

        # 방문 체크 되돌리기
        visited[i] = 0

# 입력
C = int(input())

# 하나의 케이스는 11개
# 각 케이스 별로 입력받기
for i in range(C):
    # 능력치
    kepa = [list(map(int, input().split())) for _ in range(11)]

    max_kepa = 0
    # 선수가 포지션에 있는지 방문 확인(해당 포지션이 선수가 선택된 포지션인지 확인)
    visited = [0] * 11

    # 순열 함수 호출
    # 첫번째 선수부터
    perm(0, 0)

    # 현재 케이스의 최대치 출력
    print(max_kepa)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from trapezoidal import trapezoidal

def test_trapezoidal_linear_scale():
    """Check that linear functions are integrated exactly"""
    f = lambda x: 6e8 * x - 4e6
    F = lambda x: 3e8 * x**2 - 4e6 * x  # Anti-derivative
    # a = 1.2;  b = 4.4
    a = 1.2 / 6e8
    b = 4.4 / 6e8  # Scale interval down
    exact = F(b) - F(a)
    tol = 1e-14
    for n in 2, 20, 21:
        numerical = trapezoidal(f, a, b, n)
        err = abs(exact - numerical)
        msg = "n = %d, err = %g" % (n, err)
        assert err < tol, msg
        print(msg)

def test_trapezoidal_linear_reldiff():
    """
    Check that linear functions are integrated exactly.
    Use relative and not absolute difference.
    """
    f = lambda x: 6e8 * x - 4e6
    F = lambda x: 3e8 * x**2 - 4e6 * x  # Anti-derivative
    a = 1.2
    b = 4.4  # Scale interval down
    exact = F(b) - F(a)
    tol = 1e-14
    for n in 2, 20, 21:
        numerical = trapezoidal(f, a, b, n)
        err = abs(exact - numerical) / exact
        msg = "n = %d, err = %g" % (n, err)
        assert err < tol, msg
        print(msg)

def test_trapezoidal_conv_rate():
    """Check empirical convergence rates against the expected -2."""
    # from math import exp
    f = lambda x: 6e8 * x - 4e6
    F = lambda x: 3e8 * x**2 - 4e6 * x  # Anti-derivative
    a = 1.1
    b = 1.9
    r = convergence_rates(f, F, a, b, 14)
    print(r)
    tol = 0.01
    assert abs(abs(r[-1]) - 0) < tol, r[-4:]

def convergence_rates(f, F, a, b, num_experiments=14):
    from math import log
    from numpy import zeros

    exact = F(b) - F(a)
    n = zeros(num_experiments, dtype=int)
    E = zeros(num_experiments)
    r = zeros(num_experiments - 1)
    for i in range(num_experiments):
        n[i] = 2 ** (i + 1)
        numerical = trapezoidal(f, a, b, n[i])
        E[i] = abs(exact - numerical)
        print(E[i])
        if i > 0:
            r_im1 = log(E[i] / E[i - 1]) / log(float(n[i]) / n[i - 1])
            r[i - 1] = float("%.2f" % r_im1)  # Truncate, two decimals
    return r

test_trapezoidal_linear_scale()
test_trapezoidal_linear_reldiff()
test_trapezoidal_conv_rate()


import streamlit as st
import leafmap.foliumap as leafmap

st.set_page_config(layout="wide")

# Customize page title
st.title("Welcome to Waterpix")
st.subheader("Let's inspect your water in every pixel!")

st.header("How to check water quality in your area of interest?")

markdown = """
1. Check if all areas are added to your account,
2. Get familiar with meaning of each index,
3. Check what are the newest values and how they change within your area,
4. If you need it, use timeline to see how water quality changed in time.
"""

st.markdown(markdown)

st.subheader("Your Areas of Interest")
m = leafmap.Map(minimap_control=True, center=[49.73907, 20.68443], zoom=12)
m.add_geojson(
    "https://magisterkacog.blob.core.windows.net/aois/jezioro_roznowskie.json"
)
m.to_streamlit(height=500)


import warnings

from openpyxl import load_workbook

# dobim količino iz columna b

def array_kolicina():
    warnings.simplefilter("ignore")
    wb = load_workbook(filename="C:/Podatki/newZlozenke.xlsx", read_only=True)
    ws = wb['Podatki']
    myArray = []
    for row in ws.iter_rows('C2:C20477'):
        for cell in row:
            myArray.append(cell.value)
    return myArray


from bs4 import BeautifulSoup
import requests

query = 'python'
dict =""
url ='http://www.google.com/search?q='
page = requests.get(url + query)
soup = BeautifulSoup(page.text, 'html.parser')
h3 = soup.find_all("h3",class_="r")
for elem in h3:
    el=elem.contents[0]
    url = el["href"]
    if 'wiki' in url:
        link=("https://www.google.com" + url)
        break
page = requests.get(link)
soup = BeautifulSoup(page.text, 'html.parser')
text = soup.find(id="mw-content-text")
p= text.find("p")
while p != None:
	dict+=p.get_text()+"\n"
	p = p.find_next("p")
dict=dict.split()
print(dict)


import rpyc
import os
import json
import sys
import signal

from rpyc.utils.server import ThreadedServer

file_name = "backup_json"

def int_handler(signal, frame):
    file_table = PrimaryBackUpService.exposed_BackUpServer.file_table

    # Putting the file_table on disk
    backup_json = open(file_name, 'w')
    json.dump(file_table, backup_json, ensure_ascii=False)

    sys.exit(0)

def read(fname):
    mapping = PrimaryBackUpService.exposed_BackUpServer.file_table[fname]
    return mapping

def loadFromFile():
    if os.path.isfile(file_name):
        print("local backup file found")
        PrimaryBackUpService.exposed_BackUpServer.file_table = json.load(open(file_name))

class PrimaryBackUpService(rpyc.Service):

    class exposed_BackUpServer():
        file_table = {}
        allChunkServers = {} #e.g. {"1":("127.0.0.1","8888"), "2":("127.0.0.1","8887")}
        primary_secondary_table = {}    # primary_secondary_table[primary_id] = [secondary_id_1, secondary_id_2]
                                        # e.g. {"1":["2","4"], "5":["3","6"]}

        def exposed_getFileTable(self):
            file_table_string = json.dumps(self.file_table)
            print("File table requested by MasterServer")
            return file_table_string
        def exposed_getAllChunkServers(self):
            allChunkServers_string = json.dumps(self.allChunkServers)
            print("allChunkServers requested by MasterServer")
            return allChunkServers_string
        def exposed_getPrimarySecondary(self):
            primary_secondary_table_string = json.dumps(self.primary_secondary_table)
            print("primary_secondary_table requested by MasterServer")
            return primary_secondary_table_string

        def exposed_updateFileTable(self, __file_table__):
            self.__class__.file_table = json.loads(__file_table__)
            print("File table is updated")
        def exposed_updateAllChunkServers(self, __allChunkServers__):
            self.__class__.allChunkServers = json.loads(__allChunkServers__)
            print("allChunkServers is updated")
        def exposed_updatePrimarySecondaryTable(self, __primary_secondary_table__):
            self.__class__.primary_secondary_table = json.loads(__primary_secondary_table__)
            print("primary_secondary_table is updated")

        ## master functions

        def exposed_get_file_table_entry(self, fname):
            # print("file_table in master:", self.__class__.file_table)
            if fname in self.__class__.file_table:
                return self.__class__.file_table[fname]
            else:
                return None

        def exposed_get_list_of_files(self):
            return list(self.__class__.file_table.keys())

        def exposed_get_primaryServers(self):
            primaryServers = {}
            for primary_id in list(self.__class__.primary_secondary_table.keys()):
                primaryServers[primary_id] = self.__class__.allChunkServers[primary_id]
            return primaryServers

        def exposed_get_secondaryServers(self, primary_id):
            secondaryServers = {}
            for secondary_id in self.__class__.primary_secondary_table[primary_id]:
                secondaryServers[secondary_id] = self.__class__.allChunkServers[secondary_id]
            return secondaryServers

        def exposed_get_chunkServers(self):
            return self.__class__.allChunkServers

if __name__ == "__main__":
    port = 8100 # master is told to connect to this number in master_b.py
    loadFromFile()
    signal.signal(signal.SIGINT, int_handler)
    print("Shadow Master is running on port", port)
    t = ThreadedServer(PrimaryBackUpService, port=port)
    t.start()


import frappe
from frappe.website.page_renderers.error_page import ErrorPage
from frappe.website.page_renderers.not_found_page import NotFoundPage
from frappe.website.page_renderers.not_permitted_page import NotPermittedPage
from frappe.website.page_renderers.redirect_page import RedirectPage
from frappe.website.path_resolver import PathResolver

def get_response(path=None, http_status_code=200):
	"""Resolves path and renders page"""
	response = None
	path = path or frappe.local.request.path
	endpoint = path

	try:
		path_resolver = PathResolver(path, http_status_code)
		endpoint, renderer_instance = path_resolver.resolve()
		response = renderer_instance.render()
	except frappe.Redirect:
		return RedirectPage(endpoint or path, http_status_code).render()
	except frappe.PermissionError as e:
		response = NotPermittedPage(endpoint, http_status_code, exception=e).render()
	except frappe.PageDoesNotExistError:
		response = NotFoundPage(endpoint, http_status_code).render()
	except Exception as e:
		response = ErrorPage(exception=e).render()

	return response

def get_response_content(path=None, http_status_code=200):
	response = get_response(path, http_status_code)
	return str(response.data, "utf-8")


class LigneInventaire:

    """Classe représentant une ligne d'un inventaire de vente.

    Attributs attendus par le constructeur :
        produit -- le nom du produit
        prix -- le prix unitaire du produit
        quantite -- la quantité vendue du produit.

    """

    def __init__(self, produit, prix, quantite):
        self.produit = produit
        self.prix = prix
        self.quantite = quantite

    def __repr__(self):
        return "<Ligne d'inventaire {} ({}X{})>".format(
                self.produit, self.prix, self.quantite)

# Création de l'inventaire
inventaire = [
    LigneInventaire("pomme rouge", 1.2, 19),
    LigneInventaire("orange", 1.4, 24),
    LigneInventaire("banane", 0.9, 21),
    LigneInventaire("poire", 1.2, 24),
]

from operator import attrgetter
inventaire_trie = sorted(inventaire, key = attrgetter("prix", "quantite"))

print(inventaire_trie)


# BFS
from collections import deque

N, D = map(int, input().split())
human = [tuple(map(int, input().split())) for _ in range(N)]
infected = [False] * N
infected[0] = True
queue = deque([0])
while len(queue) != 0:
    now = queue.popleft()
    for i in range(N):
        if not infected[i]:
            dist_sq = (human[i][0] - human[now][0]) ** 2 + (human[i][1] - human[now][1]) ** 2
            if dist_sq <= D ** 2:
                infected[i] = True
                queue.append(i)
for i in range(N):
    print('Yes' if infected[i] else 'No')

# DFS
N, D = map(int, input().split())
human = [tuple(map(int, input().split())) for _ in range(N)]
infected = [False] * N
infected[0] = True
stack = [0]
while len(stack) != 0:
    now = stack.pop()
    for i in range(N):
        if not infected[i]:
            dist_sq = (human[i][0] - human[now][0]) ** 2 + (human[i][1] - human[now][1]) ** 2
            if dist_sq <= D ** 2:
                infected[i] = True
                stack.append(i)
for i in range(N):
    print('Yes' if infected[i] else 'No')

# Union-Find
class UnionFind():
    # 初期化
    def __init__(self, n):
        self.par = [-1] * n
        self.rank = [0] * n
        self.siz = [1] * n

    # 根を求める
    def root(self, x):
        if self.par[x] == -1:
            return x # x が根の場合は x を返す
        else:
            self.par[x] = self.root(self.par[x]) # 経路圧縮
            return self.par[x]

    # x と y が同じグループに属するか (根が一致するか)
    def issame(self, x, y):
        return self.root(x) == self.root(y)

    # x を含むグループと y を含むグループを併合する
    def unite(self, x, y):
        # x 側と y 側の根を取得する
        rx = self.root(x)
        ry = self.root(y)
        if rx == ry:
            return False # すでに同じグループのときは何もしない
        # union by rank
        if self.rank[rx] < self.rank[ry]: # ry 側の rank が小さくなるようにする
            rx, ry = ry, rx
        self.par[ry] = rx # ry を rx の子とする
        if self.rank[rx] == self.rank[ry]: # rx 側の rank を調整する
            self.rank[rx] += 1
        self.siz[rx] += self.siz[ry] # rx 側の siz を調整する
        return True

    # x を含む根付き木のサイズを求める
    def size(self, x):
        return self.siz[self.root(x)]

def is_connected(i: int, j: int) -> bool:
    dist = (X[i] - X[j]) ** 2 + (Y[i] - Y[j]) ** 2
    return dist <= D ** 2

N, D = map(int, input().split())
X = [0] * N; Y = [0] * N
for i in range(N): X[i], Y[i] = map(int, input().split())
uf = UnionFind(N)
for i in range(N):
    for j in range(N):
        if is_connected(i, j): uf.unite(i, j)
for i in range(N):
    print('Yes' if uf.issame(0, i) else 'No')


import math
import numpy as np
import gym
from gym import spaces
from gym.utils import seeding
from gymfc.envs.fc_env import FlightControlEnv
import time
from neuroflight_trainer.gyms.step import StepEnv
from neuroflight_trainer.gyms.continuous import ContinuousEnv

class DeltaEnv(ContinuousEnv):
    """An environment in which the action provided by the agent is used as
    a delta in the control output.

    This environment was motivated by the need to reduce high frequency
    oscillations in the control output. By requiring the agent to provide a
    delta, we can constrain how much the control output will be changed and
    thus attempt to reduce the oscillations.

    The problem is the constrains ulitimately minimizes the flight
    envelope. A controller will typically output 100% to the actuator at the
    beginning of maneuver to create a moment. This would not be possible with
    this type of controller.
    """
    def __init__(self,
                 max_rate = 1200,
                 width = 2,
                 max_sim_time = 60,
                 aircraft_config=None,
                 action_bounds = [0, 1],
                 state_fn = None,
                 max_delta = 0.1,
                 state_memory_size = 1,
                 pulse_width = 2,
                 version = 1
                 ):
        super().__init__(
            aircraft_config = aircraft_config,
            action_bounds = action_bounds,
            #width = width,
            max_sim_time = max_sim_time,
            state_fn = state_fn,
            max_rate = max_rate,
            pulse_width = pulse_width
        )
        self.version = version
        self.state_memory_size = state_memory_size
        self.max_delta = max_delta
        self.state_history = []
        self.last_delta = np.zeros(4)

        self.distance = np.zeros(3)
        self.last_distance = np.zeros(3)

        self.at_zero_count = 0

    def step(self, action):
        self.action = action
        if not self.np_random:
            seed = int(time.time()* 1e6)
            self.seed(seed)

        delta = np.zeros(4)
        ac = np.clip(action, -1, 1)
        i = 0
        for a in ac:
            if -0.5 < a and a < 0.5: # -0.5 < a < 0.5
                delta[i] = 0
            elif a <= -0.5:
                a += 0.5
                delta[i] = -self.action_to_control_signal(np.abs(a), 0, 0.5, y_low=0, y_high=self.max_delta)

            elif a >= 0.5:
                a -= 0.5
                delta[i] = self.action_to_control_signal(np.abs(a), 0, 0.5, y_low=0, y_high=self.max_delta)
            i+= 1
        self.y = np.clip(self.y + delta, 0, 1)
        self.command_ys.append(self.y)

        min_throttle = 0.1 # this should have the drone hover
        y = np.minimum(min_throttle + self.y, np.ones(4))
        self.obs = self.step_sim(self.y)

        self.true_error = self.omega_target - self.imu_angular_velocity_rpy
        self.measured_error = self.true_error.copy()
        self.gyro = self.imu_angular_velocity_rpy.copy()

        if self.noise_sigma != 0:
            self.gyro += self.np_random.normal(0, self.noise_sigma, size=3)
            self.measured_error = self.omega_target - self.gyro

        done = self.sim_time >= self.max_sim_time

        reward = self.compute_reward()
        # The agent needs to apply negative output, help them go down
        if self.overshoot(amount_over = np.abs(self.omega_target)*0.3).any():
            a = self.action.copy()
            above_half = a[a >= 0.5]
            if len(above_half) > 0:
                step_time =  (self.sim_time-self.command_start_time)
                reward -= np.average(above_half) * (self.pulse_width - step_time)

        # give a bit of a reward if not maxing out
        #reward += (20 * np.sum(self.max_delta - delta))
        # if what is added will saturate output
        #over = -1e9 *  np.sum(np.maximum((self.y + delta) - np.ones(4), np.zeros(4)) )

        #under= -1e9 *  np.sum(np.abs(np.minimum((self.y + delta), np.zeros(4)) ))

        self.setpoint_generator()
        # call after state is called
        state = self.state_fn(self)

        self.last_distance = self.distance.copy()
        self.last_true_error = self.true_error
        self.iteration += 1

        self.last_y = self.y.copy()
        self.last_delta = delta.copy()
        self.last_gyro = self.gyro.copy()

        self.dbg = {
            "ac": action,
            "delta": delta
        }
        return state, reward, done, self.dbg

    def reward(self, delta):
        step_time =  (self.sim_time-self.command_start_time)
        min_ac = 0
        min_y = 0
        # The agent needs to apply negative output, help them go down
        if self.overshoot(amount_over = np.abs(self.omega_target)*0.3).any():
            a = self.action.copy()
            above_half = a[a >= 0.5]
            if len(above_half) > 0:
                min_ac -= np.average(above_half) * (self.pulse_width - step_time)

        if (self.omega_target == np.zeros(3)).all():
            # At rpy=0, this can go to zero because
            # we have the min throttle that should keep it
            # balancedkk
            min_y = -1e6 *  np.max(self.y)# * step_time

        oversaturation_penalty = -1e9 *  np.sum(np.maximum((self.y + delta) - np.ones(4), np.zeros(4)) )# * step_time

        d_y = -1e3 * np.max(np.abs(self.y - self.last_y)) * (step_time > 0.25)
        rewards = [
            min_y,
            d_y,

            min_ac,
            # reduce error
            -np.sum(np.abs(self.true_error)**2),# * step_time,
            # things that should never happen
            # Need this or it wont train
            self.doing_nothing_penalty(),
            oversaturation_penalty,
        ]
        return rewards

    def reset(self):
        self.state_history = []
        self.at_zero_count = 0
        return super().reset()


import os
from pathlib import Path

if os.environ.get("ROOT_DIR"):
    ROOT_PATH = "/root/insurance_bot"
else:
    ROOT_PATH = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), ".."))

data_dir = os.path.join(ROOT_PATH, "data")

""" bert """
bert_data_path = Path.home()/'.pytorch_pretrained_bert'
bert_vocab_path = bert_data_path / 'bert-base-chinese-vocab.txt'
bert_model_path = bert_data_path / 'bert-base-chinese.tar.gz'

tencent_w2v_path = Path.home()/'.word2vec'


#!/usr/bin/python
###########################################
#
# Raspberry Pi RGB Christmas Tree
# by James Saunders
# Based on example code by Andrew Gale (www.pocketmoneytronics.co.uk)
#
# This code uses the rpi_ws281x PWM library by Jeremy Garff located at:
#    https://github.com/jgarff/rpi_ws281x
# NOTE: the library disables analogue audio out on the Pi.
#
# LED arrangement:         2
#                         1 3
#                        0 5 4
#
# WARNING: LEDs can be very bright. Do not set the brightness too high.
# Avoid looking directly at the LEDs.
#
###########################################

from random import randint
from time import sleep
from neopixel import *

# Setup
LED_COUNT      = 6
LED_PIN        = 18
LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA        = 5       # DMA channel to use for generating signal (try 5)
LED_INVERT     = False   # True to invert the signal
LED_BRIGHTNESS = 50      # Set to 0 for darkest and 255 for brightest

tree = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
tree.begin()

####################
# Useful Functions
####################

# Turn all LEDs off
def all_leds_off():
	for pin in range(LED_COUNT):
		set_led_rgb(pin, 0, 0, 0)
	tree.show()
	return

# Turn all LEDs on
def all_leds_on():
	for pin in range(LED_COUNT):
		set_led_rgb(pin, 255, 255, 255)
	tree.show()
	return

# Set a specified LED a colour (by by RGB)
def set_led_rgb(led, red, green, blue):
	colour = (green & 255)<<16 | (red & 255)<<8 | (blue & 255) # Note: GRB not RGB
	tree.setPixelColor(led, colour)
	tree.show()
	return

# Set a specified LED a colour (by colour string)
def set_led_colour(led, colour):
	if   colour=="black":   set_led_rgb(led, 0, 0, 0)
	elif colour=="white":   set_led_rgb(led, 255, 255, 255)
	elif colour=="red":     set_led_rgb(led, 255, 0, 0)
	elif colour=="green":   set_led_rgb(led, 0, 255, 0)
	elif colour=="blue":    set_led_rgb(led, 0, 0, 255)
	elif colour=="yellow":  set_led_rgb(led, 255, 255, 0)
	elif colour=="cyan":    set_led_rgb(led, 0, 255, 255)
	elif colour=="magenta": set_led_rgb(led, 255, 0, 255)
	else:
		colour_error = "Unknown colour: " + colour
		print(colour_error)
	return

# Set all LEDs to the same colour (by RGB)
def set_all_rgb(red, green, blue):
	for pin in range(LED_COUNT):
		set_led_rgb(pin, red, green, blue)
	return

# Set all LEDs to the same colour (by colour string)
def set_all_colour(colour):
	for pin in range(LED_COUNT):
		set_led_colour(pin, colour)
	return

####################
# Main
####################
colours = ['red', 'blue', 'magenta', 'cyan', 'yellow', 'green']

while True:

	## EXAMPLE 1: Flash some colours (all LEDs the same colour)
	all_leds_off()
	for colour in colours:
		set_all_colour(colour)
		sleep(0.5)
	all_leds_off()

	## EXAMPLE 2: Cycle through the colours in turn
	all_leds_off()
	for colour in colours:
		for led in range(LED_COUNT):
		    set_led_colour(led, colour)
		    sleep(0.3)
	all_leds_off()

	## EXAMPLE 3: Sweep green/red up from the bottom
	all_leds_off()
	set_all_colour("green")
	sleep(0.4)
	for i in range(3):
		# sweep-up in RED
		set_led_colour(0, "red")
		set_led_colour(5, "red")
		set_led_colour(4, "red")
		sleep(0.4)
		set_led_colour(1, "red")
		set_led_colour(3, "red")
		sleep(0.4)
		set_led_colour(2, "red")
		sleep(0.4)
		# sweep-up in GREEN
		set_led_colour(0, "green")
		set_led_colour(5, "green")
		set_led_colour(4, "green")
		sleep(0.4)
		set_led_colour(1, "green")
		set_led_colour(3, "green")
		sleep(0.4)
		set_led_colour(2, "green")
		sleep(0.4)
	all_leds_off()

	## EXAMPLE 4: Some pulsing of the colour
	all_leds_off()
	for red in range(255):
		set_all_rgb(red, 0, 0)   # Ramp-up the RED
		sleep(0.005)
	for green in range(255):
		set_all_rgb(0, green, 0) # Ramp-up the GREEN
		sleep(0.005)
	for blue in range(255):
		set_all_rgb(0, 0, blue)  # Ramp-up the BLUE
		sleep(0.005)
	all_leds_off()

	## EXAMPLE 5: Some randomness
	all_leds_off()
	# Start off in a random state
	for led in range(LED_COUNT):
		red   = randint(0, 255)
		green = randint(0, 255)
		blue  = randint(0, 255)
		set_led_rgb(led, red, green, blue)
	# Now randomly choose an LED and set it to a random colour
	for i in range(50):
		led   = randint(1, 6)
		red   = randint(0, 255)
		green = randint(0, 255)
		blue  = randint(0, 255)
		set_led_rgb(led, red, green, blue)
		sleep(0.3)
	all_leds_off()


################################################################
# Name: Keaton Love
# CWID: 102-57-333
# Assignment: #3
# Description: This program implements the game of Othello as
# well as Mini-Max algorithim with aplha-beta pruning.
###############################################################
import math
import numpy as np
import copy
import time
import Othello

#Settings
ABPruning = True
DEBUG = False
count = 0

#Controls the users moves
def userMove(b):
    global DEBUG
    global ABPruning
    # Inital user input
    move = input("(" + b.turn + ") " + "Enter the row and column of where you would like to set your piece: ")
    if move == "exit":
        exit()
        # Access settings to turn on debug and ABpruning
    if move == "settings":
        while (move != "back"):
            print("\nSETTINGS:")
            print("\n\tDEBUG:", DEBUG)
            print("\tAlpha Beta pruning:", ABPruning)
            move = input("\nWhat would you like to do? \n\tType 'back' to return to game \n\tDEBUG to switch debug (on/off) \n\tABPruning to switch pruning (on/off)\n")
            if move == "DEBUG":
                if DEBUG:
                    print("Switching DEBUG to OFF")
                    DEBUG = False
                else:
                    print("Switching DEBUG to ON")
                    DEBUG = True
            if move == "ABPruning":
                if ABPruning:
                    print("Switching ABPruning to OFF")
                    ABPruning = False
                else:
                    print("Switching ABPruning to ON")
                    ABPruning = True
            time.sleep(2)
    # Place user piece
    else:
        b.placePiece(move)
        return True

# Contols the AI (minimax)
def controllerBot():
    b = Othello.Othello()
    depthSearch = int(input("What would you like the search depth to be? "))
    userColor = input("What color would you like to play as? ")
    print()

    # Run game until board is full
    while (b.isNotFull()):
        b.printBoard()

        # User turn
        if userColor == b.turn:
            userMove(b)

        # AI turn
        else:
            print("Preforming Minimax to find best move\n")
            time.sleep(2)
            moves = []
            global count
            count = 0

            # Iterate through all possible moves, first max
            for idx, i in enumerate(b.allValidMoves()):
                boardCopy = copy.deepcopy(b)
                boardCopy.placePiece(i)
                moves.append(minimax(i, depthSearch, boardCopy, b.turn, -math.inf, math.inf))

            # Find best move
            bestMove = np.max(moves)
            for idx, i in enumerate((moves)):
                if i == bestMove:
                    print("\nBest move is ", b.allValidMoves()[idx])
                    print("Total States searched:", count)
                    b.placePiece(b.allValidMoves()[idx])
                    break

    # End game processing
    b.printBoard()
    if b.countPieces()[0] > b.countPieces()[1]:
        print("White Wins!")
    elif b.countPieces()[0] < b.countPieces()[1]:
        print("Black Wins!")
    else:
        print("Tie Nobody Wins!")
    print("Game Over")

# minimax function
def minimax(position, depth, boardCopy, botColor, alpha, beta):
    global count
    count += 1

    # if no more depth or the board is full return heuristic value
    if (depth == 0 or not boardCopy.isNotFull()):
        return(heuristic(boardCopy, position))

    # Max
    if (boardCopy.turn != botColor):
        maxEval = -math.inf
        for idx, i in enumerate(boardCopy.allValidMoves()):
            bCopy = copy.deepcopy(boardCopy)
            bCopy.placePiece(position)
            eval = minimax(i, depth-1, bCopy, botColor, alpha, beta)
            maxEval = max(maxEval, eval)
            if ABPruning:
                alpha = max(alpha, eval)
                if beta <= alpha:
                    break
        return maxEval

    # Min
    else:
        minEval = math.inf
        for idx, i in enumerate(boardCopy.allValidMoves()):
            bCopy = copy.deepcopy(boardCopy)
            bCopy.placePiece(position)
            eval = minimax(i, depth-1, bCopy, botColor, alpha, beta)
            minEval = min(minEval, eval)
            if ABPruning:
                beta = min(beta, eval)
                if beta <= alpha:
                    break
        return minEval

# Heuristic function
def heuristic(board, position):
    # Total heuristic value
    weight = 0

    # Total piece heurisitc
    if board.turn == "White":
        weight += board.countPieces()[1] - board.countPieces()[0]
    else:
        weight += board.countPieces()[0] - board.countPieces()[1]

    # Edge position heuristic
    for i in range(7):
        if board.board[i][0] == board.turn[0] or board.board[0][i] == board.turn[0] or board.board[6][i] == board.turn[0] or board.board[i][6] == board.turn[0]:
            weight += 30
        elif board.board[i][0] == board.opposite()[0] or board.board[0][i] == board.opposite()[0] or board.board[6][i] == board.opposite()[0] or board.board[i][6] == board.opposite()[0]:
            weight -= 20

    # Corner position heuristic
    if board.board[0][0] == board.turn[0] or board.board[0][6] == board.turn[0] or board.board[6][0] == board.turn[0] or board.board[6][6] == board.turn[0]:
        weight += 200
    elif board.board[0][0] == board.opposite()[0] or board.board[0][6] == board.opposite()[0] or board.board[6][0] == board.opposite()[0] or board.board[6][6] == board.opposite()[0]:
        weight -= 50
    if DEBUG:
        print("Considering", position, "with weight", weight)
    return weight

def controller():
    b = Othello.Othello()
    while (b.isNotFull()):
        b.printBoard()
        userMove(b)

def main():
    print("\n\nWelcome to an Intelligent Othello Player")
    time.sleep(1)
    bot = input("Would you like to play against a bot? (y/n): ")
    while bot != "y" and bot != "n":
        print("Input not recognized.\n")
        bot = input("Would you like to play against a bot? (y/n): ")
    if bot == "y":
        controllerBot()
    else:
        controller()

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import sys
import http.server
import traceback
from http.server import SimpleHTTPRequestHandler
import json

import time

class MyHandler(SimpleHTTPRequestHandler):
    """
    Mock shoutbox HTTP server to test
    shoutbox API requests.
    """
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()

    def do_GET(self):
        """
        Respond to a GET with a JSON array containing one object
        that contains the following:

        test user: test message
        """

        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()

        timestamp = str(round(time.time()))
        body = json.dumps([{
            "user": "test user",
            "text": "test message",
            "timestamp": timestamp,
            "id": timestamp,
            "ip": "1.2.3.4"
        }])
        self.wfile.write(body.encode())

    def do_POST(self):
        """
        Respond to a POST by printing the message contents to console
        """
        content_len = int(self.headers.get('Content-Length'))
        post_data = self.rfile.read(content_len)

        try:
            message = json.loads(post_data.decode('utf-8'))
            print("{}: {}".format(message["user"], message["text"]))
            self.send_response(200)

        except:
            traceback.print_exc()
            self.send_response(400)

        self.end_headers()

        return

HandlerClass = MyHandler
ServerClass = http.server.HTTPServer
Protocol = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()


# Solve the N-Queens problem by reducing it to an optimization problem and solving the same using local search algorithm.

from search import *
from utils import *
import random

# Define class for n-Queens problem
class nQueens(Problem):
    # Initialize the board with dimensions N x N
    def __init__(self, N):
        super().__init__(tuple(range(N)))
        # The superclass initialization takes the initial state as input,
        # which is always a tuple of integers from 0 to N-1
        self.N = N

    # Define possible actions based on current state of the board
    def actions(self, state):
        # print(state) # Print the current state for debugging purposes
        actions = [] # Initialize an empty list of actions
        for col in range(self.N): # Loop through each column
            for row in range(self.N): # Loop through each row
                # If the queen in this column is not already in this row,
                # add an action to move it to this row
                if row != state[col]:
                    actions.append((col, row))
        return actions

    # Define the result of taking a given action
    def result(self, state, action):
        col, row = action # Unpack the action - it is a tuple of the form (column, row)
        new_state = list(state) # Convert the current state to a list so we can modify it
        new_state[col] = row # Move the queen in the specified column to the specified row
        return tuple(new_state) # Convert the modified state back to a tuple for consistency with the superclass initialization

    # Define the objective function for the problem
    def value(self, state):
        conflicts = 0 # Initialize a counter variable for the number of conflicts between queens
        for col1 in range(self.N - 1): # Loop through each pair of columns, skipping the last one (no pairs beyond that to compare to)
            for col2 in range(col1 + 1, self.N): # Loop through each pair of columns after the current one (don't repeat comparisons between pairs)
                # Get the rows of the two queens in the current pair of columns
                row1, row2 = state[col1], state[col2]
                # If the two queens are horizontally or diagonally adjacent, there is a conflict - add 1 to the counter
                if row1 == row2 or abs(row1 - row2) == (col2 - col1):
                    conflicts += 1
        # We want to minimize this value, so the less conflicts the better
        # Therefore, we return the negative number of conflicts as the value of this state
        return -conflicts # Return the negative number of conflicts as the value of this state

# Generate a random board of size N x N
def random_board(N): # Note: Initially, there is only one queen in each column
    board = [] # Initialize an empty list to store the board
    for col in range(N): # Loop through each column
        row = random.randint(0, N - 1) # Generate a random row number for the queen in this column
        board.append(row) # Add the row number to the board
    return tuple(board) # Convert the board to a tuple for consistency with the superclass initialization

# Print the board in a readable format
def print_board(board):
    for row in range(len(board)): # Loop through each row
        line = "" # Initialize an empty string to store the current line
        for col in range(len(board)): # Loop through each column
            if board[col] == row: # If the queen in this column is in this row
                line += "Q " # Add a Q to the line
            else: # Otherwise
                line += ". " # Add a . to the line
        print(line) # Print the line
    print() # Print a blank line to separate the boards

# Main method
if __name__ == '__main__':
    N = int(input("Enter the value of N: ")) # Get the value of N from the user
    problem = nQueens(N) # Initialize the problem
    initial_board = random_board(N) # Generate a random initial board
    print("Initial Board:")
    print_board(initial_board) # Print the initial board
    initial_node = Node(initial_board) # Initialize the initial node
    solution_node = hill_climbing(problem) # Solve the problem using hill-climbing
    if problem.value(solution_node.state) == 0: # If the value of the solution node is 0, we have found a solution
        print("\nSolution found:")
        print_board(solution_node.state) # Print the solution board
        print("\nNumber of moves:", solution_node.path_cost) # Print the number of moves taken to reach the solution
    else: # Otherwise, we have found a local maximum
        print("\nLocal maxima found:")
        print_board(solution_node.state) # Print the local maximum board
        print("\nValue of objective function:", problem.value(solution_node.state)) # Print the value of the objective function at the local maximum
        print("\nNumber of moves:", solution_node.path_cost) # Print the number of moves taken to reach the solution


def binarySearch(arr, l, r, x):
    while l <= r:
        mid = l + (r - l) // 2
        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            l = mid + 1
        else:
            r = mid - 1
    return -1

a = []
n = int(input("Enter the length of the list : "))
for k in range(0 , n):
    l = int(input())
    a.append(l)
print("The array is",a)

x = int(input("Enter the element to be searched : "))

result = binarySearch(a, 0, len(a)-1, x)
if result != -1:
    print("Element is present at index", result)
else:
    print("Element is not present in array")


from train import *
import ssim

def main():
    args = parse_arg()
    if not os.path.exists(args.save_dir):
        os.makedirs(args.save_dir)
    writer = SummaryWriter(os.path.join(args.save_dir, 'tb'))

    if args.use_cuda:
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')

    model = net.InPainting(args.use_cuda).to(device)
    # Load model checkpoint
    assert args.resume != ''
    ckpt = torch.load(args.resume)
    try:
        model.load_state_dict(ckpt['ckpt'])
    except RuntimeError:
        print(traceback.format_exc())
        model.load_state_dict(ckpt['ckpt'], strict=False)
    model.eval()
    # Eval metric
    loss = torch.nn.L1Loss()

    data = dataset.LargeScaleWatermarkDataset(folder_origin=os.path.join(args.path, args.path_origin),
                                                folder_watermarked=os.path.join(args.path, args.path_wm),
                                                anno_file=os.path.join(args.path, args.path_anno))
    eval_loader = torch.utils.data.DataLoader(dataset=data,
                                           batch_size=args.batchsize,
                                           shuffle=False,
                                           num_workers=2)

    avg_loss = 0
    avg_ssim = 0
    ssim_window = ssim.create_window(11, 3).to(device)
    step = 0
    for i, (img_raw, img_wm, mask_wm) in enumerate(eval_loader):
        img_raw, img_wm = img_raw.to(device), img_wm.to(device)
        with torch.no_grad():
            mask, recon = model(img_wm)
            loss_recon = loss(recon, img_raw)
            avg_loss += loss_recon.item()
            avg_ssim += ssim._ssim(img_raw, recon, ssim_window, 11, 3, True)

        if i % 5 == 0:
            step += 1
            writer.add_images('images', [torch.cat(3*[mask[0].float().to(device)]),
                                         torch.cat(3*[mask_wm[0].float().to(device).unsqueeze(0)]),
                                         util.denormalize(img_wm[0]),
                                         util.denormalize(recon[0]).clamp(0, 1)], global_step=step, dataformats='CHW')

    print('avg loss:', avg_loss / i)
    print('avg ssim:', avg_ssim / i)

if __name__ == '__main__':
    main()


from setuptools import setup, find_packages

version = '1.1.4.dev0'

setup(name='policy.cpasforest',
      version=version,
      description="'policy of CPAS Forest'",
      long_description=open("README.rst").read() + "\n" +
                       open("CHANGES.txt").read(),
      # Get more strings from
      # http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=[
        "Framework :: Plone",
        "Programming Language :: Python",
        ],
      keywords='',
      author='',
      author_email='',
      url='http://svn.plone.org/svn/collective/',
      license='GPL',
      packages=find_packages(exclude=['ez_setup']),
      namespace_packages=['policy'],
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          'setuptools',
          # -*- Extra requirements: -*-
          'collective.ckeditor',
          'collective.easyslider',
          'Solgema.fullcalendar',
          'collective.collage.maps',
          'collective.collage.easyslider',
          'collective.gallery',
          'quintagroup.analytics',
          'collective.recaptcha',
          'qi.portlet.TagClouds',
	  'Products.PloneFormGen',
          'collective.anysurfer',
          'collective.portlet.videoanysurfer',
          'collective.videoanysurfer',
          'collective.checktranslated',
          'plonetheme.cpasforest'
      ],
      entry_points="""
      # -*- Entry points: -*-

      [z3c.autoinclude.plugin]
      target = plone
      """,
      )


import requests

from discord import app_commands, Intents, Client, Interaction

print("\n".join([
    "Hey, thanks for using simpledsccommands v1 by dvl.",
    "Please enter your bot's token below to continue.",
    "",
]))

while True:
    token = input("> ")

    r = requests.get("https://discord.com/api/v10/users/@me", headers={
        "Authorization": f"Bot {token}"
    })

    data = r.json()
    if data.get("id", None):
        break

    print("\nSeems like you entered an invalid token. Try again.")

class SomeClient(Client):
    def __init__(self, *, intents: Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self) -> None:
        await self.tree.sync(guild=None)

client = SomeClient(intents=Intents.none())

@client.event
async def on_ready():
    print("\n".join([
        f"Logged in as {client.user} (ID: {client.user.id})",
        "",
        f"Invite your bot via invite link",
        f"https://discord.com/api/oauth2/authorize?client_id=[bot id]&scope=applications.commands%20bot"
    ]))

async def response(interaction: Interaction):
    print(f"> {interaction.user} used the command hello.")
    await interaction.response.send_message("\n".join([
        f"Hello {interaction.user} this is command1"
    ]))

async def response2(interaction: Interaction):
    print(f"> {interaction.user} used the command hellotwo.")
    await interaction.response.send_message("\n".join([
        f"Hello {interaction.user} This bot's source slash command atleast was originially made by dvl#0001. This is open source so feel free to use this too! www.github.com/dvlq/simpledsccommands . **Credits not a must but appreciated**"
    ]))

@client.tree.command()
async def hello(interaction: Interaction):
    """ Says hello or something """
    await response(interaction)

@client.tree.command()
async def credits(interaction: Interaction):
    """ Credits to original dev """
    await response2(interaction)

client.run(token)