import json
import requests

def district_name():
    pin = input("Enter your Postal Pin-code\n")

    try:
        pin_api = f"https://api.postalpincode.in/pincode/{pin}"

        res = requests.get(pin_api)
        data = json.loads(res.content)
        no_of_district = data[0]["Message"].split(":")
        var = int(no_of_district[1])
        print(var, "records found")

        for i in range(var):
            overall = f"{i + 1}" + ". " + data[0]["PostOffice"][i]['Name'] + ", " + data[0]["PostOffice"][i][
                'District'] + ", " + data[0]["PostOffice"][i]['State']
            print(overall)

    except Exception as e:
        print("No record found. Please enter a valid Pin-code")

def pincode():
    dis_name = str(input("Enter Branch Name or Postal Office Name\n"))

    try:
        dis_api = f"https://api.postalpincode.in/postoffice/{dis_name}"

        res = requests.get(dis_api)
        data = json.loads(res.content)
        no_of_district = data[0]["Message"].split(":")
        var = int(no_of_district[1])
        print(var, "records found")

        for i in range(var):
            overall = f"{i + 1}" + ". " + data[0]["PostOffice"][i]['Name'] + ", " + data[0]["PostOffice"][i][
                'District'] + ", " + data[0]["PostOffice"][i]['State'] + ", " + data[0]["PostOffice"][i]['Pincode']
            print(overall)

    except Exception as e:
        print("No record found. Please enter the correct name OR check the spelling once")

if __name__ == '__main__':

    while(True):
        choice = str(input("\t\t\tWhat you want to search\n1. Pin-code via Branch name\n2. Branch name via Pin-code\n3. Quit\n"))

        if choice == "1":
            pincode()

        elif choice == "2":
            district_name()

        elif choice == "3":
            print("You took a exit")
            exit()

        else:
            print("Invalid user choice. Please select again")


stratigraphy = {
    'num_layers': 0,
    'layer_names': [],
    'layer_thickness': []
}

tilt = {
    "name": "Event Name",
    "pos": (0, 0, 0),
    "rotation": 5,
    "plunge_direction": 90,
    "plunge": 5
}

fault_planar = {
    "name": "Event Name",
    "pos": (0, 0, 0),
    "dip_dir": 90,
    "dip": 60,
    "slip": 100
}

fault_curved = {
    "name": "Event Name",
    'geometry': 'Curved',
    "pos": (0, 0, 0),
    "dip_dir": 90,
    "dip": 60,
    "slip": 100,
    "amplitude": 1000,
    "radius": 2000,
    'xaxis': 5000.,
    'yaxis': 5000.0,
    'zaxis' : 39999.0
}

fold = {
    "name": "Event Name",
    "pos": (0, 0, 0),
    "wavelength": 1000,
    "amplitude": 50,
    "plunge_direction": 90,
    "plunge": 0
}

unconformity_empty = {
    "name": "Event Name",
    "pos": (0, 0, 0),
    "dip_direction": 90,
    "dip": 5,
}

unconformity_layers = {
    "name": "Event Name",
    "pos": (0, 0, 0),
    "dip_direction": 90,
    "dip": 5,
    "num_layers": 0,
    "layer_names": [],
    "layer_thickness": []
}


from unittest import mock

from game import Game
from parser import MemoryGameRepository
from parser.handlers import (InitGameEventHandler, ShutdownGameEventHandler,
                             KillEventHandler)

class TestEventHandler:

    def test_should_get_players_with_world_killer(self):
        game = Game('abc')
        handler = KillEventHandler(None)
        event = '1:26 Kill: 1022 4 22: <world> killed Zeh by MOD_TRIGGER_HURT'
        killer, killed = handler.get_players(game, event)
        assert killer.is_world() is True
        assert not killed.is_world()
        assert str(killed) == 'Zeh'

    def test_should_get_players(self):
        game = Game('abc')
        handler = KillEventHandler(None)
        event = '1:26 Kill: 1022 4 22: Foo killed Bar by MOD_TRIGGER_HURT'
        killer, killed = handler.get_players(game, event)
        assert not killer.is_world()
        assert str(killer) == 'Foo'
        assert str(killed) == 'Bar'

    @mock.patch.object(MemoryGameRepository, 'store', {})
    def test_should_handle_init_game_event(self):
        memory_repo = MemoryGameRepository()
        handler = InitGameEventHandler(memory_repo)
        handler.handle('  0:00 InitGame: \\sv_floodProtect\\1\\sv_maxPing\0')
        assert len(memory_repo.store) == 1

    @mock.patch.object(MemoryGameRepository, 'store', {})
    def test_should_handle_shutdown_game_event(self):
        memory_repo = MemoryGameRepository()
        memory_repo.add(Game('abc'))
        handler = ShutdownGameEventHandler(memory_repo)
        handler.handle('20:37 ShutdownGame:')
        game = memory_repo.get_active_game()
        assert game.is_shutted_down() is True

    @mock.patch.object(MemoryGameRepository, 'store', {})
    def test_should_handle_kill_game_event(self):
        memory_repo = MemoryGameRepository()
        memory_repo.add(Game('abc'))
        handler = KillEventHandler(memory_repo)
        event = '1:23 Kill: 5 7 7: Oootsimo killed Assasinu Credi by MOD_ROCKET_SPLASH'
        handler.handle(event)

        active_game = memory_repo.get_active_game()
        assert active_game.total_kills == 1
        assert len(active_game.players) == 2
        assert active_game.has_player('Oootsimo') is True
        assert active_game.has_player('Assasinu Credi') is True
        assert active_game.get_player('Oootsimo').kills == 1

        event = '1:23 Kill: 5 7 7: Oootsimo killed Fulera by MOD_ROCKET_SPLASH'
        handler.handle(event)

        assert active_game.total_kills == 2
        assert len(active_game.players) == 3
        assert active_game.has_player('Fulera') is True
        assert active_game.get_player('Oootsimo').kills == 2

    @mock.patch.object(MemoryGameRepository, 'store', {})
    def test_should_handle_kill_game_event_by_world_player(self):
        memory_repo = MemoryGameRepository()
        memory_repo.add(Game('abc'))
        handler = KillEventHandler(memory_repo)
        event = '1:23 Kill: 5 7 7: Oootsimo killed Assasinu Credi by MOD_ROCKET_SPLASH'
        handler.handle(event)

        event = '1:23 Kill: 5 7 7: <world> killed Oootsimo by MOD_TRIGGER_HURT'
        handler.handle(event)

        active_game = memory_repo.get_active_game()
        assert active_game.total_kills == 2
        assert len(active_game.players) == 2
        assert active_game.has_player('<world>') is False
        assert active_game.get_player('Oootsimo').kills == 0


import contextlib
import os
import pathlib
import re
import requests
import shutil
import signal
import tarfile
import tempfile
import threading
import traceback

#
# Cloudsmith API key for listing and downloading releases
#
api_key = os.getenv("CLOUDSMITH_API_KEY", None)
assert api_key, "required api key not provided: set CLOUDSMITH_API_KEY"

#
# Directory used to store extracted Redpanda releases
#
download_dir = pathlib.Path(os.getenv("DOWNLOAD_DIR", "/mnt/redpanda"))
assert download_dir.is_dir(), f"download directory {download_dir} does not exist"

#
# How often (in minutes) to query for new releases
refresh_key = "CLOUDSMITH_REFRESH_MINUTES"
refresh_seconds = 60 * int(os.getenv(refresh_key, 30))
assert refresh_seconds > 0, "invalid refresh rate: {os.getenv(refresh_key)}"

#
# Minimum major version that will be considered when syncing
#
min_major_version = int(os.getenv("MIN_MAJOR_VERSION", 22))

@contextlib.contextmanager
def cloudsmith_session():
    """
    Build a cloudsmith api request sessions with configured api key.
    """
    with requests.Session() as sesh:
        sesh.headers.update(
            {
                "Accept": "*/*",
                "X-Api-Key": api_key,
            }
        )
        yield sesh

def list_all_packages():
    """
    Fetch all known Redpanda packages.
    """

    def package_iter(sesh):
        url = "https://api.cloudsmith.io/v1/packages/redpanda/redpanda/?q=name:redpanda-amd64+format:raw"
        while url is not None:
            resp = sesh.get(url)
            resp.raise_for_status()
            yield from resp.json()
            link = resp.links.get("next", None)
            url = link.get("url", None) if link else None

    with cloudsmith_session() as sesh:
        return [p for p in package_iter(sesh)]

def sync_packages():
    """
    List all Redpanda packages eligible to sync.
    """
    for pkg in list_all_packages():
        name = pkg["name"]
        assert (
            name == "redpanda-amd64"
        ), f"Query returned package with unsupported name: {name}"
        assert (
            pkg["format"] == "raw"
        ), f"Query returned package with unsupported format: {pkg['format']}"

        version = pkg["version"]
        m = re.match(r"^(?P<major>\d{2})\.\d+\.\d{1,2}$", version)
        if not m:
            print(f"Skipping package {name} with invalid version: {version}")
            continue
        if int(m.group("major")) < min_major_version:
            print(
                f"Skipping package {name} with major version {version} < {min_major_version}"
            )
            continue
        if not pkg["is_downloadable"] or not pkg["is_sync_completed"]:
            print(
                f"Skipping package {name} not ready: d={pkg['is_downloadable']} s={pkg['is_sync_completed']}"
            )
            continue

        yield version, pkg["cdn_url"]

def download_package(version, url):
    """
    Downloads and extracts a Redpanda release into download directory.
    """
    path = download_dir / version
    if path.is_dir():
        print(f"Skipping {version} at {path}: already downloaded")
        return

    print(f"Downloading {version} from {url}")
    f = tempfile.NamedTemporaryFile(delete=False)
    try:
        with cloudsmith_session() as sesh:
            with sesh.get(url, stream=True) as s:
                shutil.copyfileobj(s.raw, f)
    except:
        os.unlink(f.name)
        raise
    finally:
        f.close()

    # create a temporary directory to unpack release into
    try:
        tdir = tempfile.mkdtemp()
    except:
        os.unlink(f.name)
        raise

    print(f"Extracting {version} at {f.name} into {tdir}")
    try:
        with tarfile.open(f.name) as tfile:
            tfile.extractall(path=tdir)
        redpanda = pathlib.Path(tdir) / "libexec" / "redpanda"
        assert (
            redpanda.is_file()
        ), "Redpanda binary not found in extracted release {version} at location {redpanda.as_posix()}"
        print(f"Moving extracted {version} from {tdir} to {path}")
        shutil.move(tdir, path)
    except:
        shutil.rmtree(tdir, ignore_errors=True)
        raise
    finally:
        os.unlink(f.name)

if __name__ == "__main__":
    stop = threading.Event()
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, lambda *_: stop.set())

    while not stop.is_set():
        try:
            for version, url in sync_packages():
                download_package(version, url)
            print(f"Refresh complete. Next refresh in {refresh_seconds} sec")
            stop.wait(refresh_seconds)

        except Exception:
            traceback.print_exc()
            print("Encountered exception. Trying refresh again in 5 minutes")
            stop.wait(300)

    print("Redpanda release synchronizer stopping")


from picamera import PiCamera
from time import sleep

camera = PiCamera()
#camera.resolution = (2592, 1944)
#camera.framerate=15
camera.rotation=180
#camera.start_preview()
#sleep(50)
#camera.capture('/home/pi/Desktop/imageHighRes.jpg')
#camera.stop_preview()
camera.start_preview()
for i in range(100):
    camera.annotate_text = "Brightness: %s" % i + " Contrast: %s" % i
    camera.brightness = i
    sleep(0.1)
camera.stop_preview()


import inspect
import re

def get_pytest_input(func):
    """
    Convert function object to pytest input string.

    Pytest allows the user to pass the name of an individual
    test to run. This function takes a function object and converts
    it into a string that can be passed to pytest to run only that
    specific test function.

    Arguments
    ---------
    func : function
        The test function object for which to generate a string input

    Returns
    -------
    str
        Input string for pytest to run the given test function

    """
    module = inspect.getmodule(func).__name__

    module = "/".join(module.split(".")) + ".py"
    func = "::".join(func.__qualname__.split("."))

    return f"{module}::{func}"

def temp_ouput_file(pytest_input):
    """
    Return the name of the temporary output file for a given test.

    Arguments
    ---------
    pytest_input : str
        The pytest input indicating for which test function to obtain
        the temporary output file name

    Returns
    -------
    str
        The temporary output file name for the given test function

    """
    return pytest_input.replace("/", ".").replace("::", ".")

def contains_failure(message):
    """
    Check if a given pytest contained a failure.

    Arguments
    ---------
    message : str
        The pytest output to check

    Returns
    -------
    bool
        True if the output contains failures; False otherwise

    """
    return "= FAILURES =" in message

def get_traceback(message):
    """
    Extract traceback from pytest output

    Parameters
    ----------
    message : str
        The pytest output

    Returns
    -------
    str
        The traceback found in the given pytest output

    Raises
    ------
    ValueError
        If message does not contain a traceback
    """
    try:
        index = message.index("= FAILURES ")
    except ValueError:
        raise ValueError("Given message does not contain a traceback")

    for _ in range(3):
        index = message.index("\n", index + 1)

    end_index = message.rindex("short test summary info")
    end_index = message.rindex("\n", 0, end_index)

    return message[index:end_index]

def get_summary(message):
    """
    Return summary statement from pytest output

    Parameters
    ----------
    message : message
        The pytest output

    Returns
    -------
    str
        The summary statement
    """
    groups = re.search(
        r"=* short test summary info =*\nFAILED .*?::.*? - (.*)", message
    ).groups()

    return groups[0]

END_OF_TEST = "%<<<<END_OF_TEST>>>>%"
"""
Placeholder at the end of an mpi output file.

Can be used to check if the entire test suite ran through.
"""


#-*- coding:utf-8 -*-
# @Time  :2019/5/28 10:38
import socket
def getfile(conn):
    #接收文件长度
    filesize=int(str(conn.recv(1024),encoding='utf8'))
    conn.sendall(bytes('ok',encoding='utf8'))#避免粘包
    #接收文件名称
    filename=str(conn.recv(1024),encoding='utf8')
    conn.sendall(bytes('ok', encoding='utf8'))  # 避免粘包
    #接收文件
    with open('./%s'%filename,'wb') as f:
        while filesize>0:
            f.write(conn.recv(1024))
            filesize-=1024
    conn.close()

sk=socket.socket()
sk.bind(('127.0.0.1',2019))
sk.listen(5)
conn,clientaddr=sk.accept()
getfile(conn)
sk.close()


import os.path
import glob
import gin
import tensorflow as tf
from input_pipeline.preprocess import augment
import tensorflow_datasets as tfds

def load(file_path=None):
    file_path = '/home/data/tensorflow_datasets/' \
        if not os.path.isdir(file_path) else file_path
    if not os.path.isdir(file_path):
        raise ValueError('No such file path for tfrecords.')
    (ds_train, ds_val, ds_test), ds_info = tfds.load(
        'diabetic_retinopathy_detection/btgraham-300',
        split=['train', 'validation', 'test'],
        shuffle_files=True,
        with_info=True,
        data_dir=file_path)
    ds_train = build_dataset_k(ds_train)
    ds_val = build_dataset_k(ds_val, is_test_set=True)
    ds_test = build_dataset_k(ds_test, is_test_set=True)
    return ds_train, ds_val, ds_test

@gin.configurable
def build_dataset_k(dataset, batch_size, is_test_set=False):
    dataset = dataset.map(lambda x: parse_example(x, is_test_set), tf.data.experimental.AUTOTUNE)
    if not is_test_set:
        dataset = dataset.shuffle(batch_size * 100, reshuffle_each_iteration=True)
    dataset = dataset.batch(batch_size)
    dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
    return dataset

def parse_example(dict, test_set=False):
    dict['image'] = tf.image.resize(tf.cast(dict['image'], tf.float32), (300, 300))
    if not test_set:
        dict['image'] = augment(dict['image'], True)
    dict['image'] = dict['image'] / 255.
    return dict['image'], dict['label']


"""
1338. Reduce Array Size to The Half
https://leetcode.com/problems/reduce-array-size-to-the-half/
"""
from collections import Counter

class Solution:
    def minSetSize(self, arr) -> int:
        length = len(arr)
        counter = Counter(arr)
        vals = [(key, val) for key, val in counter.items()]
        vals.sort(key=lambda x: -x[1])
        result = 0
        removed_count = 0
        for val in vals:
            removed_count += val[1]
            result += 1
            if removed_count >= length//2:
                break
        return result

print(Solution().minSetSize([9,77,63,22,92,9,14,54,8,38,18,19,38,68,58,19]))


import pickle
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
from flask import Flask,render_template,request
import numpy as np
import pandas as pd

with open('./SavedMateria/tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

# Load the Deep Learning Sentiment Model
sentiment_model = load_model('./SavedMateria/Sentiment-BiLSTM.h5')

# Load the Deep Learning Geninuness Model
genuineness_model = load_model('./SavedMateria/Geniuneness Model.h5')

app = Flask(__name__)
app.secret_key = 'YourSecrtekey'

def modelsPredictions(text,attributes):
    sequences = tokenizer.texts_to_sequences([text])
    padded_sequences = pad_sequences(sequences, maxlen=100)  # Assuming you have a max_sequence_length defined

    sentiment_prediction = sentiment_model.predict(padded_sequences)
    # genuineness_prediction = genuineness_model.predict([attributes, padded_sequences])

    # Print the predictions
    print("Sentiment Prediction:", sentiment_prediction)
    # print("Genuineness Prediction:",genuineness_prediction )

# , int(np.around(genuineness_prediction))
    return int(np.around(sentiment_prediction))

def convert_to_float(value):
    try:
        return float(value)
    except ValueError:
        return value  # Return the original value if it cannot be converted to float

@app.route('/',methods=["GET", "POST"])
def index():
    if request.method == 'POST':
        # Access form data submitted by the user
        tweet_text = request.form.get('tweet_text')
        protected = request.form.get('protected')
        retweet = request.form.get('retweet')
        reply_count = request.form.get('reply_count')
        like_count = request.form.get('like_count')
        quote_count = request.form.get('quote_count')
        followers_count = request.form.get('followers_count')
        listed_count = request.form.get('listed_count')
        friends_count = request.form.get('friends_count')
        attrbut = [protected,1,retweet,reply_count,like_count,quote_count,followers_count,listed_count,friends_count]
        # Use the map function to apply the conversion to each element of the list
        attrbut_float = list(map(convert_to_float, attrbut))
        df = pd.DataFrame(attrbut_float, columns=['ColumnName'])
        print(f'Attributes : {attrbut_float}')
        a,b = modelsPredictions(tweet_text,attrbut_float),1

        return render_template('index.html',sent=a,gen=b)

    return render_template('index.html',sent=2,gen=2)


import os
import argparse
import sys

# Filename as argument:
parser = argparse.ArgumentParser()
# Positional Argument:
parser.add_argument('file',
    help='The name of the file providing input'
)
args = parser.parse_args()

with open(args.file, 'rt') as f1:  # Open file for reading of text data.
    # for line in f1:
    #     print(line.strip())
    lines = [line.strip() for line in sorted(f1.readlines())]
    print(lines)
    print(len(lines))
    areaList = [0]*len(lines)
    binList = [1]*len(lines)
    #For the given input, find our bounds/ranges in x,y:
    x_init = int(lines[0].split(',')[0])
    y_init = int(lines[0].split(',')[1])
    x_min = x_init
    x_max = x_init
    y_min = y_init
    y_max = y_init
    for i in range(len(lines)):
        hey = lines[i].split(',')
        x = int(hey[0])
        y = int(hey[1])
        if x < x_min:
            x_min = x
        if x > x_max:
            x_max = x
        if y < y_min:
            y_min = y
        if y > y_max:
            y_max = y
    x_min = max(0,x_min-1)
    x_max+=1
    y_min = max(0,y_min-1)
    y_max+=1
    print(x_min,y_min,x_max,y_max)

    #Loop through each point in our ranges, comparing each input coord to it,
    #taking the Manhattan Distance, looking for the minimum value (and which input
    # it belongs to):
    m=y_min
    n=x_min
    i=0
    man_min = x_max+y_max

    while m < y_max:
        while n < x_max:
            for i in range(len(lines)):
                hey = lines[i].split(',')
                x = int(hey[0])
                y = int(hey[1])
                # calculate Manhattan Distace:
                man = abs(x-n)+abs(y-m)
                if man < man_min:
                    man_min = man
                    myIndex = i
                elif man == man_min:
                # Two inputs are equally closest, so neither can claim...
                    myIndex = None
            if myIndex is not None:
                areaList[myIndex]+=1
            # In order to eliminate infinite areas, we find the border cases:
            if n == x_min or m == y_min or n == x_max or m == y_max:
                binList[myIndex] = 0
            n+=1
        m+=1
    print(areaList)
    print(binList)


# coding=utf-8
from django.urls import reverse
from django.views.generic import (
    CreateView,
    DeleteView)
from django.http import Http404
from braces.views import LoginRequiredMixin
from ..models import (
    CourseAttendee,
    CertifyingOrganisation,
    Course)
from ..forms import CourseAttendeeForm

class CourseAttendeeMixin(object):
    """Mixin class to provide standard settings for Attendee."""

    model = CourseAttendee
    form_class = CourseAttendeeForm

class CourseAttendeeCreateView(
        LoginRequiredMixin,
        CourseAttendeeMixin, CreateView):
    """Create view for Course Attendee."""

    context_object_name = 'courseattendee'
    template_name = 'course_attendee/create.html'

    def get_success_url(self):
        """Define the redirect URL.

        After successful creation of the object, the User will be redirected
        to the Course detail page.

       :returns: URL
       :rtype: HttpResponse
       """

        return reverse('course-detail', kwargs={
            'project_slug': self.project_slug,
            'organisation_slug': self.organisation_slug,
            'slug': self.slug
        })

    def get_context_data(self, **kwargs):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """

        context = super(
            CourseAttendeeCreateView, self).get_context_data(**kwargs)
        context['certifyingorganisation'] = \
            CertifyingOrganisation.objects.get(slug=self.organisation_slug)
        context['course'] = Course.objects.get(slug=self.slug)
        return context

    def get_form_kwargs(self):
        """Get keyword arguments from form.

        :returns keyword argument from the form
        :rtype: dict
        """

        kwargs = super(CourseAttendeeCreateView, self).get_form_kwargs()
        self.project_slug = self.kwargs.get('project_slug', None)
        self.organisation_slug = self.kwargs.get('organisation_slug', None)
        self.slug = self.kwargs.get('slug', None)
        self.course = Course.objects.get(slug=self.slug)
        self.certifying_organisation = \
            CertifyingOrganisation.objects.get(slug=self.organisation_slug)
        kwargs.update({
            'user': self.request.user,
            'course': self.course,
            'certifying_organisation': self.certifying_organisation,
        })
        return kwargs

class CourseAttendeeDeleteView(
        LoginRequiredMixin,
        CourseAttendeeMixin,
        DeleteView):
    """Delete view for Course Attendee."""

    context_object_name = 'courseattendee'
    template_name = 'course_attendee/delete.html'

    def get(self, request, *args, **kwargs):
        """Get the course_slug and course attendee pk from the URL
        and define the course.

        :param request: HTTP request object
        :type request: HttpRequest

        :param args: Positional arguments
        :type args: tuple

        :param kwargs: Keyword arguments
        :type kwargs: dict

        :returns: Unaltered request object
        :rtype: HttpResponse
        """

        self.course_slug = self.kwargs.get('course_slug', None)
        self.pk = self.kwargs.get('pk', None)
        self.course = Course.objects.get(slug=self.course_slug)
        return super(
            CourseAttendeeDeleteView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        """Post the project_slug, organisation_slug, course_slug from the URL.

        :param request: HTTP request object
        :type request: HttpRequest

        :param args: Positional arguments
        :type args: tuple

        :param kwargs: Keyword arguments
        :type kwargs: dict

        :returns: Unaltered request object
        :rtype: HttpResponse
        """

        self.project_slug = self.kwargs.get('project_slug', None)
        self.organisation_slug = self.kwargs.get('organisation_slug', None)
        self.course_slug = self.kwargs.get('course_slug', None)
        self.course = Course.objects.get(slug=self.course_slug)
        return super(
            CourseAttendeeDeleteView, self).post(request, *args, **kwargs)

    def get_success_url(self):
        """Define the redirect URL.

        After successful deletion  of the object, the User will be redirected
        to the Course detail page.

        :returns: URL
        :rtype: HttpResponse
        """

        return reverse('course-detail', kwargs={
            'project_slug': self.project_slug,
            'organisation_slug': self.organisation_slug,
            'slug': self.course_slug
        })

    def get_queryset(self):
        """Get the queryset for this view.

        :returns: Course Attendee queryset filtered by Course
        :rtype: QuerySet
        :raises: Http404
        """

        if not self.request.user.is_authenticated:
            raise Http404
        qs = CourseAttendee.objects.filter(course=self.course)
        return qs


from aiogram import Router, F, Bot
from aiogram.types import Message, ErrorEvent

router = Router()

@router.error()
async def start(event: ErrorEvent, bot: Bot):
    await event.update.message.answer(
        "Congrats, you broke the bot. Now go ahead and submit an issue.\n"
        "https://github.com/aiexz/itosbot/issues/new"
    )
    raise event.exception


s=int(input("Enter a string"))
z=s
t=len(str(s))
last=0
sum=0
if(s>1):
	for i in range(2,s):
		if(s%i==0):
			print("it is not a prime number")
			break
	else:
		print("it is a prime number")
else:
	print("0 is not a prime")
while(z>0):
	last=z%10
	sum+=(last**t)
	z=z//10
if(s==sum):
	print("it is an armstrong  number")
else:
	print("it is not an armstrong number")


import os
import tempfile
import subprocess
import yaml
from modules.flistworker import AutobuilderFlistThread

class AutobuilderFlistMonitor:
    """
    This class takes care of the flist-webhooks and monitor any changes

    Workflow:
     # Initialization
     - clone configuration repository
     - parse contents (directories are repositories, files are branch settings)

     # Set webhook endpoints itself

     # When a push is receive on the configuration repository
     - re-clone this repository and re-parse the contents
     - update local configuration

     # When a push is receive to a flist-hook
     - start a container with git support
     - check if the push event is related to a monitored repository and branch
     - if we support this push, starting a flist-build-thread
    """
    def __init__(self, components):
        self.root = components
        self.configtarget = self.root.config['configuration-repository']

        self.repositories = {}
        self.compiled = True

        self.watch = {
            "monitor": self.root.config['public-host'] + self.root.config['monitor-update-endpoint'],
            "repository": self.root.config['public-host'] + self.root.config['repository-push-endpoint'],
        }

        self.default_baseimage = "ubuntu:16.04"
        self.default_archives = "/target"

        print("[+] update endpoint: %s" % self.watch['monitor'])
        print("[+] push endpoint: %s" % self.watch['repository'])

    def current_revision(self, path):
        previous = os.getcwd()
        os.chdir(path)

        commitid = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
        os.chdir(previous)

        return commitid.stdout.decode('utf-8').strip()

    def initialize(self):
        """
        Initialize repositories to watch and ensure webhooks
        """
        repo = tempfile.TemporaryDirectory(prefix="autobuild-git-")

        # initializing error flag
        self.compiled = True

        # cloning monitoring repository to a temporary directory
        args = ['git', 'clone', 'https://github.com/' + self.configtarget, repo.name]
        subprocess.run(args)

        task = self.root.buildio.create()
        task.set_name('Configuration reloader')
        task.set_commit(self.current_revision(repo.name))
        task.set_repository(self.configtarget)
        task.set_docker('system')
        task.notice('Loading configuration')

        # parsing the repository contents
        for root, dirs, files in os.walk(repo.name):
            # skipping .git directory, we assume all other directories
            # are repositories to watch
            if ".git" in dirs:
                dirs.remove(".git")

            rootdir = root[len(repo.name) + 1:].split('/')
            if len(rootdir) != 2:
                continue

            pathname = '/'.join(rootdir)

            task.log('Parsing repository: %s' % pathname)
            self.repositories[pathname] = self.parse(root, files, task)

        if not self.compiled:
            task.notice("Configuration loaded, with some errors")
            task.error("Some configuration files could not be parsed correctly")
            task.destroy()
            return False

        task.notice("Configuration loaded without any errors")
        task.success()
        task.destroy()

    def _yaml_validate(self, contents, task):
        if not contents.get('buildscripts'):
            print("[-] WARNING: buildscripts not defined, skipping")
            task.log("Error: buildscripts not defined, ignoring this branch")
            return False

        for buildscript in contents['buildscripts']:
            if not contents.get(buildscript):
                print("[-] WARNING: buildscript '%s' not defined" % buildscript)
                task.log("ERROR: buildscript '%s' not defined, ignoring this branch" % buildscript)
                return False

            if not contents[buildscript].get('artifact'):
                print("[-] WARNING: buildscripts '%s' have no artifact")
                task.log("Error: buildscript '%s' have no artifact, ignoring this branch" % buildscript)
                return False

        return True

    def parse(self, root, files, task):
        branches = {}

        for file in files:
            filepath = os.path.join(root, file)

            # removing .yaml extension
            branchname = file[:-5]

            # loading branch config
            contents = yaml.load(open(filepath, 'r'))

            if not self._yaml_validate(contents, task):
                self.compiled = False
                continue

            task.log("Tracking branch: %s" % branchname)
            branches[branchname] = contents

        return branches

    def dump(self):
        """
        Dumps the content of the parsed and loaded repositories
        """
        print("[+] watching %d repositories:" % len(self.repositories))
        print("[+]")

        for repository, contents in self.repositories.items():
            print("[+]   %s (%d branches):" % (repository, len(contents)))

            for branch in contents:
                print("[+]     - %s" % branch)

                for buildscript in contents[branch]['buildscripts']:
                    buildinfo = contents[branch][buildscript]
                    print("[+]     +--> %s:" % buildscript)
                    print("[+]          artifact : %s" % buildinfo['artifact'])
                    print("[+]          baseimage: %s" % buildinfo.get('baseimage') or self.default_baseimage)
                    print("[+]          archives : %s" % buildinfo.get('archives') or self.default_archives)
                    print("[+]          extra tag: %s" % buildinfo.get('tag') or '(none)')

            print("[+]")

    def webhooks(self, previously={}):
        """
        Ensure webhooks are all sets to forward push to the monitor
        """
        self.webhook_repository(self.configtarget, self.watch['monitor'])

        for repository in self.repositories:
            if previously.get(repository):
                print("[+] webhook: %s: already configured" % repository)
                continue

            print("[+] repository: %s, setting up webhook" % repository)
            self.webhook_repository(repository, self.watch['repository'])

        return True

    def webhook_repository(self, repository, target):
        """
        Check and update webhook of a repository if not set
        """
        print("[+] webhook: managing: %s" % repository)

        existing = self.root.github.request('/repos/%s/hooks' % repository)
        if not isinstance(existing, list):
            print("[-] webhook: repository not found probably")
            return

        for hook in existing:
            if not hook['config'].get('url'):
                continue

            # checking if webhook is already set
            if hook['config']['url'] == target:
                print("[+] webhook: %s: already up-to-date" % repository)
                return True

        # no webhook matching our url found, adding it
        options = self.root.github.webhook(target)
        print(self.root.github.request('/repos/%s/hooks' % repository, options))

    def push(self, payload):
        """
        Method triggered when a push-event is send to a monitored repository
        Basicly, this method will trigger a build (and do the most useful job)
        """
        if payload["deleted"] and len(payload['commits']) == 0:
            print("[-] this is deleting push, skipping")
            return {'status': 'success'}

        # extracting data from payload
        repository = payload['repository']['full_name']
        if not self.repositories.get(repository):
            print("[-] push: %s: we don't monitor this repository" % repository)
            return {'status': 'error', 'message': 'repository not tracked'}

        ref = payload['ref']
        branch = os.path.basename(ref)

        if not self.repositories[repository].get(branch):
            print("[-] push: %s: we don't monitor this branch: %s" % (repository, branch))
            return {'status': 'error', 'message': 'branch not tracked'}

        print("[+] push: %s: build trigger accepted (branch: %s)" % (repository, branch))

        for buildscript in self.repositories[repository][branch]['buildscripts']:
            task = self.root.buildio.create()
            task.set_from_push(payload)

            recipe = self.repositories[repository][branch][buildscript]

            print("[+] instanciating: %s" % buildscript)
            worker = AutobuilderFlistThread(self.root, task, recipe, buildscript)
            worker.start()

        return {'status': 'success'}

    def update(self, payload):
        """
        Method triggered when a push is sent to the configuration-repository
        This method will do some security check then reload the configuration-repository
        and parse again the contents in order to be sync'd with upstream data
        """
        if payload["deleted"] and len(payload['commits']) == 0:
            print("[-] this is deleting push, skipping")
            return {'status': 'success'}

        # extracting data from payload
        repository = payload['repository']['full_name']
        print(repository)

        if repository != self.configtarget:
            print("[-] wrong repository, received: %s, excepted: %s" % (repository, self.configtarget))
            return {'status': 'error', 'message': 'repository not configured as configuration-repository'}

        print("[+] webhook: reloading configuration")
        previously = self.repositories.copy()

        self.initialize()
        self.dump()
        self.webhooks(previously)

        return {'status': 'success'}


import RPi.GPIO as GPIO
import MySQLdb as mdb
import datetime

con = mdb.connect(PYTHON_CONNECT);
sensorPin = 22;

GPIO.setmode(GPIO.BCM)
GPIO.setup(sensorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

print("Starting sensor...")
try:
        while 1:
#		GPIO.wait_for_edge(sensorPin, GPIO.FALLING)
       # with con:
                #        cur = con.cursor()
                 #       cur.execute(PYTHON_QUERY_INSERT_NOW)
                  #      con.commit()
                   #     print("Sensor triggered!");
        	print(GPIO.input(sensorPin))

except KeyboardInterrupt:
    GPIO.cleanup()

GPIO.cleanup()


from tkinter import *
from quiz_brain import QuizBrain
from data import QuizData

# --- STYLING CONSTANTS --- #
# backgrounds
BG_COLOR = "#375362"
CATEGORY_BG_COLOR = "#799982"
QUESTION_BG_COLOR = 'white'
CORRECT_ANSWER_BG_COLOR = "#AFFFCF"
WRONG_ANSWER_BG_COLOR = "#FF8F8F"
START_POPUP_BG_COLOR = "#EEF5EB"
START_BUTTON_BG_COLOR = "#C5FCB1"
# fonts
FONT_NAME = 'Consolas'
SCORE_FONT = (FONT_NAME, 12, 'normal')
SCORE_FONT_COLOR = 'white'
CATEGORY_LABEL_FONT = (FONT_NAME, 9, 'bold')
CATEGORY_NAME_FONT = (FONT_NAME, 14, 'normal')
CATEGORY_FONT_COLOR = 'white'
QUESTION_FONT = (FONT_NAME, 18, 'normal')
QUESTION_FONT_COLOR = 'black'
START_POPUP_BIG_FONT = (FONT_NAME, 14, 'bold')
START_POPUP_SMALL_FONT = (FONT_NAME, 9, 'normal')

# settings values
MIN_QUESTIONS = 5
MAX_QUESTIONS = 30
DEFAULT_QUESTIONS = 10
DIFFICULTY_OPTIONS = ["easy", "medium", "hard"]

class QuizzInterface():
    def __init__(self):
        '''Generates the window for the Quiz App and displays the game settings pop up to.'''
        # app window
        self.window = Tk()
        self.window.title("Quiz Game")
        self.window.config(background=BG_COLOR, padx=20, pady=20)
        self.true_bg = PhotoImage(file="./images/true.png")
        self.false_bg = PhotoImage(file="./images/false.png")

        # start settings pop up
        self.start_popup = Toplevel(self.window)
        self.start_popup.attributes('-topmost',True)
        self.start_popup.focus_force()
        self.start_popup.protocol("WM_DELETE_WINDOW", self.close_quiz)
        self.start_popup.config(padx=20, pady=20, bg=START_POPUP_BG_COLOR)
        Label(self.start_popup, text='Welcome to the Quiz Game!', justify='center', pady='15px', font=START_POPUP_BIG_FONT, bg=START_POPUP_BG_COLOR).grid(row=0, column=0, columnspan=2)

        # number of questions
        Label(self.start_popup, text='Number of questions', pady='2px', padx='10px', font=START_POPUP_SMALL_FONT, bg=START_POPUP_BG_COLOR).grid(row=1, column=0)
        self.amount_select = IntVar()
        self.amount_select.set(DEFAULT_QUESTIONS)
        Spinbox(self.start_popup, textvariable= self.amount_select, width=10, from_=MIN_QUESTIONS, to=MAX_QUESTIONS).grid(row=2, column=0)

        # difficulty level
        Label(self.start_popup, text='Difficulty level', pady='2px', padx='10px', font=START_POPUP_SMALL_FONT, bg=START_POPUP_BG_COLOR).grid(row=1, column=1)
        self.difficulty_select = StringVar()
        self.difficulty_select.set(DIFFICULTY_OPTIONS[0])
        OptionMenu(self.start_popup, self.difficulty_select, *DIFFICULTY_OPTIONS).grid(row=2, column=1)

        # start button
        Label(self.start_popup, text='', pady='3px').grid(row=3, column=0)
        Button(self.start_popup, text='START', command= self.start_quiz, bg=START_BUTTON_BG_COLOR, font=START_POPUP_BIG_FONT, padx='15px', pady='3px').grid(row=4, column=0, columnspan=2)

        self.window.mainloop()

    def start_quiz(self):
        # get params
        amount = self.amount_select.get()
        difficulty = self.difficulty_select.get()
        params = {'amount': amount, 'difficulty': difficulty, 'type': 'boolean'}
        # get Quiz Data
        quiz_data = QuizData(params)
        # generate Quiz Brain
        self.quiz_brain = QuizBrain(quiz_data.question_bank)

        # question canvas
        self.question_canvas = Canvas(width=350, height=360, highlightthickness=0, background=BG_COLOR)
        self.question_bg = self.question_canvas.create_rectangle(0, 30, 350, 350, fill=QUESTION_BG_COLOR, outline=QUESTION_BG_COLOR)
        self.question_text = self.question_canvas.create_text(175, 190, text="", width=300, font=QUESTION_FONT, fill=QUESTION_FONT_COLOR, justify='center')
        self.question_canvas.create_rectangle(30, 0, 320, 60, fill=CATEGORY_BG_COLOR, outline=CATEGORY_BG_COLOR)
        self.category_label =self.question_canvas.create_text(175, 15, text='CATEGORY', font=CATEGORY_LABEL_FONT, fill=CATEGORY_FONT_COLOR, justify='center')
        self.category_text = self.question_canvas.create_text(175, 38, text="", width=300, font=CATEGORY_NAME_FONT, fill=CATEGORY_FONT_COLOR, justify='center')
        self.question_canvas.grid(row=1, column=0, columnspan=2, pady=25)

        # score label
        self.score_label = Label(text=f'Score: {self.quiz_brain.score}', bg=BG_COLOR, fg=SCORE_FONT_COLOR, font=SCORE_FONT)
        self.score_label.grid(row=0, column=1, sticky="E")

        # true and false buttons
        self.true_button = Button(image=self.true_bg, highlightthickness=0, command=lambda answer='True': self.check_answer(answer))
        self.true_button.grid(row=2, column=0)
        self.false_button = Button(image=self.false_bg, highlightthickness=0, command=lambda answer='False': self.check_answer(answer))
        self.false_button.grid(row=2,column=1)

        self.start_popup.destroy()
        self.window.focus_force()
        self.generate_next_question()

    def check_answer(self, user_answer: str):
        '''Called when player clicks either 'true' or 'false' button to answer to the current question, and passes the user answer to the QuizBrain
        to check if that's correct. Calls the method that gives feedback to the player passing the result of this check.'''
        is_correct_answer = self.quiz_brain.is_correct_answer(user_answer)
        self.give_feedback(is_correct_answer)

    def give_feedback(self, is_correct_answer: bool):
        '''Gives feedbck on the player's answer, by coloring the question card background with either green if player guessed it right,
        or red if player guessed it wrong. It also updates the score label and calls the next question after one second.'''
        self.false_button.config(state='disabled')
        self.true_button.config(state='disabled')
        if is_correct_answer:
            self.question_canvas.itemconfig(self.question_bg, fill=CORRECT_ANSWER_BG_COLOR)
            self.score_label.config(text=f'Score: {self.quiz_brain.score}')
        else:
            self.question_canvas.itemconfig(self.question_bg, fill=WRONG_ANSWER_BG_COLOR)
        self.window.after(1000, self.generate_next_question)

    def generate_next_question(self):
        '''Uses the QuizBrain to get the next question and displays it in the canvas, if that are still questions left.'''
        self.question_canvas.itemconfig(self.question_bg, fill=QUESTION_BG_COLOR)
        if self.quiz_brain.still_has_questions():
            self.false_button.config(state='normal')
            self.true_button.config(state='normal')
            next_question = self.quiz_brain.next_question()
            self.question_canvas.itemconfig(self.category_text, text=next_question.category)
            self.question_canvas.itemconfig(self.question_text, text=next_question.text)
        else:
            self.end_game()

    def end_game(self):
        self.question_canvas.itemconfig(self.question_text, text="You completed the quiz!")
        self.question_canvas.itemconfig(self.category_text, text='')
        self.question_canvas.itemconfig(self.category_label, text='GAME OVER')
        self.false_button.config(state='disabled')
        self.true_button.config(state='disabled')

    def close_quiz(self):
        self.window.destroy()

Udemy - 100 days of Python/Intermediate sections/day-34_gui_quiz_app/ui.py


import json
import random
import os
from collections import Counter
from glob import glob

from itertools import repeat
from multiprocessing.pool import Pool

from exprimo import get_log_dir
from exprimo.optimizers.base import BaseOptimizer
from exprimo.optimizers.utils import evaluate_placement, apply_placement, generate_random_placement, flatten, \
    get_device_assignment
from exprimo.graph import get_flattened_layer_names, ComputationGraph

import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from exprimo import PLOT_STYLE, log
import seaborn as sns

from exprimo.plotting import plot_map_elites_archive, plot_archive_animation

sns.set(style=PLOT_STYLE)

def _evaluate(individual, net_string, groups, device_graph, pipeline_batches=1, batches=1,
              simulator_comp_penalty=1, simulator_comm_penalty=1,
              device_memory_utilization=1):
    description, individual = individual

    comp_graph_dict = apply_placement(net_string, individual, groups)

    score = 1 / evaluate_placement(comp_graph_dict, device_graph,
                                   pipeline_batches=pipeline_batches, batches=batches,
                                   comp_penalty=simulator_comp_penalty, comm_penalty=simulator_comm_penalty,
                                   device_memory_utilization=device_memory_utilization)

    return score, description, individual

class MapElitesOptimizer(BaseOptimizer):

    def __init__(self, dimension_sizes=(-1, -1, 10), initial_size=50,
                 steps=1000, allow_cpu=True, mutation_rate=0.05, copy_mutation_rate=0, replace_mutation_rate=0,
                 zone_mutation_rate=0, crossover_rate=0.4, selection='random', tournament_size=10,
                 benchmarking_function=None, benchmarking_steps=0, benchmark_before_selection=False,
                 benchmarking_n_keep=None, benchmarking_time_threshold=None, include_trivial_solutions=True,
                 show_score_plot=False, plot_axes=(0, 2), plot_animation=False, animation_fps=1,
                 archive_log_period=None, **kwargs):
        super().__init__(**kwargs)
        self.dimension_sizes = dimension_sizes
        self.initial_size = initial_size
        self.steps = steps
        self.allow_cpu = allow_cpu
        self.mutation_rate = mutation_rate
        self.copy_mutation_rate = copy_mutation_rate
        self.replace_mutation_rate = replace_mutation_rate
        self.zone_mutation_rate = zone_mutation_rate
        self.crossover_rate = crossover_rate
        self.selection = selection
        self.tournament_size = tournament_size
        self.include_trivial_solutions = include_trivial_solutions
        self.benchmarking_steps = benchmarking_steps
        self.benchmark_before_selection = benchmark_before_selection
        self.benchmarking_n_keep = benchmarking_n_keep
        self.benchmarking_time_threshold = benchmarking_time_threshold
        self.benchmarking_function = benchmarking_function
        self.plot_axes = plot_axes
        self.show_score_plot = show_score_plot
        self.plot_animation = plot_animation
        self.animation_fps = animation_fps
        self.archive_log_period = archive_log_period

        if self.archive_log_period is not None:
            if not os.path.exists(os.path.join(get_log_dir(), 'archive_logs')):
                os.makedirs(os.path.join(get_log_dir(), 'archive_logs'))

        self.worker_pool = None

    def optimize(self, net_string, device_graph, return_full_archive=False):

        if self.n_threads > 1:
            self.worker_pool = Pool(self.n_threads)

        n_devices = len(device_graph.devices)
        groups = self.create_colocation_groups(get_flattened_layer_names(net_string))

        if self.dimension_sizes[0] == -1:
            self.dimension_sizes[0] = n_devices

        if self.dimension_sizes[1] == -1:
            self.dimension_sizes[1] = n_devices

        if self.dimension_sizes[2] == -1:
            comp_graph = ComputationGraph()
            comp_graph.load_from_string(net_string)
            _, max_jumps = comp_graph.get_number_of_jumps(return_max_jumps=True)
            self.dimension_sizes[2] = max_jumps

        archive_scores = np.empty(self.dimension_sizes)
        archive_scores[:] = np.NaN
        archive_individuals = np.zeros(list(self.dimension_sizes) + [len(groups)], dtype=int)

        def evaluate(individual):
            return _evaluate(individual, net_string, groups, device_graph, self.dimension_sizes, self.pipeline_batches,
                             self.batches, self.simulator_comp_penalty, self.simulator_comm_penalty,
                             self.device_memory_utilization)

        def mutate(individual):
            new_individual = []
            if random.random() < self.replace_mutation_rate:
                devices_present = list(set(individual))
                i1 = random.choice(devices_present)
                i2 = random.choice(devices_present)

                new_individual = [i2 if i == i1 else i for i in individual]
            elif random.random() < self.zone_mutation_rate:
                split1 = random.randint(0, len(individual) - 1)
                split2 = split1 + min(np.random.geometric(0.2), len(individual) - split1)
                dev = random.randint(0 if self.allow_cpu else 1, n_devices - 1)
                new_individual = individual[:split1] + [dev] * (split2 - split1) + individual[split2:]
            else:
                for i, gene in enumerate(individual):
                    if random.random() < self.copy_mutation_rate and i > 0:
                        new_individual.append(individual[i - 1])
                    elif random.random() < self.mutation_rate:
                        if self.allow_cpu:
                            new_individual.append(random.randint(0, n_devices - 1))
                        else:
                            new_individual.append(random.randint(1, n_devices - 1))
                    else:
                        new_individual.append(gene)

            return new_individual

        def crossover(parent1, parent2):
            crossover_point = random.randint(1, len(parent1) - 1)
            return parent1[:crossover_point] + parent2[crossover_point:]

        def create_candidates(n, create_random=False, create_trivial=False, selectable_candidates=None):
            if n <= 0:
                return []
            candidates = []
            if create_trivial:
                candidates.extend([
                    [i] * len(groups) for i in range(1, n_devices)
                ])
                n -= n_devices - 1

                if self.allow_cpu:
                    candidates.append([0] * len(groups))
                    n -= 1

            if create_random:
                while len(candidates) < n:
                    candidates.append(generate_random_placement(len(groups), n_devices, allow_device_0=self.allow_cpu))
            else:
                selectable_indices = np.argwhere(np.isfinite(archive_scores))
                # selectable_indices = sorted(selectable_indices, key=lambda x: -archive_scores[x[0], x[1], x[2]])
                while len(candidates) < n:
                    c = []
                    if selectable_candidates:
                        for _ in range(1 + int(random.random() < self.crossover_rate)):
                            c.append(random.choice(selectable_candidates))
                    else:
                        if self.selection == 'random':
                            for _ in range(1 + int(random.random() < self.crossover_rate)):
                                idx = random.choice(selectable_indices)
                                c.append(archive_individuals[idx[0], idx[1], idx[2], :].tolist())
                        elif self.selection == 'tournament':
                            idx = []
                            t = min(self.tournament_size, len(selectable_indices))
                            while len(idx) < 1 + int(random.random() < self.crossover_rate):
                                competitors = random.sample(selectable_indices.tolist(), t)
                                winner = max(competitors, key=lambda x: archive_scores[x[0], x[1], x[2]])
                                idx.append(winner)
                            for i in idx:
                                c.append(archive_individuals[i[0], i[1], i[2], :].tolist())

                    if len(c) == 2:
                        candidate = crossover(*c)
                    else:
                        candidate = c[0]
                    candidate = mutate(candidate)
                    candidates.append(candidate)

            return candidates

        def create_description(individual):
            c = Counter(individual)
            device_mode = c.most_common(1)[0][0]
            device_mode = round((device_mode / len(device_graph.devices)) * self.dimension_sizes[0])

            used_devices = round(((len(set(individual)) - 1) / (len(device_graph.devices))) * self.dimension_sizes[1])

            comp_graph_dict = apply_placement(net_string, individual, groups)
            comp_graph = ComputationGraph()
            comp_graph.load_from_string(json.dumps(comp_graph_dict))

            num_jumps, max_jumps = comp_graph.get_number_of_jumps(return_max_jumps=True)
            num_jumps = round((num_jumps / max_jumps) * (self.dimension_sizes[2] - 1))

            return (device_mode, used_devices, num_jumps)

        def benchmark(individual, benchmarking_function):
            device_assignment = get_device_assignment(apply_placement(net_string, individual, groups))
            time, memory_overflow = benchmarking_function(device_assignment, return_memory_overflow=True)

            description = create_description(individual)

            # Time is set to -1 if memory overflows - but we check with memory_overflow instead
            time = max(time, 0)

            if memory_overflow == -1:
                memory_overflow = 1

            if memory_overflow > 0:
                time += memory_overflow * 10 ** 9 * 1

            return 1 / time, description, individual

        def reevaluate_archive(benchmarking_function=None, n_keep=None, time_threshold=None):
            indices = list(np.argwhere(np.isfinite(archive_scores)))

            if time_threshold:
                indices = [i for i in indices if archive_scores[i[0], i[1], i[2]] >= 1 / time_threshold]

            if n_keep:
                indices = sorted(indices, key=lambda i: -archive_scores[i[0], i[1], i[2]])
                indices = indices[:n_keep]

            assert len(indices), 'No solutions fulfill the specified requirements'

            archive_scores[:] = np.NaN
            if self.verbose:
                if n_keep:
                    log(f'Reevaluating {n_keep} best individuals in archive (and throwing away the rest)')
                else:
                    log('Reevaluating all individuals in archive')
                if time_threshold:
                    log(f'Time threshold: {time_threshold}ms')
            for i in tqdm(indices, disable=not self.verbose):
                individual = archive_individuals[i[0], i[1], i[2], :].tolist()
                if benchmarking_function:
                    archive_scores[i[0], i[1], i[2]] = benchmark(individual, benchmarking_function)[0]
                else:
                    archive_scores[i[0], i[1], i[2]] = evaluate(individual)[0]

        def log_archive(file_name):
            indices = list(np.argwhere(np.isfinite(archive_scores)))
            indices = sorted(indices, key=lambda i: -archive_scores[i[0], i[1], i[2]])

            with open(os.path.join(get_log_dir(), 'archive_logs', file_name), 'w') as f:
                f.write('niche; time; placement\n')
                for i in indices:
                    niche = tuple(i)
                    time = 1 / archive_scores[i[0], i[1], i[2]]
                    placement = archive_individuals[i[0], i[1], i[2]].tolist()

                    f.write(f'{niche}; {time}; {placement}\n')

        def run_optimization(steps, benchmarking_function=None, start_step=0):
            nonlocal archive_individuals, archive_scores

            if self.verbose:
                if benchmarking_function:
                    log('Optimizing with benchmarking...')
                else:
                    log('Optimizing with simulator...')

            step_size = 1 if benchmarking_function else self.n_threads

            for i in tqdm(range(0, steps, step_size), disable=not self.verbose):
                init_number = min(max(0, self.initial_size - i), self.n_threads)

                if self.include_trivial_solutions and i == 0:
                    candidates = create_candidates(init_number, create_trivial=True, create_random=True)
                else:
                    candidates = create_candidates(init_number, create_random=True)
                if init_number > 0:
                    candidates += create_candidates(self.n_threads - init_number, selectable_candidates=candidates[:])
                else:
                    candidates += create_candidates(self.n_threads - init_number)

                if benchmarking_function:
                    eval_results = [benchmark(candidates[0], benchmarking_function)]
                elif self.n_threads == 1:
                    eval_results = [evaluate(candidates[0])]
                else:
                    fn_args = zip(((create_description(c), c) for c in candidates), repeat(net_string), repeat(groups),
                                  repeat(device_graph), repeat(self.pipeline_batches), repeat(self.batches),
                                  repeat(self.simulator_comp_penalty), repeat(self.simulator_comm_penalty),
                                  repeat(self.device_memory_utilization))

                    eval_results = self.worker_pool.starmap(_evaluate, fn_args)

                for result in eval_results:
                    score, description, individual = result

                    previous_elite_score = archive_scores[description[0], description[1], description[2]]
                    if np.isnan(previous_elite_score) or previous_elite_score < score:
                        archive_scores[description[0], description[1], description[2]] = score
                        archive_individuals[description[0], description[1], description[2], :] = individual

                if self.verbose and (i + 1) % self.verbose < step_size:
                    best_time = 1 / np.nanmax(archive_scores)
                    log(f'[{i + 1}/{steps}] Best time: {best_time:.4f}ms')

                if self.score_save_period and (i % self.score_save_period == 0 or steps - i < step_size):
                    best_time = 1 / np.nanmax(archive_scores)
                    with open(os.path.join(get_log_dir(), 'time_history.csv'), 'a') as f:
                        f.write(f'{i + start_step + 1}, {best_time}\n')

                if self.archive_log_period and (i + 1) % self.archive_log_period < step_size:
                    log_archive(f'step_{i + start_step + 1:06}.csv')

        if self.score_save_period:
            with open(os.path.join(get_log_dir(), 'time_history.csv'), 'w') as f:
                f.write('step, time\n')

        run_optimization(self.steps)

        if self.worker_pool:
            self.worker_pool.close()

        if self.archive_log_period is not None:
            log_archive('1_simulation_finished.csv')

        if self.benchmarking_steps > 0 or self.benchmark_before_selection:
            reevaluate_archive(self.benchmarking_function, n_keep=self.benchmarking_n_keep,
                               time_threshold=self.benchmarking_time_threshold)

            if self.archive_log_period is not None:
                log_archive('2_reevaluated.csv')

        if self.benchmarking_steps > 0:
            run_optimization(self.benchmarking_steps, self.benchmarking_function, self.steps)
            log_archive('3_benchmarking_finished.csv')

        if self.show_score_plot:
            if self.verbose:
                log('Plotting archive scores...', end='')
            graph = ComputationGraph()
            graph.load_from_string(net_string)
            _, max_jumps = graph.get_number_of_jumps(return_max_jumps=True)
            plot_map_elites_archive(archive_scores, n_devices, max_jumps, self.plot_axes,
                                    save_path=os.path.join(get_log_dir(), 'archive_plot.pdf'))
            if self.verbose:
                log('Done')

        if self.plot_animation:
            if not self.archive_log_period and self.verbose:
                log('self.plot_animation was set to True, but archive logging was not enabled. '
                    'Skipping animation plot.')
            else:
                if self.verbose:
                    log('Plotting archive animation...', end='')
                paths = glob(os.path.join(get_log_dir(), 'archive_logs', 'step_*.csv'))
                plot_archive_animation(paths, (os.path.join(get_log_dir(), 'archive_animation.mp4'),
                                               os.path.join(get_log_dir(), 'archive_animation.gif')),
                                       self.dimension_sizes,
                                       n_devices=n_devices, max_jumps=max_jumps, axes=self.plot_axes,
                                       fps=self.animation_fps)
                if self.verbose:
                    log('Done')

        if return_full_archive:
            return archive_scores, archive_individuals

        best_index = np.nanargmax(archive_scores)
        best_individual = archive_individuals.reshape((-1, len(groups)))[best_index]

        if self.verbose:
            log(f'Best individual: {best_individual.tolist()}')

        solution = json.dumps(apply_placement(net_string, best_individual.tolist(), groups), indent=4)

        with open(os.path.join(get_log_dir(), 'me_solution.json'), 'w') as f:
            f.write(solution)

        return solution


import cv2
import numpy as np

img = cv2.imread('circulo.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
blur = cv2.GaussianBlur(gray, (5, 5), 0)

# Definição dos valores minimo e max da mascara
image_lower_hsv1 = np.array([60,165,225])
image_upper_hsv1 = np.array([87,166,227])
image_lower_hsv2 = np.array([0,130,100])
image_upper_hsv2 = np.array([30,255,255])

mask1 = cv2.inRange(hsv, image_lower_hsv1, image_upper_hsv1)
mask2 = cv2.inRange(hsv, image_lower_hsv2, image_upper_hsv2)

mask = mask1 + mask2

contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for i in range(2):

    # Desenho do contorno dos circulos
    cv2.drawContours(img, [contours[i]], -1, (0, 170, 250), 6)

    # Calculo da area
    M = cv2.moments(contours[i])
    area = M['m00']
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])

    # Calculo das coordenadas do centro de massa
    def calcula_centro_massa(contours):
        M = cv2.moments(contours)
        cx = int(M['m10'] / M['m00'])
        cy = int(M['m01'] / M['m00'])
        return cx, cy
    cx1, cy1 = calcula_centro_massa(contours[0])
    cx2, cy2 = calcula_centro_massa(contours[1])

    # Calculo do angulo de inclinação da reta
    delta_y = cy2 - cy1
    delta_x = cx2 - cx1
    angle = np.degrees(np.arctan2(delta_y, delta_x))

    # indicação do centro +
    size = 15
    color = (0, 0, 0)
    cv2.line(img, (cx - size, cy), (cx + size, cy), color, 2)
    cv2.line(img, (cx, cy - size), (cx, cy + size), color, 2)

    cv2.line(img, (cx1, cy1), (cx2, cy2), (255, 0, 0), 3)
    text = "Inclinacao: {:.2f} graus".format(angle)
    cv2.putText(img, text, (cx1-420, cy+200), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)

    print("Objeto {}: Área={} Centro de massa=({}, {})".format(i+1, area, cx, cy))

    text = "Area: {:.2f}".format(area)
    cv2.putText(img, text, (cx-65, cy-110), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
    text = "Centro: ({}, {})".format(cx, cy)
    cv2.putText(img, text, (cx-80, cy-90), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)

cv2.imshow("Imagem Circulos", img)
cv2.waitKey(0)
cv2.destroyAllWindows()


import time
import random
import numpy as np
from ex1 import *
from ex2 import *
from ex3 import *

def time_max_elem(A, n):
    tic = time.time()
    find_max_value(A, n)
    toc = time.time()
    return round(toc - tic, 6)

def time_second_max_elem(A, n):
    tic = time.time()
    find_second_max_value(A, n)
    toc = time.time()
    return round(toc - tic, 6)

def time_mean(A, n):
    tic = time.time()
    calc_mean(A, n)
    toc = time.time()
    return round(toc - tic, 6)

def time_ex2(matrix1, matrix2, n):
    tic = time.time()
    multiply_square_matrices(matrix1, matrix2, n)
    toc = time.time()
    return round(toc - tic, 6)

def time_ex3(B):
    tic = time.time()
    is_summing_to_zero(B)
    toc = time.time()
    return round(toc - tic, 6)

def generate_random_list(n):
    A = np.zeros(n)
    for i in range(n):
        A[i] = random.randint(-10, 10)
    return A

def generate_random_square_matrix(n):
    matrix = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            matrix[i][j] = random.randint(-10, 10)
    return matrix

if __name__ == "__main__":
    n = int(input("Enter number of elements in array: "))
    A = generate_random_list(n)
    B = generate_random_list(n)
    matrix1 = generate_random_square_matrix(n)
    matrix2 = generate_random_square_matrix(n)

    time_max_elem(A, n)
    time_second_max_elem(A, n)
    time_second_max_elem(A, n)
    time_ex2(matrix1, matrix2, n)
    time_ex3(B)


#Alvaro Fernandez Payo
#fecha: 24/11/2022
#Examen de Python

#-----------#
#Ejercicio 1#
#-----------#

#-----------#
#Ejercicio 2#
#-----------#

from csv import DictReader

Datos = "/content/peliculas.csv"

def create_list(archivo):
    lista=[]
    with open(archivo, 'r') as file:
        reader = DictReader(file)
        for linea in reader:
            lista.append(linea)
    return lista

definido = create_list(Datos)

for registros in definido:
  print(f"Titulo:{registros['titulo']} - Director:{registros['director']} - Año:{registros['anyo']} - Genero:{registros['genero']}")

#-----------#
#Ejercicio 3#
#-----------#

from csv import DictWriter

Datos = "/content/peliculas.csv"

def create_list(archivo):
    lista=[]
    with open(archivo, 'r') as file:
        reader = DictReader(file)
        for linea in reader:
            lista.append(linea)
    return lista

def nueva_pelicula():
  nuevos_datos=[]

  titulo = input("Añade un titulo de la pelicula: ")
  director = input("Indica el director: ")
  año = input("El año que salio la pelicula: ")
  genero = input("El genero de la pelicula: ")
  nuevos_datos.append({"titulo": titulo, "anyo": año, "genero": genero, "director": director})
  return nuevos_datos

def lista_nueva(lista1, lista2):
  nueva_lista=[]
  nueva_lista.append(lista1)
  nueva_lista.extend(lista2)
  return lista1

lista1=create_list(Datos)
lista2=nueva_pelicula()
definido=lista_nueva(lista1, lista2)

#print(lista1)
#print(lista2)
#print(definido)
for registros in definido:
  print(f"Titulo:{registros['titulo']} - Director:{registros['director']} - Año:{registros['anyo']} - Genero:{registros['genero']}")


#!/usr/bin/python3
from tkinter import *
from PIL import Image, ImageTk
from tkinter import messagebox
import RPi.GPIO as GPIO
from threading import Timer
# define motion pin
motion_pin = 23
# set GPIO as GPIO.BOARD
GPIO.setmode(GPIO.BCM)
# set pin mode as INPUT
GPIO.setup(motion_pin, GPIO.IN)

def MotionDetected(lbl):
    #Do your shit here
    lbl.config(bg = "green")

def NoMotionDetected(lbl):
    lbl.config(bg="red")

def app_lost_focus(event):
    t.cancel()
    exit()

def on_closing():
    t.cancel()
    exit()

window = Tk() # Main form
window.geometry("400x300+400+100")
lblMotion = Label(window, bg="red", height=10, width=30)
lblMotion.place(x=80, y=50)
# Call NoMotionDetected when there's motion
# Call MotionDetected when there's no motion
window.bind("<FocusOut>", app_lost_focus)
window.protocol("WM_DELETE_WINDOW", on_closing)
def loop():
    global counter
    if(GPIO.input(motion_pin) == 0):
        NoMotionDetected(lblMotion)
    else:
        MotionDetected(lblMotion)
    t = Timer(0.1, loop)
    t.start()
counter = 0
t = Timer(0.1, loop)
t.start()
window.mainloop() # Load the form


import os, sys, datetime, functools, traceback, atexit
from collections import namedtuple
try:
    import yaml
except:
    print('*** Did you install the dependencies? try %s -m pip install -r requirements.txt' % (sys.executable,))
    raise
try:
    import regex as re
except ImportError:
    print("warning: couldn't import 'regex'; using 're' instead for pypy compat", file=sys.stderr)
    import re

try:
    import pyximport
except ImportError:
    print("warning: couldn't import 'pyximport' (Cython); using pure-Python instead", file=sys.stderr)
    def normalize_rule_text_inner(text):
        return normalize_rule_text_inner_python(text)
else:
    pyximport.install()
    from normalize_rule_text import normalize_rule_text_inner as normalize_rule_text_inner
def normalize_rule_text(text):
    if len(text) > 100000:
        raise Exception('this is definitely not a rule text')
    text = text.rstrip()
    if text.endswith('*)'):
        text = re.sub('\(\*was: .*?\*\)\s*$', '', text, flags=re.I)
    return normalize_rule_text_inner(text)

def normalize_rule_text_inner_python(text):
    return re.sub('[^a-z0-9]', '', text.lower()).encode('utf-8')

def decode(binary):
    return binary.decode('utf-8')

def assert_(cond):
    if not cond:
        raise AssertionError

FATAL_WARNINGS = True
got_any_warnings = False
def warn(x):
    with warnx():
        print(x)
class warnx:
    def __enter__(self):
        print('warning: ', end='')
    def __exit__(self, ty, val, traceback):
        if ty is not None: return False
        global got_any_warnings
        got_any_warnings = True
        return False
@atexit.register
def warn_cleanup():
    if got_any_warnings:
        if FATAL_WARNINGS: raise Exception('got warnings w/ fatal warnings enabled')

def highlight_spaces(text):
    return re.sub('[^ -~\n]+', lambda m: repr(m.group(0))[1:-1], text).replace(' ', '\x1b[7m \x1b[0m')

mboxcl2_regex = re.compile(b'From (?:[^\n]|\n[^\n])+\nContent-Length: ([0-9]+)[ \t]*(?=\n).*?\n\n', re.S)
mboxcl2_vague_regex = re.compile(b'\nFrom [^\n]* [0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4}\n')
mboxcl2_justfrom = re.compile(b'\n*(?:$|From )')
def iter_mboxcl2ish(text):
    # why the fuck is there no easy way to parse mboxcl2,
    # i.e. taking into account Content-Length
    # formail (part of procmail) can do it but for some bizarre reason it will
    # *either* treat the input as a single message and add '>' escaping
    # (default), or split messages and not add escaping (-s), but not both.
    # you can pass -s argv to make it invoke a command for each message, but
    # that's sloow
    pos = 0
    while pos != len(text):
        if text[pos:pos+1] == b'\n':
            pos += 1
            continue
        m = mboxcl2_regex.match(text, pos)
        if text[pos:pos+5] != b'From ':
            print(repr(text[pos:pos+1000]))
            raise Exception('wat')
        if m is not None:
            content_length = int(m.group(1))
            hdrend = m.end()
            endpos = m.end() + content_length
            if not mboxcl2_justfrom.match(text, endpos):
                # this could be because it has quoted Froms,
                # but agora_vanyel0/agora/proto/10 has one message that's just /completely/ wrong
                # print('Content-Length was bogus!', repr(text[endpos:endpos+20]), file=sys.stderr)
                # anyway, fall back on search
                m = None
        if m is None:
            # ack, no content-length
            # but still...
            n = mboxcl2_vague_regex.search(text, pos + 1)
            if n is not None:
                endpos = n.start()
            else:
                endpos = len(text)
            hdrend = pos # xxx

        #print('pos=', pos, 'gotcl=', m is not None, 'hdrend=', hdrend, 'endpos=', endpos, '@hdrend=', repr(text[hdrend:hdrend+10]))
        msgtext = text[pos:endpos]
        yield msgtext
        pos = endpos
        last_hdrend = hdrend

FIXED = {
    'Jan. or Feb. 1994': '1 January 1994',
    'Jun. or Jul. 1999': '1 June 1999',
    'Mar. or Apr. 2000': '1 March 2000',
    'Apr. or May 1994': '1 April 1994',
    '12 Februray 2016': '12 February 2016', # [sic]
    '16 May 011': '16 May 2011',
    '14 Augut 2012': '14 August 2012',
    '9 Febraury 2013': '9 February 2013',
    '11 Jaunuary 2013': '11 January 2013',
    '27 Apirl 2013': '27 April 2013',
    '24 Janurary 2014': '24 January 2014',
    '26 <ay 2009': '26 May 2009',
    '16 May 2011:': '16 May 2011',
    'July 1993': '1 July 1993',
    'Mar. 19 198': '19 March 1998',
    'Feb. 6 196': '6 February 1996',
    'by Agora March 26 1998': '26 March 1998',
}
@functools.lru_cache(None)
def strptime_ruleset(text):
    text = text.strip()
    text = FIXED.get(text, text)
    text = re.sub('[\.,]', '', text)
    for fmt in ['%d %B %Y', '%b %d %Y', '%b %Y', '%d %b %Y', '%b %d %Y %H:%M:%S %z']:
        try:
            return datetime.datetime.strptime(text, fmt).date()
        except ValueError:
            pass
    raise ValueError('%r could not be parsed as a date' % (text,))

#NUMBERS_STOPPED_CHANGING_AT = strptime_ruleset('24 October 1994')
FOUNDING_DATE = strptime_ruleset('28 June 1993')
REVNUM_FIXUPS = {
    'e': '3',
}
END_STUFF_RE = re.compile(r'(?:,?\s*(?:sus?bs?tantial|cosmetic|\([^\)]+\)))*$')
_1996_RE = re.compile('(.*), (?:ca\. )?([^,]* 1996)')
OTHER_DATE_RE = re.compile(r'(.*), (?!19[0-9]{2}|20[0-9]{2})(?:ca\. )?(.*?)\.?$')
INITIAL_RE = re.compile(r'ini?t?ial ', re.I)
CREATED_RE = re.compile(r'created|\benacted', re.I)
# XXX handle reenacts! rulekeepor is dead atm
RULE_N_RE = re.compile(r'(.*)Rule ([0-9]+)', re.I)
REVNUM_NOTE_RE = re.compile(r'([A-Za-z]+)\(([^\(\) ]*?)\)')
REVNUM_RE = re.compile(r'[0-9]+(?:\.[0-9]+)?$')
NUMERIC_RE = re.compile(r'[0-9]+$')
AMENDED_BY_PROP_RE = re.compile('(amended|transmuted|mutated|power changed|\?\?\?)?.*by pro[a-z]+ ([0-9][^ ]+)', re.I)
RENUMBERED_RE = re.compile(r'(?:renumbered|number changed)(?: from ([0-9]+)(?:\/[^ ]*)?)? to ([0-9]+)', re.I)
BY_RE = re.compile(r'\bby ([^,\(]*)')
@functools.lru_cache(None)
class Annotation(object):
    __slots__ = ['text', 'date', 'revnum', 'is_create', 'prev_num', 'cur_num', 'num_changed', 'proposal_num', 'is_indeterminate', '_guessed_num', '_guessed_revnum', 'latent', '_sig', '_entry']

    def __init__(self, text):
        if text is None:
            return
        text = text.strip()
        self.text = text
        self.date = None
        self.revnum = None
        self.is_create = False
        self.prev_num = None
        self.cur_num = None
        self.num_changed = False
        self.proposal_num = None
        self.is_indeterminate = text in {'...', '..', '[orphaned text]'} or '??? by' in text
        text = END_STUFF_RE.sub('', text)
        m = _1996_RE.match(text) or OTHER_DATE_RE.match(text)
        if m:
            if m.group(2) not in {'date unknown', 'datu unknown', 'XXXDATEHERE'}:
                try:
                    self.date = strptime_ruleset(m.group(2))
                except ValueError as e:
                    warn('%s, while parsing annotation %r' % (str(e), text))
            text = m.group(1)
        if INITIAL_RE.match(text):
            self.is_create = True
            self.revnum = '0'
            self.date = FOUNDING_DATE # override any existing date
        if CREATED_RE.match(text):
            self.is_create = True
            self.revnum = '0'
        if self.is_create:
            m = RULE_N_RE.match(text)
            if m and ' by' not in m.group(1):
                self.cur_num = int(m.group(2))
        ms = REVNUM_NOTE_RE.findall(text)
        if ms:
            assert self.revnum is None
            kind, revnum = ms[0]
            if kind.lower() not in {'amended', 'transmuted', 'amedned', 'amneded', 'amendd', 'repealed', 'retitled'}:
                warn("revnum attached to something other than 'amended' or 'transmuted' (or 'repealed' or 'retitled' but those are weird): %r in %r" % (kind, text))
            revnum = REVNUM_FIXUPS.get(revnum, revnum)
            if REVNUM_RE.match(revnum):
                self.revnum = revnum
            elif revnum in {'???', ''}:
                # Amended(), Amended(???)
                pass
            else:
                warn("weird revision number %r in %r" % (num, text))
            if len(ms) > 1:
                warn('got multiple revnums? %s <- %s' % (ms, text))
        m = RENUMBERED_RE.match(text)
        if m:
            self.prev_num = int(m.group(1)) if m.group(1) else None
            self.cur_num = int(m.group(2))
            self.num_changed = True
        m = AMENDED_BY_PROP_RE.search(text)
        if m:
            was_atmp = bool(m.group(1))
            self.proposal_num = m.group(2)
            try:
                num = int(self.proposal_num)
            except ValueError:
                pass
            else:
                if num < 1268 and was_atmp:
                    assert_(self.cur_num is None)
                    self.cur_num = num
                    self.num_changed = True
                    if self.revnum is None:
                        self.revnum = '0.%d' % self.cur_num

    def copy(self):
       c = self.__class__(None)
       c.text = self.text
       c.date = self.date
       c.revnum = self.revnum
       c.is_create = self.is_create
       c.prev_num = self.prev_num
       c.cur_num = self.cur_num
       c.num_changed = self.num_changed
       c.proposal_num = self.proposal_num
       c.is_indeterminate = self.is_indeterminate
       return c

    @property
    def sig(self):
        try:
            return self._sig
        except AttributeError:
            self._sig = self._calc_sig()
            return self._sig
    def _calc_sig(self):
        # get a value such that if two sigs are equal, they probably represent
        # the same change (even given corrections) OR are just
        # indistinguishable by text alone (e.g. two retitlings, see knit.py)
        if self.is_create:
            return ('0', 'create')
        if re.search('(?:renumbered|number changed)', self.text, re.I):
            distinguisher = 'renumber'
        elif re.search('(?:retitled|title changed)', self.text, re.I):
            distinguisher = 'retitle'
        elif re.search('(?:transmuted|power changed|from MI=)', self.text, re.I):
            distinguisher = 'repower'
        else:
            # dunno
            distinguisher = None
        if self.proposal_num is not None:
            doer = ('proposal', self.proposal_num)
        else:
            m = BY_RE.search(self.text)
            if m:
                doer = m.group(1).rstrip()
            else:
                # dunno
                doer = None
        if (distinguisher is not None or self.revnum is not None) and doer is not None:
            return (self.revnum, distinguisher, doer)
        else:
            return self.text

    def __repr__(self):
        extra = ''
        if hasattr(self, '_guessed_num'):
            extra += ', _guessed_num=%r' % (self._guessed_num,)
        if hasattr(self, '_guessed_revnum'):
            extra += ', _guessed_revnum=%r' % (self._guessed_revnum,)
        return 'Annotation(date=%s, revnum=%r, prev_num=%s, cur_num=%s, is_create=%s, num_changed=%s, proposal_num=%s, text=%r%s)' % (self.date, self.revnum, self.prev_num, self.cur_num, self.is_create, self.num_changed, self.proposal_num, self.text, extra)

def datetime_from_timestamp(ts):
    return datetime.datetime.fromtimestamp(ts, datetime.timezone.utc)
def datetime_from_date(date):
    return datetime.datetime.combine(date, datetime.time(tzinfo=datetime.timezone.utc))

Box = namedtuple('Box', ['value'])

def partition(func, iterable):
    yes = []
    no = []
    for item in iterable:
        if func(item):
            yes.append(item)
        else:
            no.append(item)
    return yes, no

def cmp(a, b):
    return (a > b) - (a < b)


import zbarlight
import logging
from PIL import Image

logger = logging.getLogger(__name__)

def read_qr(path, lang):
  logger.info("opening %s", path)

  with open(path, 'rb') as f:
    image = Image.open(f)
    image.load()
    qr = zbarlight.scan_codes('qrcode', image)
    if qr is not None:
      qr = qr[0].decode("utf-8")

  return qr


import json
from sklearn.base import TransformerMixin

class IntegratedActionCounterANDTrainEvalLoopCounter(TransformerMixin):
    """
    this feature divide the values of
    counters_with_time_window_size_action_changed_between_train_eval_loops_transformer
    by the value of number_of_train_eval_loops
    if the values of number_of_train_eval_loops is zero so the feature value will be zero as well
    """

    def __init__(self):
        self.configuration_data = json.loads(open("configuration.json", "r").read())
        self.possible_actions = self.configuration_data['possible_actions']
        self.column_names = []
        for action in self.possible_actions:
            self.column_names.append('#{}/#train_eval_loops'.format(action))

    def fit(self, X):
        return self

    def transform(self, X):
        return X[self.column_names]

    def get_feature_names(self):
        return self.column_names

    @staticmethod
    def append_feature_for_action(X, action):
        feature_values = []
        for index, row in X.iterrows():
            if row['number_of_train_eval_loops_in_time_window'] == 0:
                feature_values.append(0)
            else:
                feature_values.append(
                    row['{}_counter_with_time_window_size_action_was_changed_between_train_eval_loops'.format(action)] /
                    row['number_of_train_eval_loops_in_time_window'])

        X['#{}/#train_eval_loops'.format(action)] = feature_values

        return X

    def append_features(self, X):
        for action in self.possible_actions:
            X = self.append_feature_for_action(X, action)


# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.

"""For backward compatibility, we need the class definitions to deserialize."""

class LossScaler:
    def __init__(self, scale=1):
        self.cur_scale = scale

class DynamicLossScaler:
    def __init__(self,
                 init_scale=2**32,
                 scale_factor=2.,
                 scale_window=1000,
                 min_scale=1,
                 delayed_shift=1,
                 consecutive_hysteresis=False):
        self.cur_scale = init_scale
        self.cur_iter = 0
        self.last_overflow_iter = -1
        self.scale_factor = scale_factor
        self.scale_window = scale_window
        self.min_scale = min_scale
        self.delayed_shift = delayed_shift
        self.cur_hysteresis = delayed_shift
        self.consecutive_hysteresis = consecutive_hysteresis


#!/usr/bin/env python
# pylint: disable=C0116,W0613

import logging
import json
from time import sleep
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

# # #   Enable logging   # # #
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
# # #                # # #

# # #   Members   # # #
token = ""
db = {}

leaderUsernames = {"Dear_LeaderMK", "Jewkorius"}
# # #                # # #

# # #   Commands   # # #
def help(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /help is issued."""
    update.message.reply_text('Commands:\n/give name numberOfCredits\n/deduct name numberOfCredits\n/leaderboard\n/help')

def list_all(update: Update, context: CallbackContext) -> None:
    result = ""
    for key, value in db.items():
        result += key + ": " + str(value) + " credits\n"

    update.message.reply_text(result)

def add(update: Update, context: CallbackContext) -> None:
    user = context.args[0].lower()
    if (not validate_add_remove(update, context)): return
    else:
        creds = abs(int(context.args[1]))
        db[user] += creds
        update.message.reply_text("Gave " + user + " " + str(creds) + " credits. 最尊貴！")
        save_db()
        sleep(2)

def remove(update: Update, context: CallbackContext) -> None:
    user = context.args[0].lower()
    if (not validate_add_remove(update, context)): return
    else:
        creds = abs(int(context.args[1]))
        db[user] -= creds
        update.message.reply_text("Deducted " + str(creds) + " from " + user + ". 可恥！")
        save_db()
        sleep(2)

""" Must have known names for all users for this
def donate(update: Update, context: CallbackContext) -> None:
    donater = update.effective_user
    user = context.args[0].lower()
    creds = context.args[1]
    if (not is_user_valid(user) or not is_credits_valid(creds)): return
    else:
        creds = abs(int(creds))
        db[user] -= creds
        update.message.reply_text("Deducted " + str(creds) + " from " + user + ". 可恥！")
        save_db()
"""
# # #                # # #

# # #   Replies   # # #
def reply_invalid_number(update: Update):
    update.message.reply_text("Must enter a number (unsigned integer) value of credits. 最尊貴！")

def reply_invalid_user(update: Update):
    names = "["
    for key, value in db.items():
        names += "'" + key + "' "
    names += "]"
    update.message.reply_text("User invalid! Valid users are: " + names + ". 可恥！")

def reply_only_leader_can_update(update: Update):
    update.message.reply_text("Only MK can update the social credit system! 可恥！")
# # #                # # #

# # #   Validation   # # #
def validate_add_remove(update: Update, context: CallbackContext) -> bool:
    user = context.args[0].lower()
    creds = context.args[1]

    if (not is_user_valid(user)):
        reply_invalid_user(update)
        return False

    elif (not is_credits_valid(creds)):
        reply_invalid_number(update)
        return False

    elif (not is_user_leader(update.effective_user.username)):
        reply_only_leader_can_update(update)
        return False

    else:
        return True

def is_user_valid(name: str) -> bool:
    if name.lower() not in db:
        return False
    else:
        return True

def is_credits_valid(creds: str) -> bool:
    try:
        abs(int(creds))
    except:
        return False
    else:
        return True

def is_user_leader(name: str) -> bool:
    return name in leaderUsernames
# # #                # # #

# # #   Database mutations   # # #
def save_db():
    with open("/root/SocialCreditBot/db.json", "w") as f:
        json.dump(db, f)
# # #                # # #

# # #   Config   # # #
def load_token_file() -> str:
    with open("/root/SocialCreditBot/config.json") as f:
        data = json.load(f)
        return data["token"]

def load_db_file() -> dict:
    with open("/root/SocialCreditBot/db.json") as f:
        data = json.load(f)
        return data
# # #                # # #

# # #   Setup   # # #
def main() -> None:
    """Start the bot."""
    global token, db
    # Create the Updater and pass it your bot's token.
    token = load_token_file()
    sleep(2)
    db = load_db_file()
    sleep(2)
    updater = Updater(token)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("give", add))
    dispatcher.add_handler(CommandHandler("deduct", remove))
    dispatcher.add_handler(CommandHandler("help", help))
    dispatcher.add_handler(CommandHandler("leaderboard", list_all))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
# # #                # # #

if __name__ == '__main__':
    main()


from django.conf.urls.defaults import patterns, url

from api import viewshandlers
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse

try:    import json
except: import simplejson as json

# Version 1.0 URLS
urlpatterns = patterns('',

    # current api
    url(r'^1\.0/datastore/sqlite$',     viewshandlers.sqlite_handler,         name="method_sqlite"),
    url(r'^1\.0/scraper/search$',       viewshandlers.scraper_search_handler, name="method_search"),
    url(r'^1\.0/scraper/getuserinfo$',  viewshandlers.userinfo_handler,       name="method_getuserinfo"),
    url(r'^1\.0/scraper/usersearch$',   viewshandlers.usersearch_handler,     name="method_usersearch"),
    url(r'^1\.0/scraper/getruninfo$',   viewshandlers.runevent_handler,       name="method_getruninfo"),
    url(r'^1\.0/scraper/getinfo$',      viewshandlers.scraperinfo_handler,    name="method_getinfo"),

    # deprecated api
    url(r'^1\.0/datastore/search$', lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"no search is possible across different databases" }))),
    url(r'^1\.0/datastore/getkeys$', lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"use scraperwiki.datastore.sqlite with format=jsonlist and limit 0" }))),
    url(r'^1\.0/datastore/getdatabydate$', lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"use scraperwiki.datastore.sqlite with bounds on your date field" }))),
    url(r'^1\.0/datastore/getdatabylocation$', lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"use scraperwiki.datastore.sqlite bounds on the lat lng values" }))),
    url(r'^1\.0/geo/postcodetolatlng/$', lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"use the scraperwiki postcode view to do it" }))),
    url(r'^1\.0/datastore/getdata$',    lambda request: HttpResponse(json.dumps({ "error":"Sorry, this function has been deprecated.", "message":"use the scraperwiki sqlite api to do it" }))),

    # explorer redirects
    url(r'^1\.0/explore/scraperwiki.(?:scraper|datastore).(?P<shash>\w+)$',
                   lambda request, shash: HttpResponseRedirect("%s#%s" % (reverse('docsexternal'), shash))),
    url(r'^(?:1\.0|1\.0/explore/.*|)$',
                   lambda request: HttpResponseRedirect(reverse('docsexternal'))),

)