"""Solution of the task."""

class Tree:
    """Represent tree text image."""
    __slots__ = ('_data', )

    def __init__(self, tiers: int):
        self._data = self._create_tree_data(tiers)

    @property
    def width(self) -> int:
        """Return image width."""
        return len(self._data[0])

    @property
    def height(self) -> int:
        """Return image height."""
        return len(self._data)

    @property
    def data(self) -> list[str]:
        """Return image data."""
        return self._data

    def append_air_lines(self, amount: int):
        """Add filler on top of image."""
        if not amount:
            return

        new_data: list[str] = [' ' * self.width] * amount
        new_data.extend(self._data)
        self._data = new_data

    @staticmethod
    def _create_tree_data(tiers: int) -> list[str]:
        data: list[str] = []

        current_tier = ['*']
        for _ in range(0, tiers):
            current_tier.append(current_tier[-1] + '**')
            data.extend(current_tier)

        max_stars_count = len(data[-1])
        data = [line.center(max_stars_count) for line in data]
        return data

def print_forest(*args: int) -> str:
    """Print forest into string."""
    trees = [Tree(tiers) for tiers in args]

    max_height = max(trees, key=lambda item: item.height).height
    for tree in trees:
        tree.append_air_lines(max_height - tree.height)

    image_rows: list[str] = []
    for i in range(0, max_height):
        image_rows.append(''.join(tree.data[i] for tree in trees))

    return '\n'.join(image_rows)


import ast

from typing import List, Tuple, Union

from nagini_translation.lib import silver_nodes as sil
from nagini_translation.lib.context import Context
from nagini_translation.lib.jvmaccess import JVM
from nagini_translation.lib.program_nodes import (
    PythonMethod,
    PythonVar,
)
from nagini_translation.lib.typedefs import (
    Expr,
    Info,
    Field,
    Method,
    Position,
    Predicate,
    Stmt,
    StmtsAndExpr,
    VarDecl,
)
from nagini_translation.lib.typeinfo import TypeInfo
from nagini_translation.lib.util import (
    get_func_name,
    InvalidProgramException,
    UnsupportedException,
)
from nagini_translation.lib.viper_ast import ViperAST
from nagini_translation.translators.abstract import TranslatorConfig
from nagini_translation.translators.common import CommonTranslator
from nagini_translation.translators.obligation.loop import (
    LoopObligationTranslator,
)
from nagini_translation.translators.obligation.manager import (
    ObligationManager,
)
from nagini_translation.translators.obligation.method import (
    MethodObligationTranslator,
)
from nagini_translation.translators.obligation.obligation_info import (
    PythonMethodObligationInfo,
)
from nagini_translation.translators.obligation.waitlevel import (
    WaitLevelTranslator,
)

class ObligationTranslator(CommonTranslator):
    """Translator for obligations."""

    def __init__(self, config: TranslatorConfig, jvm: JVM, source_file: str,
                 type_info: TypeInfo, viper_ast: ViperAST) -> None:
        super().__init__(config, jvm, source_file, type_info, viper_ast)
        self._obligation_manager = ObligationManager()
        self._method_translator = MethodObligationTranslator(
            config, jvm, source_file, type_info, viper_ast,
            self._obligation_manager)
        self._loop_translator = LoopObligationTranslator(
            config, jvm, source_file, type_info, viper_ast,
            self._obligation_manager)
        self._wait_level_translator = WaitLevelTranslator(
            config, jvm, source_file, type_info, viper_ast,
            self._obligation_manager)

    def enter_loop_translation(
            self, node: Union[ast.While, ast.For], ctx: Context,
            err_var: PythonVar = None) -> None:
        """Update context with info needed to translate loop."""
        self._loop_translator.enter_loop_translation(node, ctx, err_var)

    def leave_loop_translation(self, ctx: Context) -> None:
        """Remove loop translation info from context."""
        self._loop_translator.leave_loop_translation(ctx)

    def create_while_node(
            self, ctx: Context, cond: Expr,
            invariants: List[Expr],
            local_vars: List[VarDecl],
            body: Stmt, node: Union[ast.While, ast.For]) -> List[Stmt]:
        """Construct a while loop AST node with obligation stuff."""
        return self._loop_translator.create_while_node(
            ctx, cond, invariants, local_vars, body, node)

    def translate_obligation_contractfunc_call(
            self, node: ast.Call, ctx: Context, impure: bool) -> StmtsAndExpr:
        """Translate a call to obligation contract function."""
        func_name = get_func_name(node)
        if func_name == 'MustTerminate':
            if not impure:
                raise InvalidProgramException(node, 'invalid.contract.position')
            return self._translate_must_terminate(node, ctx)
        elif func_name == 'MustRelease':
            if not impure:
                raise InvalidProgramException(node, 'invalid.contract.position')
            return self._translate_must_release(node, ctx)
        elif func_name == 'WaitLevel':
            raise InvalidProgramException(
                node, 'invalid.wait_level.use')
        elif func_name == 'Level':
            raise InvalidProgramException(
                node, 'invalid.level.use')
        else:
            raise UnsupportedException(
                node, 'Unsupported contract function.')

    def translate_must_invoke_token(
            self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
        """Translate a call to ``token``."""
        if ctx.obligation_context.is_translating_loop():
            return self._loop_translator.translate_must_invoke(node, ctx)
        else:
            return self._method_translator.translate_must_invoke(node, ctx)

    def translate_must_invoke_ctoken(
            self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
        """Translate a call to ``ctoken``."""
        if ctx.obligation_context.is_translating_loop():
            return self._loop_translator.translate_may_invoke(
                node, ctx)
        elif ctx.obligation_context.is_translating_posts:
            if ctx.actual_function.name != 'Gap':
                raise InvalidProgramException(
                    node, 'invalid.postcondition.ctoken_not_allowed')
            else:
                return self._method_translator.translate_may_invoke(
                    node, ctx)
        else:
            return self._method_translator.translate_may_invoke(
                node, ctx)

    def is_wait_level_comparison(self, node: ast.Compare,
                                 ctx: Context) -> bool:
        """Check if we are comparing with ``WaitLevel``."""
        return self._wait_level_translator.is_wait_level_comparison(
            node, ctx)

    def translate_wait_level_comparison(self, node: ast.Compare,
                                        ctx: Context) -> StmtsAndExpr:
        """Translate comparison with ``WaitLevel``."""
        return self._wait_level_translator.translate_wait_level_comparison(
            node, ctx)

    def create_level_call(self, expr: sil.RefExpression) -> sil.PermExpression:
        return self._wait_level_translator.create_level_call(expr)

    def create_level_below(
            self, expr: sil.PermExpression,
            residue_level_var: sil.PermExpression,
            ctx: Context) -> sil.BoolExpression:
        return self._wait_level_translator.create_level_below(
            expr, residue_level_var, ctx)

    def initialize_current_wait_level(
            self, current_wait_level: sil.PermExpression,
            residue_level_var: sil.PermExpression,
            ctx: Context) -> sil.BoolExpression:
        return self._wait_level_translator.initialize_current_wait_level(
            current_wait_level, residue_level_var, ctx)

    def _translate_must_terminate(
            self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
        """Translate a call to ``MustTerminate``."""
        if ctx.obligation_context.is_translating_loop():
            return self._loop_translator.translate_must_terminate(node, ctx)
        elif ctx.obligation_context.is_translating_posts:
            raise InvalidProgramException(
                node, 'obligation.must_terminate.in_postcondition')
        else:
            if ctx.current_function and ctx.current_function.pure:
                raise InvalidProgramException(node, 'invalid.contract.position')
            return self._method_translator.translate_must_terminate(node, ctx)

    def _translate_pure_must_terminate(
            self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
        stmts, measure = self.translate_expr(node.args[0], ctx, target_type=self.viper.Int)
        if stmts:
            raise InvalidProgramException(node, "purity.violated")
        pos = self.to_position(node, ctx)
        info = self.no_info(ctx)
        obligation_info = self._method_translator._get_obligation_info(ctx)
        guarded_obligation_instance = obligation_info.get_instance(node)
        if guarded_obligation_instance.guard:
            guards = []
            for g in guarded_obligation_instance.guard:
                stmts, new_guard = self.translate_expr(g, ctx, target_type=self.viper.Bool)
                if stmts:
                    raise InvalidProgramException(g, "purity.violated")
                guards.append(new_guard)
            guard_exp = self._conjoin(guards, pos, info)
        else:
            guard_exp = None
        decreases = self.viper.DecreasesTuple([measure], guard_exp, pos, info)
        return [], decreases

    def _translate_must_release(
            self, node: ast.Call, ctx: Context) -> StmtsAndExpr:
        """Translate a call to ``MustRelease``."""
        if ctx.obligation_context.is_translating_loop():
            return self._loop_translator.translate_must_release(node, ctx)
        else:
            return self._method_translator.translate_must_release(node, ctx)

    def get_obligation_preamble(
            self,
            ctx: Context) -> Tuple[List[Predicate], List[Field]]:
        """Construct obligation preamble.

        To track each obligation we use predicates which are defined in
        this preamble.
        """
        predicates = self._obligation_manager.create_predicates(self)
        fields = self._obligation_manager.create_fields(self)
        return predicates, fields

    def create_method_node(     # pylint: disable=too-many-arguments
            self, ctx: Context, name: str,
            args: List[VarDecl], returns: List[VarDecl],
            pres: List[Expr], posts: List[Expr],
            local_vars: List[VarDecl], body: List[Stmt],
            position: Position, info: Info,
            method: PythonMethod = None,
            overriding_check: bool = False) -> Method:
        """Construct method AST node with additional obligation stuff."""
        return self._method_translator.create_method_node(
            ctx, name, args, returns, pres, posts, local_vars, body,
            position, info, method, overriding_check)

    def create_method_call_node(
            self, ctx: Context, method_name: str, args: List[Expr],
            targets: List[Expr], position: Position, info: Info,
            target_method: PythonMethod = None,
            target_node: ast.Call = None) -> List[Stmt]:
        """Construct a method call AST node with obligation stuff."""
        return self._method_translator.create_method_call_node(
            ctx, method_name, args, targets, position, info,
            target_method, target_node)

    def create_method_fork(self, ctx: Context, targets, thread: Expr,
                           position: Position, info: Info,
                           target_node: ast.Call = None) -> List[Stmt]:
        return self._method_translator.create_method_fork(
            ctx, targets, thread, position, info, target_node)

    def create_obligation_info(self, method: PythonMethod) -> object:
        """Create obligation info for the method."""
        info = PythonMethodObligationInfo(
            self._obligation_manager, method, self)
        info.traverse_contract()
        return info


from itertools import combinations
from math import ceil
from collections import defaultdict

def multi2(N, m):
    N2 = N
    a = list(range(m, N + m))
    while N2 > 1:
        N1 = N2 % 2; N2 = N2 // 2 + N1
        for i in range(N2 - N1):
            a[i] *= a[N2 + i]
        a = a[0: N2]
    return a[0]

def C(m, n):
	ret = multi2(n, m - n + 1) // multi2(n, 1)
	return ret % 12345787

def makeList(r, g, b, number):
	ret = defaultdict(list)
	for colors in combinations([r, g, b], 2):
		c1, c2 = colors
		for n in range(0, number):
			cnt = 0
			for num1 in range(1, n // c1 + 1):
				for num2 in range(1, n // c2 + 1):
					if n - c1 * num1 - c2 * num2 < 0:
						continue
					bnum = C(n - c1 * num1 - c2 * num2 + num1 + num2, num1 + num2)
					cnum = C(num1 + num2, num1)
					cnt += bnum * cnum
			ret[colors].append(cnt)
	return ret

def Function(n, r, g, b):
	cnt = 0
	for colors in combinations([r, g, b], 2):
		c1, c2 = colors
		for num1 in range(1, n // c1 + 1):
			for num2 in range(1, n // c2 + 1):
				if n - c1 * num1 - c2 * num2 < 0:
					continue
				bnum = C(n - c1 * num1 - c2 * num2 + num1 + num2, num1 + num2) % 12345787
				cnum = C(num1 + num2, num1) % 12345787
				cnt += bnum * cnum
	return cnt % 12345787

def insane_tri_bicolor_tiling(n, r, g, b):
	'''number = 30
	chooseList = makeList(r, g, b, number)
	cnt = 0
	for cs in combinations([r, g, b], 2):
		cnt += f(n, cs, number, chooseList)
	return cnt % 12345787'''
	return Function(n, r, g, b)

print(insane_tri_bicolor_tiling(100, 2, 3, 4))


import numpy as np
from collections import namedtuple
from scipy.stats import norm

# local
import estimator
from misc import *

TestResult = namedtuple("TestResult", ["test_val", "res_joint", "res_sep"])
EPOCHS = 10000
EPOCHS_BOOTSTRAP = 500

def cheat_estimation(train_func, is_separated, *args, **kwargs):
    tau = .1
    quantile = norm.ppf(tau)

    theta1 = dict_of_pars(np.array([[0.0, 0.2], [0.2, 0.0]]) * quantile,
                          np.array([[0.5, 0.0], [0.0, 0.5]]),
                          np.array([[0.5, 0.5]]) * quantile)
    theta2 = dict_of_pars(np.array([[0.0, 0.2], [0.2, 0.0]]) * quantile,
                          np.array([[-0.5, 0.0], [0.0, 0.5]]),
                          np.array([[0.5, 0.5]]) * quantile)
    if not is_separated:
        cheat_pars = [theta1, theta2]
    else:
        cheat_pars = [pars_left_right(theta1, theta1), pars_left_right(theta1, theta2),
                      pars_left_right(theta2, theta2)]

    ress = [train_func(*args, **kwargs, init_pars=pars) for pars in cheat_pars]
    _, idx = min([(res.loss, i) for (i, res) in enumerate(ress)])
    return ress[idx]

def _train_mvcaviar(*args, **kwargs):
    return cheat_estimation(estimator.train_mvcaviar, *args, **kwargs)

def _train_mvcaviar_w_shift(*args, **kwargs):
    return cheat_estimation(estimator.train_mvcaviar_w_shift, *args, **kwargs)

def _train_mvcaviar_separated(*args, **kwargs):
    return cheat_estimation(estimator.train_mvcaviar_separated2, *args, **kwargs)

class _CPTestWrapper:

    def __init__(self, Y, tau, breaks, message="X", prev_quantile=None):
        self.Y = Y
        self.breaks = breaks
        self.tau = tau
        self.message = message
        self.counter = 0
        (self.tmax, self.n) = np.shape(Y)
        self.prev_quantile = prev_quantile

        self.do_test()

    def do_test(self):
        self.res_joint = _train_mvcaviar(self.Y, self.tau, epochs=EPOCHS, prev_quantile=self.prev_quantile)
        self.res_breaks = [
            _train_mvcaviar_separated(self.Y, self.tau, break_point, epochs=EPOCHS,
                                               #init_pars=pars_left_right(self.res_joint.pars, self.res_joint.pars),
                                               prev_quantile=self.prev_quantile)
            for break_point in self.breaks
        ]
        self.test_val = self.res_joint.loss - min([res.loss for res in self.res_breaks])

        print("Task {}: original test done".format(self.message))

    def __call__(self, weights):
        vals = []

        for i, break_point in enumerate(self.breaks):
            shift = pars_diff(get_right_pars(self.res_breaks[i].pars), get_left_pars(self.res_breaks[i].pars))
            res_joint = estimator.train_mvcaviar_w_shift(
                self.Y, self.tau, break_point, shift,
                prev_quantile=self.res_breaks[i].prev_quantile,
                init_pars=get_left_pars(self.res_breaks[i].pars),
                sample_weights=weights, epochs=EPOCHS_BOOTSTRAP
            )
            res_break = estimator.train_mvcaviar_separated(
                self.Y, self.tau, break_point,
                prev_quantile=self.res_breaks[i].prev_quantile,
                init_pars=pars_left_right(res_joint.pars, pars_sum(res_joint.pars, shift)),
                sample_weights=weights, epochs=EPOCHS_BOOTSTRAP
            )
            vals.append(res_joint.loss - res_break.loss)

        self.counter += 1
        print("Task {}: did {} bootstrap tests".format(self.message, self.counter))
        return max(vals)

def bstrap_cp_test(Y, tau, breaks, SIM_NUM, message="X", prev_quantile=None, cheat_pars=None):
    assert(len(breaks) > 0)
    wrapper = _CPTestWrapper(Y, tau, breaks, message=message, prev_quantile=prev_quantile)

    np.random.seed(1)

    weights_list = [generate_random_weights(np.shape(Y)[0]-1) for x in range(SIM_NUM)]
    btest_vals = list(map(wrapper, weights_list))
    return wrapper.test_val, btest_vals

def select_homogeneity_interval_with_single_break(Y, tau, lengths, SIM_NUM=400):
    return


import streamlit as st

"""Framework para executar vÃ¡rios aplicativos Streamlit
   como um Ãºnico aplicativo."""

class MultiApp:

    def __init__(self):
        self.apps = []

    """
    Framework for combining multiple streamlit applications.
    Usage:
        def foo():
            st.title("Hello Foo")
        def bar():
            st.title("Hello Bar")
        app = MultiApp()
        app.add_app("Foo", foo)
        app.add_app("Bar", bar)
        app.run()
    It is also possible keep each application in a separate file.
        import foo
        import bar
        app = MultiApp()
        app.add_app("Foo", foo.app)
        app.add_app("Bar", bar.app)
        app.run()
    """

    def add_app(self, title, func):
        """Adds a new application.
        Parameters
        ----------
        func:
            the python function to render this app.
        title:
            title of the app. Appears in the dropdown in the sidebar.
        """
        self.apps.append({
            "title": title,
            "function": func
        })

    def run(self):
        # COMANDOS DA BARRA LATERAL
        padding = 0
        st.sidebar.markdown(f""" <style>
        .reportview-container .main .block-container{{
            padding-top: {padding}rem;
            padding-bottom: {padding}rem;
        }} </style> """, unsafe_allow_html=True)

        st.sidebar.title("ðŸš€ Veritas")
        #st.sidebar.title("Menu")
        st.sidebar.markdown("---")

        app = st.sidebar.radio(
            '',
            self.apps,
            format_func=lambda veritas: veritas['title'])

        app['function']()

        st.sidebar.markdown("---")

        if st.sidebar.button("Fale com a gente!", key="5"):
            st.sidebar.markdown('''
                Grupo Tera

               moxÃº - dairenkonmajime@gmail.com

               felipe - fmonteirogabriel@gmail.com

               lauro - lauro.namiki@gmail.com

               mel - meliza.caug@gmail.com

               rodolpho - rodolphoya@gmail.com

                ''')
            pass


r1, r2, r3 = set(), set(), set()

while True:
    x = input()

    if x == "":
        break

    if x == "-1":
        r3 = r3 | (r1 & r2)
        r1 = r1 ^ r2
        r2 = set()
        continue

    r2.add(x)

print(*r1 - r3)

Решения/Элементы теории множеств. Множества в Python/Дополнительные задачи/Антиматерия.py

Антиматерия.py


import urllib.request
from bs4 import BeautifulSoup
import re
import os
import requests
import subprocess
import sys
import inquirer

ost_title_list = []
ost_dict = {}
ost_name = ""
dir_path = "./test/"
ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) '\
'AppleWebKit/537.36 (KHTML, like Gecko) '\
'Chrome/55.0.2883.95 Safari/537.36 '

def fetch_ost_dict():
    query = sys.argv[1].replace(" ", "+")
    base_url = 'https://downloads.khinsider.com/'
    search_url = base_url +'/search?search=' + query
    req = urllib.request.Request(search_url, headers={'User-Agent': ua})
    html = urllib.request.urlopen(req)
    soup = BeautifulSoup(html, "html.parser")
    mp3s = soup.find_all(href=re.compile("downloads.khinsider.com/game-soundtracks/album/"))
    for mp3 in mp3s:
        title = mp3.get_text()
        url = mp3.get('href')
        ost_dict[title] = url
        ost_title_list.append(title)
    return(ost_dict)

def select_ost(ost_dict):
    ost_candidate_list = []
    global ost_name
    ost_name = ""
    for title in ost_dict:
        ost_candidate_list.append(title)
    ost_candidates = [
        inquirer.List('selected',
            message="What OST do you want download?",
            choices=ost_candidate_list,
        ),
    ]

    requires = inquirer.prompt(ost_candidates)
    requires_list = list(requires.values())
    ost_name = requires_list[0]
    return(ost_name)

def get_mp3(ost_name, ost_dict):
    mp3_url_list = []
    ost_url = ost_dict[ost_name]
    req = urllib.request.Request(ost_url, headers={'User-Agent': ua})
    html = urllib.request.urlopen(req)
    soup = BeautifulSoup(html, "html.parser")
    mp3s = soup.find_all(href=re.compile(".mp3"))
    for mp3 in mp3s:
        mp3_url = mp3.get('href')
        if mp3_url not in mp3_url_list:
            mp3_url_list.append(mp3_url)
    for mp3_url in mp3_url_list:
        base_url = 'https://downloads.khinsider.com'
        url = base_url + mp3_url
        dir_path = url.split('/')[5]
        try:
            os.mkdir(dir_path)
        except FileExistsError:
            pass
        req = urllib.request.Request(url, headers={'User-Agent': ua})
        html = urllib.request.urlopen(req)
        soup = BeautifulSoup(html, "html.parser")
        audio_url = soup.find('audio').get('src')
        subprocess.call('wget -P %s %s' % (dir_path, audio_url), shell=True)

def main():
    global ost_title_list
    global ost_name
    fetch_ost_dict()
    select_ost(ost_dict)
    get_mp3(ost_name, ost_dict)

if __name__ == "__main__":
    main()


list2=input()
m=0
n=0
k=0
t=0
for i in range(len(list2)):
    if list2[i]=='[':
        m=i
    if list2[i]==']':
        n=i
    if list2[i]=='k':
        k=i
    if list2[i]=='t':
        t=i
str1=[]
str2=[]
str3=[]
for i in range(len(list2)):
    if i>m and i<n:
        str1.append(list2[i])
    if i>k and i<t:
        str2.append(list2[i])
    if i>t :
        str3.append(list2[i])
def num(list):
    str=[]
    k=1
    temp=[]
    res=[]
    for i in range(len(list)):
        if list[i] == ',' or list[i] == ' ' or list[i] == '=':
            k = 0
            if (len(temp) != 0):
                strr = "".join(temp)
                res.append(strr)
            temp = []
        else:
            temp.append(list[i])
        if i==len(list)-1:
            if (len(temp) != 0):
                strr = "".join(temp)
                res.append(strr)
    return res

list=num(str1)
a=int(num(str2)[0])
b=int(num(str3)[0])
def contains(nums, k, t) -> bool:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if abs(int(nums[i]) - int(nums[j])) <= t and j - i  <= k:
                    return True
        return False
if contains(list,a,b):
    print('true')
else:
    print('false')


import socket
import sys
import time
import json
from argparse import ArgumentParser
import cv2
import numpy as np

def build(method='POST', path='/security/camera/alert', msg=None):
    method = method
    path = path
    data = dict()
    data['time'] = time.ctime()
    data['epoch'] = int(time.time() * 1000)
    if msg is None:
        data['message'] = 'Motion Detected'
    else:
        data['message'] = msg

    return (method + ' ' + path + '\r\n\r\n' + json.dumps(data)).encode()

def alert(host_ip=None, hostname=None, port=None, data=None):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("Socket successfully created")
    except socket.error as err:
        print("socket creation failed with error {}".format(err))

    if host_ip is None:
        if hostname is None:
            print("Error: Need to include either a hostname or host ip")
            sys.exit()
        else:
            try:
                host_ip = socket.gethostbyname(hostname)
            except socket.gaierror:
                # this means could not resolve the host
                print("there was an error resolving the host")
                sys.exit()
    if port is None:
        port = 80

    try:
        s.connect((host_ip, port))

        print("the socket has successfully connected to {}".format(host_ip))

        if data is None:
            data = build()

        s.send(data)

        print(data)

        s.close()

        print("Successfully sent message")
    except ConnectionRefusedError as e:
        print("[ERROR] Unable to connect to server")
        s.close()

def main():
    parser = ArgumentParser()
    parser.add_argument("--host-name", "-hn", required=False, type=str)
    parser.add_argument("--port", "-p", required=False, type=int)
    args = parser.parse_args()
    cv2.namedWindow("TEST")
    vc = cv2.VideoCapture(0)
    if vc.isOpened():
        rval, frame = vc.read()
    else:
        rval = False

    while rval:
        cv2.imshow("TEST", frame)
        rval, frame = vc.read()
        key = cv2.waitKey(20)
        if key == 27:
            break

    cv2.destroyWindow("TEST")
    vc.release()
    i = 0
    while i < 5:
        msg = input("Input message")
        alert(hostname=args.host_name, port=args.port, data=build(msg=msg))
        i += 1

    # alert(host_ip='192.168.0.190')

if __name__ == '__main__':
    main()


# Imports the required dependencies
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon

# create the Example class, which will create the window object
class Example(QWidget):       # name declaration, will inherit stuff from the QWidget class
    def __init__(self):       # constructor for the inherited class, so will construct the QWidget class
        super().__init__()    # super() is to call the class above it, so line is constructing the QWidget class
        self.initUI()         # this line constructs the actual window, and is the function call for the next definition

    def initUI(self):                         # this function of the Example class will create the actual window
        self.setGeometry(300, 300, 300, 220)  # setGeometry will resize and move the created window
        self.setWindowTitle('Icon')           # will set the title of the window
        self.setWindowIcon(QIcon('web.png'))  # will locate an image and set it as the window icon
        self.show()                           # actually creates the window

if __name__ == '__main__':
    app = QApplication(sys.argv)   # required starting of the application

    ex = Example()                 # creating the Example and assigning the name ex
    sys.exit(app.exec_())          # will exit the application when triggered


import glob
import pandas as pd
import os
from xml.etree import ElementTree as ET

def convert_annots(annotations_path: str) -> pd.DataFrame:
    """
    Function to convert xml of annotations to a dataframe for easier processing
    Args:
        annots: a list of string file paths
        image_dir: path to the image folder

    Returns: a daframe containing xy, height, width, and label class
    """

    annotations = glob.glob(os.path.join(annotations_path, '*.xml'))
    data = {
        'image_path': [],
        'xmin': [],
        'ymin': [],
        'xmax': [],
        'ymax': [],
        'labels': []
    }

    for annot in annotations:
        tree = ET.parse(annot)
        root = tree.getroot()
        file_name = root.find('filename').text
        image_path = glob.glob(os.path.join(annotations_path, file_name))[0]

        for obj in root.findall('object'):
            data['image_path'].append(image_path)
            data['labels'].append(obj.find('name').text)
            for bb in obj.find('bndbox'):
                data[bb.tag].append(int(bb.text))

    return pd.DataFrame(data)


import re
import os
import subprocess

##START = re.compile(r'\[Ordinal/Name Pointer\] Table')
##TABLE = re.compile(r'^\s+\[([\s*\d*)\] (\w*)')

START = re.compile(r'ordinal\s+hint\s+RVA\sname')

def dump_table(dllname):
    return subprocess.Popen(['dumpbin.exe', '-exports', dllname], stdout=subprocess.PIPE).communicate()[0]

def generate_def(dllname, deffile):
    dump = dump_table(dllname).split('\n')
    for i,x in enumerate(dump):
        if 'RVA' in x:
            break
    else:
        raise ValueError("Symbol table not found")

    syms = []
    for line in dump[i+2::]:
        if 'Summary' in line:
            break
        l = line.split();
        if len(l) == 4:
            syms.append((int(l[0]), l[3]))

    d = open(deffile, 'w')
    d.write('LIBRARY        %s\n' % os.path.split(dllname)[-1])
    d.write(';CODE          PRELOAD MOVEABLE DISCARDABLE\n')
    d.write(';DATA          PRELOAD SINGLE\n')
    d.write('\nEXPORTS\n')
    for s in syms:
        d.write('%s  @%s\n' % (s[1], s[0]))
    d.close()

dllname = r'C:\Windows\System32\python26.dll'
defname = 'python26.def'
generate_def(dllname, defname)


import time

import telebot
from telebot import types
from settings import TG_TOKEN

global count_yes, count_no, count_yes_no
global chat_id
global ind
global ind_girl

bot = telebot.TeleBot(TG_TOKEN)

quest = ["Есть ли у тебя друзья?", "Появляется ли на твоём лице улыбка, когда ты смотришь на мужчин?",
         "Часто ли ты засматриваешься на мужчин, когда едешь на работу/учёбу?",
         "Хотел ли бы ты тройничёк с мужчиной и красивой девушкой?", "Часто ли ты говоришь комплименты мужчинам?",
         "Представлял ли ты мужчину в своей сексуальной фантазии?",
         "Думал ли ты, что можешь полностью отказаться от общения с мужчинами?",
         "Считаешь ли ты сумасшедшими людей, которые ущемляют права мужчин?"]

quest_girl = ["Есть ли у тебя подруги?", "Появляется ли у тебя улыбка на лице, когда ты смотришь на девушку?",
              "Часто ли ты засматриваешься на девушек, когда едешь на работу/учёбу?",
              "Хотела бы ты тройничёк с красивой девушкой и мужчиной?", "Часто ли ты говоришь девушкам комплименты?",
              "Представляла ли ты девушку в своей сексуальной фантазии?",
              "Думала ли ты, что можешь прекратить общение с девушками?",
              "Считаешь ли ты сумасшедшими людей, которые ущемляют права женщин?"]

@bot.message_handler(commands=['about'])
def about(message):
    global chat_id
    chat_id = message.chat.id
    bot.send_message(chat_id,
                     "Я - бот🤖, позволяющий проверить насколько ты гомосексуален(или склонна к лесбиянству)\n\n"
                     "Моего создателя можно найти, отсканировав следующий QR-код:")
    qr_code = open('data/t_me-filledevoler.jpg', 'rb')
    bot.send_photo(chat_id, qr_code)

@bot.message_handler(commands=['start'])
def start(message):
    global chat_id
    chat_id = message.chat.id
    global count_yes, count_no
    global ind
    global ind_girl
    count_yes = count_no = 0
    ind = 0
    ind_girl = 0

    bot.send_message(chat_id,
                     f'Приветствую, ❤{message.from_user.first_name}❤!\n' + 'Если ты решил(а) воспользоваться '
                                                                                'этим ботом, '
                                                                                'значит тебе интересна твоя '
                                                                                'ориентация 👻\n',
                     parse_mode='HTML')
    show_button(message)

def show_button(message):
    global chat_id
    chat_id = message.chat.id
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("Я парень👦🏻")
    btn2 = types.KeyboardButton("Я девушка👩🏼")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, "Для начала давай определимся с полом:", reply_markup=markup)

@bot.message_handler(content_types=['text'])
def parse_user_text(message):
    global count_yes, count_no, count_yes_no
    global chat_id
    chat_id = message.chat.id
    if message.text == "Я парень👦🏻":
        bot.send_message(chat_id, "Ну что, сладкий, поехали!", parse_mode="HTML")
        first_quest(message)
    elif message.text == "Я девушка👩🏼":
        bot.send_message(chat_id, "Ну что, сладкая, поехали!", parse_mode="HTML")
        first_quest_girl(message)
    elif message.text == "А":
        bot.send_message(chat_id, f"{count_yes} {count_no}")
    elif message.text == "Big Fat Cock":
        bot.send_message(chat_id, "Поздравляю! У вас реально big fat cock!", parse_mode="HTML")
    else:
        bot.send_message(chat_id, "Я не могу обработать такое сообщение 😢")

def first_quest(message):
    global ind
    global chat_id
    chat_id = message.chat.id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Да👍🏻", callback_data="yes")
    btn2 = types.InlineKeyboardButton("Нет👎🏻", callback_data="no")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, quest[ind], reply_markup=markup)

def first_quest_girl(message):
    global chat_id
    global ind
    chat_id = message.chat.id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Yes👍🏻", callback_data="da")
    btn2 = types.InlineKeyboardButton("No👎🏻", callback_data="net")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, quest_girl[ind], reply_markup=markup)

@bot.callback_query_handler(func=lambda call: True)
def callback_da(call):
    global chat_id
    global count_yes
    global count_no
    global ind
    if call.message:
        if call.data == "da":
            show_answer_res("")
            count_yes += 1
            ind += 1
            if ind >= len(quest_girl):
                final_quest_girl()
            else:
                send_girl(quest_girl[ind])
        elif call.data == "net":
            show_answer_res("")
            count_no += 1
            ind += 1
            if ind >= len(quest_girl):
                final_quest_girl()
            else:
                send_girl(quest_girl[ind])

        elif call.data == "first":
            bot.send_message(chat_id, "Какая ты умничка! Не предала свою подружку, горжусь тобой❤")
            sticker = open('data/momhave.webp', 'rb')
            bot.send_sticker(chat_id, sticker)
            beatiful_download()
            func_end_girl()

        elif call.data == "second":
            bot.send_message(chat_id, "Вот ты сука! Променяла подругу на мужчину...гадость🤢")
            sticker = open('data/momless.webp', 'rb')
            bot.send_sticker(chat_id, sticker)
            beatiful_download()
            func_end_girl()

        else:
            if call.data == "yes":
                show_answer_res("Да")
                count_yes += 1
                # global ind
                ind += 1
                if ind >= len(quest):
                    final_quest()
                else:
                    send(quest[ind])
            elif call.data == "no":
                # elif call.data == "no":
                show_answer_res("Нет")
                count_no += 1
                ind += 1
                if ind >= len(quest):
                    final_quest()
                else:
                    send(quest[ind])
            else:
                if call.data == "girl":
                    bot.send_message(chat_id, "Ах ты сука-то такая! Кента на женщину променял! Фу!")
                    stick = open('data/sticker.webp', 'rb')
                    bot.send_sticker(chat_id, stick)
                    bot.send_message(chat_id, "Не очень хочется продолжать с тобой дискуссию, но вот твой результат⚡")
                    beatiful_download()
                    func_end()
                    # МБ НИЖЕ КРАШ
                elif call.data == "boy":
                    bot.send_message(chat_id, "Хорош! Тест на п#дора прошёл! Кенты могут тобой гордиться")
                    stick = open('data/sticker_good.webp', 'rb')
                    bot.send_sticker(chat_id, stick)
                    beatiful_download()
                    func_end()

def send_girl(message):
    global chat_id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Yes👍🏻", callback_data="da")
    btn2 = types.InlineKeyboardButton("No👎🏻", callback_data="net")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, message, reply_markup=markup)

@bot.callback_query_handler(func=lambda call: True)
def callback_yes(call):
    global chat_id
    global count_yes
    global count_no
    global ind
    if call.message:
        if call.data == "yes":
            show_answer_res("Да")
            count_yes += 1
            # global ind
            ind += 1
            if ind >= len(quest):
                final_quest()
            else:
                send(quest[ind])
        elif call.data == "no":
            # elif call.data == "no":
            show_answer_res("Нет")
            count_no += 1
            ind += 1
            if ind >= len(quest):
                final_quest()
            else:
                send(quest[ind])
        else:
            if call.data == "girl":
                bot.send_message(chat_id, "Ах ты сука-то такая! Кента на женщину променял! Фу!")
                stick = open('data/sticker.webp', 'rb')
                bot.send_sticker(chat_id, stick)
                bot.send_message(chat_id, "Не очень хочется продолжать с тобой дискуссию, но вот твой результат⚡")
                beatiful_download()
                func_end()
                # МБ НИЖЕ КРАШ
            elif call.data == "boy":
                bot.send_message(chat_id, "Хорош! Тест на п#дора прошёл! Кенты могут тобой гордиться")
                stick = open('data/sticker_good.webp', 'rb')
                bot.send_sticker(chat_id, stick)
                beatiful_download()
                func_end()

def send(message):
    # bot.send_message(chat_id, message)
    global chat_id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Да👍🏻", callback_data="yes")
    btn2 = types.InlineKeyboardButton("Нет👎🏻", callback_data="no")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, message, reply_markup=markup)

def show_answer_res(answer):
    global chat_id
    bot.send_message(chat_id, "-----------------------------------------")

def final_quest():
    global chat_id
    bot.send_message(chat_id, "Итак, финальный вопрос❗", parse_mode="HTML")
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Подругу🧍🏼♀", callback_data="girl")
    btn2 = types.InlineKeyboardButton("Друга🧍🏻", callback_data="boy")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, "Тебя зовут гулять друг и подруга. Кого ты выберешь?", reply_markup=markup)

def final_quest_girl():
    global chat_id
    bot.send_message(chat_id, "Внимание! послоедний вопрос")
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton("Подругу💃🏻", callback_data="first")
    btn2 = types.InlineKeyboardButton("Друга🕺🏻", callback_data="second")
    markup.add(btn1, btn2)
    bot.send_message(chat_id, "Тебя зовёт гулять подруга и друг. Кого ты выберешь?", reply_markup=markup)

def func_end():
    global count_yes, count_no
    global chat_id
    final_res = round(count_yes / 8 * 100)
    bot.send_message(chat_id, f"Вы гомосексуальны на {final_res}%", parse_mode="HTML")
    if final_res > 80:
        bot.send_message(chat_id, "Поздравляю! В этой жизни нет ничего лучше, чем мужчина нетрадиционных взглядов😘")
        audio = open('data/Oleg_Gazmanov_-_Moi_yasnye_dni_right_version_Gachi_Remix_69147154.mp3', 'rb')
        bot.send_audio(chat_id, audio)
    elif final_res > 50:
        bot.send_message(chat_id,
                         "Вижу, что ты находишься на переплетении судьбы. Надеюсь, дальше ты будешь двигаться в "
                         "правильном направлении, if you know what I mean🏳🌈😉")
    else:
        bot.send_message(chat_id,
                         "Что ж, вижу ты традиционных взглядов. Ничего не сказать, твой выбор. Спасибо,"
                         " что воспользовался ботом💀")

def func_end_girl():
    global count_yes, count_no
    global chat_id
    final_res = round(count_yes / 8 * 100)
    bot.send_message(chat_id, f"Вы лесбиянка на {final_res}%", parse_mode="HTML")
    if final_res > 80:
        bot.send_message(chat_id, "Поздравляю! В этой жизни нет ничего лучше, чем девушки, любящие других девушек😘")
    elif final_res > 50:
        bot.send_message(chat_id,
                         "Вижу, что ты находишься на переплетении судьбы. Надеюсь, дальше ты будешь двигаться в "
                         "правильном направлении, if you know what I mean🏳🌈😉")
    else:
        bot.send_message(chat_id,
                         "Что ж, вижу ты традиционных взглядов. Ничего не сказать, твой выбор. Спасибо,"
                         " что воспользовалась ботом💀")

def beatiful_download():
    global chat_id
    down = bot.send_message(chat_id, "Результаты появятся через 3", parse_mode="HTML")
    time.sleep(2)
    bot.edit_message_text(chat_id=chat_id, message_id=down.id, text="Результаты появятся через 2",
                          parse_mode="HTML")
    time.sleep(2)
    bot.edit_message_text(chat_id=chat_id, message_id=down.id, text="Результаты появятся через 1",
                          parse_mode="HTML")
    time.sleep(2)
    bot.edit_message_text(chat_id=chat_id, message_id=down.id, text="А вот и результат🎉",
                          parse_mode="HTML")

bot.polling(none_stop=True)


# -*- encoding: utf-8 -*-
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, InvalidPage

from aplication.core.utils.url_gen import urlGen
from aplication.news_feed.models import NewsFeedModels, FeedModels
from aplication.news_feed.utils import split_news

def posts_feed_blog(request, slug):

    feed = get_object_or_404(FeedModels, slug=slug)
    news_list = NewsFeedModels.objects.filter(feed=feed)
    news_list = split_news(news_list)
    news_paginator = Paginator(news_list, 12)

    try:
        page = int(request.REQUEST.get('page', '1'))
    except ValueError:
        page = 1

    try:
        news = news_paginator.page(page)
    except (EmptyPage, InvalidPage):
        # If page is out of range (e.g. 9999), deliver last page of results.
        news = news_paginator.page(news_paginator.num_pages)

    url = urlGen()
    pageURI = url.generate('page', request.GET)
    items = len(news_list)

    context = {
        'title_page': 'Blog - %s' % (feed.title),
        'prefix_sub_title_page': 'Notícas',
        'sub_title_page': feed.title,
        'news_list': news,
        'total_item': items,
        'pageURI': pageURI,
        'current': page,
    }
    return render(request, 'news_feed/blog.html', context)


import unittest
import json
from src.loader import Loader

class TestLoader(unittest.TestCase):
    def setUp(self):
        self.loader = Loader(db_uri='mongodb://localhost:27017/', db_name="test_fever_unittest")
        self.coll_purchase = "purchase_detail"
        self.coll_events = "events_info"

    def tearDown(self):
        self.loader.delete_many(self.coll_purchase, {})
        self.loader.delete_many(self.coll_events, {})

    def test_insert_many_events(self):
        with open('/opt/repos/plan-test/test/out/events.json') as f:
            data = json.load(f)

        self.loader.insert_many(self.coll_events, data)

    def test_insert_many_purchase(self):
        with open('/opt/repos/plan-test/test/out/purchase.json') as f:
            data = json.load(f)

        self.loader.insert_many(self.coll_events, data)

    def test_insert_one(self):
        num_before = self.loader.count_elems(self.coll_events)

        self.loader.insert_one(self.coll_events,
                               {"city": "MAD", "event": "end_app_session", "os": "ios", "plan_id": "6846",
                                "time": 1530057600000, "user_id": 611248618,
                                "_id": "611248618|nan|2018-06-27 00:00:00|end_app_session|ios"})

        num_after = self.loader.count_elems(self.coll_events)

        self.assertEqual(num_after, num_before + 1)

    # def test_insert_many_one_by_one(self):
    #     num_before = self.loader.count_elems(self.coll_events)
    #
    #     with open('/opt/repos/plan-test/test/out/events.json') as f:
    #         data = json.load(f)
    #
    #     for json_elem in data:
    #         self.loader.insert_one(self.coll_events, json_elem)
    #
    #     num_after = self.loader.count_elems(self.coll_events)
    #
    #     self.assertEqual(num_after, num_before + len(data))

    # def test_upsert_many_one_by_one(self):
    #     jsons = [{"city": "MAD", "event": "end_app_session", "os": "ios", "plan_id": "6846",
    #      "time": 1530057600000, "user_id": 611248618,
    #      "_id": "611248618|nan|2018-06-27 00:00:00|end_app_session|ios"},
    #
    #     {"city": "MAD", "event": "end_app_session", "os": "ios", "plan_id": "6846",
    #      "time": 1530057600000, "user_id": 611248618,
    #      "_id": "ABC|nan|2018-06-27 00:00:00|end_app_session|ios"}]
    #
    #     collection = self.loader.get_collection(self.coll_events)
    #     for document in jsons:
    #         id_mongo = document['_id']
    #         collection.update_one(filter={'_id': id_mongo}, update={"$set": document},upsert=True)

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


import json
import logging
from threading import Thread

import backoff
import monotonic

from posthog.request import APIError, DatetimeSerializer, batch_post

try:
    from queue import Empty
except ImportError:
    from Queue import Empty

MAX_MSG_SIZE = 900 * 1024  # 900KiB per event

# The maximum request body size is currently 20MiB, let's be conservative
# in case we want to lower it in the future.
BATCH_SIZE_LIMIT = 5 * 1024 * 1024

class Consumer(Thread):
    """Consumes the messages from the client's queue."""

    log = logging.getLogger("posthog")

    def __init__(
        self,
        queue,
        api_key,
        flush_at=100,
        host=None,
        on_error=None,
        flush_interval=0.5,
        gzip=False,
        retries=10,
        timeout=15,
    ):
        """Create a consumer thread."""
        Thread.__init__(self)
        # Make consumer a daemon thread so that it doesn't block program exit
        self.daemon = True
        self.flush_at = flush_at
        self.flush_interval = flush_interval
        self.api_key = api_key
        self.host = host
        self.on_error = on_error
        self.queue = queue
        self.gzip = gzip
        # It's important to set running in the constructor: if we are asked to
        # pause immediately after construction, we might set running to True in
        # run() *after* we set it to False in pause... and keep running
        # forever.
        self.running = True
        self.retries = retries
        self.timeout = timeout

    def run(self):
        """Runs the consumer."""
        self.log.debug("consumer is running...")
        while self.running:
            self.upload()

        self.log.debug("consumer exited.")

    def pause(self):
        """Pause the consumer."""
        self.running = False

    def upload(self):
        """Upload the next batch of items, return whether successful."""
        success = False
        batch = self.next()
        if len(batch) == 0:
            return False

        try:
            self.request(batch)
            success = True
        except Exception as e:
            self.log.error("error uploading: %s", e)
            success = False
            if self.on_error:
                self.on_error(e, batch)
        finally:
            # mark items as acknowledged from queue
            for item in batch:
                self.queue.task_done()
            return success

    def next(self):
        """Return the next batch of items to upload."""
        queue = self.queue
        items = []

        start_time = monotonic.monotonic()
        total_size = 0

        while len(items) < self.flush_at:
            elapsed = monotonic.monotonic() - start_time
            if elapsed >= self.flush_interval:
                break
            try:
                item = queue.get(block=True, timeout=self.flush_interval - elapsed)
                item_size = len(json.dumps(item, cls=DatetimeSerializer).encode())
                if item_size > MAX_MSG_SIZE:
                    self.log.error("Item exceeds 900kib limit, dropping. (%s)", str(item))
                    continue
                items.append(item)
                total_size += item_size
                if total_size >= BATCH_SIZE_LIMIT:
                    self.log.debug("hit batch size limit (size: %d)", total_size)
                    break
            except Empty:
                break

        return items

    def request(self, batch):
        """Attempt to upload the batch and retry before raising an error"""

        def fatal_exception(exc):
            if isinstance(exc, APIError):
                # retry on server errors and client errors
                # with 429 status code (rate limited),
                # don't retry on other client errors
                if exc.status == "N/A":
                    return False
                return (400 <= exc.status < 500) and exc.status != 429
            else:
                # retry on all other errors (eg. network)
                return False

        @backoff.on_exception(backoff.expo, Exception, max_tries=self.retries + 1, giveup=fatal_exception)
        def send_request():
            batch_post(self.api_key, self.host, gzip=self.gzip, timeout=self.timeout, batch=batch)

        send_request()


import base64

import web

from os import path
from inginious.frontend.common.task_problems import DisplayableCodeFileProblem, DisplayableMultipleChoiceProblem
from inginious.frontend.webapp.pages.course_admin.utils import INGIniousAdminPage

class CourseStudentTaskSubmission(INGIniousAdminPage):
    """ List information about a task done by a student """

    def GET_AUTH(self, courseid, username, taskid, submissionid):  # pylint: disable=arguments-differ
        """ GET request """
        course, task = self.get_course_and_check_rights(courseid, taskid)
        return self.page(course, username, task, submissionid)

    def POST_AUTH(self, courseid, username, taskid, submissionid):  # pylint: disable=arguments-differ
        course, task = self.get_course_and_check_rights(courseid, taskid)
        is_admin = self.user_manager.has_admin_rights_on_course(course)

        webinput = web.input()
        submission = self.submission_manager.get_submission(submissionid, False)
        if "replay" in webinput and is_admin:
            self.submission_manager.replay_job(task, submission)
        elif "replay-copy" in webinput:  # Authorized for tutors
            self.submission_manager.replay_job(task, submission, True)
            web.seeother(self.app.get_homepath() + "/course/" + courseid + "/" + taskid)
        elif "replay-debug" in webinput and is_admin:
            self.submission_manager.replay_job(task, submission, True, "ssh")
            web.seeother(self.app.get_homepath() + "/course/" + courseid + "/" + taskid)

        return self.page(course, username, task, submissionid)

    def page(self, course, username, task, submissionid):
        """ Get all data and display the page """
        submission = self.submission_manager.get_submission(submissionid, False)
        if not submission or username not in submission["username"] or submission["courseid"] != course.get_id() or submission["taskid"] != \
                task.get_id():
            raise web.notfound()
        submission = self.submission_manager.get_input_from_submission(submission)
        submission = self.submission_manager.get_feedback_from_submission(submission, show_everything=True)

        to_display = []
        for problem in task.get_problems():
            if problem.get_id() in submission["input"]:  # present in input and in task
                data = {
                    "id": problem.get_id(),
                    "name": problem.get_name(),
                    "defined": True,
                    "present": True,
                    "context": problem.get_header(),
                    "content": None,
                    "language": "plain",
                    "feedback": submission.get("problems", {}).get(problem.get_id(), None),
                    "base64": None,
                    "mime": "text/plain"
                }
                if isinstance(problem, DisplayableCodeFileProblem):
                    extension = path.splitext(submission["input"][problem.get_id()]["filename"])[1]
                    try:
                        if extension in [".zip", ".pdf", ".tgz"]:
                            data["language"] = extension[1:]
                            data["mime"] = "application/" + extension[1:]
                        data["content"] = submission["input"][problem.get_id()]["value"].decode('utf-8')
                    except:
                        data["content"] = None
                    data["base64"] = base64.b64encode(submission["input"][problem.get_id()]["value"]).decode('utf-8')
                elif isinstance(problem, DisplayableMultipleChoiceProblem):
                    data["content"] = "Multiple choice question: \n"
                    chosen = submission["input"][problem.get_id()]
                    if not isinstance(chosen, list):
                        chosen = [chosen]
                    for c in chosen:
                        choice = problem.get_choice_with_index(int(c))
                        if choice is None:
                            t = "unknown"
                            m = ""
                        else:
                            t = "valid" if choice.get("valid", False) else "invalid"
                            m = choice["text"]
                        data["content"] += "\t- %s (%s): \n\t%s\n" % (c, t, m)
                    data["base64"] = base64.b64encode(str(submission["input"][problem.get_id()]).encode('utf-8')).decode('utf-8')
                elif isinstance(submission["input"][problem.get_id()], str):
                    data["content"] = submission["input"][problem.get_id()]
                    data["base64"] = base64.b64encode(str(submission["input"][problem.get_id()]).encode('utf-8')).decode('utf-8')
                    try:
                        data["language"] = problem.get_original_content()["language"]
                    except:
                        pass
                to_display.append(data)
            else:  # not present in input, but present in task
                data = {
                    "id": problem.get_id(),
                    "name": problem.get_name(),
                    "defined": True,
                    "present": False,
                    "context": problem.get_header(),
                    "content": None,
                    "language": "plain",
                    "feedback": submission.get("problems", {}).get(problem.get_id(), None),
                    "base64": None,
                    "mime": "text/plain"
                }
                to_display.append(data)

        done_id = [d["id"] for d in to_display]
        for pid in submission["input"]:
            if pid not in done_id:
                data = {
                    "id": pid,
                    "name": pid,
                    "defined": False,
                    "present": True,
                    "context": None,
                    "content": None,
                    "language": "plain",
                    "feedback": submission.get("problems", {}).get(pid, None),
                    "base64": None,
                    "mime": "text/plain"
                }
                if isinstance(submission["input"][pid], dict):  # file
                    extension = path.splitext(submission["input"][pid]["filename"])[1]
                    try:
                        if extension in [".zip", ".pdf", ".tgz"]:
                            data["language"] = extension[1:]
                            data["mime"] = "application/" + extension[1:]
                        data["content"] = submission["input"][pid]["value"].decode('utf-8')
                    except:
                        data["content"] = None
                    data["base64"] = base64.b64encode(submission["input"][pid]["value"]).decode('utf-8')
                elif isinstance(submission["input"][pid], str):
                    data["content"] = submission["input"][pid]
                    data["base64"] = base64.b64encode(str(submission["input"][pid]).encode('utf-8')).decode('utf-8')
                to_display.append(data)

        return self.template_helper.get_renderer().course_admin.submission(course, username, task, submissionid, submission, to_display)


import re
import urllib.request
import csv

def GetHtml(url):
    try:
        respond = urllib.request.urlopen(url)
        return respond.read()
    finally:
        respond.close()

def GetElement(html,filter):
    re_filter = re.compile(filter)
    html=html.decode('utf-8')
    result = re.findall(re_filter,html)
    return result

def GetBookInfo(url, sum, writer):
    try:
        respone = GetHtml(url).decode('utf-8').encode('utf-8')
    except:
        return sum
    # print(respone)
    filter1 = '<title>(.*)《.*</title>'
    get_author = GetElement(respone,filter1)
    if (get_author == []):
        return sum
    # print(get_author)
    filter2 = '<title>.*《(.*)》.*</title>'
    get_bookname = GetElement(respone,filter2)
    # print(get_bookname)
    filter3 = '類別：(.*)'
    get_bookTag = GetElement(respone,filter3)
    # print(get_bookTag)
    filter4 = '<meta name="description" content="(.*)"/>'
    get_bookSummary = GetElement(respone,filter4)
    # print(get_bookSummary)
    data = [url]
    data = data + get_bookname + get_author + get_bookTag + get_bookSummary
    try:
        writer.writerow(data)
    except:
        return sum
    return (sum + 1)

csvfile = open("test.csv", "w")
writer = csv.writer(csvfile)
nameList = ['url','bookname','author','tag','summary']
writer.writerow(nameList)
sum = 0;
for i in range(130000, 140000):
    url = "http://www.sto.cc/"+str(i)+"-1/"
    sum = GetBookInfo(url, sum, writer)
    print(i, sum)
csvfile.close()


t = int(input())
liN = []
liWords = []
for i in range(t):
    liN.append(int(input()))
    aline = input().split(" ")
    liWords.append(aline)
    # print(liWords)

# print("------")

for i in range(t):
    li = liWords[i]
    listWOOrder = set()
    liCnt = []
    for j in li:
        listWOOrder.add("".join(sorted(list(j))))
    for j in listWOOrder:
        cnt = 0
        for k in li:
            if set(list(k)) == set(list(j)):
                cnt += 1
        liCnt.append(cnt)

    liCnt = sorted(liCnt)
    for j in range(len(liCnt)):
        print(liCnt[j], end="")
        if j != len(liCnt) - 1:
            print(" ", end="")
    print()


#!/usr/local/bin/python
# coding=utf-8

from selenium import webdriver
import unittest
import os
import json
import time
import datetime
import timeit
import logging
import sys
sys.path.append("..")
import write_log
import check_status
import create_log

# Generate log folder and file.
# Default log level is INFO (everything). Go to create_log.py to change.
folderName = create_log.createLog("ChesProdTitle")

class ChesProdTest(unittest.TestCase):
    # Name of the JSON file containing the sites to test
    json_file = "sites-prod.json" # can modify later

    # Here are the class variables shared among all instances "self" of ChesDevNewTitleTest
    ERRORCOLOR = "\u001b[31m" #red
    WARNINGCOLOR = "\u001b[33m" #yellow
    SUCCESSCOLOR = "\u001b[32m" #green
    DEFAULTCOLOR = "\u001b[0m" #white
    browser = None
    browserType = None
    sites = None

    timeStart = None

    while (browserType!='chrome' and browserType!='firefox'):
        browserType = input("Enter the browser you wish to test on (chrome or firefox): ")

# SETUP FUNCTIONS------------------------------------------------------------------

    def __init__(self, *args, **kwargs):
        super(ChesProdTest, self).__init__(*args, **kwargs)
        if self.browser is None:
            self.setupBrowser()
        if self.sites is None:
            self.setupSites()

    def __del__(self):
        if self.browser is not None:
            try:
                self.browser.close()
                self.browser.quit()
            except:
                pass

    def setUp(self):
        if self.timeStart is None:
            self.timeStart = timeit.default_timer()

    def tearDown(self):
        if self.timeStart is not None:
            timeElapsed = timeit.default_timer() - self.timeStart
            write_log.logSummary(self.browserType, timeElapsed)

    def setupBrowser(self):
        if self.browserType=='firefox':
            try:
                driver = webdriver.Firefox()
                driver.implicitly_wait(30)
                self.browser = driver
            except:
                write_log.logSetupError("firefox")
                print("Unable to load firefox")
        else: # default to chrome
            try:
                driver = webdriver.Chrome()
                driver.implicitly_wait(30)
                self.browser = driver
            except:
                write_log.logSetupError("chrome")
                print("Unable to load chrome")

    def setupSites(self):
        #use json credentials file
        with open(os.getcwd() + '/' + self.json_file) as data_file:
            data = json.load(data_file)
            self.sites = {}
            for siteData in data['sites']:
                site = {}
                site['url']= siteData['url']
                site['title']= siteData['title']
                self.sites[siteData['siteName']] = site

# TEST FUNCTIONS--------------------------------------------------------------

    def test_admissions(self):
        self.run_test('admissions')

    def test_admstats(self):
        self.run_test("admstats")

    def test_btconference(self):
        self.run_test("btconference")

#     def test_common(self):
#         self.run_test("common")

    def test_conrooms(self):
        self.run_test("conrooms")

    def test_careercentersecure_student(self):
        self.run_test("careercentersecure-student")

    def test_careercentersecure_staff(self):
        self.run_test("careercentersecure-staff")

    def test_careercentersecure_public(self):
        self.run_test("careercentersecure-public")

#     def test_eds(self):
#         self.run_test("eds")

    def test_eop(self):
        self.run_test("eop")

    def test_eop2(self):
        self.run_test("eop2")
#
    def test_fixit(self):
        self.run_test("fixit")

    def test_fixit_queue(self):
        self.run_test("fixit-queue")
#
    def test_jdbs(self):
        self.run_test("jdbs")
#
    def test_orientation(self):
        self.run_test("orientation")

#     def test_ucforyoutransfer(self):
#         self.run_test("ucforyoutransfer")

#     def test_volunteer(self):
#         self.run_test("volunteer")

# HELPER FUNCTION-------------------------------------------------------------------

    def run_test(self,siteName):
        assert(self.browser is not None)
        assert(self.sites is not None)
        browser = self.browser
        print('\n')

        # Check that the site url exists.
        try:
            site = self.sites[siteName]
        except:
            write_log.logErrorMsg("your disk. Check to make sure the "+self.json_file+" is up to date.\n", "Test terminated prematurely. You are missing the "+siteName+" url")
            print(self.ERRORCOLOR+"ERROR: "+self.DEFAULTCOLOR + siteName + " credentials not found on your disk.")
            return

        site = self.sites[siteName]

        # Once the site is found, make sure HTTP status code is 200, 301, or 302.
        # Call the function to get status code from file check_status.py.
        result = check_status.checkStatus(site['url'], [200, 301, 302])
        if result==False:
            return # exit test

        try:
            browser.get(site['url'])
            write_log.logInfoMsg(siteName, "title test started")
            print("Testing " + siteName)# + " with " + browser.name.capitalize() + " Found site['title'] " + browser.title)
            browser.implicitly_wait(30)

            # You can also search for 'text' in browser.page_source rather than browser.title
            if site['title'] not in browser.title:
                write_log.logErrorMsg(siteName+'\n', "Desired title '" + site['title'] + "' not found")
                print(self.ERRORCOLOR+"ERROR:"+self.DEFAULTCOLOR+ "desired title '" + site['title'] + "' not found on " + siteName)
                browser.save_screenshot(folderName+'/error_'+siteName+'.png')
            else:
                write_log.logSuccess(siteName+'\n', "title")
                print(self.SUCCESSCOLOR+"passed:"+self.DEFAULTCOLOR+ "'" + site['title'] + "' found on " + siteName)

            #print("PASS: %s using %s" % (siteName,browser.name.capitalize()))

        except Exception as e:
            print(e)
            #raise e
        finally:
            browser.close()

# Kick off the test!
if __name__ == "__main__":
    #print("\n\u001b[33smAll test logs and screenshots will be saved to the following folder in your current directory:\n" + folderName + "\n\u001b[0m")
    unittest.main()


from copy import deepcopy
import boto3

DEFAULT_RESPONSE = {
    'statusCode': 500
}

class SSMHelper:

    def __init__(self, logger):
        self.client = boto3.client('ssm')
        self.logger = logger
        self.parameter_name = '/GerenciaSolo/SNSTopicARN'

    def get_parameter(self) -> dict:
        final_response = deepcopy(DEFAULT_RESPONSE)
        try:
            response = self.client.get_parameter(Name=self.parameter_name)
            message = f'Parametro {self.parameter_name} obtido!'
            final_response['statusCode'] = 200
            final_response['topicArn'] = response.get('Parameter').get('Value')
        except Exception as e:
            final_response['topicArn'] = ''
            message = f'Erro ao obter parametro .:. Exception: {e}'

        self.logger.info(message)
        final_response['message'] = message
        return final_response


import pendulum
from airflow import DAG
from airflow.providers.postgres.operators.postgres import PostgresOperator

with DAG(
    dag_id="jinja-example",
    schedule_interval="@daily",
    start_date=pendulum.datetime(2022, 1, 1, tz="Europe/Brussels"),
) as dag:
    revenue = PostgresOperator(
        task_id="query_revenue",
        postgres_conn_id="postgres_default",
        sql="sql/daily_revenue.sql",
        params={"table": "SALES"},
    )


import warnings

try:
    from pymol import cmd
    import chempy
except ImportError:
    warnings.warn(
        'Cannot import PyMOL: functionality will suffer (you can ignore this if you are just building the documentation).')

def restrain_hbonds_gmx(selection, filename, strength=1000, distance=None,
                        mindist_detect=1.1, maxdist_detect=2.5, anglemin_detect=130, verbose=False):
    """
    DESCRIPTION

        Generate harmonic distance restraints for hydrogen bonds

    USAGE

        restrain_hbonds_gmx selection, filename [, strength [, distance [, mindist_detect [, maxdist_detect [, anglemin_detect ]]]]]]

    ARGUMENTS

        selection: the selection to operate on, containing the donors, the acceptors and the hydrogens

        filename: the file name to write the constraints to (a GROMACS .itp file)

        strength: bond strength (kJ mol-1 nm-2) (default: 1000)

        distance: the hydrogen-acceptor distance to restrain to (default: the current value)

        mindist_detect: minimum hydrogen-acceptor distance to consider (default: 1.1 A)

        maxdist_detect: maximum hydrogen-acceptor distance to consider (default: 2.5 A)

        anglemin_detect: minimum donor-hydrogen-acceptor angle to consider (default: 130°)

    NOTES

        A GROMACS .itp file will be written. The restraint potential has the form:

        V(r) = strength * ( r - distance )^2

    """
    mindist = float(mindist_detect)
    maxdist = float(maxdist_detect)
    anglemin = float(anglemin_detect)
    strength = float(strength)
    if distance is not None:
        distance = float(distance)

    with open(filename, 'wt') as f:
        f.write('; hydrogen bond distance restraints\n')
        f.write('[ bonds ]\n')
        f.write(';       ai        aj  funct        b0     kb       b0_B   kb_B\n')
        for donor, hydrogen, acceptor, dist, angle in find_beta_hbonds(selection, mindist, maxdist, anglemin, verbose):
            f.write(
                '{:10d}{:10d}   6   {:10.4f} {:.6f} {:10.4f} {:.6f}; original distance: {:.6f} nm, original angle: {:.2f} degrees\n'.format(
                    hydrogen, acceptor, distance / 10. if distance is not None else dist / 10., strength,
                    distance / 10. if distance is not None else dist / 10., 0.0, dist / 10., angle))

def find_beta_hbonds(selection, mindist, maxdist, anglemin, verbose: bool = False, nitrogen_atomnames='N+NT',
                     oxygen_atomnames='O+OT1+OT2', hydrogen_atomnames='H+HN+HT1+HT2+HT+H1+H2+H3'):
    """
    Detect hydrogen bonds in beta peptides (and probably other peptides, too)

    Inputs:
        selection: a selection containing everything,

    """
    donors = cmd.get_model('({}) and name {}'.format(selection, nitrogen_atomnames))
    acceptors = cmd.get_model('({}) and name {}'.format(selection, oxygen_atomnames))
    if verbose:
        print('Finding hydrogen bonds in selection {}'.format(selection))
        print('Donors: {}'.format(len(donors.atom)))
        print('Acceptors: {}'.format(len(acceptors.atom)))
    for d in donors.atom:
        assert isinstance(d, chempy.Atom)
        hydrogens = cmd.get_model(
            '(neighbor (({}) and index {})) and name {}'.format(selection, d.index, hydrogen_atomnames))
        if verbose:
            print('Looking at donor {}, having {} hydrogens'.format(d.index, len(hydrogens.atom)))
        for h in hydrogens.atom:
            assert isinstance(h, chempy.Atom)
            for a in acceptors.atom:
                assert isinstance(a, chempy.Atom)
                # check hydrogen-acceptor distance
                dist = cmd.get_distance('({}) and name {} and index {}'.format(selection, oxygen_atomnames, a.index),
                                        '({}) and name {} and index {}'.format(selection, hydrogen_atomnames, h.index))
                cmd.unpick()
                angle = cmd.get_angle(
                    '({}) and name {} and index {}'.format(selection, oxygen_atomnames, a.index),
                    '({}) and name {} and index {}'.format(selection, hydrogen_atomnames, h.index),
                    '({}) and name {} and index {}'.format(selection, nitrogen_atomnames, d.index))
                if verbose:
                    print('Distance between hydrogen {} and acceptor {}: {}'.format(h.index, a.index, dist))
                    print('Angle between donor {}, hydrogen {} and acceptor {}: {}'.format(d.index, h.index, a.index,
                                                                                angle))
                if (dist <= float(maxdist)) and (dist >= float(mindist)) and (angle >= float(anglemin)):
                    yield d.index, h.index, a.index, dist, angle


from falcon import HTTPUnauthorized

from .models import Token
from ..utils import utcnow_datetime_aware, Session_Maker

# Authenticates Request
def authenticate_request(req, Api_Session):
    value = req.get_header('Authorization')

    # Check existence of token
    if value is None:
        msg = 'Authorization required'
        raise HTTPUnauthorized('Unauthorized', msg)
    else:
        value = value.split(' ')[1]

    # Verify validity of token
    sm = Session_Maker(Api_Session)
    with sm as session:
        token = session.query(Token).filter(Token.value == value).first()

        # Check existence of token
        if token is None:
            msg = "Invalid token."
            raise HTTPUnauthorized("Invalid token", msg)

        # Check expiration of token
        if utcnow_datetime_aware() > token.expires_at:
            msg = "Expired token."
            raise HTTPUnauthorized("Expired token", msg)


from flask import Flask, render_template,request,jsonify, make_response
import requests
import numpy as np
import bs4 as bs
import urllib.request
import re
import nltk

app = Flask(__name__)

def get_content(url,lines):
    scraped_data = urllib.request.urlopen(url)
    article = scraped_data.read()

    parsed_article = bs.BeautifulSoup(article,'lxml')

    paragraphs = parsed_article.find_all('p')

    article_text = ""

    for p in paragraphs:
        article_text += p.text

    # Removing Square Brackets and Extra Spaces
    article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
    article_text = re.sub(r'\s+', ' ', article_text)

    # Removing special characters and digits
    formatted_article_text = re.sub('[^a-zA-Z]', ' ', article_text )
    formatted_article_text = re.sub(r'\s+', ' ', formatted_article_text)
    sentence_list = nltk.sent_tokenize(article_text)
    stopwords = nltk.corpus.stopwords.words('english')

    word_frequencies = {}

    for word in nltk.word_tokenize(formatted_article_text):
        if word not in stopwords:
            if word not in word_frequencies.keys():
                word_frequencies[word] = 1
            else:
                word_frequencies[word] += 1
    maximum_frequncy = max(word_frequencies.values())

    for word in word_frequencies.keys():
        word_frequencies[word] = (word_frequencies[word]/maximum_frequncy)
    sentence_scores = {}

    for sent in sentence_list:
        for word in nltk.word_tokenize(sent.lower()):
            if word in word_frequencies.keys():
                if len(sent.split(' ')) < 30:
                    if sent not in sentence_scores.keys():
                        sentence_scores[sent] = word_frequencies[word]
                    else:
                        sentence_scores[sent] += word_frequencies[word]

    import heapq
    summary_sentences = heapq.nlargest(int(lines), sentence_scores, key=sentence_scores.get)

    summary = ' '.join(summary_sentences)
    return(summary)

@app.route("/")

def test():
    return render_template("files.html")

def func():
    return "Task completed"

@app.route("/create", methods = ["POST"])

def create_entry():
    req = request.get_json()
    print(req)

    name = req["name"]
    lines = req["message"]
    print(name)

    url = (name)
    lines = (lines)

    url_content = get_content(url,lines)

    res=make_response(jsonify({"message": url_content}),200)

    return res

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


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

# # Welcome to Covid19 Data Analysis Notebook
# ------------------------------------------

# ### Let's Import the modules

# In[2]:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
print('Modules are imported.')

# ### importing covid19 dataset
# importing "Covid19_Confirmed_dataset.csv" from "./Dataset" folder.
#

# In[3]:

corona_dataset_csv = pd.read_csv("Datasets/covid19_Confirmed_dataset.csv")
corona_dataset_csv.head(10)

# #### checking the shape of the dataframe

# In[4]:

corona_dataset_csv.shape

# ### Delete the useless columns

# In[5]:

corona_dataset_csv.drop(["Lat","Long"],axis=1, inplace=True)

# In[6]:

corona_dataset_csv.head(10)

# ###  Aggregating the rows by the country

# In[7]:

corona_dataset_aggregated = corona_dataset_csv.groupby("Country/Region").sum()

# In[8]:

corona_dataset_aggregated.head()

# In[9]:

corona_dataset_aggregated.shape

# ###  Visualizing data related to a country for example China
# visualization always helps for better understanding of our data.

# In[10]:

corona_dataset_aggregated.loc["China"]

# ### Calculating a good measure
# we need to find a good measure reperestend as a number, describing the spread of the virus in a country.

# In[11]:

corona_dataset_aggregated.loc['China'].plot()
corona_dataset_aggregated.loc["Italy"].plot()
corona_dataset_aggregated.loc["Spain"].plot()
plt.legend()

# In[12]:

corona_dataset_aggregated.loc["China"][:3].plot()

# ### caculating the first derivative of the curve

# In[13]:

corona_dataset_aggregated.loc["China"].diff().plot()

# ### maxmimum infection rate for China

# In[14]:

corona_dataset_aggregated.loc["China"].diff().max()

# In[15]:

corona_dataset_aggregated.loc["Italy"].diff().max()

# In[16]:

corona_dataset_aggregated.loc["Spain"].diff().max()

# ### maximum infection rate for all of the countries.

# In[17]:

countries = list(corona_dataset_aggregated.index)
max_infection_rates =[]
for c in countries :
    max_infection_rates.append(corona_dataset_aggregated.loc[c].diff().max())
corona_dataset_aggregated["max_infection_rate"] = max_infection_rates

# In[18]:

corona_dataset_aggregated.head()

# ###  create a new dataframe with only needed column

# In[19]:

corona_data = pd.DataFrame(corona_dataset_aggregated["max_infection_rate"])

# In[20]:

corona_data.head()

# ###
# - Importing the WorldHappinessReport.csv dataset
# - selecting needed columns for our analysis
# - join the datasets
# - calculate the correlations as the result of our analysis

# ### importing the dataset

# In[21]:

happiness_report_csv= pd.read_csv("Datasets/worldwide_happiness_report.csv")

# In[22]:

happiness_report_csv.head()

# ### drop useless columns

# In[23]:

useless_columns = ["Overall rank","Score","Generosity","Perceptions of corruption"]

# In[24]:

happiness_report_csv.drop(useless_columns,axis = 1, inplace = True)
happiness_report_csv.head()

# ### changing the indices of the dataframe

# In[25]:

happiness_report_csv.set_index("Country or region",inplace = True)

# In[26]:

happiness_report_csv.head()

# ### join the two dataset

# #### Corona Dataset :

# In[27]:

corona_data.head()

# In[28]:

corona_data.shape

# #### wolrd happiness report Dataset :

# In[29]:

happiness_report_csv.head()

# In[30]:

happiness_report_csv.shape

# In[31]:

data = corona_data.join(happiness_report_csv,how= "inner")
data.head()

# ### Task 4.5: correlation matrix

# In[32]:

data.corr()

# ### Visualization of the results
# our Analysis is not finished unless we visualize the results in terms figures and graphs so that everyone can understand what you get out of our analysis

# In[33]:

data.head()

# ### Plotting GDP vs maximum Infection rate

# In[35]:

x = data["GDP per capita"]
y = data["max_infection_rate"]
sns.scatterplot(x, np.log(y))

# In[36]:

sns.regplot(x, np.log(y))

# ### Plotting Social support vs maximum Infection rate

# In[38]:

y = data["max_infection_rate"]
x = data["Social support"]
sns.scatterplot(x, np.log(y))

# In[39]:

sns.regplot(x, np.log(y))

# ### Plotting Healthy life expectancy vs maximum Infection rate

# In[40]:

x = data["Healthy life expectancy"]
y = data["max_infection_rate"]
sns.scatterplot(x, np.log(y))

# In[43]:

sns.regplot(x, np.log(y))

# ### Plotting Freedom to make life choices vs maximum Infection rate

# In[44]:

x = data["Freedom to make life choices"]
y = data["max_infection_rate"]
sns.scatterplot(x, np.log(y))

# In[45]:

sns.regplot(x, np.log(y))

# In[ ]:


import torch
import torch.nn as nn
import torchvision.models as models
from get_loader import get_loader

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

class Encoder(nn.Module):
    def __init__(self, encode_image_size=14, fine_tune=False):
        super(Encoder, self).__init__()
        resnet50 = models.resnet50(pretrained=True)# aux_logits: special parameters of inception
        #Remove linear and pool layers
        modules = list(resnet50.children())[:-2]
        self.resnet50 = nn.Sequential(*modules)

        # AdaptiveAvgPool2d-->自适应池化层，将输入尺寸变换为 encode_image_size * encode_image_size
        self.adaptive_pool = nn.AdaptiveAvgPool2d((encode_image_size,encode_image_size))

        # 是否训练resnet50
        self.fine_tune(fine_tune)

    def forward(self,images):

        out = self.resnet50(images)  # (batch_size, 2048, image_size/32, image_size/32)
        out = self.adaptive_pool(out)  # (batch_size, 2048, encoded_image_size, encoded_image_size)
        out = out.permute(0, 2, 3, 1)  # (batch_size, encoded_image_size, encoded_image_size, 2048)
        return out

    def fine_tune(self, fine_tune=False):
        """
        Allow or prevent the computation of gradients for convolutional blocks 2 through 4 of the encoder.

        :param fine_tune: Allow?
        """
        for p in self.resnet50.parameters():
            p.requires_grad = False
        # If fine-tuning, only fine-tune convolutional blocks 2 through 4
        for c in list(self.resnet50.children())[5:]:
            for p in c.parameters():
                p.requires_grad = fine_tune

class Attention(nn.Module):
    def __init__(self, feature_dim, hidden_size, attention_dim):
        """
        :param feature_dim: feature channels of encoded images
        :param hidden_size: hidden size of decoder's RNN
        :param attention_dim: size of the attention network
        """
        super(Attention, self).__init__()
        self.encoder_att = nn.Linear(feature_dim, attention_dim)  # linear layer to transform encoded image
        self.decoder_att = nn.Linear(hidden_size, attention_dim)  # linear layer to transform decoder's output
        self.full_att = nn.Linear(attention_dim, 1)  # linear layer to calculate values to be softmax-ed
        self.relu = nn.ReLU()
        self.softmax = nn.Softmax(dim=1)  # softmax layer to calculate weights

    def forward(self, encoder_out, decoder_hidden):
        """
        Forward propagation.

        :param encoder_out: encoded images, a tensor of dimension (batch_size, num_pixels, encoder_dim)
        :param decoder_hidden: previous decoder output, a tensor of dimension (batch_size, decoder_dim)
        :return: attention weighted encoding, weights
        """  #encoder_out (2,196,2048), decoder_hidden(2,512)
        att1 = self.encoder_att(encoder_out)  # (batch_size, num_pixels, attention_dim)(2,196,512)
        att2 = self.decoder_att(decoder_hidden)  # (batch_size, attention_dim)(2,512)
        att = self.full_att(self.relu(att1 + att2.unsqueeze(1))).squeeze(2)  # (batch_size, num_pixels) (2,196)
        alpha = self.softmax(att)  # (batch_size, num_pixels) (2,196)
        attention_weighted_encoding = (encoder_out * alpha.unsqueeze(2)).sum(dim=1)  # (batch_size, encoder_dim) (2,2048)

        return attention_weighted_encoding, alpha

class DecoderWithAttention(nn.Module):

    def __init__(self, attention_dim, embed_dim, hidden_size, vocab_size, feature_dim=2048, dropout=0.5):
        """
        :param attention_dim: size of attention network
        :param embed_dim: embedding size
        :param hidden_size: hidden size of decoder's RNN
        :param vocab_size: size of vocabulary
        :param feature_dim: feature size of encoded images
        :param dropout: dropout
        """
        super(DecoderWithAttention, self).__init__()

        self.feature_dim = feature_dim
        self.attention_dim = attention_dim
        self.embed_dim = embed_dim
        self.hidden_size = hidden_size
        self.vocab_size = vocab_size
        self.dropout = dropout

        self.attention = Attention(feature_dim, hidden_size, attention_dim)  # attention network

        self.embedding = nn.Embedding(vocab_size, embed_dim)  # embedding layer
        self.dropout = nn.Dropout(p=self.dropout)
        self.decode_step = nn.LSTMCell(embed_dim + feature_dim, hidden_size, bias=True)  # decoding LSTMCell
        self.init_h = nn.Linear(feature_dim, hidden_size)  # linear layer to find initial hidden state of LSTMCell
        self.init_c = nn.Linear(feature_dim, hidden_size)  # linear layer to find initial cell state of LSTMCell
        self.f_beta = nn.Linear(hidden_size, feature_dim)  # linear layer to create a sigmoid-activated gate
        self.sigmoid = nn.Sigmoid()
        self.fc = nn.Linear(hidden_size, vocab_size)  # linear layer to find scores over vocabulary
        self.init_weights()  # initialize some layers with the uniform distribution

    def init_weights(self):
        """
        Initializes some parameters with values from the uniform distribution, for easier convergence.
        """
        self.embedding.weight.data.uniform_(-0.1, 0.1)
        self.fc.bias.data.fill_(0)
        self.fc.weight.data.uniform_(-0.1, 0.1)

    def load_pretrained_embeddings(self, embeddings):
        """
        Loads embedding layer with pre-trained embeddings.

        :param embeddings: pre-trained embeddings
        """
        self.embedding.weight = nn.Parameter(embeddings)

    def fine_tune_embeddings(self, fine_tune=True):
        """
        Allow fine-tuning of embedding layer? (Only makes sense to not-allow if using pre-trained embeddings).

        :param fine_tune: Allow?
        """
        for p in self.embedding.parameters():
            p.requires_grad = fine_tune

    def init_hidden_state(self, encoder_out):
        """
        Creates the initial hidden and cell states for the decoder's LSTM based on the encoded images.

        :param encoder_out: encoded images, a tensor of dimension (batch_size, num_pixels, encoder_dim)
        :return: hidden state, cell state
        """
        mean_encoder_out = encoder_out.mean(dim=1)
        h = self.init_h(mean_encoder_out)  # (batch_size, decoder_dim)
        c = self.init_c(mean_encoder_out)
        return h, c

    def forward(self, encoder_out, encoded_captions):
        """
        Forward propagation.

        :param encoder_out: encoded images, a tensor of dimension (batch_size, enc_image_size, enc_image_size, encoder_dim)
        :param encoded_captions: encoded captions, a tensor of dimension (batch_size, max_caption_length)
        :return: scores for vocabulary, sorted encoded captions, decode lengths, weights, sort indices
        """
        #encoder_out (2,14,14,2048), encoded_captions (2,20)
        batch_size = encoder_out.size(0)
        feature_dim = encoder_out.size(-1)
        vocab_size = self.vocab_size # 10000

        # Flatten image
        encoder_out = encoder_out.view(batch_size, -1, feature_dim)  # (batch_size, num_pixels, encoder_dim) (2,196,2048)
        num_pixels = encoder_out.size(1) #14*14=196

        # Embedding
        embeddings = self.embedding(encoded_captions)  # (batch_size, max_caption_length, embed_dim) [2,20,512]

        # Initialize LSTM state
        h, c = self.init_hidden_state(encoder_out)  # (batch_size, decoder_dim) (2,512)

        # Create tensors to hold word predicion scores and alphas
        predictions = torch.zeros(batch_size, encoded_captions.shape[1], vocab_size).to(device) #shape [2,20,10000]
        alphas = torch.zeros(batch_size, encoded_captions.shape[1], num_pixels).to(device) #shape [2,20,196]

        # At each time-step, decode by
        # attention-weighing the encoder's output based on the decoder's previous hidden state output
        # then generate a new word in the decoder with the previous word and the attention weighted encoding
        for t in range(encoded_captions.shape[1]):
            attention_weighted_encoding, alpha = self.attention(encoder_out, h)
            gate = self.sigmoid(self.f_beta(h))  # gating scalar, (batch_size_t, encoder_dim) （2，2048）
            attention_weighted_encoding = gate * attention_weighted_encoding #（2，2048）
            h, c = self.decode_step(torch.cat([embeddings[:, t, :], attention_weighted_encoding], dim=1),(h, c))  # (batch_size_t, decoder_dim)
            preds = self.fc(self.dropout(h))  # (batch_size_t, vocab_size) （2，10000）
            predictions[:, t, :] = preds
            alphas[:, t, :] = alpha

        return predictions, encoded_captions,alphas

if __name__=='__main__':
    vocab_size = 10000
    emb_dim = 512  # dimension of word embeddings
    attention_dim = 512  # dimension of attention linear layers
    hidden_size = 512  # dimension of decoder RNN, 其实就是hidden_size
    dropout = 0.5
    decoder = DecoderWithAttention(attention_dim=attention_dim,
                                       embed_dim=emb_dim,
                                       hidden_size=hidden_size,
                                       vocab_size=vocab_size,
                                     dropout=dropout)
    encoder = Encoder()
    decoder = decoder.to('cuda')
    encoder = encoder.to('cuda')
    img = torch.ones(2,3,448,448).to('cuda')
    cap = torch.ones(2,20,dtype=int).to('cuda')
    img = encoder(img) #(1,3,448,448)--->(2,14,14,2048)
    scores, caps_sorted, alphas = decoder(img, cap)


from django.contrib import admin
from .models import Candidate
from .forms import CandidateForm
from django.utils.html import format_html

class CandidateAdmin(admin.ModelAdmin):
  radio_fields = {"smoker": admin.HORIZONTAL}
  form = CandidateForm
  exclude = ['status']
  list_filter = ['Situation']
  list_display = ['name', 'job', 'email', 'created_at', 'status', '_']
  search_fields = ['firstname', 'lastname', 'email', 'Situation']
  list_per_page = 10

  #Read Only field
  readonly_fields = ['experience', 'gender', 'firstname', 'lastname', 'job', 'email',
  'phone', 'salary', 'birth', 'personality', 'smoker', 'file', 'image', 'frameworks',
  'languages', 'databases', 'libraries', 'mobile', 'others', 'message', 'status_course',
  'started_course', 'finished_course', 'course', 'institution', 'about_course', 'started_job',
  'finished_job', 'company', 'position', 'about_job', 'employed', 'remote', 'travel']

  #Fieldset
  fieldsets = [
    # HR Operations
    ("HR OPERATIONS", {"fields": ['Situation', 'company_note']}),
    # Personal
    ("Personal", {"fields": ['experience', 'gender', 'job', 'email', 'phone',
    'salary', 'birth', 'personality', 'smoker', 'file', 'image', 'message']}),
    #Skills
    ("Skills", {"fields": ['frameworks', 'languages', 'databases', 'libraries', 'mobile', 'others']}),
    #Education
    ("Education", {"fields": ['status_course', 'started_course', 'finished_course',
    'course', 'institution', 'about_course']}),
    #Professional
    ("Professional", {"fields": ['started_job', 'finished_job', 'company', 'position',
    'about_job']}),
    #Note
    ("Note", {"fields": ['employed', 'remote', 'travel']}),
  ]

  #func to hide name
  def get_fields(self, request, obj = None):
    fields = super().get_fields(request, obj)
    if obj:
      fields.remove('firstname')
      fields.remove('lastname')
    return fields

  # Function to change the icon
  def _(self, obj):
    if obj.Situation == 'Accepted':
      return True
    elif obj.Situation == 'Pending':
      return None
    else:
      return False
  _.boolean = True

  # Func to color the text
  def status(self, obj):
    if obj.Situation == 'Accepted':
      color = '#28a745'
    elif obj.Situation == 'Pending':
      color = '#fea95e'
    else:
      color = 'red'
    return format_html('
{}
'.format(color, obj.Situation))
  status.allow_tags = True

admin.site.register(Candidate, CandidateAdmin)


# item_of_list (pyStage, converted from Scratch 3)

from pystage.en import Sprite, Stage

stage = Stage()
stage.add_backdrop('backdrop1')
stage.create_variable('my variable', 0)
stage.create_list_variable("second list", ['branden', 'branden', 'branden', 'thing', 'branden', 'thing'])
stage.show_list("second list", 84, 170)
sprite1 = stage.add_a_sprite(None)
sprite1.set_name("Sprite1")
sprite1.set_x(-39)
sprite1.set_y(-39)
sprite1.go_to_back_layer()
sprite1.go_forward(1)
sprite1.add_costume('costume1', center_x=48, center_y=50)
sprite1.add_costume('costume2', center_x=46, center_y=53)
sprite1.add_sound('meow')

def when_program_starts_1(self):
    self.say(self.item_in_list("second list", 1))
    self.wait(1.0)
    self.say(self.item_in_list("second list", 4))

sprite1.when_program_starts(when_program_starts_1)

def when_program_starts_2(self):
    self.add_value_to_list("second list", "branden")
    self.add_value_to_list("second list", "thing")

sprite1.when_program_starts(when_program_starts_2)
stage.play()


#!/usr/bin/python3
# -*- coding: latin-1 -*-

import re
import os

#filename=input("Give DNA string in FASTA format :\n")
file=open("test.fa","r")
gc=0
GC=0
sequence=''
name=''
liste=''
for line in file:
	if re.match('>', line):
		name=re.split('\s',line)
		print(name)
	if re.match('>',line)==None:
		while re.search('\d',line)==None or re.match('^\S',line):
			print('move')
			line=file.readline()
file.close()
#print('%s\n%s'%(liste,round(GC,6)))
#print(Gc)


import streamlit as st
import requests
from datetime import datetime
import logging

default_max_tokens=100
default_temperature=0.9
default_top_p=1.0
default_presence_penalty=0.0
default_frequency_penalty=0.0

def f(prompt,
        name,
        max_tokens=default_max_tokens,
        temperature=default_temperature,
        top_p=default_top_p,
        presence_penalty=default_presence_penalty,
        frequency_penalty=default_frequency_penalty):
    headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + st.secrets["API_KEY"],
    }
    data = '{\n  "prompt": "' + prompt + '",\n  "max_tokens": 100\n}'
    data = '{\n' + \
            f'"prompt": "{prompt}",\n' + \
            f'"max_tokens": {max_tokens},\n' + \
            f'"temperature": {temperature},\n' + \
            f'"top_p": {top_p},\n' + \
            f'"presence_penalty": {presence_penalty},\n' + \
            f'"frequency_penalty": {frequency_penalty},\n' + \
            f'"echo": true\n' + \
            '}'
    response = requests.post('https://api.openai.com/v1/engines/davinci/completions', headers=headers, data=data)
    if name != "":
        st.header(name + "!")
    else:
        name = 'guest'
    response_text = response.json()['choices'][0]['text'].replace("\n", " ")
    st.subheader(response_text)
    logging.error(f"{name},{response_text}")

advanced = st.sidebar.checkbox("Advanced settings", False)

st.write("# I will tell your fortune")

name = st.text_input("How do they call you?")

if advanced:
    prompt = st.text_input("Write anything here, I will continue", "Once upon a time, ")
    temprerature = st.slider("temperature (higher the temperature = crazyer fortune)", 0.0, 1.0, default_temperature, 0.01)
    max_tokens = st.slider("max_tokens", 1, 100, default_max_tokens, 1)
    top_p=st.slider("top_p", 0.0, 1.0, default_top_p, 0.01)
    presence_penalty=st.slider("presence_penalty", -2.0, 2.0, default_presence_penalty, 0.01)
    frequency_penalty=st.slider("frequency_penalty", -2.0, 2.0, default_frequency_penalty, 0.01)
    st.button("Tell fortune", on_click=f, args=(prompt, name, max_tokens, temprerature, top_p, presence_penalty, frequency_penalty))
else:
    prompt = st.selectbox(
        'What do you seek?',
        ('When I look into your palm, the future reveals itself to me. Next week you will',
        'The tarot cards never lie... I can cleary see that next year you will'))
    st.button("Tell fortune", on_click=f, args=(prompt, name))

st.image("https://s3-eu-west-1.amazonaws.com/dailyartartwork/img-2017031258c5aa9390ee2_ipad")


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

from db import *

class ETL:
    def __init__(self, name, db):
        self.name = name
        self.db = db

    def etl(self):
        self._color_print_('ETL start')
        etl_timer = Timer()
        logger.debug(f'---- {self.name} extract start ----')
        extract_timer = Timer()
        self._extract_()
        logger.debug(f'---- {self.name} extract end elapse {extract_timer.elapse()} ----')
        logger.debug(f'---- {self.name} transfer start ----')
        transfer_timer = Timer()
        self._transfer_()
        logger.debug(f'---- {self.name} transfer end elapse {transfer_timer.elapse()} ----')
        logger.debug(f'---- {self.name} load start ----')
        load_timer = Timer()
        self._load_()
        logger.debug(f'---- {self.name} load end elapse {load_timer.elapse()} ----')
        self._color_print_(f'ETL end elapse {etl_timer.elapse()}')

    def _extract_(self):
        pass

    def _transfer_(self):
        pass

    def _load_(self):
        pass

    def _color_print_(self, msg):
        print(color_line(f'{self.name} {msg}', offset=4, border=True))

class FileETL(ETL):
    def __init__(self, name, db):
        super().__init__(name, db)
        self.filepaths = []
        self.dataset = {}

    def _extract_(self):
        for filepath in self.filepaths:
            with open(filepath, 'r') as fd:
                data = self._extract_file_(fd)
                self.dataset[filename_of(filepath)] = data

    def _extract_file_(self, fd):
        pass

class CsvETL(FileETL):
    def __init__(self, name, db):
        super().__init__(name, db)

    def _extract_file_(self, fd):
        reader = csv.reader(fd)
        data = list(map(lambda row: row, reader))
        dataframe = {}
        for i, r in enumerate(data):
            dataframe[i] = {}
            row = data[i]
            for j, c in enumerate(row):
                dataframe[i][j] = c
        return pd.DataFrame(dataframe)

class JsonETL(FileETL):
    def __init__(self, name, db):
        super().__init__(name, db)
        self.csv_dataframes = {}

    def _extract_file_(self, fd):
        return json.load(fd)

class ETLUnitTests(UnitTests):
    def __init__(self):
        super().__init__(__file__)

    @UnitTests.skip
    def csv_etl_test(self):
        etl = CsvETL('csv-etl', None)
        etl.filepaths = [
            os.path.join(INPUT_DIR, '0000001', '002.csv')
        ]
        etl.etl()
        assert len(etl.dataset) is not None
        print(etl.dataset)

    # @UnitTests.skip
    def json_etl_test(self):
        etl = JsonETL('json-etl', None)
        etl.filepaths = [
            os.path.join(INPUT_DIR, 'shanghai_resident', 'shanghai_resident_2022-04-05 00:00:00.json')
        ]
        etl.etl()
        assert len(etl.dataset) is not None
        print(etl.dataset)

ETLUnitTests().run()