# -*- coding: utf_8 -*-

from interpreter.exceptions import CommandNotInThisModule
from interpreter.structs import Result

import sqlite3

class Dictionary(object):
    def __init__(self):
        pass

    def initDbConnection(self):
        self.connection = sqlite3.connect("./modules/vocable/vocables.db")
        self.cursor = self.connection.cursor()

    def getCommands(self):
        return {
            "dictionary.commands" : self.commands,

            "dictionary.hebrew" : self.hebrew,
            "dictionary.greek" : self.greek,
            "dictionary.aramaic" : self.aramaic,
            "dictionary.akkadian" : self.akkadian,
        }

    def interpreter(self, command, args, queue):
        print("args:", args)

        commands = self.getCommands()

        return commands.get(command, self.commandNotFound)(command, args)

    def commandNotFound(self, c, a):
        raise CommandNotInThisModule("command not found in module quran")

    def commands(self, c, a):
        dic = self.getCommands()

        commands = sorted(dic.items())

        all_commands = []
        for key in commands:
            line = str(key).split(",")[0]
            all_commands.append(str(line[2:-1]))

        result_object = Result()
        result_object.category = "list"
        result_object.payload = all_commands
        return result_object

    def hebrew(self, c, args):
        return self.dictionaryHelper(args, 'hebrew')
    def greek(self, c, args):
        return self.dictionaryHelper(args, 'greek')
    def aramaic(self, c, args):
        return self.dictionaryHelper(args, 'aramaic')
    def akkadian(self, c, args):
        return self.dictionaryHelper(args, 'akkadian')

    def dictionaryHelper(self, args, language):
        result_object = Result()

        query = """
        SELECT display, gloss
        FROM {0}
        WHERE display LIKE ? OR gloss LIKE ?
        """.format(language)
        try:
            param = '%'+str(args[0])+'%'
        except IndexError:
            result_object.error = 'invalid parameter'
        else:
            self.initDbConnection()
            self.cursor.execute(query, [param, param])
            result_object.payload = self.cursor.fetchall()

        result_object.category = "itemized"
        result_object.name = "dictionary result"
        return result_object


# Task 1
grade = int(input("Enter Grade: "))
if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("E")

# Task 2
dayRented = input("Enter the Day on which DVD is rented: ")
daysKept = int(input("Enter the days customer kept the DVD: "))
time = input("Enter the time at which DVD is returned (HH AM/PM): ")
condition = input("Was the DVD scratched? (Y/N): ")
# Checking Time for return
if time[-2:-1] == "P" and int(time[0:2]) >= 8:
    daysKept += 1
# Calculating bill
bill = daysKept * 1.59
# Discount and Extra Charge for Damage
if condition == "Y":
    bill += 1
if dayRented == "Sunday":
    if condition == "Y":
        bill += 1
    bill -= bill * 0.3
elif dayRented == "Thursday":
    bill -= bill * 0.5

print("The bill is: {:.2f} $".format(bill))

# Task 3
list1 =[]
for i in range(0,10,1):
    list1.append(int(input("Enter number {} : ".format(i+1))))
i=0
while i<len(list1):
    if list1[i] == 6:
        print("Index = {}".format(i))
        break
    i +=1
if (i == len(list1)):
    print("Not Found")

# List of Dictionaries of List and Dictionaries
# In [10]:
l1=[
        {"name":"Waleed",
         "Marks":{"math":30,"english":80,"phy":80},
         "hobbies": ["cricket","book reading"]
        },

        {"name":"Bilal",
         "Marks":{"math":45,"english":89,"phy":70},
         "hobbies": ["painting","traveling"]
        }
    ]
print(l1)

Q1/Classes/Class06 Revision till dictionaries.py


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

import os, datetime
import torch, pyro, numpy as np
torch.set_default_tensor_type(torch.cuda.FloatTensor)
from torch import tensor
import torch.nn as nn
import torchvision.transforms.functional as TF

import click

import swyft

DEVICE = 'cuda'

from utils import *

@click.command()
@click.option("--m",    type=int, default = 12, help="Exponent of subhalo mass.")
@click.option("--nsub", type=int, default = 1, help="Number of subhaloes.")
@click.option("--nsim", type=int, default = 100, help="Number of simulations to run.")

def run(m, nsub, nsim):
    time_start = datetime.datetime.now()

    # Set definitions (should go to click)
    system_name = "ngc4414"

    # Set utilities
    sim_name, sim_path = get_sim_path(m, nsub, nsim, system_name)

    torch.set_default_tensor_type(torch.cuda.FloatTensor)  # HACK
    CONFIG = get_config(system_name, str(nsub), str(m))
    torch.set_default_tensor_type(torch.FloatTensor)

    torch.set_default_tensor_type(torch.cuda.FloatTensor)  # HACK
    ppd = CONFIG.ppd()['model_trace'].nodes
    torch.set_default_tensor_type(torch.FloatTensor)

    prior, uv, lows, highs = get_prior(CONFIG)
    L = CONFIG.kwargs["defs"]["nx"]
    print(f'Image has L = {L}.')

    assert nsub == CONFIG.umodel.alphas["main"].sub.nsub
    if m > 4:
        assert all([i == pow(10, m) for i in ppd['main/sub/m_sub']['value']])
    else:
        print(f'm = {m} <= 0!', ppd['main/sub/m_sub']['value'])

    # Create Store
    pnames = [f'{z}_{i+1}' for i in range(nsub) for z in ['x', 'y', 'm']]
    print(pnames)
    simulator = swyft.Simulator(model = lambda v: simul(v, CONFIG),
                                pnames = pnames,
                                sim_shapes={"image": (L, L)})

    store = swyft.DirectoryStore(path = sim_path, simulator = simulator)
    store.add(nsim, prior)
    store.simulate()

    print('Done!')
    print(f"Total creating time is {str(datetime.datetime.now() - time_start).split('.')[0]}!")

if __name__ == "__main__":
    run()


import time
import urllib.request
import urllib.error
import urllib.parse
import logging
import json
from arbitrage import config
from arbitrage.fiatconverter import FiatConverter
from arbitrage.utils import log_exception

class Market(object):
    def __init__(self, currency, cryptowatch_code=None):
        self.name = self.__class__.__name__
        self.currency = currency
        self.cryptowatch_code = cryptowatch_code
        self.cryptowatch_price = 0
        self.depth_updated = 0
        self.update_rate = 60
        self.fc = FiatConverter()
        self.fc.update()

    def get_cryptowatch_price(self):
        if not self.cryptowatch_code:
            return

        url = ('https://api.cryptowat.ch/markets/' +
            self.name.lower().replace('usd', '').replace('eur', '') +
            '/' + self.cryptowatch_code + '/price')

        res = urllib.request.urlopen(url)
        jsonstr = res.read().decode('utf8')
        try:
            price = json.loads(jsonstr)
        except Exception:
            logging.error("Cryptowatch %s - Can't parse json: %s" % (self.name, jsonstr))
        self.cryptowatch_price = self.fc.convert(price["result"]["price"], self.currency , "USD")

    def double_ckeck_price(self, price, direction, allowed_percent=None):
        if self.cryptowatch_price == 0:
            self.get_cryptowatch_price()

        allowed_percent = allowed_percent if allowed_percent else 10

        if abs(price - self.cryptowatch_price) > self.cryptowatch_price * allowed_percent / 100:
            logging.error("Big diff. @%s depth price(%s) vs Cryptowatch price %f / %f" %
                          (self.name, direction, price, self.cryptowatch_price))
            return False

        return True

    def get_depth(self):
        timediff = time.time() - self.depth_updated
        if timediff > self.update_rate:
            self.ask_update_depth()
        timediff = time.time() - self.depth_updated
        if timediff > config.market_expiration_time:
            logging.warning('Market: %s order book is expired' % self.name)
            self.depth = {'asks': [{'price': 0, 'amount': 0}], 'bids': [
                {'price': 0, 'amount': 0}]}
        return self.depth

    def convert_to_usd(self):
        if self.currency == "USD":
            return
        for direction in ("asks", "bids"):
            for order in self.depth[direction]:
                # self.double_ckeck_price(order["price"], direction, order)
                # we don't do it here any more
                order["price"] = self.fc.convert(order["price"], self.currency, "USD")

    # there are some prices inside the market depth that are ment to de destabilize the market
    # clear them out
    def sort_out_market_crush_prices(self):
        new_depth = {'asks': [], 'bids': []}
        for direction in ("asks", "bids"):
            for order in self.depth[direction]:
                if self.double_ckeck_price(order["price"], direction, 30):
                    new_depth[direction].append(order)

        if len(new_depth["ask"]) != len(self.depth["ask"]) or len(new_depth["bids"]) != len(self.depth["bids"]):
            logging.warning('Market: %s removed some market crush crush items' % self.name)

        self.depth = new_depth

    def ask_update_depth(self):
        try:
            self.update_depth()
            self.convert_to_usd()
            self.get_cryptowatch_price()
            self.depth_updated = time.time()
        except (urllib.error.HTTPError, urllib.error.URLError) as e:
            logging.error("HTTPError, can't update market: %s" % self.name)
            log_exception(logging.DEBUG)
        except Exception as e:
            logging.error("Can't update market: %s - %s" % (self.name, str(e)))
            log_exception(logging.DEBUG)

    def get_ticker(self):
        depth = self.get_depth()
        res = {'ask': 0, 'bid': 0}
        if len(depth['asks']) > 0 and len(depth["bids"]) > 0:
            res = {'ask': depth['asks'][0],
                   'bid': depth['bids'][0]}
        return res

    ## Abstract methods
    def update_depth(self):
        pass

    def buy(self, price, amount):
        pass

    def sell(self, price, amount):
        pass


def f(x):
    return (x * x) + (6 * x) + 12

def svenn(x0, t):
    x = [x0]
    k = 0
    f1 = f(x[0] - t)
    f2 = f(x[0])
    f3 = f(x[0] + t)
    if f1 >= f2 and f3 >= f2:
        a0 = x[0] - t
        b0 = x[0] + t
    elif f1 <= f2 and f3 <= f2:
        print('Выберите другое x0')
    else:
        if f1 >= f2 >= f3:
            delta = t
            a0 = x[0]
            x.append(x[0] + t)
            k = 1
        elif f1 <= f2 <= f3:
            delta = 0 - t
            b0 = x[0]
            x.append(x[0] - t)
            k = 1
        while True:
            x.append(x[k] + pow(2, k) * delta)
            if f(x[k + 1]) < f(x[k]) and delta == t:
                a0 = x[k]
                k += 1
            if f(x[k + 1]) < f(x[k]) and delta == -t:
                b0 = x[k]
                k += 1
            if f(x[k + 1]) >= f(x[k]):
                if delta == t:
                    b0 = x[k + 1]
                    break
                elif delta == -t:
                    a0 = x[k + 1]
                    break
    return a0, b0

def popolam(a0, b0, e):
    global x
    a = [a0]
    b = [b0]
    xc = []
    y = []
    z = []
    L = []
    k = 0
    while True:
        xc.append((a[k] + b[k]) / 2)
        L.append(abs(b[k] - a[k]))
        fxc = f(xc[k])
        y.append(a[k] + L[k] / 4)
        z.append(b[k] - L[k] / 4)
        fy = f(y[k])
        fz = f(z[k])
        if fy < fxc:
            b.append(xc[k])
            a.append(a[k])
            xc.append(y[k])
            L.append(abs(b[k + 1] - a[k + 1]))
        else:
            if fz < fxc:
                a.append(xc[k])
                b.append(b[k])
                xc.append(z[k])
            elif fz >= fxc:
                a.append(y[k])
                b.append(z[k])
                xc.append(xc[k])
        if L[(k + 1)] <= e:
            x = xc[(k + 1)]
            break
        elif L[(k + 1)] > e:
            k += 1

def dihotomia(a0, b0, e, m):
    global x
    a = [a0]
    b = [b0]
    y = []
    z = []
    L = []
    k = 0
    L.append(abs(b[k] - a[k]))
    while True:
        y.append((a[k] + b[k] - m) / 2)
        fy = f(y[k])
        z.append((a[k] + b[k] + m) / 2)
        fz = f(z[k])
        if fy <= fz:
            a.append(a[k])
            b.append(z[k])
            L.append(abs(b[k + 1] - a[k + 1]))
        else:
            a.append(y[k])
            b.append(b[k])
            L.append(abs(b[k + 1] - a[k + 1]))
        if L[k + 1] <= e:
            x = (a[k + 1] + b[k + 1]) / 2
            break
        else:
            k += 1

def gold(a0, b0, e):
    global x
    a = [a0]
    b = [b0]
    y = []
    z = []
    k = 0
    y.append(a[k] + 0.38196 * (b[k] - a[k]))
    z.append(a[k] + b[k] - y[k])
    while True:
        fy = f(y[k])
        fz = f(z[k])
        if fy <= fz:
            a.append(a[k])
            b.append(z[k])
            y.append(a[k + 1] + b[k + 1] - y[k])
            z.append(y[k])
        else:
            a.append(y[k])
            b.append(b[k])
            y.append(z[k])
            z.append(a[k + 1] + b[k + 1] - z[k])
        delta = abs(a[k + 1] - b[k + 1])
        if delta <= e:
            x = (a[k + 1] + b[k + 1]) / 2
            break
        else:
            k += 1

global x
a0, b0 = svenn(1, 2)
e = 0.1
m = 0.05
print(f'Начальный интервал неопределенности: [{a0}, {b0}] (метод Свенна)')
popolam(a0, b0, e)
print(f'Минимум функции составляет {f(x)} и достигается в точке х = {x} (метод деления интервала пополам)')
dihotomia(a0, b0, e, m)
print(f'Минимум функции составляет {f(x)} и достигается в точке х = {x} (метод дихотомии)')
gold(a0, b0, e)
print(f'Минимум функции составляет {f(x)} и достигается в точке х = {x} (метод золотого сечения)')


def insertion(lis):
	for i in range(1,len(lis)):
		pos = lis[i]
		j = i - 1
		while(j>=0 and pos<lis[j]):
			lis[j+1] = lis[j]
			j-=1
		lis[j+1] = pos
	return lis
print(insertion([9,8,1,2,3,7]))


"""
bento_meta.util.changelog

Common functions shared by changelog generation scripts
"""
import configparser
import logging
from typing import Generator, Optional

logger = logging.getLogger(__name__)

def get_initial_changeset_id(config_file_path: str) -> int:
    """Gets initial changeset id from changelog config file"""
    config = configparser.ConfigParser()
    config.read(config_file_path)
    try:
        return config.getint(section="changelog", option="changeset_id")
    except (configparser.NoSectionError, configparser.NoOptionError) as error:
        logger.error(f"Reading changeset ID failed: {error}")
        raise

def changeset_id_generator(config_file_path: str) -> Generator[int, None, None]:
    """Generates sequential changeset IDs by reading the latest ID from a config file."""
    i = get_initial_changeset_id(config_file_path)
    while True:
        yield i
        i += 1

def update_config_changeset_id(config_file_path: str, new_changeset_id: int) -> None:
    """Updates changelog config file with new changeset id."""
    config = configparser.ConfigParser()
    config.read(config_file_path)
    config.set(section="changelog", option="changeset_id", value=str(new_changeset_id))
    with open(file=config_file_path, mode="w", encoding="UTF-8") as config_file:
        config.write(fp=config_file)


import gettext
import os
import re
import langtable
import locale as locale_mod
import glob
from collections import namedtuple
import functools

from pyanaconda.core import constants
from pyanaconda.core.util import setenv, execWithRedirect
from pyanaconda.core.string import upcase_first_letter
from pyanaconda.modules.common.constants.services import BOSS

from pyanaconda.anaconda_loggers import get_module_logger
log = get_module_logger(__name__)

SCRIPTS_SUPPORTED_BY_CONSOLE = {'Latn', 'Cyrl', 'Grek'}

class LocalizationConfigError(Exception):
    """Exception class for localization configuration related problems"""

    pass

class InvalidLocaleSpec(LocalizationConfigError):
    """Exception class for the errors related to invalid locale specs"""

    pass

def is_valid_langcode(langcode):
    """Check if the given locale has a language specified.

    :return: whether the language or locale is valid
    :rtype: bool
    """
    parsed = langtable.parse_locale(langcode)
    return bool(parsed.language)

def raise_on_invalid_locale(arg):
    """Helper to abort when a locale is not valid.

    :raise: InvalidLocaleSpec
    """
    if not is_valid_langcode(arg):
        raise InvalidLocaleSpec("'{}' is not a valid locale".format(arg))

def get_language_id(locale):
    """Return language id without territory or anything else."""
    return langtable.parse_locale(locale).language

@functools.cache
def get_common_languages():
    """Return common languages to prioritize them"""
    return langtable.list_common_languages()

def is_supported_locale(locale):
    """Function that tells if the given locale is supported by the Anaconda or
    not. We consider locales supported by the langtable as supported by the
    Anaconda.

    :param locale: locale to test
    :type locale: str
    :return: whether the given locale is supported or not
    :rtype: bool
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    en_name = get_english_name(locale)
    return bool(en_name)

def locale_supported_in_console(locale):
    """Function that tells if the given locale can be displayed by the Linux console.

    The Linux console can display Latin, Cyrillic and Greek characters reliably,
    but others such as Japanese, can't be correctly installed.

    :param str locale: locale to test
    :return: whether the given locale is supported by the console or not
    :rtype: bool
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    locale_scripts = get_locale_scripts(locale)
    return set(locale_scripts).issubset(SCRIPTS_SUPPORTED_BY_CONSOLE)

def find_best_locale_match(locale, langcodes):
    """Find the best match for the locale in a list of langcodes. This is useful
    when e.g. pt_BR is a locale and there are possibilities to choose an item
    (e.g. rnote) for a list containing both pt and pt_BR or even also pt_PT.

    :param locale: a valid locale (e.g. en_US.UTF-8 or sr_RS.UTF-8@latin, etc.)
    :type locale: str
    :param langcodes: a list or generator of langcodes (e.g. en, en_US, en_US@latin, etc.)
    :type langcodes: list(str) or generator(str)
    :return: the best matching langcode from the list of None if none matches
    :rtype: str or None
    """
    # Parse the locale.
    if not is_valid_langcode(locale):
        return None

    locale_parsed = langtable.parse_locale(locale)

    # Get a score for each langcode.
    scores = {}

    for langcode in langcodes:
        if not is_valid_langcode(langcode):
            continue

        langcode_parsed = langtable.parse_locale(langcode)

        # Don't match a non-POSIX locale with a POSIX langcode.
        if langcode_parsed.variant == "POSIX" and locale_parsed.variant != "POSIX":
            continue

        score = _evaluate_locales(locale_parsed, langcode_parsed)

        # Matches matching only script or encoding or both are not useful.
        # The score of 100 requires at least territory to have matched.
        if score <= 100:
            continue

        scores[langcode] = score

    # Find the best one.
    return max(scores.keys(), key=scores.get, default=None)

def _evaluate_locales(locale, langcode):
    """Compare a locale with a langcode.

    :param locale: a parsed locale
    :param langcode: a parsed langcode
    :return: a score
    """
    return \
        _evaluate_values(locale.language, langcode.language, 1000) + \
        _evaluate_values(locale.territory, langcode.territory, 100) + \
        _evaluate_values(locale.script, langcode.script, 10) + \
        _evaluate_values(locale.variant, langcode.variant, 10) + \
        _evaluate_values(locale.encoding, langcode.encoding, 1)

def _evaluate_values(locale_value, langcode_value, weight):
    """Compare a locale value with a langcode value.

    :param locale_value: an item of the parsed locale
    :param langcode_value: an item of the parsed langcode
    :return: a score
    """
    if locale_value and langcode_value:
        if locale_value == langcode_value:
            # Match.
            return weight
        else:
            # Not match.
            return -weight

    if langcode_value and not locale_value:
        # The langcode has something the locale doesn't have.
        return -weight

    return 0

def setup_locale(locale, localization_proxy=None, text_mode=False):
    """Procedure setting the system to use the given locale and store it in to the
    localization module (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    We also try to set a proper console font for the locale in text mode.
    If the font for the locale can't be displayed in the Linux console,
    we fall back to the English locale.

    This function returns the locale that was used in the setlocale call, which,
    depending on what the environment and interface is able to support, may be
    different from the locale requested.

    :param str locale: locale to setup
    :param localization_proxy: DBus proxy of the localization module or None
    :param bool text_mode: if the locale is being setup for text mode
    :return: the locale that was actually set
    :rtype: str
    """
    if localization_proxy:
        localization_proxy.Language = locale

    # not all locales might be displayable in text mode
    if text_mode:
        # check if the script corresponding to the locale/language
        # can be displayed by the Linux console
        # * all scripts for the given locale/language need to be
        #   supported by the linux console
        # * otherwise users might get a screen full of white rectangles
        #   (also known as "tofu") in text mode
        # then we also need to check if we have information about what
        # font to use for correctly displaying the given language/locale

        script_supported = locale_supported_in_console(locale)
        log.debug("scripts found for locale %s: %s", locale, get_locale_scripts(locale))

        console_fonts = get_locale_console_fonts(locale)
        log.debug("console fonts found for locale %s: %s", locale, console_fonts)

        font_set = False
        if script_supported and console_fonts:
            # try to set console font
            for font in console_fonts:
                if set_console_font(font):
                    # console font set successfully, skip the rest
                    font_set = True
                    break

        if not font_set:
            log.warning("can't set console font for locale %s", locale)
            # report what exactly went wrong
            if not script_supported:
                log.warning("script not supported by console for locale %s", locale)
            if not console_fonts:  # no fonts known for locale
                log.warning("no console font found for locale %s", locale)
            if script_supported and console_fonts:
                log.warning("none of the suggested fonts can be set for locale %s", locale)
            log.warning("falling back to the English locale")
            locale = constants.DEFAULT_LANG
            os.environ["LANG"] = locale  # pylint: disable=environment-modify

    # set the locale to the value we have selected
    # Since glibc does not install all locales, an installable locale may not
    # actually be available right now. Give it a shot and fallback.
    log.debug("setting locale to: %s", locale)
    setenv("LANG", locale)

    try:
        locale_mod.setlocale(locale_mod.LC_ALL, locale)
    except locale_mod.Error as e:
        log.debug("setlocale failed: %s", e)
        locale = constants.DEFAULT_LANG
        setenv("LANG", locale)
        locale_mod.setlocale(locale_mod.LC_ALL, locale)

    set_modules_locale(locale)

    return locale

def set_modules_locale(locale):
    """Set locale of all modules."""
    boss_proxy = BOSS.get_proxy()
    boss_proxy.SetLocale(locale)

def get_english_name(locale):
    """Function returning english name for the given locale.

    :param locale: locale to return english name for
    :type locale: str
    :return: english name for the locale or empty string if unknown
    :rtype: st
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    name = langtable.language_name(languageId=locale, languageIdQuery="en")
    return upcase_first_letter(name)

def get_native_name(locale):
    """Function returning native name for the given locale.

    :param locale: locale to return native name for
    :type locale: str
    :return: english name for the locale or empty string if unknown
    :rtype: st
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    return langtable.language_name(languageId=locale)

def get_available_translations(localedir=None):
    """Method that generates (i.e. returns a generator) available translations
    for the installer in the given localedir.

    :type localedir: str
    :return: generator yielding available translations (languages)
    :rtype: generator yielding strings
    """
    localedir = localedir or gettext._default_localedir

    # usually there are no message files for en
    messagefiles = sorted(glob.glob(localedir + "/*/LC_MESSAGES/anaconda.mo") +
                          ["blob/en/blob/blob"])
    trans_gen = (path.split(os.path.sep)[-3] for path in messagefiles)

    langs = set()

    for trans in trans_gen:
        lang = get_language_id(trans)
        if lang and lang not in langs:
            langs.add(lang)
            # check if there are any locales for the language
            locales = get_language_locales(lang)
            if not locales:
                continue

            yield lang

@functools.lru_cache(2048)
def locale_has_translation(locale):
    """Does the locale have a translation available?

    Checks if a given locale will receive a gettext translation. That could be either because the
    locale has a translation, or because there is another translation to fall back onto. In
    reality, the fallback is mostly of the type "ja_JP" -> "ja".

    For English, always return true, because that is the "untranslated" state which does not need
    translation files present to work.

    :param str locale: locale to check
    :return bool: is there a translation
    """
    if get_language_id(locale) == "en":
        return True

    files = gettext.find("anaconda", None, [locale], True)
    return bool(files)

def get_language_locales(lang):
    """Function returning all locales available for the given language.

    :param lang: language to get available locales for
    :type lang: str
    :return: a list of available locales
    :rtype: list of strings
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(lang)

    return langtable.list_locales(languageId=lang)

def get_territory_locales(territory):
    """Function returning list of locales for the given territory. The list is
    sorted from the most probable locale to the least probable one (based on
    langtable's ranking.

    :param territory: territory to return locales for
    :type territory: str
    :return: list of locales
    :rtype: list of strings
    """
    return langtable.list_locales(territoryId=territory)

def get_locale_keyboards(locale):
    """Function returning preferred keyboard layouts for the given locale.

    :param locale: locale string
    :type locale: str
    :return: list of preferred keyboard layouts
    :rtype: list of strings
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    return langtable.list_keyboards(languageId=locale)

def get_common_keyboard_layouts():
    """Function returning common keyboard layouts carrying high ranks.

    :return: list of common keyboard layouts
    :rtype: list of strings
    """
    return langtable.list_common_keyboards()

def get_locale_timezones(locale):
    """Function returning preferred timezones for the given locale.

    :param locale: locale string
    :type locale: str
    :return: list of preferred timezones
    :rtype: list of strings
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    return langtable.list_timezones(languageId=locale)

def get_locale_console_fonts(locale):
    """Function returning preferred console fonts for the given locale.

    :param str locale: locale string
    :return: list of preferred console fonts
    :rtype: list of strings
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    return langtable.list_consolefonts(languageId=locale)

def get_locale_scripts(locale):
    """Function returning preferred scripts (writing systems) for the given locale.

    :param locale: locale string
    :type locale: str
    :return: list of preferred scripts
    :rtype: list of strings
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    raise_on_invalid_locale(locale)

    return langtable.list_scripts(languageId=locale)

def get_xlated_timezone(tz_spec_part):
    """Function returning translated name of a region, city or complete timezone
    name according to the current value of the $LANG variable.

    :param tz_spec_part: a region, city or complete timezone name
    :type tz_spec_part: str
    :return: translated name of the given region, city or timezone
    :rtype: str
    :raise InvalidLocaleSpec: if an invalid locale is given (see is_valid_langcode)
    """
    locale = os.environ.get("LANG", constants.DEFAULT_LANG)

    raise_on_invalid_locale(locale)

    xlated = langtable.timezone_name(tz_spec_part, languageIdQuery=locale)
    return xlated

def get_firmware_language(text_mode=False):
    """Procedure that returns the firmware language information (if any).

    :param boot text_mode: if the locale is being setup for text mode
    :return: the firmware language translated into a locale string, or None
    :rtype: str
    """
    try:
        n = "/sys/firmware/efi/efivars/PlatformLang-8be4df61-93ca-11d2-aa0d-00e098032b8c"
        with open(n, 'r') as f:
            d = f.read()
    except OSError:
        return None

    # the contents of the file are:
    # 4-bytes of attribute data that we don't care about
    # NUL terminated ASCII string like 'en-US'.
    if len(d) < 10:
        log.debug("PlatformLang was too short")
        return None
    d = d[4:]
    if d[2] != '-':
        log.debug("PlatformLang was malformed")
        return None

    # they use - and we use _, so fix it...
    d = d[:2] + '_' + d[3:-1]

    # UEFI 2.3.1 Errata C specifies 2 aliases in common use that
    # aren't part of RFC 4646, but are allowed in PlatformLang.
    # Because why make anything simple?
    if d.startswith('zh_chs'):
        d = 'zh_Hans'
    elif d.startswith('zh_cht'):
        d = 'zh_Hant'
    d += '.UTF-8'

    if not is_supported_locale(d):
        log.debug("PlatformLang was '%s', which is unsupported.", d)
        return None

    locales = get_language_locales(d)
    if not locales:
        log.debug("No locales found for the PlatformLang '%s'.", d)
        return None

    log.debug("Using UEFI PlatformLang '%s' ('%s') as our language.", d, locales[0])
    return locales[0]

_DateFieldSpec = namedtuple("DateFieldSpec", ["format", "suffix"])

def resolve_date_format(year, month, day, fail_safe=True):
    """Puts the year, month and day objects in the right order according to the
    currently set locale and provides format specification for each of the
    fields.

    :param year: any object or value representing year
    :type year: any
    :param month: any object or value representing month
    :type month: any
    :param day: any object or value representing day
    :type day: any
    :param bool fail_safe: whether to fall back to default in case of invalid
                           format or raise exception instead
    :returns: a pair where the first field contains a tuple with the year, month
              and day objects/values put in the right order and where the second
              field contains a tuple with three :class:`_DateFieldSpec` objects
              specifying formats respectively to the first (year, month, day)
              field, e.g. ((year, month, day), (y_fmt, m_fmt, d_fmt))
    :rtype: tuple
    :raise ValueError: in case currently set locale has unsupported date
                       format and fail_safe is set to False
    """
    FAIL_SAFE_DEFAULT = "%Y-%m-%d"

    def order_terms_formats(fmt_str):
        # see date (1), 'O' (not '0') is a mystery, 'E' is Buddhist calendar, '(.*)'
        # is an arbitrary suffix
        field_spec_re = re.compile(r'([-_0OE^#]*)([yYmbBde])(.*)')

        # see date (1)
        fmt_str = fmt_str.replace("%F", "%Y-%m-%d")

        # e.g. "%d.%m.%Y" -> ['d.', 'm.', 'Y']
        fields = fmt_str.split("%")[1:]

        ordered_terms = []
        ordered_formats = []
        for field in fields:
            match = field_spec_re.match(field)
            if not match:
                # ignore fields we are not interested in (like %A for weekday name, etc.)
                continue

            prefix, item, suffix = match.groups()
            if item in ("d", "e"):
                # "e" is the same as "_d"
                ordered_terms.append(day)
            elif item in ("Y", "y"):
                # 4-digit year, 2-digit year
                ordered_terms.append(year)
            elif item in ("m", "b", "B"):
                # month number, short month name, long month name
                ordered_terms.append(month)

            # "%" + prefix + item gives a format for date/time formatting functions
            ordered_formats.append(_DateFieldSpec("%" + prefix + item, suffix.strip()))

        if len(ordered_terms) != 3 or len(ordered_formats) != 3:
            raise ValueError("Not all fields successfully identified in the format '%s'" % fmt_str)

        return (tuple(ordered_terms), tuple(ordered_formats))

    fmt_str = locale_mod.nl_langinfo(locale_mod.D_FMT)

    if not fmt_str or "%" not in fmt_str:
        if fail_safe:
            # use some sane default
            fmt_str = FAIL_SAFE_DEFAULT
        else:
            raise ValueError("Invalid date format string for current locale: '%s'" % fmt_str)

    try:
        return order_terms_formats(fmt_str)
    except ValueError:
        if not fail_safe:
            raise
        else:
            # if this call fails too, something is going terribly wrong and we
            # should be informed about it
            return order_terms_formats(FAIL_SAFE_DEFAULT)

def set_console_font(font):
    """Try to set console font to the given value.

    :param str font: console font name
    :returns: True on success, False on failure
    :rtype: bool
    """
    log.debug("setting console font to %s", font)
    rc = execWithRedirect("setfont", [font])
    if rc == 0:
        log.debug("console font set successfully to %s", font)
        return True
    else:
        log.error("setting console font to %s failed", font)
        return False

def setup_locale_environment(locale=None, text_mode=False, prefer_environment=False):
    """Clean and configure the local environment variables.

    This function will attempt to determine the desired locale and configure
    the process environment (os.environ) in the least surprising way. If a
    locale argument is provided, it will be attempted first. After that, this
    function will attempt to use the language environment variables in a manner
    similar to gettext(3) (in order, $LANGUAGE, $LC_ALL, $LC_MESSAGES, $LANG),
    followed by the UEFI PlatformLang, followed by a default.

    When this function returns, $LANG will be set, and $LANGUAGE, $LC_ALL,
    and $LC_MESSAGES will not be set, because they get in the way when changing
    the language after startup.

    This function must be run before any threads are started. This function
    modifies the process environment, which is not thread-safe.

    :param str locale: locale to setup if provided
    :param bool text_mode: if the locale is being setup for text mode
    :param bool prefer_environment: whether the process environment, if available, overrides the locale parameter
    :return: None
    :rtype: None
    """
    # pylint: disable=environment-modify

    # Look for a locale in the environment. If the variable is setup but
    # empty it doesn't count, and some programs (KDE) actually do this.
    # If prefer_environment is set, the environment locale can override
    # the parameter passed in. This can be used, for example, by initial-setup,
    # to prefer the possibly-more-recent environment settings before falling back
    # to a locale set at install time and saved in the kickstart.
    if not locale or prefer_environment:
        for varname in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):
            if varname in os.environ and os.environ[varname]:
                locale = os.environ[varname]
                break

    # Look for a locale in the firmware if there was nothing in the environment
    if not locale:
        locale = get_firmware_language(text_mode)

    # parse the locale using langtable
    if locale:
        try:
            env_langs = get_language_locales(locale)
            # the first language is the best match
            locale = env_langs[0]
        except (InvalidLocaleSpec, IndexError):
            log.error("Invalid locale '%s' given on command line, kickstart or environment", locale)
            locale = None

    # If langtable returned no locales, or if nothing was configured, fall back to the default
    if not locale:
        locale = constants.DEFAULT_LANG

    # Save the locale in the environment
    os.environ["LANG"] = locale

    # Cleanup the rest of the environment variables
    for varname in ("LANGUAGE", "LC_ALL", "LC_MESSAGES"):
        if varname in os.environ:
            del os.environ[varname]


from jax import jit
from jax import numpy as jnp

def mse(data, fitted):
    x, y = check_data(data, fitted)
    return jnp.mean((x - y) ** 2, axis=1)

def mae(data, fitted):
    x, y = check_data(data, fitted)
    return jnp.mean(jnp.abs(x - y), axis=1)

@jit
def correlate(data, fitted):
    """ Designed for images (n_imgs, pxs). """
    x, y = check_data(data, fitted)

    Ex = jnp.mean(x, axis=1, keepdims=True)
    Ey = jnp.mean(y, axis=1, keepdims=True)

    cov = jnp.mean((x - Ex) * (y - Ey), axis=1)

    var_x = jnp.sqrt(jnp.var(x, axis=1))
    var_y = jnp.sqrt(jnp.var(y, axis=1))

    return cov / (var_x * var_y)

def check_data(data, fitted):
    if data.shape != fitted.shape:
        print(f"Len data={data.shape} but {fitted.shape}.")
    n = data.shape[0]
    x = jnp.reshape(data, (n, -1))
    y = jnp.reshape(fitted, (n, -1))
    return x, y

def zscore_img(img):
    ori = img.shape
    if len(img.shape) == 3:
        img = img.reshape((img.shape[0], -1))
    else:
        raise Exception("Not image!")

    # Using JAX instead of scipy.
    zed = (img - jnp.mean(img, axis=1, keepdims=1)) / jnp.sqrt(jnp.var(img, axis=1, keepdims=1))
    return zed.reshape(ori)


import errno
import json
import os
import sys
import time

import numpy as np
import torch

def rand(a=0., b=1.):
    return np.random.rand() * (b - a) + a

def get_path_root():
    '''os.path.dirname(os.path.abspath(__file__))'''
    debug_vars = dict((a, b) for a, b in os.environ.items() if a.find('IPYTHONENABLE') >= 0)
    # 根据不同场景获取根目录
    if len(debug_vars) > 0:
        """当前为debug运行时"""
        path_root = sys.path[2]
    elif getattr(sys, 'frozen', False):
        """当前为exe运行时"""
        path_root = os.getcwd()
    else:
        """正常执行"""
        path_root = sys.path[1]
    path_root = path_root.replace("\\", "/")  # 替换斜杠
    return path_root

def is_float(str):
    from f_tools.GLOBAL_LOG import flog
    if str.count('.') == 1:  # 小数有且仅有一个小数点
        left = str.split('.')[0]  # 小数点左边（整数位，可为正或负）
        right = str.split('.')[1]  # 小数点右边（小数位，一定为正）
        lright = ''  # 取整数位的绝对值（排除掉负号）
        if str.count('-') == 1 and str[0] == '-':  # 如果整数位为负，则第一个元素一定是负号
            lright = left.split('-')[1]
        elif str.count('-') == 0:
            lright = left
        else:
            flog.debug('%s 不是小数' % str)
            return False
        if right.isdigit() and lright.isdigit():  # 判断整数位的绝对值和小数位是否全部为数字
            flog.debug('%s 是小数' % str)
            return True
        else:
            flog.debug('%s 不是小数' % str)
            return False

    else:
        flog.debug('%s 不是小数' % str)
        return False

def show_time(f, *arg):
    import time
    from f_tools.GLOBAL_LOG import flog

    start = time.time()
    flog.debug('show_time---开始---%s-------' % (f.__name__))
    ret = f(*arg)
    flog.debug('show_time---完成---%s---%s' % (f.__name__, time.time() - start))
    return ret

def show_progress(epoch, epochs, title, context):
    '''
    完成后在循环的外层需要补一个        print()
    '''
    rate = (epoch + 1) / epochs
    a = "*" * int(rate * 50)
    b = "." * int((1 - rate) * 50)
    time.sleep(0.2)
    print("\r{}: {:^3.0f}%[{}->{}] {}".format(title, int(rate * 100), a, b, context), end="")

class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)

def mkdir(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

def labels2onehot4ts(labels, num_class):
    '''
    这里是必须0开始  需labels-1  通常 label 从1开始
    :param labels: 类别 index [,2,1,1,3,5]
    :param num_class:
    :return: torch.Size([1, 20])
    '''
    # labels = labels - 1
    batch = labels.shape[0]
    labels.resize_(batch, 1)  # labels[:,None]
    zeros = torch.zeros(batch, num_class, device=labels.device, dtype=torch.int64)
    return zeros.scatter_(1, labels.long(), 1)  # dim,index,value 数组索引

class Dict2Obj(object):
    def __init__(self, d):
        for a, b in d.items():
            if isinstance(b, (list, tuple)):
                setattr(self, a, [Dict2Obj(x) if isinstance(x, dict) else x for x in b])
            else:
                setattr(self, a, Dict2Obj(b) if isinstance(b, dict) else b)

if __name__ == "__main__":
    pass


import os
import json

def main(file_path, activated, cardio_circle, output_dir, name_rule):
    file_number = len(os.listdir(file_path))
    with open(file_path+"/"+os.listdir(file_path)[0], "r") as f:
        time_slice = -1
        for step, row in enumerate(f):
            time_slice += 1
            pass
        f.close()
    if time_slice >= 100:
        cardio_circle = cardio_circle / time_slice
    elif time_slice >= 90:
        print("WARNING: Only {} time-slice detected!".format(time_slice))
        cardio_circle = cardio_circle / time_slice
    else:
        print("WARNING: Only {} time-slice detected, please confirm the cardio circle...".format(time_slice))
        cardio_circle = input("Cardio Circle:")
    prof = [file_path, file_number, str(activated), cardio_circle, output_dir, name_rule]

    with open('./forward_difference_starter.bat', 'w') as file:
        file.write('set current_path=%~dp0')
        file.write('\n')
        file.write('start  %current_path%\\forward_difference.py %1 %2 %3 %4 %5 %6')
        file.close()

    with open('./global.json', 'w') as file:
        json.dump(prof, file)

    with open('./global.json', 'r') as file:
        data = json.load(file)

    for item in data[2]:
        para = "forward_difference_starter.bat {} {} {} {} {} {}"\
            .format(data[0], data[1], item, data[3], data[4], data[5])
        os.system(para)


from static.python.full_sass import do_full_sass
import os
import subprocess

scss_Folder = 'static/scss'
css_Folder = 'static/css'

if __name__=='__main__':

    def do_initialize(css):
        new_css_Folder = css
        os.system('pip install -r requirements.txt')
        os.system('npm install')
        try:
            subprocess.check_call('sass', shell=True)
            do_full_sass()
        except subprocess.CalledProcessError:
            print("Error: 'sass' is not recognized as a command.")

            new_css_Folder = 'static/scss'
            print("Need sass variable in PATH!")
        return new_css_Folder

    def do_full_sass():
       os.system(f'py static/python/full_sass.py {scss_Folder} {css_Folder}')

    _ = "New-Item -Path $profile -Type File -Force"
    _ = "notepad $PROFILE"

    do_initialize(css_Folder)


import os
import sys

import torch
from pytorch_lightning import LightningModule, Trainer, seed_everything

# loop = True;

# inferTest 불러오기
root_path = sys.path[0]
model_path = os.path.join(root_path, '../models')
sys.path.append(model_path)
# inferTest 불러오기

from single_task_model import Model
from clean import clean

MODEL_PATH = "../checkpoint/single_kcbert-l_0.000005_0/epoch=2-val_loss=0.07.ckpt"
#HPARAMS_PATH = "./lightning_logs/version_2/hparams.yaml"

from glob import glob

latest_ckpt = sorted(glob(MODEL_PATH))[0]
#model = trainning.Model.load_from_checkpoint(latest_ckpt, hparams_file=HPARAMS_PATH)
model = Model.load_from_checkpoint(latest_ckpt)

model.eval()
#map location 해주면 환경 바뀌어도 가능
def main():
    while True:
        sentence = input("문장을 입력하시오! ")
        judge(sentence=sentence)

def infer(x):
    return model(**model.tokenizer(x, return_tensors='pt'))
def judge(sentence):
    sentence=str(sentence)
    if sentence == "":
        print("빈 문장")
    else:
        LABEL_COLUMNS=["욕설","모욕","폭력위협/범죄조장","외설","성혐오","연령","인종/출신지","장애","종교","정치성향","직업혐오"]
        test_prediction = infer(clean(sentence))
        output = torch.sigmoid(test_prediction.logits)
        output = output.detach().flatten().numpy()
        for i in zip(LABEL_COLUMNS, output):
            if i[1] > 0.5:
                return 1
                #print(i)
                #print(f'probability : {prediction}')
        return 0

if __name__ == "__main__":
    main()


from rdflib import URIRef
from provworkflow import Workflow, Block, Entity, Agent

# set up the Workflow and Block
w = Workflow(label="My Simple Workflow 2")
b = Block()

# Block 1
b.used = [
    Entity(value="local data"),
    Entity(access_uri="http://example.com/endpoint", service_parameters="x=42"),
]
e_int = Entity(label="Internal Entity")
e_ext = Entity(label="External Entity", external=True)
b.generated = [e_int, e_ext]
w.blocks.append(b)

# Block 2
b2 = Block()
b2.used = [Entity(value="other local data"), e_int, e_ext]
b2.generated.append(
    Entity(access_uri="http://somewhere-on-s3/d/e/f", label="Final Workflow Output")
)
w.blocks.append(b2)

# print out
print(w.persist("string"))


#!/usr/bin/python3
"""
Copy notes from previous beta releases to make notes for an ESR
"""

import argparse
import os
import re
import json
from pathlib import Path
from urllib.request import urlopen
from packaging.version import Version

from tools_lib import guess_release_date, yaml, notes_template
from ruamel.yaml.comments import CommentedSeq as CS

topdir = Path(os.path.dirname(__file__)) / ".."
beta_dir = Path(os.path.join(topdir, "beta"))
release_dir = Path(os.path.join(topdir, "release"))
ver_notes_yaml = "{this_esr}.yml"

MERCURIAL_TAGS_URL = "https://hg.mozilla.org/releases/comm-esr{major}/json-tags"
RELEASE_TAG_RE = re.compile(r"THUNDERBIRD_([\d_b]+)_RELEASE")
CHANGESET_URL_TEMPLATE = "https://hg.mozilla.org/releases/comm-esr{major}/json-pushes?fromchange={from_version}&tochange={to_version}&full=1"
BUG_NUMBER_REGEX = re.compile(r"bug \d+", re.IGNORECASE)
BACKOUT_REGEX = re.compile(r"back(\s?)out|backed out|backing out", re.IGNORECASE)

PD_VERSIONS = "https://product-details.mozilla.org/1.0/thunderbird_versions.json"
CUR_VERSION_URL = (
    "https://hg.mozilla.org/releases/{repo}/raw-file/{rev}/mail/config/version.txt"
)

ESR_VERSIONS = ("102", "115")

class RelNote:
    def __init__(self, bugs, tag, note_text):
        bugs.sort()
        self.bugs = bugs
        self.tag = tag
        self.note = note_text

    @property
    def output(self):
        rv = {"note": self.note, "tag": self.tag}
        if self.bugs:
            rv["bugs"] = self.bugs
        return rv

def sec_version(this_esr):
    if this_esr.endswith("esr"):
        this_esr = this_esr[:-3]
    version = Version(this_esr)

    if version.micro == 0:
        return f"thunderbird{version.major}.{version.minor}"
    return False

def load_notes(this_esr, previous_esr, previous_esr_rev):
    beta_notes = {}
    new_notes = []
    rel_notes = []

    esr_major = previous_esr.split(".")[0]
    min_version = Version("{}.0.0".format(esr_major))

    print(
        """Generating notes for Thunderbird {this_esr}
Previous esr: {previous_esr}
    """.format(
            this_esr=this_esr, previous_esr=previous_esr
        )
    )

    bug_list, backout_list = get_buglist(esr_major, previous_esr_rev)
    bugs_fixed = set.union(bug_list, backout_list)

    note_files = os.listdir(str(beta_dir))
    for _file in note_files:
        if not _file.endswith("beta.yml"):
            continue
        version = Version(_file[:-8])
        # Exclude versions lower than the beta for the previous esr
        # anything newer than the current beta
        if version < min_version:
            continue

        with open(os.path.join(beta_dir, _file), "r") as fp:
            doc = yaml.load(fp)
            beta_notes[_file[:-8]] = doc

    versions = sorted([Version(v) for v in beta_notes.keys()])

    for ver_str in [str(v) for v in versions]:
        ver_notes = beta_notes[ver_str]["notes"]
        for note in ver_notes:
            if "bugs" not in note:
                continue
            if note["tag"] == "unresolved":
                continue

            rel_note = RelNote(note["bugs"], note["tag"], note["note"])

            new_notes.append(rel_note)

    noted_bugs = set()
    for note in new_notes:
        # Only add this note if it is for bugs that are new/changed/fixed in this release
        if any([b for b in note.bugs if b in bugs_fixed]):
            # Remove references to other bugs that might be on the note
            for b2 in note.bugs:
                if b2 not in bugs_fixed:
                    note.bugs.remove(b2)
                else:
                    noted_bugs.add(b2)
            rel_notes.append(note.output)

    sec_v = sec_version(this_esr)
    if sec_v:  # sec_version returns False for non-.0 esrs (like 115.5.1)
        sec_url = notes_template.TMPL_SEC_NOTE.format(thunderbird_version=sec_v)
        sec_note = RelNote([], "fixed", sec_url)
        rel_notes.append(sec_note.output)

    RELEASE_TEMPLATE = f"TMPL_{esr_major}_TEXT"
    new_yaml = yaml.load(notes_template.TMPL_HEADER)
    new_yaml["release"]["text"] = getattr(notes_template, RELEASE_TEMPLATE)
    new_yaml["release"][
        "import_system_requirements"
    ] = notes_template.REQUIREMENTS_IMPORT[esr_major]
    release_date, human_date = guess_release_date()
    new_yaml["release"]["release_date"] = release_date

    notes_sequence = CS()
    note_counter = 0
    for tag_name in ["new", "changed", "fixed"]:
        tag_notes = [n for n in rel_notes if n["tag"] == tag_name]
        if tag_notes:
            notes_sequence.extend(tag_notes)
            notes_sequence.yaml_set_comment_before_after_key(
                note_counter, "{}\n".format(tag_name.capitalize()), 2
            )
            note_counter += len(tag_notes)

    new_yaml["notes"] = notes_sequence

    out_yaml = ver_notes_yaml.format(this_esr=this_esr)
    with open(release_dir / out_yaml, "w") as fp:
        yaml.dump(new_yaml, fp)

    print("Wrote notes to {}.".format(out_yaml))

    no_note_bugs = sorted(bugs_fixed - noted_bugs)
    if no_note_bugs:
        # Print out bugs where no note is available
        print("")
        print("Bugs that do not have an associated note:")

        bugzilla_url = "https://bugzilla.mozilla.org/rest/bug?include_fields=id,summary&id={}".format(
            ",".join([str(b) for b in no_note_bugs])
        )
        with urlopen(bugzilla_url) as response:
            data = json.load(response)

        for note in data["bugs"]:
            print("{} - {}".format(note["id"], note["summary"]))

def get_bugs_in_changeset(changeset_data):
    unique_bugs, unique_backout_bugs = set(), set()
    for data in changeset_data.values():
        for changeset in data["changesets"]:
            if is_excluded_change(changeset):
                continue

            changeset_desc = changeset["desc"]
            bug_re = BUG_NUMBER_REGEX.search(changeset_desc)

            if bug_re:
                bug_number = bug_re.group().split(" ")[1]

                if is_backout_bug(changeset_desc):
                    unique_backout_bugs.add(int(bug_number))
                else:
                    unique_bugs.add(int(bug_number))

    return unique_bugs, unique_backout_bugs

def is_excluded_change(changeset):
    excluded_change_keywords = [
        "a=test-only",
        "a=release",
    ]
    return any(keyword in changeset["desc"] for keyword in excluded_change_keywords)

def is_backout_bug(changeset_description):
    return bool(BACKOUT_REGEX.search(changeset_description))

def get_buglist(esr_major, from_rev):
    """Retrieve the list of bugs since the last release"""
    to_rev = "tip"
    changeset_url = CHANGESET_URL_TEMPLATE.format(
        major=esr_major, from_version=from_rev, to_version=to_rev
    )
    print(changeset_url)
    with urlopen(changeset_url) as response:
        data = json.load(response)
    unique_bugs, unique_backout_bugs = get_bugs_in_changeset(data)

    if unique_bugs:
        print("Fixed bugs:")
        print(" ".join([str(bug) for bug in sorted(unique_bugs)]))
        print("")
    if unique_backout_bugs:
        print("Backout bugs:")
        print(" ".join([str(bug) for bug in sorted(unique_backout_bugs)]))

    return unique_bugs, unique_backout_bugs

def fetch(url, data_type="text"):
    with urlopen(url) as response:
        if data_type == "json":
            data = json.load(response)
        else:
            data = response.read().strip().decode("utf-8")
    return data

def get_prev_release_rev(tags):
    for tag in tags[:10]:
        match = RELEASE_TAG_RE.match(tag["tag"])
        if match:
            print("Using tag {} at rev {}.".format(tag["tag"], tag["node"]))
            return tag["node"]
    raise Exception("Did not find a RELEASE tag in the first 10 tags")

def get_version_from_rev(repo, rev):
    return fetch(CUR_VERSION_URL.format(repo=repo, rev=rev))

def get_versions(major_version):
    versions = {}

    esr_tags = fetch(MERCURIAL_TAGS_URL.format(major=major_version), data_type="json")
    prev_esr_rev = get_prev_release_rev(esr_tags["tags"])
    versions["prev_esr_rev"] = prev_esr_rev
    prev_esr_version = get_version_from_rev(f"comm-esr{major_version}", prev_esr_rev)
    versions["previous_esr"] = prev_esr_version

    this_esr_version = get_version_from_rev(f"comm-esr{major_version}", "tip")
    versions["this_esr"] = this_esr_version

    return versions

def main():
    parser = argparse.ArgumentParser(description="Make ESR notes")
    parser.add_argument(
        "major_ver",
        metavar="major_version",
        choices=ESR_VERSIONS,
        help="Major ESR version",
    )
    args = parser.parse_args()

    versions = get_versions(args.major_ver)

    load_notes(versions["this_esr"], versions["previous_esr"], versions["prev_esr_rev"])

if __name__ == "__main__":
    main()


# day3 of the advent of code
# by Geir Owe

#read the test puzzle input
#map_file = open('day3_test_puzzle_input.txt', 'r')

#read the puzzle input
map_file = open('day3_puzzle_input.txt', 'r')

#challenge:
# Starting at the top-left corner of your map and
# following a slope of right 3 and down 1, how many trees would you encounter?

#where to start, what lane and how to move
absolutelyFirstLane = True
myPosition = 0
currentLane = 1

#count number of threes - ie. to get the answer to the puzzle
aThree = '#'
noOfThrees = 0

#in part two there are many scenarios for how much to move ahead and how many lanes to go down
move = 2
noOfLanesDown = 2
remainingLanesLeft = noOfLanesDown

#let´s get going - move ahead and stop; then go to next lane and check what's there
for lane in map_file:
    lane = lane.strip() #remove any trailing spaces or line-shift

    if absolutelyFirstLane: #first lane only, move ahead and prepare for next lane
        myPosition = myPosition + move
        absolutelyFirstLane = False
    else:
        #the lane is not a line - it's a circle
        if myPosition > (len(lane)-1): #since length of lane starts from 1 and myPosition starts from zero
            myPosition = 0 + (myPosition - len(lane))

        #you are now in the right position - prepare to go down to next lane
        currentLane = currentLane + 1

        # only check the postion if you are in right lane - if not continue to next lane
        # you are at the right postion when remainingLanesLeft = 1
        if remainingLanesLeft == 1:
            #check for a three in the new position
            if lane[myPosition] == aThree:
                noOfThrees = noOfThrees + 1

            myPosition = myPosition + move #move ahead
            remainingLanesLeft = noOfLanesDown # prepare for moving down again
        else:
            #one lane down
            remainingLanesLeft = remainingLanesLeft - 1

print('Number of threes in my way:', noOfThrees)
print('multiply together the number of trees in part two:', 82*242*71*67*24)


from project.room import Room

class Hotel:
    def __init__(self, name):
        self.name = name
        self.rooms = []
        self.guests = 0

    @classmethod
    def from_stars(cls, stars_count):
        return cls(f"{stars_count} stars Hotel")

    def add_room(self, room: Room):
        self.rooms.append(room)

    def take_room(self, room_number, people):
        for room in self.rooms:
            if room.number == room_number:
                return room.take_room(people)

    def free_room(self, room_number):
        for room in self.rooms:
            if room.number == room_number:
                return room.free_room()

    def status(self):
        total_guests = 0
        free_rooms = []
        taken_rooms = []
        for room in self.rooms:
            total_guests += room.guests
            if not room.is_taken:
                free_rooms.append(room.number)
            else:
                taken_rooms.append(room.number)
        return f"Hotel {self.name} has {total_guests} total guests\n" \
               f"Free rooms: {', '.join(map(str, free_rooms))}\n" \
               f"Taken rooms: {', '.join(map(str, taken_rooms))}"

Class and Static Methods/4.Hotel Rooms/project/hotel.py


from tendims import TenDimensionsClassifier
from flask import Flask, request, redirect , jsonify ,send_from_directory
from flask_cors import CORS
import json

# Load models
models_dir = 'models/lstm_trained_models'
embeddings_dir = 'embeddings'  # change urls to embeddings dir
success_model_file = 'models/meeting_success/xgboost_10dims_success_prediction_model.dat'
model = TenDimensionsClassifier(models_dir=models_dir, embeddings_dir=embeddings_dir)
success_predictor = SuccessPredictor(success_model_file)
print('Models loaded')

app = Flask(__name__)

@app.route("/tenDimensions", methods=['POST'])
def tenDimensions():
        text = [request.form['text']]
        print(f"received Text : {sentences}")
        try:
                # you can give in input one string of text
                # dimensions = None extracts all dimensions
                tendim_scores = model.compute_score(text, dimensions=None)
                success_probability = success_predictor.predict_success(tendim_scores)
                tendim_scores['success'] = success_probability
                return jsonify(scores)
        except Exception as e:
                print (e)
                print("Something went wrong while opening summary")
                return '400'

if __name__ == "__main__":
        CORS(app)
        app.run(host="0.0.0.0",port=5000,threaded=True)


from typing import Optional

from pydantic import BaseModel

class FormattedBody(BaseModel):
    title: str
    data: str
    description: Optional[str]

class MsgToSend(BaseModel):
    subject: str
    recipients: list[str]
    regular_body: Optional[str] = None
    formatted_body: Optional[FormattedBody] = None
    subtype: str = "html"

    def __pretty_recipients(self) -> str:
        return ", ".join([r for r in self.recipients])

    def __str__(self) -> str:
        recipients = self.__pretty_recipients()
        subj = self.subject

        if self.formatted_body:
            body_title = self.formatted_body.title
            body_data = self.formatted_body.data
            body_description = self.formatted_body.description
        else:
            body_title = ""
            body_data = ""
            body_description = ""

        return f"Recipients: {recipients}. Subject: {subj}, Title: {body_title}, Data: {body_data}, Description: {body_description}"


"""This module is the background of the window"""

from tkinter import Tk, Canvas

class Background:
    """The background of the window"""

    def __init__(
        self,
        window: Tk,
        init_width: int,
        init_height: int,
        init_background_color: str = "#4E3D28",
    ):
        self.canvas: Canvas = Canvas(
            master=window,
            width=init_width,
            height=init_height,
            bg=init_background_color,
        )
        self.canvas.place(x=0, y=0)

    def update(self, window: Tk):
        """Update the background width and height"""

        self.canvas.config(width=window.winfo_width(), height=window.winfo_height())


from src.common.base_enum import BaseEnum

class ServerOS(BaseEnum):
    UBUNTU_XENIAL = 'ubuntu_xenial'
    UBUNTU_BIONIC = 'ubuntu_bionic'
    CENTOS_7 = 'centos_7'
    CENTOS_8 = 'centos_8'

class Deployment(BaseEnum):
    DOCKER = 'docker'
    VIRTUALENV = 'virtualenv'

class WebServer(BaseEnum):
    NGINX = 'nginx'
    APACHE = 'apache'

class Database(BaseEnum):
    MYSQL = 'mysql'
    POSTGRESQL = 'postgres'
    SQLITE = 'sqlite'
    MONGODB = 'mongodb'


# Import flask dependencies
from flask import Blueprint, jsonify, request

# request, render_template, flash, g, session, redirect, url_for

from ..services import user_service
from ..schema.user_schema import user_schema, users_schema

user_controller = Blueprint('users', __name__, url_prefix='/users')

# Set the route and accepted methods

@user_controller.route('', methods=['GET'])
def get_all_users():
    # all_users = user_service.get_all_users()
    # return users_schema.jsonify(all_users), 200
    return jsonify({
        'hola': 'mundo'
    })

@user_controller.route('/add', methods=['POST'])
def add_user():
    post_data = request.get_json()

    if not post_data or 'username' not in request.args or 'email' not in request.args:
        response_object = {
            'status': 'fail',
            'message': 'Invalid payload'
        }
        return jsonify(response_object), 400

    username = post_data['username']
    email = post_data['email']
    try:
        new_user = user_service.add_user(username, email)
        return user_schema.jsonify(new_user), 200
    except Exception as e:
        response_object = {
            'status': 'fail',
            'message': e.args[0]
        }
        return jsonify(response_object), 500


import pandas as pd

# Eu criei um banco de dados para que não seja necessário fazer o input de 100 alunos todas as vezes.
# O csv com os dados está no repositório.

# O delimiter é o delimitador das colunas.
# O index_col coloca as colunas como index.
bancoDeDados = pd.read_csv("bd-Desen6.csv", delimiter=";", index_col=0)

# Mostrar informções do Banco de Dados
# print(bancoDeDados.info())

contadorGeral = 0
contadorA = 0
contadorB = 0
contadorC = 0
contadorD = 0
maiorNota = 0
alunoMaiorNota = 0
turmaMaiorNota = 0
maiorNotaA = 0
maiorNotaB = 0
maiorNotaC = 0
maiorNotaD = 0

for linha in bancoDeDados.itertuples():
    if linha[1] >= 7.0:
        if linha[2] == "A":
            # print(linha[2])
            contadorA += 1
            if linha[1] > maiorNotaA:
                maiorNotaA = linha[1]
        elif linha[2] == "B":
            # print(linha[2])
            contadorB += 1
            if linha[1] > maiorNotaB:
                maiorNotaB = linha[1]
        elif linha[2] == "C":
            # print(linha[2])
            contadorC += 1
            if linha[1] > maiorNotaC:
                maiorNotaC = linha[1]
        else:
            # print(linha[2])
            contadorD += 1
            if linha[1] > maiorNotaD:
                maiorNotaD = linha[1]
        # print(linha[1])
        contadorGeral += 1
    if linha[1] > maiorNota:
        maiorNota = linha[1]
        turmaMaiorNota = linha[2]
        alunoMaiorNota = linha[0]

print(f"Se formaram {contadorGeral} estudantes!")

# Quantos alunos formados em cada turma?
print(f"{contadorA} estudantes da turma A se formaram!")
print(f"{contadorB} estudantes da turma B se formaram!")
print(f"{contadorC} estudantes da turma C se formaram!")
print(f"{contadorD} estudantes da turma D se formaram!")
print("---------------------")

# Qual aluno teve a maior nota e em qual turma?
print(
    f"O aluno que obteve a maior foi {alunoMaiorNota}, da turma {turmaMaiorNota}. A nota dele foi: {maiorNota}!")
print("---------------------")

# Qual a maior nota em cada turma?
print(f"A nota {maiorNotaA} foi a maior da turma A!")
print(f"A nota {maiorNotaB} foi a maior da turma B!")
print(f"A nota {maiorNotaC} foi a maior da turma C!")
print(f"A nota {maiorNotaD} foi a maior da turma D!")

Lógica de Programação OO/Módulo 1 - Lógica Imperativa/Desenvolvimento 6/Desenvolvimento 6.py


#!/usr/bin/env python

import scapy.all as scapy
import optparse

def get_arguments():

    parser = optparse.OptionParser()
    parser.add_option('-t', '--target', dest='target', help='IP address or Set IP range ')
    (options, arguments) = parser.parse_args()
    return options

def scan(ip):
    arp_req=scapy.ARP(pdst=ip)
    broadcast=scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_req_broadcast=broadcast/arp_req
    answered=scapy.srp(arp_req_broadcast,timeout=1,verbose=False)[0]

    client_list=[]
    for element in answered:
        client_dict={"ip":element[1].psrc,"MAC":element[1].hwdst}
        client_list.append(client_dict)

    return (client_list)
def printt(result):
    print("IP\t\t\tMac Address\n--------------------------------------------")
    for data in result:
        print(data["ip"]+" \t\t"+data["MAC"])

ipdata = get_arguments()
ip_address=scan(ipdata.target)
printt(ip_address)


import stanza
import nltk
import keyword_list as kl
#Uncomment if you want to use this file separatly
# nlp = stanza.Pipeline("en")

def test_stanza(sentence,indice):
    '''
    input:
        sentence: str
        indice: int

    output:
        dict

    Cette fonction prend en argument une phrase et un indice i et
    renvoie les informations stanza du i-eme mot de la phrase sous la
    forme d'un dictionnaire
    '''
    doc = nlp(sentence)
    phrase = doc.sentences[0].to_dict()
    return phrase[indice]

def is_commer(sword):
    '''
    renvoie True si le mot est ','  ';'  ou  ':'
    et False sinon
    '''
    return sword['lemma'] in [',',';',':']

def Conjugaison(sentence,indice,time,method='Any'):
    '''
    input:
        sentence: str
        indice: int
        time: str
        method: str

    output:
        bool

    Cette fonction prend en argument une phrase contenant un mot clé se trouvant à
    la position indice ainsi qu'un temps (exemple 'Past') et un méthode qui peut
    être un entier, 'Any', 'Next' ou 'UC' (untill commer) la fonction renvoie True si il existe un verbe
    conjugué au temps time dans la phrase.

    method:     int -> on regarde à la position indice + method
                'Any' -> on regarde partout
                'UC' -> on regarde jusqu'à la virgule
                'Next' -> on regarde le premier verbe (ou jusqu'à la virgule)

    Exemple:    sentence: 'If I were here'
                indice: 0
                time: 'Past'
                method: 2
    Cet appel renvoie True car à la position indice + method = 2 il y a bien un verbe
    'were' conjugué au passé.

    Remarque: la méthode 'Any' permet de rechercher n'importe où dans la phrase
    '''
    if time == 'Past':
        time_condition = ['Tense=Past']
    elif time == '-ing':
        time_condition = ['Tense=Pres|VerbForm=Part','VerbForm=Ger']
    else:
        raise Exception('''Le temps rentré n'est pas pris en charge''')
    doc = nlp(sentence)
    phrase = doc.sentences[0].to_dict()
    if method=='Any':
        for mot in phrase:
            if 'feats' in mot:
                for tc in time_condition:
                    if tc in mot['feats']:
                        return True
    elif method == 'UC': #untill commer
        for k in range(indice,len(phrase)):
            mot = phrase[k]
            if is_commer(mot):
                break
            if 'feats' in mot:
                for tc in time_condition:
                    if tc in mot['feats']:
                        return True
    elif method == 'Next':
        for k in range(indice,len(phrase)):
            mot = phrase[k]
            if is_commer(mot):
                break
            if mot['upos'] == 'VERB' or mot['upos'] == 'AUX':
                if 'feats' in mot:
                    for tc in time_condition:
                        if tc in mot['feats']:
                            return True
                    return False
                break
    elif type(method) == int:
        if indice+method < 0 or indice+method >= len(phrase):
            return False
        mot = phrase[indice+method]
        if 'feats' in mot:
            for tc in time_condition:
                if tc in mot['feats']:
                    return True
    return False

def sentencify(text):
    '''
    Input : Un texte complet (string).
    Output : Une liste contenant la liste des phrases du texte ainsi
    que le numéro de la phrase,
    l'indice de début et de fin (list of (string,int,int,int)).
    '''
    liste_phrases = []
    debut_phrase = 0
    num_phrase = 0
    indice_texte = 0
    while indice_texte < len(text):
        if text[indice_texte] in ['.','!','?']:
            if indice_texte+2<len(text) and text[indice_texte+2] == '.':
                indice_texte += 2
            liste_phrases.append((text[debut_phrase:indice_texte+1],num_phrase,debut_phrase,indice_texte))
            debut_phrase = indice_texte + 2
            num_phrase += 1
        indice_texte += 1
    return liste_phrases

def wordify(sentence):
    '''
    Entree : Une phrase (string).
    Sortie : liste des mots constitutifs de la phrase (list of string).
    '''
    return nltk.word_tokenize(sentence)

def is_exception(sentence,list_excep,indice):
    '''
    input:
        sentence: str
        list_excep: list((str,method,str)) avec method qui peut être un int ou 'Any'
        indice: int

    output:
        bool

    la fonction renvoie True si le mot clé à la position indice dans la phrase est une exception
    selon la règle donnée dans list_excep

    Remarque : list_excep ne contient qu'une seule exception, c'est une liste car une exception peut être issue
    de plusieurs conditions exemple When + passé + ! => exception

    Remarque 2 : La terminologie est trompeuse, cette fonction permet à la fois de savoir si le mot
    clé est une exception et si c'est une forme composite.
    '''
    for excep in list_excep:
        if excep[0] == 'Word':
            liste_mots = wordify(sentence.upper())
            if type(excep[1]) == int:
                if ((indice + excep[1] < 0) or (indice + excep[1] >= len(liste_mots)) or (liste_mots[indice+excep[1]] != excep[2])):
                    return False
            else:
                #Rentrer ici les différents mots clés d'emplacement
                if  excep[1] == 'Any':
                    for k in range(len(liste_mots)):
                        if not liste_mots[k] == excep[2]:
                            return False
                else:
                    raise Exception("Cette méthode n'est pas traitée")
        elif excep[0] == 'Verb':
            if not Conjugaison(sentence,indice,excep[2],method=excep[1]):
                return False
        elif excep[0] == 'Upos':
            liste_mots = wordify(sentence.upper())
            if type(excep[1]) == int:
                if (indice + excep[1] < 0) or (indice + excep[1] >= len(liste_mots)):
                    return False
                phrase = nlp(sentence)
                sword = phrase.sentences[0].to_dict()[indice + excep[1]]
                return ('upos' in sword) and (excep[2] in sword['upos'])
            else:
                raise Exception('''Pour l'instant, le upos n'est traité qu'avec la méthode int''')
    return True

def is_rule(sentence):
    '''
    Entree : une phrase (string).
    Sortie : un booléen qui donne si la phrase est une condition (bool).
    '''
    if len(sentence) == 0 or sentence[-1] == '?':
        return False
    liste_mots = wordify(sentence.upper())
    for i in range(len(liste_mots)):
        if liste_mots[i] in kl.keyword_list:
            is_rule = True
            if 'Composite' in kl.keyword_list[liste_mots[i]]:
                is_rule = False
                for list_comp in kl.keyword_list[liste_mots[i]]['Composite']:
                    if is_exception(sentence,list_comp,i):
                        is_rule = True
                        break
            if is_rule and 'Exception' in kl.keyword_list[liste_mots[i]]:
                for list_excep in kl.keyword_list[liste_mots[i]]['Exception']:
                    if is_exception(sentence,list_excep,i):
                        is_rule = False
                        break
            if is_rule:
                return True
    return False

def keyword_extract(text):
    '''
    Entree : un texte (string).
    Sortie : une liste de couple (phrase,indice) où phrase est une phrase
    contenant une condition et indice est le numéro (commençant à 0) de la phrase
    en question (list of (string,int)).
    '''
    indices = []
    i = 0
    liste_phrases = sentencify(text)
    for sentence in [sent for sent,_,_,_ in liste_phrases]:
        su = sentence.upper()
        if is_rule(su):
            indices.append(i)
        i += 1
    return [(liste_phrases[i]) for i in indices]

print(sentencify('If yes then no. Do not worry.'))


import os
import sys
import re
import math

instructionRe = re.compile('^(?P<instruction>(nop|acc|jmp))\s+(?P<amount>[+-][0-9]+)')

class InstructionRun():
    def __init__(self):
        self.accumulate = 0

    def nop(self, x, index):
        return index + 1

    def acc(self, x, index):
        self.accumulate += x
        return index + 1

    def jmp(self, x, index):
        return index + x

class DataCheck():
    def __init__(self):
        self.data = []
        self.mementoData = []
        self.Reset()

    def Reset(self):
        self.stack = []
        self.instructions = InstructionRun()

    def ParseLine(self, line):
        match = instructionRe.match(line)
        if match:
            instruction = match.group('instruction')
            amount = int(match.group('amount'))
            self.data.append((instruction, amount))
        else:
            print("Parse line failure: ", line)

    def LoadInput(self):
        with open('input.txt') as inputFile:
            i = 0
            for line in inputFile:
                if len(line.rstrip()) > 0:
                    self.ParseLine(line)

    def Execute(self, index):
        if index == len(self.data):
            print("program completed!")
            return True
        elif index > len(self.data):
            # Assum program is completed when we reach the end
            print("Index out of program: ", index)
            return False
        if index in self.stack:
            print("Infinit loop: ", index)
            return False
        self.stack.append(index)
        info = self.data[index]
        next_index = getattr(self.instructions, info[0])(info[1], index)
        return self.Execute(next_index)

    def RunTest1(self):
        self.Reset()
        if not self.Execute(0):
            print("Test 1: ", self.stack[-1], self.instructions.accumulate)
        else:
            print("Test 1: ", "program completed")

    def SwapNextInstruction(self, start):
        for i in range(start, len(self.data)):
            if self.data[i][0] == 'nop':
                self.data[i] = ('jmp', self.data[i][1])
                return i
            elif self.data[i][0] == 'jmp':
                self.data[i] = ('nop', self.data[i][1])
                return i
        # no solution found!
        return len(self.data) + 1

    def TestData(self, start_index):
        self.data = self.mementoData.copy()
        index = self.SwapNextInstruction(start_index)
        self.Reset()
        if self.Execute(0):
            return (True, index)
        return (False, index + 1) # Move to next index next time

    def RunTest2(self):
        self.mementoData = self.data.copy()
        index = 0
        success = False
        while not success and index < len(self.data):
            success, index = self.TestData(index)
        self.data = self.mementoData.copy()
        print("Test 2: success: ", success, " replace index:", index, " acc: ", self.instructions.accumulate)

if __name__ == "__main__":
    data = DataCheck()
    data.LoadInput()
    data.RunTest1()
    data.RunTest2()


import argparse
import numpy as np

from data_loader import DataLoader
from rnn import RNN, rnn_training_step, init_params, sample
from optim import Adam

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', default='data/input.txt')
    parser.add_argument('--hidden_size', type=int, default=100)
    parser.add_argument('--seq_length', type=int, default=25)
    parser.add_argument('--sample_every', type=int, default=10000)
    parser.add_argument('--sample_size', type=int, default=200)
    parser.add_argument('--num_epochs', type=int, default=2)
    parser.add_argument('--lr', type=float, default=1e-3)
    parser.add_argument('--print_every', type=int, default=10000)
    return parser.parse_args()

def main():
    args = parse_args()
    with open(args.input, 'r') as fp:
        data_loader = DataLoader(fp.read(), batch_size=args.seq_length)

    rnn = RNN()
    params = init_params(data_loader.vocab_size, hidden_size=args.hidden_size)
    optimizer = Adam(params, lr=args.lr)
    it = 0
    for epoch in range(args.num_epochs):
        hidden_state = np.zeros((1, args.hidden_size))
        for x, y in data_loader:
            if it % args.sample_every == 0:
                one_hot = sample(rnn, hidden_state, x[0], params, args.sample_size)
                generated_text = data_loader.decode(one_hot)
                print(generated_text)
            loss, hidden_state, dparams = rnn_training_step(rnn, hidden_state, x, y, params)
            if it % args.print_every == 0:
                print('iteration: {}, loss: {}'.format(it, loss))
            optimizer.step(dparams)
            it += 1

if __name__ == '__main__':
    main()


import pygame
from projectile import Projectile
from game_object import GameObject

class Invader(GameObject):

    MOVING_RIGHT = 0
    MOVING_RDOWN = 1
    MOVING_LEFT = 2
    MOVING_LDOWN = 3

    'Inits the invader'
    def __init__(self, projectile_list, x, y, max_side_move, max_down_move = 40):
        GameObject.__init__(self, x, y, 30, 30)
        self.speed = 0.05
        self.direction = self.MOVING_RIGHT

        self.projectile_list = projectile_list

        self.max_down_move = max_down_move
        self.max_side_move = max_side_move
        self._moved = max_side_move

        self.fire_delay = 0

    'Calculates the invader move'
    def _move(self, dt):
        #Quantifies the amount it must move
        move = round(self.speed*dt)
        self._moved -= move
        if self._moved < 0:
            move += self._moved

        #moves depending in the current direction
        if self.direction == self.MOVING_RIGHT:
            self.box.x += move
        elif self.direction == self.MOVING_RDOWN or self.direction == self.MOVING_LDOWN:
            self.box.y += move
        elif self.direction == self.MOVING_LEFT:
            self.box.x -= move

        #Determines the next direction
        if self._moved < 0:
            self._next_direction()

    def _next_direction(self):
        #sets the direction it will move to
        self.direction += 1
        if self.direction >3:
            self.direction = 0

        #sets the amount it must move
        if self.direction == self.MOVING_RDOWN or self.direction == self.MOVING_LDOWN:
            self._moved = self.max_down_move
        else:
            self._moved = self.max_side_move

    'Maybe used to speed up the invader velocity'
    def speedUp(self, amount = 1):
        self.speed += amount

    'Calculates the invader shoot'
    def _shoot(self, dt):
        #create a new projectile object moving downward
        if self.fire_delay > 30:
            self.fire_delay = 0

            self.projectile_list.append(Projectile(self.box.x+12.25, self.box.y+15, 2.5))

        #increases the fire time
        else:
            self.fire_delay += 0.01*dt

    '''
    update() is called by the manager class individually for each invader, and will handle calling
    that invader's _move() and _shoot()
    '''
    def update(self, dt):
        self._move(dt)
        self._shoot(dt)

    def render(self, screen):
        pygame.draw.rect(screen, pygame.Color(230,230,230),
                         (self.box.x, self.box.y, self.box.width, self.box.height))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  2 15:29:27 2022

@author: chris
"""

#part 1
def topcalories(path):
    file = open(path, 'r')
    cals = file.readlines()

    total = 0
    totals = []
    for i in cals:
        i = i.strip()
        print(i)
        if i == '':
            print(total)
            totals.append(total)
            total = 0
            continue
        total += int(i)
    totals.append(total)

    return totals

#part 2
def topthreecalories(totals):
    totals.sort(reverse=True)
    return totals[0]+totals[1]+totals[2]

tots = topcalories('input.txt')
print(topthreecalories(tots))


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from scipy.stats import linregress
from sklearn.preprocessing import PolynomialFeatures
import statsmodels.api as sm

df = pd.read_excel(r'E:\大一下学期\SI100\Project\cv信息的提取_汇总_新_带领域(最终版本).xlsx')
groups = df.groupby(df.columns[2])
fields = {
    'Economics of Education': 'education',
    'Applied Microeconomics': 'micro',
    'Labor Economics': 'labor',
    'Environment Economics': 'environ',
    'Public Economics': 'public',
    'Macroeconomics': 'macro',
    'Behavioral Economics': 'behav',
    'Political Economics': 'poli',
    'International Trade': 'trade'or'inter',
    'Regional Economics': 'region',
    'Finance': 'finan',
    'Industrial Organization': 'organization',
    'Game Theory': 'game',
    'Monetary Economics': 'monetary',
    'Urban Economics': 'urban',
    'Econometrics': 'econometrics',
    'Mathematical Economics': 'math',
    'Health Economics': 'health',
    'Economics of Population': 'popu'
}

result = []
for group_name, data in groups:
    data_str = ','.join(data[data.columns[4]].astype(str))
    data_str = data_str.lower()
    GDP = data[data.columns[3]].unique().astype(int)
    GDP = GDP.item()
    GDP = GDP / 10000
    pop = data[data.columns[5]].unique().astype(int)
    pop = pop.item()
    pop = pop / 1000000
    field_counts = {field: 0 for field in fields}

    for field, keyword in fields.items():
        count = data_str.count(keyword)
        field_counts[field] += count

    score = 0
    for field, count in field_counts.items():
        if field == 'Economics of Education':
            score += 5 * count
        elif field == 'Applied Microeconomics':
            score += 5 * count
        elif field == 'Labor Economics':
            score += 5 * count
        elif field == 'Environment Economics':
            score += 4 * count
        elif field == 'Public Economics':
            score += 4 * count
        elif field == 'Macroeconomics':
            score += 8 * count
        elif field == 'Behavioral Economics':
            score += 4 * count
        elif field == 'Political Economics':
            score += 3 * count
        elif field == 'International Trade':
            score += 6 * count
        elif field == 'Regional Economics':
            score += 2 * count
        elif field == 'Finance':
            score += 7 * count
        elif field == 'Industrial Organization':
            score += 7 * count
        elif field == 'Game Theory':
            score += 7 * count
        elif field == 'Monetary Economics':
            score += 8 * count
        elif field == 'Urban Economics':
            score += 4 * count
        elif field == 'Econometrics':
            score += 10 * count
        elif field == 'Mathematical Economics':
            score += 10 * count
        elif field == 'Health Economics':
            score += 4 * count
        elif field == 'Economics of Population':
            score += 4 * count

    line_count = len(data)
    data_count = sum(len(item.split(',')) for item in data[data.columns[4]].astype(str))

    result.append({'国家': group_name, '人数': len(data), '国家得分均值': score / data_count, '人均GDP(万美元)': GDP, '人口(百万人)': pop})

result_df = pd.DataFrame(result)
print(result_df)
column_names = result_df.columns
plt.scatter(result_df[column_names[3]], result_df[column_names[2]], s=result_df[column_names[1]], alpha=0.5)
plt.show()

variables = result_df.iloc[:, [3, 4]].values
y = result_df.iloc[:, 2].values
variables = sm.add_constant(variables)
model = sm.OLS(y, variables)
results = model.fit()
print(results.summary())


#!/usr/bin/env python
# coding: Latin-1

# sudo pip3 install evdev
# sudo pip3 install explorerhat

# if you see the following erro rthen ther is no keyboard connected:

# keyboard = devices[0]
#       IndexError: list index out of range

# Load library functions we want
from evdev import InputDevice, list_devices, ecodes
from explorerhat import motor

# Depend on which way round your wires are to each motor pair these may need to be a negative number
LEFT_MOTOR_MAX_POWER_FWD  = 100
RIGHT_MOTOR_MAX_POWER_FWD = 100

# Depending on which side of your robot wires are connected these might need swapping
left_motor = motor.one
right_motor = motor.two

def get_first_keyboard():

    # see: # https://gpiozero.readthedocs.io/en/stable/recipes.html#keyboard-controlled-robot

    # Get the list of available input devices
    devices = [InputDevice(device) for device in list_devices()]
    # Filter out everything that's not a keyboard. Keyboards are defined as any
    # device which has keys, and which specifically has keys 1..31 (roughly Esc,
    # the numeric keys, the first row of QWERTY plus a few more) and which does
    # *not* have key 0 (reserved)
    must_have = {i for i in range(1, 32)}
    must_not_have = {0}
    devices = [
        dev
        for dev in devices
        for keys in (set(dev.capabilities().get(ecodes.EV_KEY, [])),)
        if must_have.issubset(keys)
        and must_not_have.isdisjoint(keys)
    ]
    # Pick the first keyboard

    return devices[0]

# Motor Control

def forward():
    left_motor.speed(LEFT_MOTOR_MAX_POWER_FWD)
    right_motor.speed(RIGHT_MOTOR_MAX_POWER_FWD)

def backward():
    left_motor.speed(-LEFT_MOTOR_MAX_POWER_FWD)
    right_motor.speed(-RIGHT_MOTOR_MAX_POWER_FWD)

def left():
    left_motor.speed(-LEFT_MOTOR_MAX_POWER_FWD)
    right_motor.speed( RIGHT_MOTOR_MAX_POWER_FWD)

def right():
    left_motor.speed( LEFT_MOTOR_MAX_POWER_FWD)
    right_motor.speed(-RIGHT_MOTOR_MAX_POWER_FWD)

def stop():
    left_motor.speed(0)
    right_motor.speed(0)

keypress_actions = {
    # Arrow keys:
    ecodes.KEY_UP: forward,
    ecodes.KEY_DOWN: backward,
    ecodes.KEY_LEFT: left,
    ecodes.KEY_RIGHT: right,

    # 8BitDo 'keys'
    ecodes.KEY_C: forward,
    ecodes.KEY_D: backward,
    ecodes.KEY_E: left,
    ecodes.KEY_F: right,
}

try:
    print('Press CTRL+C to quit')
    keyboard = get_first_keyboard()

    for event in keyboard.read_loop():
        if event.type == ecodes.EV_KEY and event.code in keypress_actions:
            if event.value == 1:  # key down
                keypress_actions[event.code]()
            if event.value == 0:  # key up
                stop()

except KeyboardInterrupt:
    # CTRL+C exit, disable all drives
    print("stop")
    motor.stop()
print("Bye")


import django

PROJECT_APPS = (
    "django_fsm",
    "testapp",
)

INSTALLED_APPS = (
    "django.contrib.contenttypes",
    "django.contrib.auth",
    "guardian",
) + PROJECT_APPS

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",  # this is default
    "guardian.backends.ObjectPermissionBackend",
)

DATABASE_ENGINE = "sqlite3"
SECRET_KEY = "nokey"
MIDDLEWARE_CLASSES = ()
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
    }
}

if django.VERSION < (1, 9):

    class DisableMigrations(object):
        def __contains__(self, item):
            return True

        def __getitem__(self, item):
            return "notmigrations"

    MIGRATION_MODULES = DisableMigrations()
else:
    MIGRATION_MODULES = {
        "auth": None,
        "contenttypes": None,
        "guardian": None,
    }

ANONYMOUS_USER_ID = 0

DEFAULT_AUTO_FIELD = "django.db.models.AutoField"


from django.urls import path,include
from . import views
from rest_framework import routers,authtoken

router = routers.DefaultRouter()
router.register(r'movies', views.AddMovie)
router.register(r'movies_timings', views.AddTimings)
router.register('user', views.userviewsets)

urlpatterns = [
    path('',include(router.urls)),
    path('api-token-auth/', authtoken.views.obtain_auth_token),
    path('purchase/<int:id>/',views.purchase,name='purchase'),
    path('total_admin/',views.total_admin,name='total_admin'),
]


lst = [[]]
with open("input/day_01.txt", "r", encoding="utf-8") as file:
    for row in file:
        if row == "\n":
            lst.append([])
        else:
            lst[-1].append(int(row.strip()))

maximum = 0
for i in lst:
    _sum = sum(i)
    if _sum > maximum:
        maximum = _sum

print(maximum)