import numpy as np
import pytest

from sklearn.compose import make_column_transformer
from sklearn.datasets import load_breast_cancer, make_classification
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_recall_curve
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC, SVR
from sklearn.utils import shuffle

from sklearn.metrics import PrecisionRecallDisplay, plot_precision_recall_curve

# TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved
pytestmark = pytest.mark.filterwarnings(
    "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:"
    "matplotlib.*"
)

def test_precision_recall_display_validation(pyplot):
    """Check that we raise the proper error when validating parameters."""
    X, y = make_classification(
        n_samples=100, n_informative=5, n_classes=5, random_state=0
    )

    with pytest.raises(NotFittedError):
        PrecisionRecallDisplay.from_estimator(SVC(), X, y)

    regressor = SVR().fit(X, y)
    y_pred_regressor = regressor.predict(X)
    classifier = SVC(probability=True).fit(X, y)
    y_pred_classifier = classifier.predict_proba(X)[:, -1]

    err_msg = "PrecisionRecallDisplay.from_estimator only supports classifiers"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_estimator(regressor, X, y)

    err_msg = "Expected 'estimator' to be a binary classifier, but got SVC"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_estimator(classifier, X, y)

    err_msg = "{} format is not supported"
    with pytest.raises(ValueError, match=err_msg.format("continuous")):
        # Force `y_true` to be seen as a regression problem
        PrecisionRecallDisplay.from_predictions(y + 0.5, y_pred_classifier, pos_label=1)
    with pytest.raises(ValueError, match=err_msg.format("multiclass")):
        PrecisionRecallDisplay.from_predictions(y, y_pred_regressor, pos_label=1)

    err_msg = "Found input variables with inconsistent numbers of samples"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred_classifier[::2])

    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    y += 10
    classifier.fit(X, y)
    y_pred_classifier = classifier.predict_proba(X)[:, -1]
    err_msg = r"y_true takes value in {10, 11} and pos_label is not specified"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred_classifier)

# FIXME: Remove in 1.2
def test_plot_precision_recall_curve_deprecation(pyplot):
    """Check that we raise a FutureWarning when calling
    `plot_precision_recall_curve`."""

    X, y = make_classification(random_state=0)
    clf = LogisticRegression().fit(X, y)
    deprecation_warning = "Function plot_precision_recall_curve is deprecated"
    with pytest.warns(FutureWarning, match=deprecation_warning):
        plot_precision_recall_curve(clf, X, y)

@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
def test_precision_recall_display_plotting(pyplot, constructor_name, response_method):
    """Check the overall plotting rendering."""
    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    pos_label = 1

    classifier = LogisticRegression().fit(X, y)
    classifier.fit(X, y)

    y_pred = getattr(classifier, response_method)(X)
    y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label]

    # safe guard for the binary if/else construction
    assert constructor_name in ("from_estimator", "from_predictions")

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier, X, y, response_method=response_method
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y, y_pred, pos_label=pos_label
        )

    precision, recall, _ = precision_recall_curve(y, y_pred, pos_label=pos_label)
    average_precision = average_precision_score(y, y_pred, pos_label=pos_label)

    np.testing.assert_allclose(display.precision, precision)
    np.testing.assert_allclose(display.recall, recall)
    assert display.average_precision == pytest.approx(average_precision)

    import matplotlib as mpl

    assert isinstance(display.line_, mpl.lines.Line2D)
    assert isinstance(display.ax_, mpl.axes.Axes)
    assert isinstance(display.figure_, mpl.figure.Figure)

    assert display.ax_.get_xlabel() == "Recall (Positive label: 1)"
    assert display.ax_.get_ylabel() == "Precision (Positive label: 1)"

    # plotting passing some new parameters
    display.plot(alpha=0.8, name="MySpecialEstimator")
    expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})"
    assert display.line_.get_label() == expected_label
    assert display.line_.get_alpha() == pytest.approx(0.8)

@pytest.mark.parametrize(
    "constructor_name, default_label",
    [
        ("from_estimator", "LogisticRegression (AP = {:.2f})"),
        ("from_predictions", "Classifier (AP = {:.2f})"),
    ],
)
def test_precision_recall_display_name(pyplot, constructor_name, default_label):
    """Check the behaviour of the name parameters"""
    X, y = make_classification(n_classes=2, n_samples=100, random_state=0)
    pos_label = 1

    classifier = LogisticRegression().fit(X, y)
    classifier.fit(X, y)

    y_pred = classifier.predict_proba(X)[:, pos_label]

    # safe guard for the binary if/else construction
    assert constructor_name in ("from_estimator", "from_predictions")

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(classifier, X, y)
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y, y_pred, pos_label=pos_label
        )

    average_precision = average_precision_score(y, y_pred, pos_label=pos_label)

    # check that the default name is used
    assert display.line_.get_label() == default_label.format(average_precision)

    # check that the name can be set
    display.plot(name="MySpecialEstimator")
    assert (
        display.line_.get_label()
        == f"MySpecialEstimator (AP = {average_precision:.2f})"
    )

@pytest.mark.parametrize(
    "clf",
    [
        make_pipeline(StandardScaler(), LogisticRegression()),
        make_pipeline(
            make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression()
        ),
    ],
)
def test_precision_recall_display_pipeline(pyplot, clf):
    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    with pytest.raises(NotFittedError):
        PrecisionRecallDisplay.from_estimator(clf, X, y)
    clf.fit(X, y)
    display = PrecisionRecallDisplay.from_estimator(clf, X, y)
    assert display.estimator_name == clf.__class__.__name__

def test_precision_recall_display_string_labels(pyplot):
    # regression test #15738
    cancer = load_breast_cancer()
    X, y = cancer.data, cancer.target_names[cancer.target]

    lr = make_pipeline(StandardScaler(), LogisticRegression())
    lr.fit(X, y)
    for klass in cancer.target_names:
        assert klass in lr.classes_
    display = PrecisionRecallDisplay.from_estimator(lr, X, y)

    y_pred = lr.predict_proba(X)[:, 1]
    avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1])

    assert display.average_precision == pytest.approx(avg_prec)
    assert display.estimator_name == lr.__class__.__name__

    err_msg = r"y_true takes value in {'benign', 'malignant'}"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred)

    display = PrecisionRecallDisplay.from_predictions(
        y, y_pred, pos_label=lr.classes_[1]
    )
    assert display.average_precision == pytest.approx(avg_prec)

@pytest.mark.parametrize(
    "average_precision, estimator_name, expected_label",
    [
        (0.9, None, "AP = 0.90"),
        (None, "my_est", "my_est"),
        (0.8, "my_est2", "my_est2 (AP = 0.80)"),
    ],
)
def test_default_labels(pyplot, average_precision, estimator_name, expected_label):
    """Check the default labels used in the display."""
    precision = np.array([1, 0.5, 0])
    recall = np.array([0, 0.5, 1])
    display = PrecisionRecallDisplay(
        precision,
        recall,
        average_precision=average_precision,
        estimator_name=estimator_name,
    )
    display.plot()
    assert display.line_.get_label() == expected_label

@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method):
    # check that we can provide the positive label and display the proper
    # statistics
    X, y = load_breast_cancer(return_X_y=True)
    # create an highly imbalanced version of the breast cancer dataset
    idx_positive = np.flatnonzero(y == 1)
    idx_negative = np.flatnonzero(y == 0)
    idx_selected = np.hstack([idx_negative, idx_positive[:25]])
    X, y = X[idx_selected], y[idx_selected]
    X, y = shuffle(X, y, random_state=42)
    # only use 2 features to make the problem even harder
    X = X[:, :2]
    y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object)
    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        stratify=y,
        random_state=0,
    )

    classifier = LogisticRegression()
    classifier.fit(X_train, y_train)

    # sanity check to be sure the positive class is classes_[0] and that we
    # are betrayed by the class imbalance
    assert classifier.classes_.tolist() == ["cancer", "not cancer"]

    y_pred = getattr(classifier, response_method)(X_test)
    # we select the correcponding probability columns or reverse the decision
    #  function otherwise
    y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0]
    y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1]

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier,
            X_test,
            y_test,
            pos_label="cancer",
            response_method=response_method,
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y_test,
            y_pred_cancer,
            pos_label="cancer",
        )
    # we should obtain the statistics of the "cancer" class
    avg_prec_limit = 0.65
    assert display.average_precision < avg_prec_limit
    assert -np.trapz(display.precision, display.recall) < avg_prec_limit

    # otherwise we should obtain the statistics of the "not cancer" class
    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier,
            X_test,
            y_test,
            response_method=response_method,
            pos_label="not cancer",
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y_test,
            y_pred_not_cancer,
            pos_label="not cancer",
        )
    avg_prec_limit = 0.95
    assert display.average_precision > avg_prec_limit
    assert -np.trapz(display.precision, display.recall) > avg_prec_limit


#!/usr/bin/python3
if __name__ == "__main__":
    from sys import argv
    entry = argv[1:]
    size = len(entry)
    print("{:d} {:s}{:s}".
          format(size,
                 "arguments" if size != 1 else "argument",
                 "." if size == 0 else ":"))
    for count, arg in enumerate(entry, 1):
        print("{:d}: {:s}".format(count, arg))


from elasticsearch_dsl import (  # pylint: disable=no-name-in-module
    DocType,
    Keyword,
    Text,
)

class Article(DocType):
    title = Text(analyzer="snowball", fields={"raw": Keyword()})
    body = Text(analyzer="snowball")

    class Meta:
        index = "test-index"

dsl_create_statement = {
    "mappings": {
        "article": {
            "properties": {
                "title": {
                    "analyzer": "snowball",
                    "fields": {"raw": {"type": "keyword"}},
                    "type": "text",
                },
                "body": {"analyzer": "snowball", "type": "text"},
            }
        }
    },
}
dsl_index_result = (1, {}, '{"created": true}')
dsl_index_span_name = "Elasticsearch/test-index/article/2"
dsl_index_url = "/test-index/article/2"
dsl_search_method = "GET"


import json
from django.http import JsonResponse

def calculate_similarity(user1, user2):
    # age similarity
    age_difference = abs(user1['age'] - user2['age'])
    age_similarity = 1 / (age_difference + 1)  # handling divided by zero

    # interest similarity (common interest)
    shared_interests = set(user1['interests'].keys()) & set(user2['interests'].keys())
    interest_similarity = sum(
        user1['interests'][interest] * user2['interests'][interest]
        for interest in shared_interests
    )

    # calculating score after combining
    overall_similarity = (age_similarity + interest_similarity) / 2

    # print(overall_similarity)

    return overall_similarity

def recommend_friends(user_data, all_users_data):
    # similarity score for each user
    user_scores = []
    for user in all_users_data:
        if user['id'] != user_data['id']:
            similarity_score = calculate_similarity(user_data, user)
            user_scores.append((user, similarity_score))

    # users by similarity score in descending order
    user_scores.sort(key=lambda x: x[1], reverse=True)

    # Return the sorted list of users
    return [user_data for user_data, _ in user_scores]

# returning json file
def get_suggested_friends(request, user_id):
    # print(int(user_id))
    # loading json data
    with open('friends/users.json', 'r') as json_file:
        data = json.load(json_file)

    # Get the user data for the specified user_id

    # print(data['users'][0])

    data = data['users']
    # user_id = 5 # for testing
    user_data = None
    for user in data:
        if user['id'] == user_id:
            user_data = user
            break

    if not user_data:
        return JsonResponse({'error': 'User not found'}, status=404)

    # algorithm
    suggested_friends = recommend_friends(user_data, data)

    # top 5 suggested friends
    top_5_suggested_friends = suggested_friends[:5]

    context = {
        'user_data': user_data,
        'user_id': user_id,
        'suggested_friends': top_5_suggested_friends,
    }

    return JsonResponse(context)


import argparse
import jinja2
import json
import os
import string
import sys

# Schema: performance_models[data_mode][tps] = [model]
performance_models = {}

def add_performance_model(model):
    """
    Adds performance model to the list of performance models.
    """
    # process model values
    model["avgCpu"] = "{:.2f}".format(model["avgCpu"])
    model["avgMem"] = "{:.2f}".format(model["avgMem"])
    model["maxCpu"] = "{:.2f}".format(model["maxCpu"])
    model["maxMem"] = "{:.2f}".format(model["maxMem"])
    model["receivers"].sort()
    model["processors"].sort()
    model["exporters"].sort()
    model["receivers"] = ", ".join(model["receivers"])
    model["processors"] = ", ".join(model["processors"])
    model["exporters"] = ", ".join(model["exporters"])

    data_mode = model["dataMode"].capitalize()
    data_rate = model["dataRate"]

    if data_mode not in performance_models:
        performance_models[data_mode] = {}
    if data_rate not in performance_models[data_mode]:
        performance_models[data_mode][data_rate] = []

    performance_models[data_mode][data_rate].append(model)

def flatten_performance_models():
    """
    Flattens performance model into list of grouped models where each group
    corresponds to a table in the report.
    """
    models_list = []

    for data_mode, data_rates in performance_models.items():
        for data_rate, models in data_rates.items():
            model = {}
            model["data_mode"] = data_mode
            model["data_rate"] = data_rate
            # sort by name and type
            model["models"] = sorted(
                models, key=lambda x: (x["receivers"], x["testcase"], x["dataType"]))
            models_list.append(model)

    # sort by data mode and rate
    models_list = sorted(models_list, key=lambda x: (
        x["data_mode"], x["data_rate"]))
    return models_list

def get_benchmark_entry(model, data_mode, data_rate, value_field, unit, subgroup):
    benchmark_entry = {}
    benchmark_entry["name"] = model["testcase"]
    benchmark_entry["value"] = model[value_field]
    benchmark_entry["unit"] = unit
    benchmark_entry["extra"] = f"{data_mode} (TPS: {data_rate}) - {subgroup}"
    return benchmark_entry

def get_benchmark_data():
    """
    Splits models by testcase and groups by data mode, data rate, and field type.
    """
    benchmark_data = []

    for data_mode, data_rates in performance_models.items():
        for data_rate, models in data_rates.items():
            for model in models:
                benchmark_data.append(get_benchmark_entry(model, data_mode, data_rate, "avgCpu", "%", "Average CPU Usage"))
                benchmark_data.append(get_benchmark_entry(model, data_mode, data_rate, "avgMem", "MB", "Average Memory Usage"))

    return benchmark_data

if __name__ == "__main__":
    parser = argparse.ArgumentParser("Generate performance-report.md and performance-data.json from artifacts")
    parser.add_argument('-v', '--version', help="version to tag the report with", required=True)
    args = parser.parse_args()
    aoc_version = args.version

    templateLoader = jinja2.FileSystemLoader(searchpath="e2etest/templates/")
    env = jinja2.Environment(autoescape=jinja2.select_autoescape(['html', 'xml', 'tpl', 'yaml', 'yml']), loader=templateLoader)

    # get performance models from artifacts
    artifacts_path = "artifacts/"
    commit_id = ""
    collection_period = None
    testing_ami = ""
    for sub_dir in os.listdir(artifacts_path):
        with open(artifacts_path + sub_dir + "/performance.json") as f:
            model = json.load(f)
            commit_id = model["commitId"]
            collection_period = model["collectionPeriod"]
            testing_ami = model["testingAmi"]
            add_performance_model(model)

    models_list = flatten_performance_models()

    # render performance models into markdown
    template = env.get_template('performance_model.tpl')
    rendered_result = template.render({
        "aoc_version": aoc_version,
        "commit_id": commit_id,
        "collection_period": collection_period,
        "testing_ami": testing_ami,
        "models_list": models_list,
    })
    print(rendered_result)

    # write rendered result to report.md
    with open("performance-report.md", "w+") as f:
        f.write(rendered_result)

    # write benchmark-data.json
    with open("performance-data.json", "w+") as f:
        json.dump(get_benchmark_data(), f, indent=4)


from tkinter import *
root=Tk()
root.title("Sales Application")
root.geometry("800x800")
root.configure(background="lightblue")
label_month=Label(root)
label_profit=Label(root)
label_max=Label(root)
label_min=Label(root)
label_month.place(relx=0.5,rely=0.2,anchor=CENTER)
label_profit.place(relx=0.5,rely=0.3,anchor=CENTER)
label_max.place(relx=0.5,rely=0.5,anchor=CENTER)
label_min.place(relx=0.5,rely=0.7,anchor=CENTER)
month=("January","February","March","April","May","June","July","August","September","October","November","December")
label_month["text"]="Months:"+str(month)
profit=(22000,44000,77000,55000,88000,23000,100000,290000,190000,128000,458700,1100000)
label_profit["text"]="Show Profits"+str(profit)
def calMaxProfit():
    MaximumProfit=max(profit)
    MaximumProfitIndex=profit.index(MaximumProfit)
    MaximumProfitMonth=month[MaximumProfitIndex]
    label_max["text"]="maximum profit of "+str(MaximumProfit)+" In The Month Of "+str(MaximumProfitMonth)

def calMinProfit():
    MinimumProfit=min(profit)
    MinimumProfitIndex=profit.index(MinimumProfit)
    MinimumProfitMonth=month[MinimumProfitIndex]
    label_min["text"]="minimum profit of "+str(MinimumProfit)+" In The Month Of "+str(MinimumProfitMonth)

button_max_profit=Button(root,text="Maximum Profit Month",command=calMaxProfit)
button_max_profit.place(relx=0.5,rely=0.4,anchor=CENTER)
button_min_profit=Button(root,text="Minimum Profit Month",command=calMinProfit)
button_min_profit.place(relx=0.5,rely=0.6,anchor=CENTER)

root.mainloop()


# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################

flag=0
from gluon.tools import Crud
crud = Crud(db)
auth.settings.login_next=URL('Gallery')
auth.settings.logout_next=URL('index')
auth.settings.register_next = URL('Gallery')
crud.settings.delete_next = URL('Gallery')

if db(db.auth_group.role=='manager').isempty():
    group_id=auth.add_group('manager', 'can access the manage action')
    auth.add_permission(group_id, 'access to manage')
    auth.add_permission(group_id, 'create', db, 0)
    auth.add_permission(group_id, 'read', db, 0)
    auth.add_permission(group_id, 'delete', db, 0)
    auth.add_permission(group_id, 'update', db, 0)
    auth.add_permission(group_id, 'select', db, 0)

@auth.requires_permission('access to manage')
def manage():
    grid = SQLFORM.smartgrid(db.image)
    return dict(grid=grid)

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    images = db().select(db.image.ALL, orderby=db.image.title)
    return dict(images=images)

@auth.requires_login()
def Gallery():
    form = SQLFORM(db.image)
    if form.process().accepted:
        response.flash = 'The image is uploaded!'
    images = db().select(db.image.ALL, orderby=db.image.title)
    return dict(images=images, form=form)

def show():
    image = db.image(request.args(0)) or redirect(URL('index'))
    db.comment.image_id.default = image.id
    form = crud.create(db.comment, next=URL(args=image.id),
                     message='Your comment is posted!')
    comments = db(db.comment.image_id==image.id).select()
    return dict(image=image, comments=comments, form=form)

def delete():
    crud.delete(db.image, request.args(0))
    return dict()

def list_items():
    items = db().select(db.image.ALL, orderby=~db.image.votes)
    counter = db(db.auth_user.id > 0).count()
    return dict(items=items,counter=counter)

def download():
    return response.download(request, db)

def vote():
    item = db.image[request.vars.id]
    new_votes = item.votes
    l = item.voted
    if auth.user.username not in l:
        new_votes = item.votes + 1
        l = l + [str(auth.user.username)]
    item.update_record(voted=l)
    item.update_record(votes=new_votes)
    return str(new_votes)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())

def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)

def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()

@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id]
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs must be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())


from random import randint

def CompteurMotsLettres(string):
    """
    string: une chaine de caractères
    Renvoie un tuple de valeurs: (nombre de mots, liste du nombre de lettres par mot)
    """
    liste = [0]
    i = 0
    for lettre in string:
        if lettre is not ' ':
            liste[i] += 1
        else:
            liste.append(0)
            i += 1
    return i+1, liste

def MélangeurLetterCase(string):  # Rend tout sarcastique
    """
    string: une chaine de caractères
    Renvoie: NvString: la chaine de caractères modifiée
    """
    nvString = str()
    for lettre in string:
        randomInteger = randint(0, 1)
        if randomInteger == 0:
            nvString += lettre.upper()
        else:
            nvString += lettre.lower()
    return nvString

def RechercherMot(string, mot):
    """
    string: une chaine de caractères
    mot: une chaine de caractères
    Renvoie: indiceMot: l'indice de la première lettre du mot recherché dans string
    """
    indiceMot = int()
    lettreVerif = len(mot) * [False]
    for indiceLettre in range(len(string)):
        if string[indiceLettre] == mot[0]:  # On est tombé sur le mot
            indiceMot = indiceLettre
            for indice in range(len(mot)):
                if string[indiceLettre + indice] == mot[indice]:
                    lettreVerif[indice] = True
                else:
                    lettreVerif = len(mot) * [False]
                    break
            if False not in lettreVerif:
                return indiceMot

# tests

string = "Une chaîne de caractères" \
         " >-|-< To be or not to be"
print(CompteurMotsLettres(string))
for k in range(10):
    string = MélangeurLetterCase(string)
    print(string)

string = "sandwich, serpent, fourbe, et métalexicographie ! haha."

print(RechercherMot(string, "métalexicographie"))


def kod(k): #создаем функцию, увеличивающую элементы выбранной строки на 3
    for i in range(0, len(matriza)):
        matriza[n-1][i]=matriza[n-1][i]*3
    return matriza

matriza = [[2,5,7], #задаем матрицу
           [4,7,9],
           [1,2,0]]

n = int(input("Введите номер строки")) #получаем исходные данные
print(kod(n)) #выводим результат


import tkinter
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
FONT_NAME = "Ariel"

common_random_index = 0
to_learn_list = []

try:
    data = pandas.read_csv("./data/words_to_learn.csv")
    to_learn_list = data.to_dict(orient="records")  # With `orient="records"` returns list
except FileNotFoundError:
    original_data = pandas.read_csv("./data/french_words.csv")
    to_learn_list = original_data.to_dict(orient="records")  # With `orient="records"` returns list

def next_card():
    global common_random_index, flip_timer
    common_random_index = random.randint(0, len(to_learn_list)-1)
    window.after_cancel(flip_timer)
    canvas.itemconfig(canvas_image, image=front_img)
    french_word = to_learn_list[common_random_index]["French"]
    canvas.itemconfig(title_on_canvas, text = "French")
    canvas.itemconfig(word_on_canvas, text = french_word)
    flip_timer = window.after(3000, switch_to_english)

def switch_to_english():
    canvas.itemconfig(canvas_image, image=back_img)
    canvas.itemconfig(title_on_canvas, text="English")
    english_word = to_learn_list[common_random_index]["English"]
    canvas.itemconfig(word_on_canvas, text=english_word)

def know_card():
    to_learn_list.remove(to_learn_list[common_random_index])
    next_card()
    data = pandas.DataFrame(to_learn_list)
    data.to_csv("data/words_to_learn.csv", index=False)

window = tkinter.Tk()
window.title("Flash card")
window.config(bg=BACKGROUND_COLOR, pady=50, padx=50)

flip_timer = window.after(3000, switch_to_english)

# Canvas
canvas = tkinter.Canvas(width=800,height=526, bg=BACKGROUND_COLOR, highlightthickness=0)
front_img = tkinter.PhotoImage(file="./images/card_front.png")
back_img = tkinter.PhotoImage(file="./images/card_back.png")
canvas_image = canvas.create_image(400, 263, image=front_img)
## Canvas text: 1)Title, 2)Word
title_on_canvas = canvas.create_text(400, 150, text="Title", fill="black", font=(FONT_NAME, 40, "italic"))
word_on_canvas = canvas.create_text(400,263, text="Word", fill="black", font=(FONT_NAME,60, "bold"))
canvas.grid(column=0, row=0, columnspan=2)

# Buttons
wrong_img = tkinter.PhotoImage(file="./images/wrong.png")
right_img = tkinter.PhotoImage(file="./images/right.png")
the_dontknow_button = tkinter.Button(image=wrong_img, command=next_card, highlightthickness=0, border=0)
the_know_button = tkinter.Button(image=right_img, command=know_card, highlightthickness=0, border=0)
the_dontknow_button.grid(column=0, row=1)
the_know_button.grid(column=1, row=1)

next_card()

window.mainloop()


from scmm.problems.cite.configurations.common_conf import cv_params, standard_lgbm_cite_conf, original_dim
from scmm.problems.metrics import common_metrics
from scmm.problems.cite.concrete import LGBMwSVDCite

model_label = "lgbm_w_svd_baseline"
model_class = LGBMwSVDCite
seed = 0

embedder_params = {
    "seed": seed,
    "input_dim": original_dim,
    "output_dim": 64,
}

configuration = {
    "cv_params": cv_params,
    "estimator_params": standard_lgbm_cite_conf,
    "embedder_params": embedder_params,
    "seed": seed,
}


import pytest

from opentrons.protocol_api.module_validation_and_errors import (
    validate_heater_shaker_temperature,
    validate_heater_shaker_speed,
    InvalidTargetTemperatureError,
    InvalidTargetSpeedError,
)

@pytest.mark.parametrize("valid_celsius_value", [37.0, 37.1, 50, 94.99, 95])
def test_validate_heater_shaker_temperature(valid_celsius_value: float) -> None:
    """It should return the validated temperature value."""
    validated = validate_heater_shaker_temperature(celsius=valid_celsius_value)
    assert validated == valid_celsius_value

@pytest.mark.parametrize("invalid_celsius_value", [-1, 0, 36.99, 95.01])
def test_validate_heater_shaker_temperature_raises(
    invalid_celsius_value: float,
) -> None:
    """It should raise an error for invalid temperature values."""
    with pytest.raises(InvalidTargetTemperatureError):
        validate_heater_shaker_temperature(celsius=invalid_celsius_value)

@pytest.mark.parametrize("valid_rpm_value", [200, 201, 1000, 2999, 3000])
def test_validate_heater_shaker_speed(valid_rpm_value: int) -> None:
    """It should return the validated speed value."""
    validated = validate_heater_shaker_speed(rpm=valid_rpm_value)
    assert validated == valid_rpm_value

@pytest.mark.parametrize("invalid_rpm_value", [0, 199, 3001])
def test_validate_heater_shaker_speed_raises(invalid_rpm_value: int) -> None:
    """It should raise an error for invalid speed values."""
    with pytest.raises(InvalidTargetSpeedError):
        validate_heater_shaker_speed(rpm=invalid_rpm_value)


#
# CS1010S --- Programming Methodology
#
# Mission 8 Template
#
# Note that written answers are commented out to allow us to run your
# code easily while grading your problem set.

from ippt import *
import csv

##########
# Task 1 #
##########

# Function read_csv has been given to help you read the csv file.
# The function returns a tuple of tuples containing rows in the csv
# file and its entries.

# Alternatively, you may use your own method.

def read_csv(csvfilename):
    rows = ()
    with open(csvfilename) as csvfile:
        file_reader = csv.reader(csvfile)
        for row in file_reader:
            rows += (tuple(row), )
    return rows

def read_data(filename):
    rows = read_csv(filename)
    data = ()
    age_title = ()
    rep_title = ()
    count = 1
    for i in rows[1:]:
        age_title += (int(i[0]),)

    for i in range(1,len(rows[0])):
        rep_title += (int(rows[0][i]),)

    for row in rows[1:]:
        data_seq = ()
        for i in row[1:]:
            data_seq += (int(i),)
        data += ((data_seq),)

    return create_table(data, age_title, rep_title)

pushup_table = read_data("pushup.csv")
situp_table = read_data("situp.csv")
run_table = read_data("run.csv")

ippt_table = make_ippt_table(pushup_table, situp_table, run_table)

print("## Q1 ##")
# Sit-up score of a 24-year-old who did 10 sit-ups.
print(access_cell(situp_table, 24, 10))    # 0

# Push-up score of a 18-year-old who did 30 push-ups.
print(access_cell(pushup_table, 18, 30))   # 16

# Run score of a 30-year old-who ran 12 minutes (720 seconds)
print(access_cell(run_table, 30, 720))     # 36

# Since our run.csv file does not have data for 725 seconds, we should
# get None if we try to access that cell.
print(access_cell(run_table, 30, 725))     # None

##########
# Task 2 #
##########

def pushup_score(pushup_table, age, pushup):
    rows = read_csv('pushup.csv')
    if pushup > int(rows[0][len(rows[0])-1]):
        pushup = int(rows[0][len(rows[0])-1])
    elif pushup < int(rows[0][1]):
        pushup = int(rows[0][1])
    else:
        pushup = pushup
    return access_cell(pushup_table, age, pushup)

def situp_score(situp_table, age, situp):
    rows = read_csv('situp.csv')
    if situp > int(rows[0][len(rows[0])-1]):
        situp = int(rows[0][len(rows[0])-1])
    elif situp < int(rows[0][1]):
        situp = int(rows[0][1])
    else:
        situp = situp
    return access_cell(situp_table, age, situp)

def run_score(run_table, age, run):
    rows = read_csv('run.csv')
    if run > int(rows[0][len(rows[0])-1]):
        run = int(rows[0][len(rows[0])-1])
    elif run < int(rows[0][1]):
        run = int(rows[0][1])
    if run % 10 == 0:
        run = run
    else:
        run = run + 10 - run % 10
    return access_cell(run_table, age, run)

# print("## Q2 ##")
print(pushup_score(pushup_table, 18, 61))   # 25
print(pushup_score(pushup_table, 18, 70))   # 25
print(situp_score(situp_table, 24, 0))      # 0

print(run_score(run_table, 30, 720))        # 36
print(run_score(run_table, 30, 725))        # 35
print(run_score(run_table, 30, 735))        # 35
print(run_score(run_table, 30, 500))        # 50
print(run_score(run_table, 30, 1300))       # 0

##########
# Task 3 #
##########

def ippt_award(score):
    if score < 51:
        return 'F'
    elif score >= 51 and score < 61:
        return 'P'
    elif score >= 61 and score < 75:
        return 'P$'
    elif score >= 75 and score < 85:
        return 'S'
    elif score >= 85:
        return 'G'

print("## Q3 ##")
print(ippt_award(50))     # F
print(ippt_award(51))     # P
print(ippt_award(61))     # P$
print(ippt_award(75))     # S
print(ippt_award(85))     # G

##########
# Task 4 #
##########

def ippt_results(ippt_table, age, pushup, situp, run):
    score = (int(pushup_score(ippt_table[0],age,pushup)) + int(situp_score(ippt_table[1],age,situp)) + \
             int(run_score(ippt_table[2],age,run)))
    return (score,ippt_award(int(score)))

print("## Q4 ##")
print(ippt_results(ippt_table, 25, 30, 25, 820))      # (53, 'P')
print(ippt_results(ippt_table, 28, 56, 60, 530))      # (99, 'G')
print(ippt_results(ippt_table, 38, 18, 16, 950))      # (36, 'F')
print(ippt_results(ippt_table, 25, 34, 35, 817))      # (61, 'P$')
print(ippt_results(ippt_table, 60, 70, 65, 450))      # (100, 'G')

##########
# Task 5 #
##########
def make_training_program(rate_pushup, rate_situp, rate_run):
    def training_program(ippt_table, age, pushup, situp, run, days):
        pushup += days //rate_pushup
        situp += days // rate_situp
        run -= days // rate_run
        return (pushup, situp, run, ippt_results(ippt_table, age, pushup, situp, run))

    return training_program

print("## Q5 ##")
tp = make_training_program(7, 3, 10)
print(tp(ippt_table, 25, 30, 25, 820, 30))        # (34, 35, 817, (61, 'P$'))

##########
# Bonus  #
##########

def make_tp_bonus(rate_pushup, rate_situp, rate_run):
    def tp_bonus(ippt_table, age, pushup, situp, run, days):
        "Your solution here"

    return tp_bonus

tp_bonus = make_tp_bonus(7, 3, 10)

# Note: Depending on your implementation, you might get a different number of
# sit-up, push-up, and 2.4km run timing. However, the IPPT score and grade
# should be the same as the sample output.

# print(tp_bonus(ippt_table, 25, 20, 30, 800, 30))      # (20, 40, 800, (58, 'P'))
# print(tp_bonus(ippt_table, 25, 20, 30, 800, 2))       # (20, 30, 800, (52, 'P'))


import os

from robot.libraries.BuiltIn import BuiltIn
from xlrd import open_workbook

class ExcelUtility(object):
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    __instance = None

    @staticmethod
    def get_instance():
        if ExcelUtility.__instance == None:
            ExcelUtility()
        return ExcelUtility.__instance

    def __init__(self):
        self._builtin = BuiltIn()

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    # region Read Value Methods In Excel
    '''
    This method return list array of all value in sheet rows
    Examples:
    |Read All Rows Values| C:\\TestData\\DataFile.xlsx | SheetExample | ishaveheader=true
    '''

    def read_all_rows_values(self, file_path, sheet_name, isheader=True):
        workbook = self.__get_excel_file(file_path)
        isheader = bool(isheader)
        sheet = self.__get_excel_sheet(workbook, sheet_name, file_path)
        start_row = self.__is_has_header(isheader)
        max_row = sheet.nrows
        max_column = sheet.ncols
        data = []
        for row in range(start_row, max_row, 1):
            data.append(sheet.row_values(row, 0, max_column))
        return tuple(data)

    '''
    This method return list array of all value in column rows
    Examples:
    TestData.xlsx has sample data in sheet 'SheetExample'
    Column1  Column2 Column3
    A        B       C
    1        2       3
    Row3     Row3    Row3
    |Read All Rows In Column Index| C:\\TestData\\DataFile.xlsx | SheetExample | 2  |  True => ('C','3','Row3')
    |Read All Rows In Column Index| C:\\TestData\\DataFile.xlsx | SheetExample | 2  |  False => ('Column3','C','3','Row3')
    '''

    def read_all_rows_in_column_index(self, file_path, sheet_name, column_index=0, is_has_header=True):
        try:
            index = int(column_index)
            workbook = self.__get_excel_file(file_path)
            start_row = self.__is_has_header(is_has_header)
            sheet_data = self.__get_excel_sheet(workbook, sheet_name, file_path)
            max_row = sheet_data.nrows
            data = sheet_data.col_values(index, start_row, max_row)
            return tuple(data)
        except ValueError as e:
            raise ValueError("Column Index should be integer. [" + str(e.message) + "]")

    def read_cell_value(self, file_path, sheet_name, row_index, column_index):
        if type(column_index) is not int or type(row_index) is not int:
            raise ValueError("Column index and row index should be integer")
        workbook = self.__get_excel_file(file_path)
        sheet_data = self.__get_excel_sheet(workbook, sheet_name, file_path)
        cell_value = sheet_data.cell_value(row_index, column_index)
        return cell_value

    # endregion

    # region Get Status Excel File Methods
    def get_max_row(self, file_path, sheet_name):
        workbook = self.__get_excel_file(file_path)
        sheet_data = self.__get_excel_sheet(workbook, sheet_name, file_path)
        return sheet_data.nrows

    def get_max_column(self, file_path, sheet_name):
        workbook = self.__get_excel_file(file_path)
        sheet_data = self.__get_excel_sheet(workbook, sheet_name, file_path)
        return sheet_data.ncols

    def get_column_index_by_name(self, file_path, sheet_name, column_name, header_row=None):
        workbook = self.__get_excel_file(file_path)
        sheet_data = self.__get_excel_sheet(workbook, sheet_name, file_path)
        max_column = sheet_data.ncols
        first_column = 0
        if header_row is None:
            header_row = 0
        header = sheet_data.row_values(int(header_row), first_column, max_column)
        return header.index(column_name)

    def get_row_index_by_value(self, file_path, sheet_name, row_value, column_index):
        values_in_columns = self.read_all_rows_in_column_index(file_path, sheet_name, column_index, False)
        return values_in_columns.index(row_value)

    # endregion

    # region Private Methods
    def __get_excel_file(self, file_path):
        file_path = str(file_path).replace("\\", "\\\\")
        if os.path.exists(file_path) is False:
            file_dir = self.__get_project_path()
            file_path_with_project_path = file_dir + file_path
            if os.path.exists(file_path_with_project_path) is False:
                raise IOError('Can not find data file in ' + file_path_with_project_path + " or in " + file_path)
            workbook = open_workbook(file_path_with_project_path)
        else:
            workbook = open_workbook(file_path)
        return workbook

    def __get_excel_sheet(self, work_book, sheet_name, file_path):
        sheet_data = work_book.sheet_by_name(sheet_name)
        if (sheet_data.nrows > 1 or sheet_data.ncols > 1) is False:
            raise ValueError('Sheet "' + sheet_name + '" in ' + file_path + ' does not contains values')
        return sheet_data

    # TODO consider solution for config with relative path for data file
    def __get_project_path(self):
        if self._builtin.get_variable_value('${PROJECT_PATH_CMD}') is not None:
            return self._builtin.get_variable_value('${PROJECT_PATH_CMD}')
        if self._builtin.get_variable_value('${PROJECT_PATH}') is None:
            raise ValueError("Missing value for ${PROJECT_PATH} in Config.txt method Instance Global Variable")
        return self._builtin.get_variable_value('${PROJECT_PATH}')

    def __is_has_header(self, is_has_header):
        if bool(is_has_header) is True:
            return 1
        else:
            return 0

    # endregion
    ''''''


class CasillaDeVotacion:

    def __init__(self, identificador, pais):
        self._identificador = identificador
        self._pais = pais
        self._region = None

    @property
    def region(self):
        return self._region

    @region.setter
    def set_region(self, region):
        if region in self._pais:
            self._region = region
        else:
            raise ValueError(f'La region {region} no es válida en {self._pais}')

casilla = CasillaDeVotacion(123, ['Bogotá', 'Ibagué'])
print(casilla.region)
casilla.region = 'Bogotá'
print(casilla.region)


import random
from random import randint
from BaseAI import BaseAI
import time
import math

class getAvailableMoves:
    infinite = float('inf')

    def __init__(self, grid):
        self.parent = grid
        self.blankTiles = [2, 4]
        self.depth = 0
        self.valueAlpha = -getAvailableMoves.infinite
        self.valueBeta = getAvailableMoves.infinite
        self.maxDepth = 6

    def choice(self):
        largestValue = -getAvailableMoves.infinite
        bestChoice = None

        for availMove in self.parent.getAvailableMoves():
            nextBox = self.parent.clone()
            nextBox.availMove(availMove)
            value = self.minimum(nextBox)

            if largestValue < value:
                largestValue, bestChoice = value, availMove
        return bestChoice

    def maximum(self, grid):
        self.depth += 1
        moves = grid.getAvailableMoves()
        if moves == [] or self.depth > self.maxDepth:
            self.depth -= 1
            return self.examine(grid)

        valueAlphaBeta = -getAvailableMoves.infinite

        for availMove in moves:
            nextBox = grid.clone()
            nextBox.availMove(availMove)
            valueAlphaBeta = max(valueAlphaBeta, self.minimum(nextBox))
            if valueAlphaBeta >= self.valueBeta:
                self.depth -= 1
                return valueAlphaBeta

            self.valueAlpha = max(self.valueAlpha, valueAlphaBeta)

        self.depth -= 1
        return valueAlphaBeta

    def minimum(self, grid):
        self.depth += 1
        boxes = grid.getAvailableCells()
        if boxes == [] or self.depth > self.maxDepth:
            self.depth -= 1
            return self.examine(grid)

        valueAlphaBeta = getAvailableMoves.infinite
        for box in boxes:
            for boxValue in self.blankTiles:
                nextBox = grid.clone()
                nextBox.setBoxValue(box, boxValue)
                nextValue = self.maximum(nextBox)
                valueAlphaBeta = min(valueAlphaBeta, nextValue)
                if valueAlphaBeta <= nextValue:
                    self.depth -= 1
                    return valueAlphaBeta

        self.depth -= 1
        return valueAlphaBeta

    def examine(self, grid):
        matrixSeq =    [[32768, 16384, 8192, 4096  ],
                        [  256,   512, 1024, 2048  ],
                        [  128,    64,   32,   16  ],
                        [    1,     2,    4,    8  ]]

        depthValue = self.depth + 1

        valueDiff = 0

        mergeValue = 0

        totalValue = 0

        seqValue = 0

        for r1 in range(0, 4):

            for r2 in range(0, 4):
                totalValue += grid.map[r1][r2]

                if grid.map[r1][r2] == 0:
                    pass
                seqValue += matrixSeq[r1][r2] * grid.map[r1][r2]

                if r1 > 0:
                    valueDiff += alphaBeta(grid.map[r1][r2] - grid.map[r1 - 1][r2])

                    if grid.map[r1][r2] == grid.map[r1 - 1][r2]:
                        mergeValue += grid.map[r1][r2]

                if r2 > 0:
                    valueDiff += alphaBeta(grid.map[r1][r2] - grid.map[r1][r2 - 1])

                    if grid.map[r1][r2] == grid.map[r1][r2 - 1]:
                        mergeValue += grid.map[r1][r2]

                if r1 < 3:
                    valueDiff += alphaBeta(grid.map[r1][r2] - grid.map[r1 + 1][r2])

                    if grid.map[r1][r2] == grid.map[r1 + 1][r2]:
                        mergeValue += grid.map[r1][r2]

                if r2 < 3:
                    valueDiff += alphaBeta(grid.map[r1][r2] - grid.map[r1][r2 + 1])

                    if grid.map[r1][r2] == grid.map[r1][r2 + 1]:
                        mergeValue += grid.map[r1][r2]

        return depthValue * (totalValue + valueDiff + mergeValue + 2 * seqValue)

class IntelligentAgent(BaseAI):
    def getMove(self, grid):
        # Selects a random move and returns it
        moveset = grid.getAvailableMoves()
        return random.choice(moveset)[0] if moveset else None


import torch
import torch.nn as nn
import numpy as np

device = torch.device("cpu")
if torch.cuda.is_available():
  device = torch.device("cuda")

class YoloLoss(nn.Module):
  def __init__(self):
    super(YoloLoss, self).__init__()
    self.coords_scale = 1
    self.class_scale = 1
    self.rescore_confidence = False
    self.object_scale = 5
    self.no_object_scale = 1
    self.num_classes = 20
    self.one_hot_matrix = np.identity(self.num_classes)

  def forward(self, detector_mask, true_boxes, yolo_output, yolo_head_output, box_xywh):
    box_confidence, box_xy, box_wh, box_class_prob = yolo_head_output

    # box_xywh = box_xywh.to(device)
    batch_size, num_boxes, box_params = box_xywh.size()
    box_xywh = torch.reshape(box_xywh, (batch_size, 1, 1, 1, num_boxes, box_params))
    real_xy = box_xywh[..., 0:2]
    real_wh = box_xywh[..., 2:4]

    real_wh_half = real_wh / 2.
    real_mins = real_xy - real_wh_half
    real_maxes = real_xy + real_wh_half

    box_xy = box_xy.unsqueeze(4)
    box_wh = box_wh.unsqueeze(4)

    box_wh_half = box_wh / 2.
    box_mins = box_xy - box_wh_half
    box_maxes = box_xy + box_wh_half

    intersect_mins = torch.min(box_mins, real_mins)
    intersect_maxs = torch.max(box_maxes, real_maxes)
    intersect_wh = torch.max(intersect_maxs - intersect_mins , 0).values
    intersect_area = intersect_wh[..., 0]*intersect_wh[..., 1]

    box_area = box_wh[...,0]* box_wh[...,1]
    real_area = real_wh[...,0]*real_wh[...,1]

    union_areas = box_area + real_area - intersect_area
    iou_scores = intersect_area / union_areas
    best_iou = torch.max(iou_scores, axis = 4).values

    iou_scores = iou_scores.unsqueeze(-1)

    # detector_mask = detector_mask.squeeze(-1)

    object_detections = torch.ge(best_iou, 0.6)

    not_object_detections =  torch.logical_not(object_detections.float()).float()
    not_detection_mask = torch.logical_not(detector_mask.squeeze()).float()

    no_object_mask = self.no_object_scale* torch.mul(not_object_detections,not_detection_mask)
    no_object_loss = torch.sum( no_object_mask.unsqueeze(-1) * torch.pow(-box_confidence, 2))

    objects_loss = 0
    if self.rescore_confidence:
      objects_loss = torch.sum(self.object_scale * detector_mask * (torch.pow( torch.sub(best_iou, box_confidence), 2)))

    else:
      objects_loss = torch.sum(self.object_scale * detector_mask * torch.pow( 1 - box_confidence, 2))

    bbox_predictions = yolo_output[...,0:4]
    bbox_predictions = torch.cat((nn.Sigmoid()(yolo_output[...,:2]), yolo_output[...,2:4]), dim=-1)
    bbox_gt = true_boxes[...,0:4]

    coords_loss= torch.sum(self.coords_scale* detector_mask * torch.pow(torch.sub(bbox_gt, bbox_predictions), 2))

    all_classes_in_batch = true_boxes[:,:,:,:, -1].cpu().data.numpy().astype(np.int32)

    one_hot_batch_classes = torch.Tensor(self.one_hot_matrix[all_classes_in_batch])
    one_hot_batch_classes = one_hot_batch_classes.to(device)
    class_loss = torch.sum(self.class_scale* detector_mask * torch.pow(torch.sub(one_hot_batch_classes, box_class_prob), 2))

    total_loss = (coords_loss + class_loss + objects_loss + no_object_loss)/batch_size

    return total_loss


from pathlib import Path
import sys

import openpyxl
import pandas as pd
import pytest

try:
    from ..RynekPierwotny import Raport, localisation
except:
    sys.path.append(str(Path(sys.path[0]).parent))
    from RynekPierwotny import Raport, localisation

def test_raport_read_excel(tmpdir):
    df = pd.DataFrame({"Mieszkanie1": [30, "A"], "Mieszkanie2": [40, "B"]})
    fake_file_path = Path(tmpdir / "test_file.xlsx")
    df.to_excel(fake_file_path, index=False)
    function_result = Raport.zad_1(fake_file_path)
    assert df.equals(function_result)

def test_raport_read_excel_raises_exception():
    with pytest.raises(Exception):
        fake_file_path = Path()
        function_result = Raport.zad_1(fake_file_path)
        assert function_result

@pytest.mark.skip(
    reason="""If you want to test this function you need to append your API key,
than you are free to take of the skip fixture"""
)
def test_localisation():
    assert localisation("Marszałkowska 10") == (52.22, 21.02)


#!/usr/bin/env python
import json
import os

if __name__ == "__main__":
    with open(os.path.join(".vscode", "c_cpp_properties.json"), "r") as f:
        props = json.load(f)
    configs = {}
    for config in props["configurations"]:
        configs[config["name"]] = config

    for dirname, _, filenames in os.walk("firmware"):
        if "project_description.json" in filenames:
            parts = dirname.split(os.sep)
            if parts[-1] != "bootloader":
                project_name = f"{parts[1]}:{parts[-1]}"
                with open(os.path.join(dirname, "project_description.json"), "r") as f:
                    desc = json.load(f)
                configs[project_name] = {
                    "name": project_name,
                    "includePath": sorted([
                        "${workspaceFolder}/" + os.path.relpath(os.path.join(comp["dir"], dir), os.curdir).replace(os.sep, "/")
                        for comp in desc["build_component_info"].values()
                        for dir in comp["include_dirs"]
                    ] + [f"${{workspaceFolder}}/{dirname.replace(os.sep, '/')}/config"]),
                    "cStandard": "c17",
                    "cppStandard": "c++17",
                    "intelliSenseMode": "gcc-x86",
                    "compilerPath": "${workspaceFolder}/" + os.path.relpath(desc["c_compiler"], os.curdir).replace(os.sep, "/")
                }

    props = {
        "configurations": list(configs.values()),
        "version": 4
    }
    with open(os.path.join(".vscode", "c_cpp_properties.json"), "w") as f:
        json.dump(props, f, indent=4, sort_keys=True)
        f.write("\n")


from PySide import QtCore, QtGui , QtUiTools
import os
import sys

#Loading UI Files
loader = QtUiTools.QUiLoader()
CURR = sys.path[0]
ui = loader.load(os.path.join(CURR, "UIFiles/interface.ui"))
dataSetLoader = loader.load(os.path.join(CURR, "UIFiles/datasetviewer.ui"))
screenshot = loader.load(os.path.join(CURR, "UIFiles/screeshot.ui"))

def setTitle():
    ui.setWindowTitle('Brain Visualizer')

setTitle()


def checkio(words):
    alpha_count = 0
    if len(words) > 0 and len(words) < 100:
        for word in words.split(" "):
            if word.isalpha() == True:
                alpha_count += 1
                if alpha_count >= 3:
                    return True
            elif word.isdecimal() == True:
                alpha_count = 0
        return False

# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio("Hello World hello") == True, "Hello"
    assert checkio("He is 123 man") == False, "123 man"
    assert checkio("1 2 3 4") == False, "Digits"
    assert checkio("bla bla bla bla") == True, "Bla Bla"
    assert checkio("Hi") == False, "Hi"


cores = {'azul': '\033[1:34m',
         'red': '\033[1:31m',
         'verde':'\033[1:32m',
         'amarelo': '\033[1:33m',
         'negrito': '\033[1m',
         'cls': '\033[m'}
print(f'{cores["amarelo"]}-={cores["cls"]}' * 25)
print(f"{cores['verde']}{'TUPLA ANÁLISE DE VALORES':^50}{cores['cls']}")
print(f'{cores["amarelo"]}-={cores["cls"]}' * 25)
num = []
cont = 0
n1 = int(input('DIGITE UM NÚMERO: '))
n2 = int(input('DIGITE OUTRO NÚMERO: '))
n3 = int(input('DIGITE MAIS UM NÚMERO: '))
n4 = int(input('DIGITE O ÚLTIMO NÚMERO: '))
num.extend((n1, n2, n3, n4))
tupla = num
for nove in tupla:
    nove = tupla.count(9)
print(f'O VALOR 9 APARECEU {nove} VEZES.')
try:
    tres = tupla.index(3)
except:
    tres = 0
if tres == 0:
    print('O VALOR 3 NÃO FOI DIGITADO EM NENHUMA POSIÇÃO.')
else:
    print(f'O VALOR 3 APARECEU NA {tres + 1}ª POSIÇÃO.')
par = []
for p in range(0, len(num)):
    if num[p] % 2 == 0:
       par.append(num[p])
print(f'ENTRE OS VALORES DIGITADOS, ESTES SÃO PARES: {", ".join(map(str, par))}')
#print(num)
#print(f'Essa é a tupla: {tupla}')


#-*- coding: utf8 -*-

from django import template

from staff.models import EducationDepartments, OfficialDepartments, PersonToPosition

register = template.Library()

@register.inclusion_tag('education_departments_list.html', takes_context=True)
def educationDepartments(context):
    departments = EducationDepartments.objects.all()
    return {'departments': departments}

@register.inclusion_tag('core_contacts.html', takes_context=True)
def coreContacts(context):
    departments = []
    deansoffice = OfficialDepartments.objects.get(title='Деканат')
    departments.append({
        'title': u'Деканат',
        'longtitle': u'Деканат Факультета управления и информационных технологий СПбГТУ',
        'department': deansoffice,
        'persons': []
    })
    for title in ['Декан факультета', 'Заместители декана']:
        do_persons_departments = OfficialDepartments.objects.get(title=title)
        do_positions = do_persons_departments.department_positions.all()
        do_persons = PersonToPosition.objects.filter(position__in=do_positions)
        for person in do_persons:
            departments[0]['persons'].append(person)

    edu_departments = EducationDepartments.objects.order_by('index')

    for department in edu_departments:
        departments.append({
            'title': u"Кафедра %s" % (department.abbr),
            'longtitle': u"Кафедра «%s»" % (department.title),
            'department': department,
            'persons': PersonToPosition.objects.filter(education_department=department.id)
        })

    return {'departments': departments}


from dataclasses import dataclass, field
import sigma
from typing import Optional, Set

@dataclass
class ProcessingItemTrackingMixin:
    """
    Provides attributes and methods for tracking processing items applied to Sigma rule objects
    like detection items and conditions.
    """
    applied_processing_items : Set[str] = field(init=False, compare=False, default_factory=set)

    def add_applied_processing_item(self, processing_item : Optional["sigma.processing.pipeline.ProcessingItem"]):
        """Add identifier of processing item to set of applied processing items."""
        if processing_item is not None and processing_item.identifier is not None:
            self.applied_processing_items.add(processing_item.identifier)

    def was_processed_by(self, processing_item_id : str) -> bool:
        """Determines if detection item was processed by a processing item with the given id."""
        return processing_item_id in self.applied_processing_items


"""pecp_to_pcp

Revision ID: 839af60c1e2d
Revises: cfd5ea7ea8ef
Create Date: 2023-04-10 12:20:50.350342

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '839af60c1e2d'
down_revision = 'cfd5ea7ea8ef'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("UPDATE milestones SET name = REPLACE(name, 'PECP', 'PCP')")
    op.execute("UPDATE milestone_types SET name = REPLACE(name, 'PECP', 'PCP')")
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("UPDATE milestones SET name = REPLACE(name, 'PCP', 'PECP')")
    op.execute("UPDATE milestone_types SET name = REPLACE(name, 'PCP', 'PECP')")
    # ### end Alembic commands ###


def solution(arr):
  rows = []
# traversing through each element in array
  for height in arr:
    found = -1
# checking with already available rows
    for i in range(len(rows)):
      if height < rows[i]:
        found = i
# if that height can be put in already available rows
    if found != -1:
      rows[found] = height
# else create a new row
    else:
      rows.append(height)
# return nno of rows
  return len(rows)

print("Number of rows required: ", solution([5,4,3,6,8,7,1,2,1,2,1,2]))


def run(ctx, args):
  # Use
  # --compiler-filter=quicken to make sure that the test is not compiled AOT
  # and to make sure the test is not compiled  when loaded (by PathClassLoader)
  # -Xjitsaveprofilinginfo to enable profile saving
  # -Xusejit:false to disable jit and only test profiles.
  # -Xjitinitialsize:32M to prevent profiling info creation failure.
  ctx.default_run(
      args,
      Xcompiler_option=["--compiler-filter=quicken"],
      runtime_option=[
          "-Xcompiler-option --compiler-filter=quicken",
          "-Xjitinitialsize:32M",
          "-Xjitsaveprofilinginfo",
          "-Xusejit:false",
          "-Xps-profile-boot-class-path",
      ])


liczba = -1
suma = 0
ile = -1
while liczba != 0:
    liczba = int(input("Podaj liczbe: "))
    suma += liczba
    ile += 1

if ile == 0:
    print("Nie wprowadzono danych")
else:
    print(suma/ile)

#jesli user poda cos innego niz liczba to mozna by zrobic na instrukcji wczytywania i konwersji blok try a w except wpisac np brek


from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponse
from .models import Message

# Create your views here.
@csrf_exempt
def write(request):
    if request.method == 'POST':
        ds18b20value = request.POST.get('ds18b20value', '')
        dht11value = request.POST.get('dht11value', '')
        mq2value = request.POST.get('mq2value', '')
        lightvalue = request.POST.get('lightvalue', '')
        Message.objects.filter(id=1).update(ds18b20value=ds18b20value,
                                            dht11value=dht11value,
                                            mq2value=mq2value,
                                            lightvalue=lightvalue)
        return HttpResponse('success')

def show(request):
    if request.user.is_superuser:
        show_list = Message.objects.all()
        print(show_list)

        context = {}
        context['show_list'] = show_list
        return render(request, 'sensor/show.html', context)
    else:
        return render(request, 'error.html')

def ajax(request):
    ds18b20value = Message.objects.all().values('ds18b20value')[0].get('ds18b20value')
    dht11value = Message.objects.all().values('dht11value')[0].get('dht11value')
    mq2value = Message.objects.all().values('mq2value')[0].get('mq2value')
    lightvalue = Message.objects.all().values('lightvalue')[0].get('lightvalue')
    context = {}
    context['ds18b20value'] = ds18b20value
    context['dht11value'] = dht11value
    context['mq2value'] = mq2value
    context['lightvalue'] = lightvalue
    return JsonResponse(context)


"""
Functions for meetings
"""

import datetime
import uuid

from bson import ObjectId as BaseObjectId

from app.schemas.meetings import MeetingProperty, MeetingDetail

async def create_meeting(db, property_data, property_option: MeetingProperty):
    """
    Create meeting and add it to the current property
    """

    now = datetime.datetime.now()
    meeting = MeetingDetail(
        uuid=str(uuid.uuid4()),
        event_id=property_data.get("event_id"),
        property_id=property_data.get("id"),
        starts_at=property_data.get("starts_at"),
        ends_at=property_data.get("ends_at"),
    ).dict()

    meeting = {
        **meeting,
        "created_at": now,
        "updated_at": now
    }

    meeting_result = await db.meetings.insert_one(meeting)
    await db[property_option.value].update_one(
        {"_id": BaseObjectId(property_data.get("id"))},
        {"$set": {"meeting": meeting_result.inserted_id}}
    )

    return {**property_data, "meeting": meeting_result.inserted_id}


# from flask import Flask, jsonify
# from ably import AblyRest

# app = Flask(__name__)
# ably = AblyRest('WnIRrA.xFlb_Q:m93uJLI1BHRHAotTYtV0XY8keVa6isAZRT8GhXZMbXg')

# @app.route('/data/<path:ticker_symbols>')
# def get_data(ticker_symbols):
#     data = {}
#     for ticker_symbol in ticker_symbols.split(','):
#         channel = ably.channels.get(ticker_symbol)
#         history_items = channel.history().items
#         print(f"Data for {ticker_symbol}: {history_items}")  # Check the AblyRest API data
#         data[ticker_symbol] = history_items
#     return jsonify(data)

# @app.route('/')
# def home():
#     return "Welcome to my realtime stock dashboard!"

# if __name__ == "__main__":
#     app.run(debug=True)

from fastapi import FastAPI
from ably import AblyRest
import asyncio

app = FastAPI()
ably = AblyRest('WnIRrA.HAR2lw:wdRstrLRRq9Y4i8ype6_QfllGjPOY8oD-yruzK7CbVM')

@app.get('/data/{ticker_symbols}')
async def get_data(ticker_symbols: str):
    data = {}
    for ticker_symbol in ticker_symbols.split(','):
        channel = ably.channels.get(ticker_symbol)
        history_items = await channel.history().items
        print(f"Data for {ticker_symbol}: {history_items}")  # Check the AblyRest API data
        if not history_items:
            print(f"No data returned for {ticker_symbol}")
        data[ticker_symbol] = history_items
    print(f"Data to be returned: {data}")  # Check the data before it's returned
    return data


from typing import List, Optional, Tuple

import boto3
import botocore

from johnsnowlabs.py_models.install_info import InstallSuite, LocalPy4JLib
from johnsnowlabs.utils.boto_utils import BotoException
from johnsnowlabs.utils.s3_utils import create_bucket, upload_file_to_s3

def create_glue_bucket(boto_session: boto3.Session, bucket=None):
    """Create a bucket for EMR cluster logs
    :param boto_session: Boto3 session
    :param bucket: Bucket name
    """
    try:
        sts_client = boto_session.client("sts")
        account_id = sts_client.get_caller_identity()["Account"]
        region = boto_session.region_name
        if not bucket:
            bucket = f"aws-glue-assets-{account_id}-{region}"

        return create_bucket(boto_session=boto_session, bucket=bucket)

    except botocore.exceptions.ClientError as e:
        if e.response["Error"]["Code"] == "BucketAlreadyOwnedByYou":
            return bucket
        raise BotoException(
            code=e.response["Error"]["Code"], message=e.response["Error"]["Message"]
        )

def upload_pylibs_jars_to_glue_bucket(
    boto_session: boto3.Session, install_suite: InstallSuite, bucket: Optional[str]
) -> Tuple[List[str], List[str]]:
    """Uploads jars and python packages to glue bucket
    :param boto_session: Boto3 session
    :param install_suite: Install suite
    :param bucket: Bucket name
    :return: List of uploaded jars and python packages
    """
    if not boto_session:
        raise ValueError("Boto3 session is required")

    libs: List[LocalPy4JLib] = [install_suite.nlp, install_suite.ocr, install_suite.hc]
    uploaded_python_packages = []
    uploaded_jars = []
    for lib in libs:
        if lib:
            if lib.java_lib:
                print(f"ðŸ‘· Uploading {lib.java_lib.file_name} ...")
                s3_jar_file_name = upload_file_to_s3(
                    boto_session=boto_session,
                    file_path=lib.get_java_path(),
                    bucket=bucket,
                    file_name=f"assets/jars/{lib.java_lib.file_name}",
                )
                uploaded_jars.append(s3_jar_file_name)
                print(f"âœ… Successfully uploaded to {s3_jar_file_name}")
            if lib.py_lib:
                print(f"ðŸ‘· Uploading {lib.py_lib.file_name} ...")
                pypi_jar_file_name = upload_file_to_s3(
                    boto_session=boto_session,
                    file_path=lib.get_py_path(),
                    bucket=bucket,
                    file_name=f"assets/packages/{lib.py_lib.file_name}",
                )
                uploaded_python_packages.append(pypi_jar_file_name)
                print(f"âœ… Successfully uploaded to {pypi_jar_file_name}")
    return [uploaded_jars, uploaded_python_packages]


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
dir = "userdata/sessions"
import glob
import os
import json
import cgi
print('Content-Type: text-plain; charset=utf-8\r\n\r\n')

def listdirectory(path):
    fichier=[]
    l = glob.glob(path+'/*')
    for i in l:
        if os.path.isdir(i): fichier.extend(listdirectory(i))
        else: fichier.append(i)
    return fichier

result = []

listfic = listdirectory(dir)
for fic in listfic:
    statinfo = os.stat(fic)
    if statinfo.st_size > 0:
		# on recherche les extensions .txt
        extension = os.path.splitext(fic)
        if extension[1] == '.txt':
            session = dict()
            session["fichier"] = fic
            session["stats"] = statinfo.st_size
            T = fic.split(".")
            session["filename"] = T[0]
            session["filetype"] = T[1]
            # on recherche un "-" dans le nom du fichier
            T = session["filename"].split("-")
            if len(T) > 1:
                session["fileroot"] = T[0]
                session["filetime"] = T[1]
                FD = open(fic, 'r')
                info = FD.read()
                T = info.split(";") # c'est au format csv avec le séparateur ";"
                session["date_session"] = T[0]
                session["heure_session"] = T[1]
                session["circuit_session"] = T[2]
                session["infos"] = info
                FD.close()
                result.append(session)
json_str = json.dumps(result)
print(json_str)


# -*- coding:utf-8 -*-
# 单纯的使用 logging 将 数据 写入 .log 文件
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='test.log',
                    # w 为覆盖 ， a 为追加
                    filemode='w')
test = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in xrange(5):
    logging.debug(test)


"""
Define the World class
"""
from random import choice
import numpy as np
import os

from traveller_utils.tables import *
from traveller_utils.enums import WorldTag, WorldCategory, TradeGood, Contraband, Bases, Title, LandTitle
from traveller_utils.utils import roll, d100, roll1d
from traveller_utils.trade_goods import ALL_GOODS, TradeGoods
from traveller_utils.name_gen import create_name
from traveller_utils.person import Person
from traveller_utils.coordinates import HexID

WorldTag._value2member_map_.keys()

star_hex = list(range(10))
star_hex+=[
    "A",
    "B",
    "C",
    "E",
    "F",
    "G",
    "H",
    "I"
]

star_hex = [str(entry) for entry in star_hex]

class Government:
    def __init__(self, dict_entry:dict, is_faction=False):
        self._gov_type = dict_entry["type"]
        self._desc = dict_entry["description"]
        self._what = choice(dict_entry["examples"])
        self._contraband = []
        for entry in dict_entry["contraband"]:
            for good in Contraband:
                if entry.lower() in good.name.lower():
                    self._contraband.append(good)
        self._strength = factions.access(roll() if is_faction else 12)
        self._is_faction = is_faction

    @property
    def gov_type(self):
        return self._gov_type
    @property
    def description(self):
        return self._desc
    @property
    def title(self):
        return self._what
    @property
    def contraband(self):
        return self._contraband

    @property
    def strength(self):
        return self._strength

    @property
    def is_faction(self):
        return self._is_faction

    @classmethod
    def unpack(cls, packed:dict):
        new = cls(packed, is_faction=packed["is_faction"])
        new._what= packed["examples"]
        new._strength = packed["strength"]
        return new

    def pack(self)->dict:
        out = {
            "type":self._gov_type,
            "description":self._desc,
            "examples":self._what,
            "contraband":[entry.name for entry in self._contraband],
            "strength":self._strength,
            "is_faction":self._is_faction
        }
        return out

class World:
    def __init__(self, generate =True, modifier = 0):
        """
            Initialize a minimal world, generate full world if `generate`
        """
        self._name = ""
        self._fuel = False
        self._tags = []
        self._size= 0
        self._atmosphere= 0
        self._pressure = -1
        self._temperature=0
        self._trade_score = 0
        self._biosphere = 0
        self._population_raw=0
        self._population=0
        self._hydro=0
        self._tech_level=0
        self._government_raw=0
        self._government=Government(govs[0], False)
        self._law_level=0
        self._factions=[]
        self._starport_raw=0
        self._liege = None
        self._liege_name = None
        self._vassals = []
        self._vassal_names = []
        self._services = []
        self._retailers = []
        self._has_gas_giant = False
        self._persistent_passengers={
            "high":[],
            "middle":[],
            "basic":[],
            "low":[],
        }
        self._generated = False
        self._passengers ={
            "high":[],
            "middle":[],
            "basic":[],
            "low":[],
        }
        self._category =[WorldCategory.Common,]
        self._title = Title.Lord

        if generate:
            self.populate(modifier=modifier)

    @property
    def desireability(self):
        mod = 1

        if self._population_raw<=1:
            mod -= 4
        elif self._population_raw==6 or self._population_raw==7:
            mod += 1
        elif self._population_raw>8:
            mod += self._population_raw-8 + 3

        letter = self.starport_cat
        if letter=="A":
            mod +=2
        elif letter=="B":
            mod +=1
        elif letter=="E":
            mod -=1
        elif letter=="X":
            mod -=3
        if WorldCategory.red_zone in self._category:
            mod -=4
        if WorldCategory.amber_zone in self._category:
            mod -=1

        return mod

    @property
    def retailers(self):
        return self._retailers

    @property
    def liege(self)->HexID:
        return self._liege
    @property
    def liege_world(self)->'World':
        return self._liege_name

    def set_liege(self, hid:HexID, which:'World'):
        self._liege = hid
        self._liege_name = which

    @property
    def wealth(self):
        score = int(self.trade_score / 5)
        if self._population_raw>8:
            score+=1
        if self._starport_raw>8:
            score+=1
        if self._starport_raw>10:
            score+=1
        if self._tech_level>10:
            score+=1
        if self._tech_level>14:
            score+=2
        if self._tech_level<4:
            score -= 4
        if self._tech_level<8:
            score -= 2
        return score

    @property
    def trade_score(self):
        return self._trade_score
    def iterate_ts(self):
        self._trade_score = self._trade_score + 1
    def set_ts(self, value):
        self._trade_score = value

    @property
    def title(self):
        return self._title

    @property
    def vassals(self)->'list[HexID]':
        return self._vassals
    @property
    def vassals_worlds(self)->'list[World]':
        return self._vassal_names

    def add_vassal(self, hid:HexID, which:'World'):
        self._vassals.append(hid)
        self._vassal_names.append(which)

    def fuel_present(self):
        """
            0 - none
            1 - gas giant
            2 - unrefined
            3 - refined
        """
        cat = self.starport_cat
        if cat=="A" or cat=="B":
            fuel = 3
        elif cat=="C" or cat=="D":
            fuel = 2
        elif self._has_gas_giant:
            fuel = 1
        elif cat=="E" or cat=="X":
            fuel = 0
        else:
            raise NotImplementedError("This should be un-reachable!")
        return fuel

    def populate(self,name="",rng=None,
                atmosphere=-1, temperature=-1,biosphere=-1,
                population=-1, tech_level=-1,*world_tag,modifier=0, **kwargs) -> None:

        if not isinstance(world_tag,(list,tuple)):
            raise TypeError("World Tags should be type {}, not {}".format(list, type(world_tag)))

        if name=="":
            self._name=create_name("planet")
        else:
            self._name = name

        self._fuel=False

        if "seed" in kwargs.keys():
            np.random.seed(kwargs["seed"])

        self._tags = []

        for entry in world_tag:
            if isinstance(entry, str):
                parsed = WorldTag.__getitem__(entry)
            elif not isinstance(entry, WorldTag):
                raise TypeError("Cannot index with type {}, try an {}".format(type(entry, int)))
            else:
                parsed = entry
            self._tags.append(parsed)

        if len(world_tag)==0:
            self._tags=[ choice(list(WorldTag)) for i in range(2) ]

        self._size = roll(rng, mod=-2)

        self._atmosphere = roll(rng, -7+self._size) if atmosphere==-1 else atmosphere
        if self._atmosphere<0:
            self._atmosphere =0
        self._pressure = -1

        atmo_t_mods=[
            0,0, -2,-2,-1,-1, 0,0,1,1,2,6,6,2,-1,2,2
        ]

        self._temperature = roll(rng, atmo_t_mods[self._atmosphere]) if temperature==-1 else temperature
        self._biosphere = roll(rng) if biosphere==-1 else biosphere
        self._population_raw = roll(rng, -2) if population==-1 else population
        self._population_raw += modifier
        if self._size<2 or self._atmosphere==0:
            self._hydro = 0
        else:
            self._hydro = roll(rng)
            if self._atmosphere < 2 or (self._atmosphere>9 and self._atmosphere < 13):
                self._hydro -= 4

            if self._temperature>=12:
                self._hydro -= 6
            elif self._temperature>=10:
                self._hydro -= 2

            self._hydro= min([10, max([self._hydro, 0])])

        if self._population_raw==0:
            self._population=0
            self._tech_level = 0
            self._government = Government(govs[0], False)
            self._government_raw = 0
            self._law_level = 0
            self._factions = []

        else:
            self._population = int(round(np.random.rand(),4)*(10**self._population_raw))

            self._government_raw = roll(rng, -7+self._population_raw) + modifier
            if self._population_raw>3 and self._government_raw==0:
                self._government_raw = np.random.randint(1,3)
            self._government_raw = min([len(govs)-1, self._government_raw])
            self._government = Government(govs[self._government_raw], False)
            self._law_level = roll(rng, -7+ self._government_raw)

            faction_mod = 0
            if self._government_raw==7:
                faction_mod = 1
            elif self._government_raw>=10:
                faction_mod = -1
            if self._government_raw<2:
                self._factions = []
            else:
                self._factions = [Government(govs[min([roll(rng, -7+self._population_raw), len(govs)-1])], True) for i in range(np.random.randint(1,4)+faction_mod)]

        star_mod = 0
        if self._population_raw>=8:
            star_mod = 1
        if self._population_raw>=10:
            star_mod=2
        if self._population_raw<=4:
            star_mod=-1
        if self._population_raw<=2:
            star_mod=-2

        self._starport_raw = roll(rng, star_mod) + modifier
        if self._starport_raw>= len(starports_str):
            self._starport_raw = len(starports_str)-1
        if self._population_raw==0:
            self._tech_level=0
        else:
            self._tech_level = np.random.randint(1,7)+ self._get_tl_mod()
            self._tech_level = min([15, self._tech_level])

        self._tech_level = self._tech_level if tech_level==-1 else tech_level

        self._category =[WorldCategory.Common,]

        self.update_category()

        self._has_gas_giant = roll() < 10

        naval_roll = roll()
        scout_roll = roll()
        research_roll = roll()
        tas_roll = roll()

        tas_lim = 14
        naval_lim = 14
        scout_lim = 14
        res_lim = 14
        if starports_str[self._starport_raw]=="A":
            tas_lim = 0
            naval_lim = 7
            scout_lim = 9
            res_lim = 7
        elif starports_str[self._starport_raw]=="B":
            tas_lim = 0
            naval_lim = 7
            scout_lim = 7
            res_lim = 9
        elif starports_str[self._starport_raw]=="C":
            tas_lim = 9
            scout_lim = 7
            res_lim = 9
        elif starports_str[self._starport_raw]=="D":
            scout_lim = 6

        if scout_roll>scout_lim:
            self._services.append(Bases.Scout)
        if naval_roll>naval_lim:
            self._services.append(Bases.Naval)
        if tas_roll>tas_lim:
            self._services.append(Bases.TAS)
        if research_roll>res_lim:
            self._services.append(Bases.Research)

    @property
    def services(self):
        return self._services

    def pack(self)->dict:
        liege_packed = "" if self._liege is None else self.liege.pack()
        packed = {
            "liege":liege_packed,
            "vassals":[ entry.pack() for entry in self._vassals ],
            "name":self._name,
            "title":self._title.value,
            "tags":[entry.name for entry in self._tags],
            "size":self._size,
            "atmo":self._atmosphere,
            "pressure":self._pressure,
            "temperature":self._temperature,
            "bio":self._biosphere,
            "raw_population":self._population_raw,
            "population":self._population,
            "hydro":self._hydro,
            "trade_score":self._trade_score,
            "tech":self._tech_level,
            "law":self._law_level,
            "government":self._government.pack(),
            "gov_raw":self._government_raw,
            "factions":[fact.pack() for fact in self._factions],
            "generated":self._generated,
            "gas_giant":self._has_gas_giant,
            "starport_raw":self._starport_raw,
            "services":[entry.name for entry in self._services],
            "persistent_pass":{
                key:[entry.pack() for entry in self._persistent_passengers[key]] for key in self._persistent_passengers.keys()
            },
            "passengers":{
                key:[entry.pack() for entry in self._passengers[key]] for key in self._passengers.keys()
            }
        }

        return packed

    @classmethod
    def unpack(cls, packed:dict):
        new = cls(
            generate=False
        )
        new._liege = None if packed["liege"]=="" else HexID.unpack(packed["liege"])
        new._vassals = [HexID.unpack(entry) for entry in packed["vassals"]]
        new._name=packed["name"]
        new._title=Title(packed["title"])
        new._tags=[WorldTag.__getitem__(entry) for entry in packed["tags"]]
        new._size=packed["size"]
        new._atmosphere=packed["atmo"]
        new._pressure=packed["pressure"]
        new._temperature=packed["temperature"]
        new._biosphere=packed["bio"]
        new._population_raw=packed["raw_population"]
        new._population=packed["population"]
        new._hydro=packed["hydro"]
        new._tech_level=packed["tech"]
        new._trade_score = packed["trade_score"]
        new._law_level=packed["law"]
        new._has_gas_giant = packed["gas_giant"]
        new._government=Government.unpack(packed["government"])
        new._government_raw=packed["gov_raw"]
        new._generated=packed["generated"]
        new._services=[Bases.__getitem__(entry) for entry in packed["services"]]
        new._factions=[Government.unpack(entry) for entry in packed["factions"]]
        new._starport_raw=packed["starport_raw"]
        new._passengers={
            key:[Person.unpack(entry) for entry in packed["passengers"][key]] for key in packed["passengers"].keys()
        }
        new._persistent_passengers={
            key:[Person.unpack(entry) for entry in packed["persistent_pass"][key]] for key in packed["persistent_pass"].keys()
        }
        new.update_category()

        return new

    @property
    def generated(self):
        return self._generated
    def generate_passengers(self, steward_mod:int)->'dict[Person]':
        if self._generated:
            return self._passengers

        for key in self._persistent_passengers:
            self._generated = True
            self._passengers[key] = []
            mod = 0
            mod += steward_mod
            if key=="high":
                mod -=4
            elif key=="low":
                mod +=1

            mod += self.desireability

            die_roll = roll(mod=mod)
            if die_roll<0:
                n_passengers = 0
            if die_roll>len(passenger_table)-1:
                n_passengers = sum(np.random.randint(1,7,10))
            else:
                n_passengers =  sum(np.random.randint(1,7,passenger_table[die_roll]))
            if len(self._persistent_passengers[key])>0:
                self._passengers[key] += self._persistent_passengers[key]
            self._passengers[key] += [Person.generate() for i in range(n_passengers - len(self._persistent_passengers[key]))]
        return self._passengers

    def world_profile(self, location):
        profile = str(location)+" "
        profile+=starports_str[self._starport_raw]
        profile+=star_hex[self._size]
        profile+=star_hex[self._atmosphere]
        profile+=star_hex[self._hydro]
        profile+=star_hex[self._population_raw]
        profile+=star_hex[self._government_raw]
        profile+=star_hex[min([self._law_level, len(star_hex)-1])]
        profile+=star_hex[self._tech_level]
        return profile

    def list_available_goods(self)->'set[TradeGoods]':
        """
        Returns a set of available goods. We use a set here so that each entry is unique
        """
        avail = []
        present_names = []

        for category in self._category:
            # take all the trade goods, and filter out only the ones that are available for this category
            extra = list(filter(lambda entry: entry.is_available(category), list(ALL_GOODS.values())))

            for entry in extra:
                if entry.name not in present_names:
                    present_names.append(entry.name)
                    avail.append(entry)

        return avail

    def get_purchase_price(self, entry:TradeGoods, modifier=0):
        """
            Returns the purchase price of the given trade good on this world
            Returns -1 if the good is not available here
        """

        return entry.sample_purchase_price(self.category, modifier)

        if any(entry.is_available(wc) for wc in self._category ):
            return entry.sample_purchase_price(self.category, modifier)
            #return min([entry.sample_purchase_price(wc, modifier) for wc in self.category])
        return -1

    def get_sale_price(self, entry:TradeGoods, modifier=0):

        return entry.sample_sale_price(self._category, modifier)

    def update_category(self):
        if self._population<1000:
            self._title = Title.Lord
        elif self._population<1e5:
            self._title = Title.Count
        elif self._population<1e8:
            self._title = Title.Duke
        elif self._population<1e11:
            self._title = Title.King
        else:
            self._title = Title.Emperor

        wealth = self.wealth
        if wealth>8:
            self._title = Title.Emperor
            print(self.name)
        elif wealth>=6:
            self._title = Title.King
        elif wealth>=4:
            self._title = Title.Duke
        elif wealth>=2:
            self._title = Title.Count
        else:
            self._title = Title.Lord

        self._category = []
        if self._atmosphere==0 and self._size==0 and self._hydro==0:
            self._category.append(WorldCategory.Asteroid)

        if self._atmosphere>=4 and self._atmosphere<=9:
            if self._hydro>3 and self._hydro<9:
                if self._population_raw>4 and self._population_raw<8:
                    self._category.append(WorldCategory.Agricultural)

        if self._population_raw==0:
            self._category.append(WorldCategory.Barren)

        if self._hydro==2 and self._atmosphere>2:
            self._category.append(WorldCategory.Desert)

        if self._atmosphere>9 and self._hydro>0:
            self._category.append(WorldCategory.Fluid_Oceans)

        if self._atmosphere==5 or self._atmosphere==6 or self._atmosphere==8:
            if self._size>=6 and self._size<=8:
                    if self._hydro>4 and self._hydro<8:
                        self._category.append(WorldCategory.Garden)

        if self._population_raw>=9:
            self._category.append(WorldCategory.High_Pop)

        if self._tech_level>11:
            self._category.append(WorldCategory.High_Tech)

        if self._hydro>1 and self._atmosphere<2:
            self._category.append(WorldCategory.Ice_Capped)

        if self._population_raw>8:
            if self._atmosphere<3 or self._atmosphere==4 or self._atmosphere==7 or self._atmosphere==9:
                self._category.append(WorldCategory.Industrial)

        if self._population_raw<4:
            self._category.append(WorldCategory.Low_Pop)

        if self._tech_level<6:
            self._category.append(WorldCategory.Low_Tech)

        if self._population_raw>=6:
            if self._hydro<4:
                if self._atmosphere<4:
                    self._category.append(WorldCategory.Non_Agricultural)

            if self._government_raw>3 and self._government_raw<10:
                if self._atmosphere==6 or self._atmosphere==8:
                    if self._population_raw<9:
                        self._category.append(WorldCategory.Rich)
        else:
            self._category.append(WorldCategory.Non_Industrial)

        if self._hydro<4:
            if self._atmosphere<6 and self._atmosphere>1:
                self._category.append(WorldCategory.Poor)

        if self._hydro>9:
            self._category.append(WorldCategory.Water_World)

        if len(self._category)==0:
            self._category=[WorldCategory.Common]

    @property
    def gravity(self)->float:
        """
            Returns the approximate acceleration at the surface
        """
        sizes = [
            0, 0.05,0.15,0.25,0.35,0.45,0.7,0.9,1.0,1.25,1.4
        ]
        assert len(sizes)==11

        return sizes[self._size]

    @property
    def pressure(self)->float:

        pressures = [
            0.00, 0.05,
            0.1,0.3,
            0.43, 0.65,
            1.0, 1.0,
            1.5, 2.5,
            -1, -1,
            -1, 8.2,
            0.3, -1
        ]
        self._pressure = pressures[self._atmosphere]

        if self._pressure==-1:
            self._pressure = np.random.rand()*2
            self._pressure = float(str(self._pressure)[:4])
        return self._pressure

    @property
    def category(self)->'list[WorldCategory]':
        return self._category

    @property
    def atmosphere(self):
        return self._atmosphere

    @property
    def temperature(self):
        return self._temperature

    @property
    def biosphere(self):
        return self._biosphere

    @property
    def tech_level(self):
        return self._tech_level

    @property
    def tags(self):
        return self._tags

    @property
    def weapons_banned(self):
        if self._law_level>10:
            return law_levels[-1]
        else:
            return law_levels[self._law_level]
    def approach_check(self):
        die_roll = roll()
        if die_roll<self._law_level:
            return True
        else:
            return False

    @property
    def government(self):
        return self._government

    @property
    def factions(self):
        return self._factions

    @property
    def atmosphere_str(self)->str:
        what= "{} atmosphere.".format(atmo.access(self._atmosphere).lower())
        return  what[0].upper() + what[1:].lower()

    @property
    def hydro_str(self)->str:
        return "The planet " + hydro.access(self._hydro).lower()

    @property
    def temperature_str(self)->str:
        return "The planet is " + temp.access(self._temperature)

    @property
    def population_str(self)->str:
        return "It has a population of approximately {}".format(self._population)

    @property
    def tech_level_str(self)->str:
        return "{}".format(tl.access(self._tech_level))

    @property
    def biosphere_str(self)->str:
        return "The biosphere is " + bio.access(self._biosphere)

    @property
    def starport_cat(self):
        return starports_str[self._starport_raw]

    @property
    def starports_str(self)->str:
        return "{} - {}".format(starports_str[self._starport_raw], starports_quality[self._starport_raw])

    @property
    def name(self):
        return "The {} of {}".format(LandTitle(self._title.value).name, self._name)

    def description(self)->str:
        """
        Returns a string describing this world!
        """
        x= ", ".join([self.atmosphere_str, self.temperature_str, self.population, self.tech_level_str, self.biosphere_str])+". \n\n"
        return x

    def _pretty_fmt(self, what):
        return what[0].upper() + what[1:].lower() + ". \n\n"

    def _make_nice(self, what:str):
        return what.replace("_", " ")

    def full_line(self)->str:
        output = "# The Planet {}\n\n".format(self.name)
        sentence = "\n    ".join(["Characteristics: ", self.atmosphere_str, self.temperature_str, self.population_str, self.tech_level_str, self.biosphere_str])
        sentence += "\n\n"
        output += sentence

        tags = "\n    ".join(["World Tags: "] + [tag.name for tag in self.tags])
        output += tags + "\n\n"

        cats = "\n    ".join(["World Categories: "] + [tag.name for tag in self.category])
        output += cats+ "\n\n"

        goods = "\n    ".join(["Available goods: "] + [self._make_nice(good.name) for good in self.list_available_goods()])
        goods += "\n\n"
        output+= goods

        return output

    def get_image_name(self)->str:
        if self._size<2 or self._atmosphere<2:
            return "RClassC" + str(choice(range(3)) +1)

        if self._temperature>12:
            return "RClassA1"
        elif self._temperature>11:
            return "RClassB1"
        elif self._temperature<3:
            return "RClassP"+str(choice([1,2]))

        if self._hydro<2:
            return "RClassH1"
        elif self._hydro<3:
            return "RClassH3"
        elif self._hydro<4:
            return "RClassH2"
        elif self._hydro<9:
            if self._temperature<5:
                return "RClassL"+str(choice([1,2]))
            return "RClassM"+str(choice(range(5))+1)
        else:
            return "RClassO" + str(choice([1,2]))

    def _get_tl_mod(self):
        mod = 0
        if self._starport_raw<3:
            mod-=4
        elif self._starport_raw==10:
            mod+=6
        elif  self._starport_raw==11:
            mod+=4
        elif self._starport_raw==12:
            mod+=2

        if self._size==0 or self._size==1:
            mod+=2
        elif self._size>1 and self._size<5:
            mod+=1

        if self._atmosphere <4 or self._atmosphere>9:
            mod+=1

        if self._hydro==0:
            mod+=1
        elif self._hydro==9:
            mod+=1
        elif self._hydro==10:
            mod+=2

        if self._population_raw>0 and self._population_raw<6:
            mod +=1
        elif self._population_raw==8:
            mod +=1
        elif self._population==9:
            mod+=2
        elif self._population_raw==10:
            mod += 4

        if self._government_raw==0:
            mod +=1
        elif self._government_raw==5:
            mod +=1
        elif self._government_raw==7:
            mod +=2
        elif self._government_raw==13 or self._government_raw==14:
            mod -=2

        return mod

    def notes(self):
        serv = ""

        if self.starport_cat=="A":
            fuel = "Refined"
            berth_scale = 1000
            fuel_cost = "at Cr500 per ton."
            facility = "Fully functioning capital-class shipyard. \n Repair"
        elif self.starport_cat=="B":
            fuel = "Refined"
            berth_scale = 500
            fuel_cost = "at Cr500 per ton."
            facility = "Shipyard capable of building all craft up to 5,000 tons. \n Repair"
        elif self.starport_cat=="C":
            fuel = "Unrefined"
            fuel_cost = "at Cr100 per ton."
            berth_scale = 100
            facility = "Shipyard capable of building all craft below 100 tons. \n Repair"
        elif self.starport_cat=="D":
            fuel = "Unrefined"
            berth_scale = 10
            fuel_cost = "at Cr100 per ton."
            facility = "Limited Repair. Can only fix hull damage."
        else:
            fuel = "No"
            berth_scale = 0
            facility = "No repair facilities."
            fuel_cost=0

        serv += "{} fuel available {}\n".format(fuel, fuel_cost)
        serv+=facility+"\n"
        serv+="Berthing costs Cr{}.".format(roll1d()*berth_scale)
        serv+="\n\n"
        if Bases.Naval in self.services:
            serv+="Has naval base. Ex-Naval Travellers may meet Contacts or Allies here, and mercenary Travellers can try to pick up work. "
            serv+="Naval bases also have an advanced hospital, though it is normally available only to naval personnel. "
            serv+="Travellers may also be able to purchase navy-surplus weapons here.\n\n"
        if Bases.Scout in self.services:
            serv+="The scout base here offers refined fuel and supplies to scout ships (including retired scout ships obtained by retired scouts). "
            serv+="They are also an excellent place to pickup rumors and news. "
            serv+="\n\n"
        if Bases.TAS in self.services:
            serv+="Has a Traveller's Aid Society Hostel, where Travellers with TAS memberships and their guests can stay. "
            serv+="In the Third Imperium TAS Hostels offer medical facilities for members, as well as supplies and luxuries notnormally available on most worlds. TAS Hostels are a good source of rumors and passengers. "
            serv+="\n\n"
        if Bases.Research in self.services:
            serv+="A Research base is here. It might be a weapons testing facility, or a solar observatory, or part of a secret Imperial project. "
            serv+="A research base may have Contacts or Allies of Travellers who followed a Scholar career. "
            serv+="Such bases may have advanced medical facilities. "
            serv+="\n\n"

        serv+="Wealth Score: {}\n".format(self.wealth)
        serv+="Trade Score: {}\n".format(self._trade_score)

        return serv