#!/usr/bin/python

import sys

for line in sys.stdin:
    data = line.strip().split("\t")
    if len(data) == 10:
        (
            productid,
            title,
            Price,
            userId,
            profileName,
            helpfulness,
            score,
            time,
            summary,
            text,
        ) = data

        # Emitir el par clave-valor: productid y title como clave y score como valor
        key = [productid, title]

        if score != "empty":
            print("{0}\t{1}".format(key, score))


from typing import Tuple, Optional

import numpy as np
import torch
from torch import nn
from einops.layers.torch import Rearrange

from gluonts.core.component import validated
from gluonts.model import Input, InputSpec
from gluonts.torch.scaler import StdScaler, MeanScaler, NOPScaler
from gluonts.torch.distributions import StudentTOutput

class Residual(nn.Module):
    def __init__(self, fn):
        super().__init__()
        self.fn = fn

    def forward(self, x):
        return self.fn(x) + x

class MLPPatchMap(nn.Module):
    """
    Module implementing MLPMap for the reverse mapping of the patch-tensor.

    Parameters
    ----------
    patch_size : Tuple[int, int]
        Patch size.
    context_length : int
        Context length.
    prediction_length : int
        Number of time points to predict.
    input_size : int
        Input size.

    Returns
    -------
    x : torch.Tensor
    """

    def __init__(
        self,
        patch_size: Tuple[int, int],
        context_length: int,
        prediction_length: int,
        input_size: int,
    ):
        super().__init__()
        p1 = int(context_length / patch_size[0])
        p2 = int(input_size / patch_size[1])
        self.fc = nn.Sequential(
            Rearrange("b c w h -> b c h w"),
            nn.Linear(p1, prediction_length),
            Rearrange("b c h w -> b c w h"),
            nn.Linear(p2, input_size),
        )

    def forward(self, x):
        x = self.fc(x)
        return x

def RevMapLayer(
    layer_type: str,
    pooling_type: str,
    dim: int,
    patch_size: int,
    context_length: int,
    prediction_length: int,
    input_size: int,
):
    """
    Returns the mapping layer for the reverse mapping of the patch-tensor to [b nf h ns].

    :argument
        layer_type: str = "pooling" or "mlp" or "conv1d"
        pooling_type: str = "max" or "mean"
        dim: int = dimension of the embeddings
        patch_size: Tuple[int, int] = patch size
        prediction_length: int = prediction length
        context_length: int = context length
        input_size: int = input size

    :returns
        nn.Module = mapping layer

    """
    if layer_type == "pooling":
        if pooling_type == "max":
            return nn.AdaptiveMaxPool2d((prediction_length, input_size))
        elif pooling_type == "mean":
            return nn.AdaptiveAvgPool2d((prediction_length, input_size))
    elif layer_type == "mlp":
        return MLPPatchMap(patch_size, context_length, prediction_length, input_size)
    else:
        raise ValueError("Invalid layer type: {}".format(layer_type))

class TsTModel(nn.Module):
    """
    Module implementing TsT for forecasting.

    Parameters
    ----------
    prediction_length
        Number of time points to predict.
    context_length
        Number of time steps prior to prediction time that the model.
    hidden_dimensions
        Size of hidden layers in the feed-forward network.
    distr_output
        Distribution to use to evaluate observations and sample predictions.
        Default: ``StudentTOutput()``.
    batch_norm
        Whether to apply batch normalization. Default: ``False``.
    """

    @validated()
    def __init__(
        self,
        prediction_length: int,
        context_length: int,
        scaling: str,
        input_size: int,
        depth: int,
        dim: int,
        nhead: int,
        patch_size: Tuple[int, int],
        dim_feedforward: int,
        dropout: float,
        activation: str,
        norm_first: bool,
        patch_reverse_mapping_layer: str = "mlp",
        pooling_type: str = "max",
        num_feat_dynamic_real: int = 0,
        num_feat_static_real: int = 0,
        num_feat_static_cat: int = 0,
        distr_output=StudentTOutput(),
        num_parallel_samples: int = 100,
    ) -> None:
        super().__init__()

        assert prediction_length > 0
        assert context_length > 0
        assert depth > 0

        self.prediction_length = prediction_length
        self.context_length = context_length
        self.input_size = input_size
        self.dim = dim
        self.num_feat_static_real = num_feat_static_real
        self.num_feat_dynamic_real = num_feat_dynamic_real
        self.num_parallel_samples = num_parallel_samples

        if scaling == "mean":
            self.scaler = MeanScaler(keepdim=True, dim=1)
        elif scaling == "std":
            self.scaler = StdScaler(keepdim=True, dim=1)
        else:
            self.scaler = NOPScaler(keepdim=True, dim=1)

        self.distr_output = distr_output

        self.conv_proj = nn.Conv2d(
            self._number_of_features, dim, kernel_size=patch_size, stride=patch_size
        )

        self.patch_num = (self.context_length // patch_size[0]) * (
            self.input_size // patch_size[1]
        )

        self.positional_encoding = SinusoidalPositionalEmbedding(self.patch_num, dim)

        layer_norm_eps: float = 1e-5
        encoder_layer = nn.TransformerEncoderLayer(
            d_model=dim,
            nhead=nhead,
            dim_feedforward=dim_feedforward,
            dropout=dropout,
            activation=activation,
            layer_norm_eps=layer_norm_eps,
            batch_first=True,
            norm_first=norm_first,
        )
        encoder_norm = nn.LayerNorm(dim, eps=layer_norm_eps)
        self.encoder = nn.TransformerEncoder(encoder_layer, depth, encoder_norm)

        self.rev_map_layer = RevMapLayer(
            layer_type=patch_reverse_mapping_layer,
            pooling_type=pooling_type,
            dim=dim,
            patch_size=patch_size,
            prediction_length=self.prediction_length,
            context_length=self.context_length,
            input_size=self.input_size,
        )

        self.args_proj = self.distr_output.get_args_proj(
            dim + self.num_feat_dynamic_real
        )

    @property
    def _number_of_features(self) -> int:
        return (
            self.num_feat_dynamic_real
            + self.num_feat_static_real
            + 3  # 1 + the log(loc) + log1p(scale)
        )

    def describe_inputs(self, batch_size=1) -> InputSpec:
        return InputSpec(
            {
                "past_target": Input(
                    shape=(batch_size, self.context_length, self.input_size),
                    dtype=torch.float,
                ),
                "past_observed_values": Input(
                    shape=(batch_size, self.context_length, self.input_size),
                    dtype=torch.float,
                ),
            },
            torch.zeros,
        )

    def forward(
        self,
        feat_static_cat: Optional[torch.Tensor] = None,
        feat_static_real: Optional[torch.Tensor] = None,
        past_time_feat: Optional[torch.Tensor] = None,
        past_target: Optional[torch.Tensor] = None,
        past_observed_values: Optional[torch.Tensor] = None,
        future_time_feat: Optional[torch.Tensor] = None,
        future_target: Optional[torch.Tensor] = None,
        future_observed_values: Optional[torch.Tensor] = None,
    ) -> Tuple[Tuple[torch.Tensor, ...], torch.Tensor, torch.Tensor]:
        past_target_scaled, loc, scale = self.scaler(past_target, past_observed_values)
        # [B, C, D], [B, D], [B, D]

        # [B, 1, C, D]
        past_target_scaled = past_target_scaled.unsqueeze(1)  # channel dim

        log_abs_loc = loc.abs().log1p().unsqueeze(1).expand_as(past_target_scaled)
        log_scale = scale.log().unsqueeze(1).expand_as(past_target_scaled)

        # [B, C, F] -> [B, F, C, 1] -> [B, F, C, D]
        past_time_feat = (
            past_time_feat.transpose(2, 1)
            .unsqueeze(-1)
            .repeat_interleave(dim=-1, repeats=self.input_size)
        )

        proj_input = torch.cat(
            (
                past_target_scaled,
                log_abs_loc,
                log_scale,
                past_time_feat,
            ),
            dim=1,
        )

        x = self.conv_proj(proj_input)
        B, C, H, W = x.shape

        x = x.reshape(B, self.dim, -1)
        x = x.permute(0, 2, 1)  # [B, P, D]
        embed_pos = self.positional_encoding(x.size())
        enc_out = self.encoder(x + embed_pos)

        nn_out = self.rev_map_layer(enc_out.permute(0, 2, 1).reshape(B, C, H, W))

        # [B, F, C, D] -> [B, F, P, D]

        nn_out_reshaped = nn_out.transpose(1, -1).transpose(1, 2)
        future_time_feat_repeat = future_time_feat.unsqueeze(2).repeat_interleave(
            dim=2, repeats=self.input_size
        )
        distr_args = self.args_proj(
            torch.cat((nn_out_reshaped, future_time_feat_repeat), dim=-1)
        )

        return distr_args, loc, scale

class SinusoidalPositionalEmbedding(nn.Embedding):
    """This module produces sinusoidal positional embeddings of any length."""

    def __init__(self, num_positions: int, embedding_dim: int) -> None:
        super().__init__(num_positions, embedding_dim)
        self.weight = self._init_weight(self.weight)

    @staticmethod
    def _init_weight(out: nn.Parameter) -> nn.Parameter:
        """
        Features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:]
        """
        n_pos, dim = out.shape
        position_enc = np.array(
            [
                [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)]
                for pos in range(n_pos)
            ]
        )
        # set early to avoid an error in pytorch-1.8+
        out.requires_grad = False

        sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
        out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
        out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
        out.detach_()
        return out

    @torch.no_grad()
    def forward(
        self, input_ids_shape: torch.Size, past_key_values_length: int = 0
    ) -> torch.Tensor:
        """`input_ids_shape` is expected to be [bsz x seqlen x ...]."""
        _, seq_len = input_ids_shape[:2]
        positions = torch.arange(
            past_key_values_length,
            past_key_values_length + seq_len,
            dtype=torch.long,
            device=self.weight.device,
        )
        return super().forward(positions)


#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
    i = 0
    newlist = []
    while i < list_length:
        try:
            output = my_list_1[i] / my_list_2[i]
        except ZeroDivisionError:
            output = 0
            print("division by 0")
        except TypeError:
            output = 0
            print("wrong type")
        except IndexError:
            output = 0
            print("out of range")
        finally:
            newlist += [output]
        i += 1
    return newlist


import json

from django.db import models
from django_celery_beat.models import PeriodicTask, IntervalSchedule

from .services import *

class Asset(models.Model):
    class Meta:
        db_table = "asset"
        constraints = [
            models.UniqueConstraint(
                fields=["name", "created_by"], name="unique asset_constraint"
            )
        ]

    PERIOD_CHOICES = [
        ("days", "Days"),
        ("hours", "Hours"),
        ("minutes", "Minutes"),
        ("seconds", "Seconds"),
    ]
    name = models.CharField(max_length=250, blank=True)
    created_by = models.ForeignKey("users.User", on_delete=models.CASCADE)

    # Fields to control sending emails
    min_value = models.DecimalField(max_digits=8, decimal_places=2)
    max_value = models.DecimalField(max_digits=8, decimal_places=2)

    # Fields to control the task periodicity
    period_type = models.CharField(
        choices=PERIOD_CHOICES, max_length=7, default="minutes"
    )
    period_time = models.IntegerField(default=0, blank=True)
    monitoring = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.name}_{self.created_by.first_name}"

    def save(self, *args, **kwargs):
        # Update periodic task only if asset object already exists
        if self.id:
            asset = Asset.objects.get(id=self.id)
            schedule, created = IntervalSchedule.objects.get_or_create(
                period=self.period_type, every=self.period_time
            )
            task = PeriodicTask.objects.get(
                kwargs__contains=json.dumps(
                    {"created_by": asset.created_by.id, "asset_name": asset.name}
                )
            )
            task.kwargs = json.dumps(
                {"created_by": self.created_by.id, "asset_name": self.name}
            )
            task.interval = schedule
            task.enabled = self.monitoring
            task.save()
            if self.name != asset.name:
                AssetData.objects.filter(asset=self).delete()
        else:
            schedule, created = IntervalSchedule.objects.get_or_create(
                period=self.period_type, every=self.period_time
            )
            task_name = f"{self.created_by.email}_{self.name}"
            task = PeriodicTask.objects.create(
                name=task_name,
                interval=schedule,
                task="assets.tasks.get_asset_data",
                kwargs=json.dumps(
                    {"created_by": self.created_by.id, "asset_name": self.name}
                ),
            )
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        PeriodicTask.objects.get(
            kwargs__contains=json.dumps(
                {
                    "created_by": self.created_by.id,
                    "asset_name": self.name,
                }
            )
        ).delete()
        super().delete(*args, **kwargs)

class AssetData(models.Model):
    asset = models.ForeignKey("assets.Asset", on_delete=models.CASCADE)
    value = models.DecimalField(max_digits=8, decimal_places=2)
    data_extraction_time = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if self.asset.monitoring:
            if not self.asset.min_value < self.value < self.asset.max_value:
                send_email(
                    self.asset.name,
                    self.asset.min_value,
                    self.asset.max_value,
                    self.value,
                    self.asset.created_by.id,
                )

        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.asset.name}_{self.asset.period_time}_{self.asset.period_type}_{self.asset.created_by.first_name}"


# https://www.acmicpc.net/problem/11562
n, m = map(int,input().split())

INF = int(1e9)
graph = [ [INF] * (n+1) for _ in range(n+1)]

for _ in range(m):
    a, b, c = map(int,input().split())
    if c == 0 :
        graph[a][b] = 0
        # 일방통행이므로 지나가는데 드는 비용이 1
        graph[b][a] = 1
    else:
        graph[a][b] = 0
        graph[b][a] = 0

# 자기 자신으로 가는 비용 0으로 초기화
for i in range(1,n+1) :
    for j in range(1,n+1):
        if i == j :
            graph[i][j] = 0

# 최소 통로 건설 개수 구하기
for k in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])

k = int(input())
for _ in range(k):
    x, y = map(int,input().split())
    print(graph[x][y])

Baekjoon_Algorithm/8. Graph Theory/11562 백양로 브레이크.py


s = 0
d = {}
f = {}

n = int(input())
for i in range(n):
    a, b = map(int, input().split())
    if a in d:
        a = d[a]
    else:
        d[a] = s
        s += 1
        a = d[a]
    if b in d:
        b = d[b]
    else:
        d[b] = s
        s += 1
        b = d[b]
    f[a] = b

while True:
    a, b = map(int, input().split())
    if a == 0 and b == 0:
        break
    if a not in d or b not in d:
        print("No")
        continue
    a, b = d[a], d[b]
    node = f[a]
    dist = 0
    while node not in [a, b]:
        node = f[node]
        dist += 1
    if node == a:
        print("No")
    else:
        print("Yes", dist)


import TreeNode

"""Convert Binary Search Tree to Sorted Doubly Linked List
(https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/Links)"""

def treeToDoublyList(self, root: TreeNode) -> TreeNode:
    prev = TreeNode()
    dummy = prev
    node = root
    stack = []

    if not node:
        return None

    while node is not None or stack:
        while node:
            stack.append(node)
            node = node.left

        node = stack.pop()
        prev.right = node
        node.left = prev
        prev = node
        node = node.right

    first = dummy.right
    dummy.right.left = prev
    prev.right = dummy.right
    return dummy.right


import os
import json
import tweepy
from pprint import pprint as pp
from tweepy import OAuthHandler

# getting keys from OS ENV variables (stored there to avoid commiting secrets to the repo)
consumer_key = os.environ['TWITTER_TWEETLEAD_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_TWEETLEAD_CONSUMER_SECRET']
access_token = os.environ['TWITTER_TWEETLEAD_ACCESS_TOKEN']
access_secret = os.environ['TWITTER_TWEETLEAD_ACCESS_SECRET']

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

# api.search_users('@AndrzejDuda')
u_name = 'kornislaw'

def print_followers():
    u = api.get_user(u_name)

    nodes = 'nodes = [\n'
    nodes += f"\t\t{{id: {u.id}, shape: 'circularImage', image: '{u.profile_image_url}', label:'{u.screen_name}'}},\n"
    for flr in api.followers(u_name):
        nodes += f"\t\t{{id: {flr.id}, shape: 'circularImage', image: '{flr.profile_image_url}', label:'{flr.screen_name}'}},\n"
    nodes += '];\n'

    edges = 'edges = [\n'
    for flr in api.followers(u_name):
        edges += f'\t\t{{from: {flr.id}, to: {u.id}}},\n'
    edges += '];\n'

    print(nodes)
    print(edges)

def get_followers(u_name):
    u = api.get_user(u_name)
    flrs = api.followers(u_name)
    nodes = [{'id': flr.id, 'shape': 'circularImage', 'image': flr.profile_image_url, 'label': flr.screen_name} for flr in flrs]
    nodes.append({'id': u.id, 'shape': 'circularImage', 'image': u.profile_image_url, 'label': u.screen_name, 'size': 70 })
    edges = [{'from': flr.id, 'to': u.id} for flr in flrs]

    return json.dumps({'nodes': nodes, 'edges': edges})
    # return {'nodes': nodes, 'edges': edges}

print(get_followers('kornislaw'))
# def print_followed():
    # API.friends_ids(id/screen_name/user_id[, cursor]


# Leetcode 347: Top K Frequent Elements (medium)
# arrays, hashing

from collections import defaultdict
class Solution:
    # defaultdict revisited, fastest
    def topKFrequent(self, nums, k):
        freq, ans = defaultdict(int), []
        for n in nums:
            freq[n] += 1

        sorted_freq = sorted(freq.items(), key=lambda x:x[1], reverse=True)

        for i in range(k):
            ans.append(sorted_freq[i][0])

        return ans

    # revisited
    def topKFrequent2(self, nums, k):
        freq, ans = {}, []
        for n in nums:
            if n in freq: freq[n] += 1
            else: freq[n] = 1

        sorted_freq = sorted(freq.items(), key=lambda x:x[1], reverse=True)

        for i in range(k):
            ans.append(sorted_freq[i][0])

        return ans

# test cases
solution = Solution()
nums = [1,1,1,2,2,3]
k = 2
print(solution.topKFrequent(nums, k)) # [1,2]
print(solution.topKFrequent([1], 1)) # [1]

# old
# LEETCODE 347 TESTCASES NOT WORKING CORRECTLY, BUT THE EXACT TESTCASE WORKS HERE? see bottom
    # def topKFrequent(self, nums: list[int], k: int) -> list[int]:
    #     count_map = defaultdict(list) # number : count
    #     result = []

    #     # appending each number and the amount of times it appears to the count map
    #     for n in nums:
    #         if count_map[n]: # if the value is not null / already exists
    #             count_map[n] = count_map[n] + 1 # increment the count value
    #         else:
    #             count_map[n] = 1 # set the count to 1

    #     # sort hashmap by its values in reverse order, basically its count in descending order
    #     # sorted returns a list therefore cast back to defaultdict
    #     sorted_count_map = dict(sorted(count_map.items(), key=lambda x:x[1], reverse=True))

    #     # append the sorted keys to the result list until k amount is reached
    #     for i, key in enumerate(sorted_count_map):
    #         if i < k:
    #             result.append(key)

    #     return result


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 12:56:23 2021

@author: rakesh
"""

import random
import matplotlib.pyplot as plt

account = 0 #details of my gain or loss
x = []
y = []

for i in range(365):
    x.append(i+1)
    bet = random.randint(1,10)
    lucky_draw = random.randint(1,10)
    #print("Your number is:",bet)
    #print("Your lucky draw number is:",lucky_draw)

    # I need keep amount 100/- if i won i will get 900
    # or i will loose my 100/-

    if bet == lucky_draw:
        account = account + 900 - 100 # which gives my net gain/loss
    else:
        account = account-100

    y.append(account)

print("Amount in my game account",account)
plt.plot(x,y)
plt.show()


# This module contains an implementation of a pseudo-random number generator
# based on the RC4 stream encryption algorithm

class RC4:
    def __init__(self, iv: str, n: int = 8):
        """
        Pseudorandom number generator based on the RC4 algorithm for streaming encryption.

        Args:
            iv: a string in hexadecimal format that initializes the value.
            n: size of generated number in bits.
        """
        if not isinstance(iv, str):
            raise TypeError("The iv must be of type str!")

        if not iv:
            raise ValueError("Initialization vector is empty!")

        try:
            self.iv = bytes.fromhex(iv)
        except ValueError:
            raise ValueError("Error iv value! (must be hex)")

        self.n = n
        self.s = []
        self.i = 0
        self.j = 0
        self._ksa()

    def _ksa(self):
        """S-box initialization."""
        len_iv = len(self.iv)
        module = 2 ** self.n

        self.s = list(range(module))

        j = 0
        for i in range(256):
            j = (j + self.s[i] + self.iv[i % len_iv]) % module
            self.s[i], self.s[j] = self.s[j], self.s[i]

    def _prga(self):
        """Pseudo-random word generation K."""
        module = 2 ** self.n
        i, j = self.i, self.j

        i = (i + 1) % module
        j = (j + self.s[i]) % module

        self.i, self.j = i, j
        self.s[i], self.s[j] = self.s[j], self.s[i]

        t = (self.s[i] + self.s[j]) % module
        return self.s[t]

    def __iter__(self):
        return self

    def __next__(self):
        return self._prga()


"""Takes claims, corpus and results of the predictions using longchecker and
for each claim extracts additional information for each evidence document but
also for the various relationsships between them.

example usage:
    python ccv/feature_visualization.py \
        --output "./data/graphs.jsonl" \
        --claims "./data/predict_claims.jsonl" \
        --corpus "./data/predict_corpus.jsonl" \
        --predictions "./data/predict_result.jsonl" \
        --erelations "./data/erelations.jsonl" \
        --emap "./data/emap.json"
"""

"""
get_features() saved dict structure:
    "claim": str,
    "docs": {
        corpusid: {
            "label": str,
            "label_prob": float,
            "evidence": {"text": str, "prob": float},
            "aliases": [int],
            "pinfo": {
                "citationCount": int,
                "influentialCitationCount": int
            },
            "ainfo": {
                "authors": {str: str},
                "paperCounts": [int],
                "citationCounts": [int],
                "hIndices": [int],
            },
            "rinfo": {
                corpusid: {
                    "isInfluential": bool,
                    "intents": [str],
                    "contexts": [str]
                }
                }
            },
            "publish_time": str,
            "journal": str
        }
    "alinks": {
        "doc": corpusid,
        "common": list[str]
    },
    "rlinks": {
        corpusid: [
            {
                "reference": corpusid,
                "isInfluential": bool,
                "intent": [str]
            }
        ]
    }
    "elinks": {
        id: {
            claim_id: int,
            'fdoc_id': corpusid,
            'fdoc_e_num': int,
            'sdoc_id': corpusid,
            'sdoc_e_num': int,
        },
    }
"""

import argparse
from graph import create_graph
import json
import pandas as pd
from tqdm import tqdm
from typing import Dict, Any, List
from utility import get_request

def get_args() -> argparse.Namespace:
    """Returns the given arguments.

    Returns:
        argparse.Namespace: The arguments.
    """

    parser = argparse.ArgumentParser()

    parser.add_argument("--output", type=str, help="output file", required=True)
    parser.add_argument("--claims", type=str, help="claims file", required=True)
    parser.add_argument("--corpus", type=str, help="corpus file", required=True)
    parser.add_argument(
        "--predictions", type=str, help="predictions file", required=True
    )
    parser.add_argument(
        "--erelations", type=str, help="evidence relations file"
    )
    parser.add_argument("--emap", type=str, help="evidence map file")

    return parser.parse_args()

def process_paper(corpusid: str) -> Dict[str, Any]:
    """Retrieves various information related to the document associated with
    the given corpusid.

    Args:
        corpusid (str): The corpusid of a document.

    Returns:
        Dict[str, Any]: Dict containing various information about the document.
    """

    fields = ",".join(["citationCount", "influentialCitationCount"])
    url = f"https://api.semanticscholar.org/graph/v1/paper/corpusid:{corpusid}?fields={fields}"
    res = get_request(url)
    res.pop("paperId")
    return res

def process_authors(corpusid: str) -> Dict[str, Any]:
    """Retrieves various information related to the authors of the paper
    associated with the given corpusid.

    Args:
        corpusid (str): The corpusid of a document.

    Returns:
        Dict[str, Any]: Dict containing various author related information.
    """

    fields = ",".join(
        [
            "authors.name",
            "authors.paperCount",
            "authors.citationCount",
            "authors.hIndex",
        ]
    )
    url = f"https://api.semanticscholar.org/graph/v1/paper/corpusid:{corpusid}?fields={fields}"
    res = get_request(url)
    authors = res["authors"]

    d = dict(zip(authors[0].keys(), zip(*[a.values() for a in authors])))
    d = {k: list(v) for k, v in d.items()}

    result = {}
    result["authors"] = dict(zip(d["authorId"], d["name"]))
    result["paperCounts"] = [v if v is not None else 0 for v in d["paperCount"]]
    result["citationCounts"] = [
        v if v is not None else 0 for v in d["citationCount"]
    ]
    result["hIndices"] = [v if v is not None else 0 for v in d["hIndex"]]

    return result

def process_references(corpusid: str) -> Dict[str, Any]:
    """Retrieves various information related to the references of the paper
    associated with the given corpusid.

    Args:
        corpusid (str): The corpusid of a document.

    Returns:
        Dict[str, Any]: Dict containing various reference related information.
    """

    fields = ",".join(["externalIds", "contexts", "intents", "isInfluential"])
    url = f"https://api.semanticscholar.org/graph/v1/paper/corpusid:{corpusid}/references?fields={fields}&limit=1000"
    res = get_request(url)

    d = res["data"]

    d = {
        str(r["citedPaper"]["externalIds"]["CorpusId"]): r
        for r in d
        if r["citedPaper"]["externalIds"] is not None
    }
    for v in d.values():
        v.pop("citedPaper")
    return d

def get_ref_links(dinfo: Dict[str, Any]) -> Dict[str, Any]:
    """Looks for reference links between documents identified as evidence to a
    claim.

    Args:
        dinfo (Dict[str, Any]): Dictionary containing various claim related
            evidence.

    Returns:
        Dict[str, Any]: Dictionary where the key is the referencing document
            and the value is a dictionary containing information about that
            reference.
    """

    d = {}
    docs = list(dinfo.keys())
    for d1 in docs:
        for d2 in docs:
            references = dinfo[d1]["rinfo"].keys()
            ids = dinfo[d2]["aliases"].copy()
            ids.append(d2)
            for id in ids:
                if id in references:
                    if not d.get(d1, None):
                        d[d1] = []
                    d[d1].append(
                        {
                            "reference": d2,
                            "isInfluential": dinfo[d1]["rinfo"][d2][
                                "isInfluential"
                            ],
                            "intent": dinfo[d1]["rinfo"][d2]["intents"],
                        }
                    )
                    break
    return d

def get_aut_links(dinfo: Dict[str, Any]) -> Dict[str, Any]:
    """Looks for common authors between documents identified as evidence to a
    claim.

    Args:
        dinfo (Dict[str, Any]): Dictionary containing various claim related
            evidence.

    Returns:
        Dict[str, Any]: Dictionary containing information about which documents
            have common authors.
    """

    d = {}
    docs = list(dinfo.keys())
    for i in range(len(docs)):
        for j in range(i + 1, len(docs)):
            d1, d2 = docs[i], docs[j]
            a1 = set(dinfo[d1]["ainfo"]["authors"].keys())
            a2 = set(dinfo[d2]["ainfo"]["authors"].keys())
            common = a1.intersection(a2)
            if common:
                d[d1] = {"doc": d2, "common": list(common)}
    return d

def get_evi_links(
    evidence_relations: pd.DataFrame, emap: Dict[str, Any]
) -> Dict[str, List[Dict[str, Any]]]:
    """Loads the evidence stances from the given datastructures.

    Args:
        evidence_relations (pd.DataFrame): Result from longchecker
            ran on the output from stance_evidence.py
        emap (Dict[str, Any]): Mapping claim ids from output of
            stance_evidence.py to various information.

    Returns:
        Dict[str, List[Dict[str, Any]]]: Dictionary where a key is a claim_id
            and its value is a list of evidence links for that claim.
    """

    evi_links = {}
    for _, er in evidence_relations.iterrows():
        evidence = er["evidence"]
        if not evidence:
            continue
        k = list(evidence.keys())[0]
        d = emap[str(er["id"])]
        d["label"] = evidence[k]["label"]
        d["label_prob"] = evidence[k]["label_probs"][
            0 if d["label"] == "CONTRADICT" else 2
        ]
        d["sent_prob"] = evidence[k]["sentences_probs"][0]
        id = d.pop("claim_id")
        if id not in evi_links:
            evi_links[id] = []
        evi_links[id].append(d)
    return evi_links

def get_features(args: argparse.Namespace) -> None:
    """Extracts features used for visualization.

    Args:
        args (argparse.Namespace): The provided arguments.
    """

    claims = pd.read_json(args.claims, lines=True).set_index("id")
    corpus = pd.read_json(args.corpus, lines=True).set_index("doc_id")
    predictions = pd.read_json(args.predictions, lines=True).set_index("id")

    if args.erelations and args.emap:
        evidence_relations = pd.read_json(args.erelations, lines=True)
        with open(args.emap, "r") as f:
            emap = json.load(f)

    evi_links = get_evi_links(evidence_relations, emap)

    with open(args.output, "w") as f:
        for index, row in tqdm(
            predictions.iterrows(), total=predictions.shape[0]
        ):
            evidence_dict = row.iloc[0]
            if not evidence_dict:  # Did not find any evidence for claim.
                continue

            info = {}
            info["claim"] = claims.loc[index][0]
            info["claim_id"] = index
            info["docs"] = {}
            for doc_id, evidence in evidence_dict.items():
                doc = corpus.loc[int(doc_id)]

                d = {}
                d["label"] = evidence["label"]
                d["label_prob"] = evidence["label_probs"][
                    0 if evidence["label"] == "CONTRADICT" else 2
                ]
                d["title"] = doc["title"]
                d["evidence"] = [
                    {
                        "text": doc["abstract"][s],
                        "prob": evidence["sentences_probs"][s],
                    }
                    for s in evidence["sentences"]
                ]
                d["aliases"] = doc["aliases"]
                d["pinfo"] = process_paper(doc_id)
                d["ainfo"] = process_authors(doc_id)
                d["rinfo"] = process_references(doc_id)
                try:
                    d["publish_time"] = doc["publish_time"].strftime("%Y-%m-%d")
                except ValueError:
                    d["publish_time"] = None
                d["journal"] = doc["journal"]

                info["docs"][doc_id] = d
            info["alinks"] = get_aut_links(info["docs"])
            info["rlinks"] = get_ref_links(info["docs"])
            if args.erelations and args.emap:
                info["elinks"] = evi_links.get(info["claim_id"], {})

            graph = create_graph(info)
            f.write(json.dumps(graph) + "\n")

def main():
    """Executes the script."""

    args = get_args()
    get_features(args)

if __name__ == "__main__":
    main()


import pygame
FPS = 500
m = 1

class Ball():
    def __init__(self, pas):
        self.x = pas[0]
        self.y = pas[1]
        self.color = (255, 255, 0)
        self.r = 50
        self.m = 1
        self.step_x = 0
        self.step_y = 0

    def move(self):
        self.x += self.step_x
        self.y += self.step_y

    def change_dir(self, x, y):
        self.step_x = x
        self.step_y = y
        if self.x + 50 == 800:
            self.m = -1
        if self.x == 50:
            self.m = 1
        self.x = self.x + self.m

    def update(self):
        pygame.draw.circle(screen, self.color, (self.x, self.y), self.r)

clock = pygame.time.Clock()

pygame.init()
screen = pygame.display.set_mode((800, 600))
x, y = 100, 100
running = True
first_ball = Ball((100, 100))
first_ball.change_dir(1, 0)
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill((0, 0, 0))
    first_ball.update()
    first_ball.move()
    if first_ball.x + first_ball.r == 800 or first_ball.x == first_ball.r:
        first_ball.change_dir(-first_ball.step_x,0)

    clock.tick(FPS)
    pygame.display.flip()
    pass

pygame.quit()


from core.evaluator.model import ReinforceAgent
from collections import deque
from itertools import compress
from math import log
from utils.plot import lineXY
import torch, pickle

class MovingBatch:
    """
    Class which deals with a "moving array"

    Example with a capacity of 4
    `|` represents a value

      n  n + 1  n + 2  n + 3  n + 4
    [ |    |      |      |    ]
    [ |    |      |      |    ]  round t
    [ |    |      |      |    ]
    --------------------------------------------
        [  |      |      |      |  ]
    --->[  |      |      |      |  ] round t + 1
        [  |      |      |      |  ]
    """

    def __init__(self, capacity, device):
        self.states = deque([], maxlen=capacity)
        self.rewards = deque([], maxlen=capacity)
        self.actions = deque([], maxlen=capacity)
        self.size = 0
        self.capacity = capacity
        self.device = device

    def totorch(self):
        """
        Return three tensors namely rewards and the log of probabilities
        """
        rewards = torch.FloatTensor(self.rewards).to(self.device)
        states = torch.FloatTensor(self.states).to(self.device)
        actions = torch.stack(tuple(self.actions)).to(self.device)
        return states, rewards, actions

    def update_size(self):
        """
        Add 1 to the size attribute (maximum: capacity)
        """
        self.size = min(self.capacity, self.size + 1)

    def isfull(self):
        """
        Return True if the batch is full (to start the
        learning process)
        """
        return self.capacity == self.size

    def clear(self):
        self.states.clear()
        self.rewards.clear()
        self.actions.clear()
        self.size = 0

class BaseServer:
    """
    This class is an abstract class used as a pattern for
    other main classes.
    """

    def __init__(self, global_model, size_traindata, size_testdata):
        """
        Initialize the class

        Parameters:

            global_model (nn.Module):   the global model
            size_traindata (list):      the list of sizes of local data for training
                                        (supposed gotten by Federated Analytic)
            size_testdata (list):       the list of sizes of local data for testing
                                        (supposed gotten by Federated Analytic)
        """
        self.global_model = global_model
        self.participants_updates = []
        self.n = size_traindata  # list
        self.t = size_testdata  # list
        self.path = None

    def send(self):
        """
        The server sends his global model parameters through this method
        """
        return self.global_model.state_dict()

    def receive(self, worker_update):
        """
        The server collects local model parameters through this method
        """
        self.participants_updates.append(worker_update)

    def communicatewith(self, worker):
        """
        For convenience, this method is used for communication.
        """
        self.receive(worker.send(False))

    def local_size(self, indices, train=True):
        """
        Return the sum of sizes depending of the indices of participants
        """
        sizes = self.n if train else self.t
        return sum((sizes[i] for i in indices))

    def compute_glb_acc(self, workers_accuracies, indices, train=False):
        """
        Compute the global accuracy based on the Federated Averaging algorithm
        """
        return sum(workers_accuracies) / self.local_size(indices, train)

    def reset(self, *args, **kwargs):
        pass

    def finish(self, *args, **kwargs):
        pass

class EvaluatorServer(BaseServer):
    """
    This class is a base class for `EvaluatorV1` and
    `EvaluatorV2` which are two different classes where
    the state and the reward of the agent for a better
    aggregation, are defined differently.
    """

    def __init__(
        self,
        global_model,
        size_traindata,
        size_testdata,
        size=None,
        capacity=3,
        gamma=0.99,
        optimizer=None,
        *args,
        **kwargs
    ):
        """
        Initialize the class

        Parameters:

            global_model (nn.Module):   the global model
            size_traindata (list):      the list of sizes of local data for training
                                        (supposed gotten by Federated Analytic)
            size_testdata (list):       the list of sizes of local data for testing
                                        (supposed gotten by Federated Analytic)
            size (int):                 the number of workers
            capacity (int):             the capacity of the moving batch size
            gamma (float):              the discount factor used for reward
            optimizer (Optimizer):      the optimizer for the agent
        """
        assert size is not None, "`size` must be specified in configuration file"
        super(EvaluatorServer, self).__init__(
            global_model, size_traindata, size_testdata
        )
        device = self.global_model.device
        self.agent = ReinforceAgent(size, size, device).to(device)
        self.optimizer = (
            torch.optim.Adam(self.agent.parameters(), lr=1e-3)
            if optimizer is None
            else optimizer(self.agent.parameters())
        )
        self.nworkers = size
        self.gamma = gamma
        self.accuracies = []  # accuracies during training of task model
        self.global_accuracies = []  # accuracies during testing of global task model
        self.alpha = 0.9  # window for exponential moving average
        self.capacity = capacity
        self.batchs = MovingBatch(capacity, device)
        self.tracking_rewards = []
        self.rewards = []
        self.losses = []
        self.batch_loss = []
        self.selections = []  # selections over time for analysis
        self.curr_selection = []

    def collects_training_accuracies(self, accuracies):
        """
        The server collects local model accuracy
        on local worker data through this method
        """
        self.accuracies.extend(accuracies)

    def collects_global_accuracies(self, accuracies):
        """
        The server collects global model accuracy
        on local worker data through this method
        """
        self.global_accuracies.extend(accuracies)

    def discount_rewards(self):
        """
        Compute the discount reward of the current step
        """
        tstep = torch.arange(len(self.rewards))
        rewards = torch.tensor(self.rewards)
        r = rewards * self.gamma**tstep
        r = r.flip(0).cumsum(0).flip(0)
        return (r / self.gamma**tstep)[-1]

    def update_batch(self, state, action):
        """
        Update MovingBatch class
        """
        pass

    def update(self, state):
        """
        Update the global model
        """
        # Selection of gradients which are going
        # to participate to the next aggregation
        probas = self.agent.forward(state)
        p = 0  # number of participants
        minp = self.nworkers // 10
        action = torch.tensor([])
        with torch.no_grad():
            while p <= minp:
                action = torch.bernoulli(probas)
                self.curr_selection = action[:, 0].tolist()
                p = sum(self.curr_selection)
        self.selections.append(self.curr_selection)
        participants = compress(self.participants_updates, self.curr_selection)

        # Update the global model
        new_weights = map(lambda layer: sum(layer) / p, zip(*participants))
        for target_param, param in zip(self.global_model.parameters(), new_weights):
            target_param.data.copy_(param.data)
        self.participants_updates.clear()
        self.global_accuracies.clear()
        return action

    def train_agent(self):
        """
        Train the agent
        """
        # Optimization if batch is complete
        if self.batchs.isfull():
            self.optimizer.zero_grad()
            states, rewards, actions = self.batchs.totorch()

            # Compute the loss value
            probas = self.agent.forward(states)
            log_prob = (torch.log(probas) * actions).sum(1)
            batch_loss = (-log_prob * rewards.unsqueeze(1)).sum(1)
            self.batch_loss = batch_loss.tolist()
            loss = batch_loss.mean()
            self.losses.append(loss.item())

            loss.backward()  # Compute gradients
            self.optimizer.step()  # Apply gradients

    def reset(self, filename=None):
        """
        Reset work values for the next round
        """
        self.batchs.clear()
        self.participants_updates.clear()
        self.rewards.clear()
        self.accuracies.clear()
        self.global_accuracies.clear()
        self.batch_loss.clear()
        self.curr_selection.clear()
        if filename is not None:
            attrbs = {"title": "Evolution of loss function"}
            attrbs.update({"xrange": (0, len(self.losses) - 1)})
            attrbs.update({"x_title": "Steps", "y_title": "Loss values"})
            lineXY({"Losses": self.losses}, filename, **attrbs)
            pkl = str(filename).replace("png", "pkl")
            with open(pkl, "wb") as file:
                pickle.dump(self.losses, file)
        self.losses.clear()

    def finish(self):
        """
        Save results at the end of the training for the agent
        """
        path = self.path / "agent"
        filename = path / "rl_rewards.png"
        attrbs = {"title": "Evolution of reward function"}
        attrbs.update({"xrange": (0, len(self.tracking_rewards) - 1)})
        attrbs.update({"x_title": "Steps", "y_title": "Rewards values"})
        lineXY({"Rewards": self.tracking_rewards}, filename, **attrbs)
        with open(path / "rl_rewards.pkl", "wb") as file:
            pickle.dump(self.tracking_rewards, file)
        with open(path / "selections.pkl", "wb") as file:
            pickle.dump(self.selections, file)
        torch.save(self.agent.state_dict(), path / "agent.pt")


# encoding=utf-8

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES,StrategyFiled,Strategy,MockConfig,ReportHistory,ReportField, MockConfigHistory
#
#
# class SnippetSerializer(serializers.Serializer):
#     pk = serializers.IntegerField(read_only=True)
#     title = serializers.CharField(required=False, allow_blank=True, max_length=100)
#     code = serializers.CharField(style={'base_template': 'textarea.html'})
#     linenos = serializers.BooleanField(required=False)
#     language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
#     style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
#
#     def create(self, validated_data):
#         """
#         如果数据合法就创建并返回一个snippet实例
#         """
#         return Snippet.objects.create(**validated_data)
#
#     def update(self, instance, validated_data):
#         """
#         如果数据合法就更新并返回一个存在的snippet实例
#         """
#         instance.title = validated_data.get('title', instance.title)
#         instance.code = validated_data.get('code', instance.code)
#         instance.linenos = validated_data.get('linenos', instance.linenos)
#         instance.language = validated_data.get('language', instance.language)
#         instance.style = validated_data.get('style', instance.style)
#         instance.save()
#         return instance

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

class StrategyFiledSerializer(serializers.ModelSerializer):
    class Meta:
        model = StrategyFiled
        fields = ('id','creditName','strategy','service','interface','description','logic','result','remarks','testSuccess','paramType','isDelete','testEnv')

class StrategySerializer(serializers.ModelSerializer):
    strategyfiled = StrategyFiledSerializer(many=True,read_only=True)

    class Meta:
        model = Strategy
        fields = ('id','strategy','alias','strategyfiled','description','isDelete','testEnv')

class MockConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = MockConfig
        fields = ('id','title','json','description','testEnv','decisionName')

class MockConfigHistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = MockConfigHistory
        fields = ('id','title','json','description','subItems','testEnv','decisionName')

class ReportFieldSerializer(serializers.ModelSerializer):
    creditName = serializers.CharField(source='field.creditName',read_only=True)
    service = serializers.CharField(source='field.service',read_only=True)
    description = serializers.CharField(source='field.description',read_only=True)
    logic = serializers.CharField(source='field.logic',read_only=True)
    remarks = serializers.CharField(source='field.remarks',read_only=True)
    class Meta:
        model = ReportField
        fields = ('id','report','strategyName','strategyAlias','field','creditName','description','service','logic','remarks','paramType','interface','currentValueType','currentValue','testResult','isTestFaild','isTestSuccess','isDelete')

class ReportWithoutFieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReportHistory
        fields = ('id','title','createWay','cid','sqs','content','remarks','isDelete','created','testEnv')

class ReportSerializer(serializers.ModelSerializer):
    reportfileds = ReportFieldSerializer(many=True,read_only=True)
    class Meta:
        model = ReportHistory
        fields = ('id','title','createWay','cid','sqs','content','remarks','reportfileds','isDelete','created','testEnv')
        depth = 3


import cv2
import numpy as np

#Stream Camera
cap = cv2.VideoCapture(2)

#Loop Frames
while True:
    ret, frame = cap.read()
    if not ret:
        print("No more frames")
        break
    cv2.imshow('Capture', frame)
    if cv2.waitKey(1) == ord('q'):
        break

#Close Window
cap.release()
cv2.destroyAllWindows()


import pygame

from api.StageAutoManage import StageAutoManage
from api.StageState import StageState

class StageConsole(StageAutoManage):
    """ Stage appelé en appuyant sur 'c' , crée une invite de commande qui s'affiche en haut à gauche, qui s'éteint en retournant la commande en appuyant sur ESPACE"""

    def __init__(self, previous_stage):
        super().__init__()
        self.console = ""
        self.font = pygame.font.Font("freesansbold.ttf", 15)
        self.previous_stage = previous_stage

    def draw(self):
        super().draw()

        self.screen.blit(self.font.render(self.console, True, (255, 0, 255)), (0, 0))   #colle surface générée par render ( chaine, aliasing, couleur, bckgrnd ) sur écran

    def quit(self):
        super().quit()

        self.previous_stage.state = StageState.RESUME       # relance stage précédent
        self.previous_stage.execute(self.console)           # appelle la fonction execute su stage précédent avec pour argument la strg de la console

    def handle_keydown(self, unicode, key, mod):
        super().handle_keydown(unicode, key, mod)
        if key == pygame.K_RETURN:                          # permet de valider l'entrée
            self.state = StageState.QUIT
        elif key == pygame.K_BACKSPACE:                     # permet d'utiliser la touche  <----
            self.console = self.console[:-1]
        else:
            self.console += unicode


# -*- coding: utf-8 -*-

import os, sys

paths = os.path.dirname(os.path.realpath(__file__)).split(os.sep)
sys.path.append(os.sep.join(paths[:len(paths)-2]))
import tools

class Nyaa:
	NAME = "nyaa"
	OUTPUT = "output"
	URL = "http://www.nyaa.se/?page=rss&term={}"

	def __init__(self):
		tools.logo("nyaa.se Torrent Crawler")


from dotenv import load_dotenv
import os
import requests

def main():
    try:
        # Get Configuration Settings
        load_dotenv()
        key = os.getenv('COG_SERVICE_KEY')
        region = os.getenv('COG_SERVICE_REGION')
        endpoint = 'https://api.cognitive.microsofttranslator.com'

        text = 'Hello world!'
        print('Detected language of "' + text + '":', detect_language(text, key, region, endpoint))
        target_lang = 'el'
        print(target_lang + ":", translate(text, 'en', target_lang, key, region, endpoint))
    except Exception as ex:
        print(ex)

def detect_language(text, key, region, endpoint):
    # Use the Translator detect function
    path = '/detect'
    url = endpoint + path
    # Build the request
    params = {
        'api-version': '3.0'
    }
    headers = {
    'Ocp-Apim-Subscription-Key': key,
    'Ocp-Apim-Subscription-Region': region,
    'Content-type': 'application/json'
    }
    body = [{
        'text': text
    }]
    # Send the request and get response
    request = requests.post(url, params=params, headers=headers, json=body)
    response = request.json()
    # Get language
    language = response[0]["language"]
    # Return the language
    return language

def translate(text, source_language, target_language, key, region, endpoint):
    # Use the Translator translate function
    url = endpoint + '/translate'
    # Build the request
    params = {
        'api-version': '3.0',
        'from': source_language,
        'to': target_language
    }
    headers = {
        'Ocp-Apim-Subscription-Key': key,
        'Ocp-Apim-Subscription-Region': region,
        'Content-type': 'application/json'
    }
    body = [{
        'text': text
    }]
    # Send the request and get response
    request = requests.post(url, params=params, headers=headers, json=body)
    response = request.json()
    # Get translation
    translation = response[0]["translations"][0]["text"]
    # Return the translation
    return translation

if __name__ == "__main__":
    main()


from bs4 import BeautifulSoup
import requests
import concurrent.futures
import pandas as pd
import re
import logging

class FacultyScraper:
    """
    A web scraping tool to extract data from a faculty directory website.

    Attributes:
        url (str): The URL of the faculty directory website.
        session (requests.Session): A session object to handle HTTP requests.
        soup (BeautifulSoup): A BeautifulSoup object to parse HTML content.
        list_of_dicts (list): A list of dictionaries containing faculty information.

    Methods:
        scrape_data(): Scrapes the data from the faculty directory website.
        make_request(): Sends an HTTP request to the specified URL.
        parse_html(): Parses the HTML content of the response.
        find_email_addresses(): Finds and stores the email addresses of faculty members.
        find_professors(): Finds and stores the names and colleges of faculty members.
        check_length(): Checks if the number of unique emails matches the number of faculty names.
        find_links(): Finds and stores the profile links of faculty members.
        create_faculty_dicts(): Creates faculty dictionaries with basic information.
        extract_subjects(): Extracts and stores the subjects taught by each faculty member.
        extract_research_topics(): Extracts and stores the research topics of each faculty member.
    """

    def __init__(self, url):
        """
        Initializes a FacultyScraper object.

        Args:
            url (str): The URL of the faculty directory website.
        """
        self.url = url
        self.session = requests.Session()
        self.soup = None
        self.list_of_dicts = []
        self.logger = self._setup_logger()

    def _setup_logger(self):
        """
        Sets up a logger for error handling and logging.

        Returns:
            logging.Logger: The configured logger object.
        """
        logger = logging.getLogger("FacultyScraper")
        logger.setLevel(logging.ERROR)

        # Define log file handler
        file_handler = logging.FileHandler("scraper.log")
        file_handler.setLevel(logging.ERROR)

        # Define log message format
        formatter = logging.Formatter(
            "%(asctime)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)

        # Add file handler to logger
        logger.addHandler(file_handler)

        return logger

    def scrape_data(self):
        """
        Scrapes the data from the faculty directory website.

        Returns:
            list: A list of dictionaries containing faculty information.
        """
        try:
            self.make_request()
            self.parse_html()
            self.find_email_addresses()
            self.find_professors()
            self.check_length()
            self.find_links()
            self.create_faculty_dicts()

            # Create a ThreadPoolExecutor with maximum threads
            with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
                # Execute extract_subjects and extract_research_topics concurrently
                subject_futures = [executor.submit(
                    self.extract_subjects, url) for url in self.links]
                research_futures = [executor.submit(
                    self.extract_research_topics, url) for url in self.links]

                # Retrieve the results from the futures
                subjects_list = [
                    future.result() for future in concurrent.futures.as_completed(subject_futures)]
                research_list = [
                    future.result() for future in concurrent.futures.as_completed(research_futures)]

            # Update the subjects and research topics in the faculty dictionaries
            for i in range(len(self.list_of_dicts)):
                self.list_of_dicts[i]["Subjects"] = subjects_list[i]
                self.list_of_dicts[i]["Research"] = research_list[i]

            return self.list_of_dicts
        except Exception as e:
            self.logger.error("An error occurred during scraping: %s", str(e))

    def make_request(self):
        """
        Sends an HTTP request to the specified URL.
        """
        self.response = self.session.get(self.url)

    def parse_html(self):
        """
        Parses the HTML content of the response.
        """
        self.soup = BeautifulSoup(self.response.content, "html.parser")

    def find_email_addresses(self):
        """
        Finds and stores the email addresses of faculty members.
        """
        email_addresses = [
            link.get("href").replace("mailto:", "")
            for link in self.soup.find_all("a", href=lambda href: href and href.startswith("mailto:"))
        ]
        self.unique_emails = []
        for mail in email_addresses:
            if mail not in self.unique_emails:
                self.unique_emails.append(mail)

    def validate_email_format(self, email):
        """
        Validates if an email address is in the correct format.

        Args:
            email (str): Email address to validate.

        Returns:
            bool: True if the email is valid, False otherwise.
        """
        pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
        return re.match(pattern, email) is not None

    def clean_data(self):
        """
        Cleans the scraped data by removing duplicates and handling missing values.
        """
        unique_emails = []
        cleaned_data = []

        for faculty in self.list_of_dicts:
            email = faculty["Email"]
            if email and email not in unique_emails:
                unique_emails.append(email)
                cleaned_data.append(faculty)

        self.list_of_dicts = cleaned_data

        # Validate and clean email addresses
        for faculty in self.list_of_dicts:
            email = faculty["Email"]
            if email and not self.validate_email_format(email):
                faculty["Email"] = ""

        # Handle missing values
        for faculty in self.list_of_dicts:
            for key, value in faculty.items():
                if value is None:
                    faculty[key] = ""

    def find_professors(self):
        """
        Finds and stores the names and colleges of faculty members.
        """
        professors = self.soup.find_all(
            "div", class_="profileinfo-teaser-name")
        self.names = []
        self.prof_college = []
        for div in professors:
            name_parts = div.text.split(',')
            name = name_parts[0].strip()
            self.prof_college.append(name_parts[2].strip())
            if "PhD" in name_parts[1]:
                new_name = "Dr. " + name
                self.names.append(new_name)
            else:
                self.names.append(name)

    def check_length(self):
        """
        Checks if the number of unique emails matches the number of faculty names.
        """
        self.is_length_equal = len(self.unique_emails) == len(self.names)

    def find_links(self):
        """
        Finds and stores the profile links of faculty members.
        """
        professors = self.soup.find_all(
            "div", class_="profileinfo-teaser-name")
        self.links = [
            "https://engineering.buffalo.edu/" +
            div.find('a', class_='title')['href'][:-4] + "teaching.html"
            for div in professors
        ]

    def create_faculty_dicts(self):
        """
        Creates faculty dictionaries with basic information.
        """
        for name, college, email, profile_url in zip(self.names, self.prof_college, self.unique_emails, self.links):
            faculty_dict = {
                "Name": name,
                "College": college,
                "Email": email,
                "Subjects": [],
                "Research": [],
                "Profile": profile_url  # Add the 'Profile' key with the URL
            }
            self.list_of_dicts.append(faculty_dict)

    def extract_subjects(self, url):
        """
        Extracts and returns the subjects taught by a faculty member.

        Args:
            url (str): The URL of the faculty member's profile page.

        Returns:
            list: A list of subjects taught by the faculty member.
        """
        try:
            response = self.session.get(url)
            soup = BeautifulSoup(response.content, "html.parser")
            div = soup.find("div", class_="text parbase section")
            ul = div.find("ul")
            subjects = []
            try:
                for li in ul.find_all("li"):
                    subjects.append(li.text)
            except:
                pass
            return subjects
        except Exception as e:
            self.logger.error(
                "An error occurred during subject extraction: %s", str(e))

    def extract_research_topics(self, url):
        """
        Extracts and returns the research topics of a faculty member.

        Args:
            url (str): The URL of the faculty member's profile page.

        Returns:
            list: A list of research topics of the faculty member.
        """
        try:
            response = self.session.get(url)
            soup = BeautifulSoup(response.content, "html.parser")
            research_topics = []
            try:
                for div in soup.find_all("div", class_="profileinfo-interest title"):
                    raw_string = div.text[15:].strip()
                    research_topics.extend(raw_string.strip().split("; "))
            except:
                pass
            return research_topics
        except Exception as e:
            self.logger.error(
                "An error occurred during research topic extraction: %s", str(e))

    def dump_to_csv(self, filename):
        """
        Dumps the scraped data to a CSV file.

        Args:
            filename (str): The name of the CSV file.
        """
        df = pd.DataFrame(self.list_of_dicts)
        df.to_csv(filename, index=False)

    def return_df(self,):
        """
        Returns the data in a pandas dataframe.
        """
        df = pd.DataFrame(self.list_of_dicts)
        return df


import random

palavras = set()
acertos = set()
erros = set()

def configurar_jogo():
    while True:
        palavra = input("Digite uma palavra (ou 'SAIR' para encerrar a configuração): ").strip().lower()
        if palavra == 'sair':
            break
        palavra_criptografada = criptografar_palavra(palavra)
        if palavra_criptografada not in palavras:
            palavras.add(palavra_criptografada)
        else:
            print("Essa palavra já foi inserida. Digite outra palavra.")

def criptografar_palavra(palavra):
    return ''.join(reversed(palavra))

def descriptografar_palavra(palavra_criptografada):
    return ''.join(reversed(palavra_criptografada))

def jogar():
    if not palavras:
        print("Você precisa configurar o jogo primeiro.")
        return

    palavra_secreta_criptografada = random.choice(list(palavras))
    palavras.remove(palavra_secreta_criptografada)
    palavra_secreta = descriptografar_palavra(palavra_secreta_criptografada)
    tentativas = 3

    print(f"A palavra a ser adivinhada tem {len(palavra_secreta)} caracteres.")

    while tentativas > 0:
        tentativa = input(f"Você tem {tentativas} tentativa(s) restante(s). Tente adivinhar a palavra: ").strip().lower()

        if tentativa == palavra_secreta:
            print("Parabéns! Você acertou a palavra.")
            acertos.add(palavra_secreta)
            break
        else:
            tentativas -= 1
            if tentativas > 0:
                print("Tentativa incorreta. Tente novamente.")

    if tentativas == 0:
        print(f"Suas tentativas se esgotaram. A palavra era '{palavra_secreta}'.")
        erros.add(palavra_secreta)

def menu():
    while True:
        print("\nMenu:")
        print("1) CONFIGURAR JOGO")
        print("2) JOGAR")
        print("3) SAIR")
        opcao = input("Escolha uma opção: ").strip()

        if opcao == '1':
            configurar_jogo()
        elif opcao == '2':
            jogar()
        elif opcao == '3':
            print("\nFim do jogo!")
            print("Palavras corretamente adivinhadas:", acertos)
            print("Palavras erradas:", erros)
            break
        else:
            print("Opção inválida. Escolha uma opção válida (1, 2 ou 3).")

menu()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

# This scripts generates a report of open bugs in the product 'Core' with the
# severity S2.

import csv
import datetime
import json
from libmozdata.bugzilla import Bugzilla
from logger import logger
import pytz
import urllib.request

from utils.bugzilla import BUG_LIST_WEB_URL, get_component_to_team, get_relevant_bug_changes

import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

BUGZILLA_CONFIG_URL = 'https://bugzilla.mozilla.org/rest/configuration'

PRODUCTS_TO_CHECK = [
    'Core',
    'DevTools',
    'Firefox',
    'Toolkit',
]

SEVERITIES = ['S2']

STATUS_OPEN = ['UNCONFIRMED', 'NEW', 'ASSIGNED', 'REOPENED']

TEAMS_IGNORED = [
  'Credential Management',
  'Desktop Integrations',
  'Frontend',
  'Pocket and User Journey',
  'Search and New Tab',
  'Services',
  'Telemetry',
  'Web Extensions',
]

BUG_CREATION_START = '2020-07-01'
# BUG_CREATION_BEFORE = '2022-07-01'

def get_bugs(time_intervals):

    def bug_handler(bug_data):
        creation_time = datetime.datetime.strptime(bug_data['creation_time'], '%Y-%m-%dT%H:%M:%SZ')
        creation_time = pytz.utc.localize(creation_time).date()
        for time_interval in time_intervals:
            start_date = time_interval['from']
            end_date = time_interval['to']
            date_label = time_interval['label']
            if creation_time >= end_date:
                continue
            bug_states = get_relevant_bug_changes(bug_data, ["product", "component", "severity", "status", "resolution"], start_date, end_date)
            if bug_states["severity"]["new"] not in SEVERITIES:
                continue
            if bug_states["product"]["new"] not in PRODUCTS_TO_CHECK:
                continue
            team = get_component_to_team(bug_states["product"]["new"], bug_states["component"]["new"]) or "Unknown"
            if team in TEAMS_IGNORED:
                continue
            if team not in teams:
                teams.add(team)
            if bug_states["status"]["new"] in STATUS_OPEN:
                if bug_data['id'] not in bugs_by_date[date_label]:
                    bugs_by_date[date_label][bug_data['id']] = team
            if bug_states["status"]["old"] in STATUS_OPEN and bug_states["resolution"]["new"] == "FIXED":
                if bug_data['id'] not in fixed_bugs_by_date[date_label]:
                    fixed_bugs_by_date[date_label][bug_data['id']] = team

    teams = set()

    bugs_by_date = {}
    fixed_bugs_by_date = {}
    for data_series in [bugs_by_date, fixed_bugs_by_date]:
        for time_interval in time_intervals:
            date_label = time_interval['to'].isoformat()
            data_series[time_interval['label']] = {}

    fields = [
              'id',
              'product',
              'component',
              'status',
              'resolution',
              'severity',
              'creation_time',
              'history',
             ]

    params = {
        'include_fields': fields,
        'f1': 'bug_severity',
        'o1': 'equals',
        'v1': SEVERITIES,
        'f2': 'creation_ts',
        'o2': 'greaterthan',
        'v2': BUG_CREATION_START,
        # 'f3': 'creation_ts',
        # 'o3': 'lessthan',
        # 'v3': BUG_CREATION_BEFORE,
    }

    Bugzilla(params,
             bughandler=bug_handler,
             timeout=960).get_data().wait()

    params = {
        'include_fields': fields,
        'f1': 'bug_severity',
        'o1': 'changedfrom',
        'v1': SEVERITIES,
        'f2': 'creation_ts',
        'o2': 'greaterthan',
        'v2': BUG_CREATION_START,
        # 'f3': 'creation_ts',
        # 'o3': 'lessthan',
        # 'v3': BUG_CREATION_BEFORE,
    }

    Bugzilla(params,
             bughandler=bug_handler,
             timeout=960).get_data().wait()

    teams = sorted(list(teams))
    open_bugs_by_day_and_team = []
    bugs_by_date_list = sorted([{key: value} for key, value in bugs_by_date.items()], key = lambda item: list(item.keys())[0])
    for bugs_for_single_day_dict in bugs_by_date_list:
        date = list(bugs_for_single_day_dict.keys())[0]
        open_bugs_for_day_by_team = {}
        for team in teams:
            open_bugs_for_day_by_team[team] = []
        open_bugs = bugs_for_single_day_dict[date]
        for bug_id, team in open_bugs.items():
            open_bugs_for_day_by_team[team].append(bug_id)
        open_bugs_by_day_and_team.append({
            "date": date,
            "teams": open_bugs_for_day_by_team
        })

    fixed_bug_count_by_day = []
    bugs_by_date_list = sorted([{key: value} for key, value in fixed_bugs_by_date.items()], key = lambda item: list(item.keys())[0])
    for bugs_for_single_day_dict in bugs_by_date_list:
        key = list(bugs_for_single_day_dict.keys())[0]
        fixed_bug_count_by_day.append({key: bugs_for_single_day_dict[key]})

    return open_bugs_by_day_and_team, fixed_bug_count_by_day

def write_csv(open_bugs_by_day_and_team, fixed_bug_count_by_day):
    with open('data/core_s2_burndown.csv', 'w') as Out:
        writer = csv.writer(Out, delimiter=',')

        writer.writerow(['Open Core bugs with severity S2 filed since 2020-07-01'])
        writer.writerow([])

        row = ['date'] + [day_data["date"] for day_data in open_bugs_by_day_and_team]
        writer.writerow(row)

        row = ['open']
        for day_data in open_bugs_by_day_and_team:
            row.append(sum([len(bugs_for_team) for bugs_for_team in day_data["teams"].values()]))
        writer.writerow(row)
        row = ['bugs']
        for day_data in open_bugs_by_day_and_team:
            bugs = []
            for bugs_for_team in day_data["teams"].values():
                bugs.extend(bugs_for_team)
            row.append(BUG_LIST_WEB_URL + ",".join(list(map(str, sorted(bugs)))))
        writer.writerow(row)

        row = ['fixed'] + [len(list(day_data.values())[0]) for day_data in fixed_bug_count_by_day]
        writer.writerow(row)

        writer.writerow([])

        row = ['date'] + [day_data["date"] for day_data in open_bugs_by_day_and_team]
        writer.writerow(row)

        teams = sorted(open_bugs_by_day_and_team[0]["teams"].keys())
        for team in teams:
            row = [team] + [len(day_data["teams"][team]) for day_data in open_bugs_by_day_and_team]
            writer.writerow(row)

        writer.writerow([])

        row = ['date'] + [day_data["date"] for day_data in open_bugs_by_day_and_team]
        writer.writerow(row)

        teams = sorted(open_bugs_by_day_and_team[0]["teams"].keys())
        for team in teams:
            row = [team] + [BUG_LIST_WEB_URL + ",".join(list(map(str, sorted(day_data["teams"][team])))) for day_data in open_bugs_by_day_and_team]
            writer.writerow(row)

start_day = datetime.datetime.strptime(BUG_CREATION_START, '%Y-%m-%d')
if start_day.weekday() < 6:
    start_day = start_day - datetime.timedelta(start_day.weekday() + 1 - 7)

time_intervals = []
from_day = start_day - datetime.timedelta(7)
day_max = min(datetime.datetime(2023, 1, 1), datetime.datetime.now())
while from_day < day_max:
    to_day = from_day + datetime.timedelta(7)
    time_intervals.append({
        'from': from_day.date(),
        'to': to_day.date(),
        'label': to_day.date().isoformat(),
    })
    from_day += datetime.timedelta(7)
# time_intervals.reverse()

open_bugs_by_day_and_team, fixed_bug_count_by_day = get_bugs(time_intervals)
write_csv(open_bugs_by_day_and_team, fixed_bug_count_by_day)


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

# @Time    : 2018/2/5 14:31
# @Author  : BigDin
# @Contact : dinglei_1107@outlook.com

import re
from functools import wraps
from collections import deque

def uniqueness(func):
    @wraps(func)
    def _func(*a, **kw):
        seen = set()
        it = func(*a, **kw)
        while 1:
            x = next(it)
            if x not in seen:
                yield x
                seen.add(x)
    return _func

class TrieTree:
    def __init__(self, corpus):
        self._tree = self.make_trie(
            self._words(open(corpus).read())
        )
        self.candidate = set()

    @staticmethod
    def make_trie(words):
        """构造Trie（用dict登记结点信息和维持子结点集合）"""
        trie = {}
        for word in words:
            t = trie
            for c in word:
                if c not in t:
                    t[c] = {}
                t = t[c]
            t[None] = None
        return trie

    @staticmethod
    def _words(text):
        """读取文本单词作为训练数据"""
        return re.findall(r'\w+', text.lower())

    @uniqueness
    def search(self, word, tol=1):
        q = deque([(self._tree, word, '', tol)])
        while q:
            trie, word, path, tol = q.popleft()
            if word == '':
                if None in trie:
                    if path not in self.candidate:
                        self.candidate.add(path)
                        yield path
                if tol > 0:
                    for k in trie:
                        if k is not None:
                            q.appendleft((trie[k], '', path + k, tol - 1))
            else:
                if word[0] in trie:
                    q.appendleft((trie[word[0]], word[1:], path + word[0], tol))
                if tol > 0:
                    for k in trie.keys():
                        if k is not None and k != word[0]:
                            q.append((trie[k], word[1:], path + k, tol - 1))
                            q.append((trie[k], word, path + k, tol - 1))
                    q.append((trie, word[1:], path, tol - 1))
                    if len(word) > 1:
                        q.append((trie, word[1] + word[0] + word[2:], path, tol - 1))

if __name__ == "__main__":
    trie_spc = TrieTree("../data/training.txt")
    print(list(trie_spc.search('schol')))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Target visibility plotting.
@TODO: Move to flows-tools.

.. codeauthor:: Rasmus Handberg <rasmush@phys.au.dk>
"""

import logging
import os.path
import warnings
from datetime import datetime
from typing import Optional

import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from astropy.coordinates import AltAz, SkyCoord, get_moon, get_sun
from astropy.time import Time
from astropy.visualization import quantity_support
from matplotlib.dates import DateFormatter
from tendrils import api

from .target import Target

# --------------------------------------------------------------------------------------------------
def visibility(target: Target, siteid: Optional[int] = None, date=None, output=None, overwrite=True):
    """
    Create visibility plot.

    Parameters:
        target (str or int):
        siteid (int): Identifier of site.
        date (datetime or str, optional): Date for which to create visibility plot.
            Default it to use the current date.
        output (str, optional): Path to file or directory where to place the plot.
            If not given, the plot will be created in memory, and can be shown on screen.
        overwrite (bool, optional): Should existing file specified in ``output`` be overwritten?
            Default is to overwrite an existing file.

    .. codeauthor:: Rasmus Handberg <rasmush@phys.au.dk>
    """

    logger = logging.getLogger(__name__)
    warnings.warn(DeprecationWarning("This module is moved to SNFLOWS/flows-tools."))

    if date is None:
        date = datetime.utcnow()
    elif isinstance(date, str):
        date = datetime.strptime(date, '%Y-%m-%d')

    # Coordinates of object:
    obj = SkyCoord(ra=target.ra, dec=target.dec, unit='deg', frame='icrs')

    if siteid is None:
        sites = api.get_all_sites()
    else:
        sites = [api.get_site(siteid)]

    plotpaths = []
    for site in sites:
        # If we are saving plot to file, determine the path to save to
        # and check that it doesn't already exist:
        if output:
            if os.path.isdir(output):
                plotpath = os.path.join(output, "visibility_%s_%s_site%02d.png" % (
                    target.name, date.strftime('%Y%m%d'), site['siteid']))
            else:
                plotpath = output
            logger.debug("Will save visibility plot to '%s'", plotpath)

            # If we are not overwriting and
            if not overwrite and os.path.exists(plotpath):
                logger.info("File already exists: %s", plotpath)
                continue
        logger.debug(f"{site}, type: {type(site)}")
        # Observatory:
        observatory = site.get('EarthLocation', None)
        if observatory is None:
            observatory = site.get('earth_location')
        utcoffset = (site['longitude'] * u.deg / (360 * u.deg)) * 24 * u.hour

        # Create timestamps to calculate for:
        midnight = Time(date.strftime('%Y-%m-%d') + ' 00:00:00', scale='utc') - utcoffset
        delta_midnight = np.linspace(-12, 12, 1000) * u.hour
        times = midnight + delta_midnight

        # AltAz frame:
        AltAzFrame = AltAz(obstime=times, location=observatory)

        # Object:
        altaz_obj = obj.transform_to(AltAzFrame)

        # The Sun and Moon:
        altaz_sun = get_sun(times).transform_to(AltAzFrame)
        altaz_moon = get_moon(times).transform_to(AltAzFrame)

        sundown_astro = (altaz_sun.alt < -6 * u.deg)
        if np.any(sundown_astro):
            min_time = np.min(times[sundown_astro]) - 2 * u.hour
            max_time = np.max(times[sundown_astro]) + 2 * u.hour
        else:
            min_time = times[0]
            max_time = times[-1]

        quantity_support()
        fig, ax = plt.subplots(1, 1, figsize=(15, 9), squeeze=True)
        plt.grid(ls=':', lw=0.5)
        ax.plot(times.datetime, altaz_sun.alt, color='y', label='Sun')
        ax.plot(times.datetime, altaz_moon.alt, color=[0.75] * 3, ls='--', label='Moon')
        objsc = ax.scatter(times.datetime, altaz_obj.alt, c=altaz_obj.az, label=target.name, lw=0, s=8,
                           cmap='twilight')
        ax.fill_between(times.datetime, 0 * u.deg, 90 * u.deg, altaz_sun.alt < -0 * u.deg, color='0.5',
                        zorder=0)  # , label='Night'
        ax.fill_between(times.datetime, 0 * u.deg, 90 * u.deg, altaz_sun.alt < -18 * u.deg, color='k',
                        zorder=0)  # , label='Astronomical Night'

        plt.colorbar(objsc, ax=ax, pad=0.01).set_label('Azimuth [deg]')
        ax.legend(loc='upper left')
        ax.minorticks_on()
        ax.set_xlim(min_time.datetime, max_time.datetime)
        ax.set_ylim(0 * u.deg, 90 * u.deg)
        ax.set_title("%s - %s - %s" % (target.name, date.strftime('%Y-%m-%d'), site['sitename']),
                     fontsize=14)
        plt.xlabel('Time [UTC]', fontsize=14)
        plt.ylabel('Altitude [deg]', fontsize=16)
        fig.autofmt_xdate()

        formatter = DateFormatter('%d/%m %H:%M')
        ax.xaxis.set_major_formatter(formatter)

        if output:
            fig.savefig(plotpath, bbox_inches='tight', transparent=True)
            plt.close(fig)
            plotpaths.append(plotpath)

    if output:
        return plotpaths

    plt.show()
    return ax


#https://programmers.co.kr/learn/courses/30/lessons/12909
from collections import deque

def solution(s):
    answer = True
    q = deque(s)
    count = 0
    while q :
        x = q.popleft()
        # ( 이면 +1
        if x == '(':
            count += 1
        # ) 이면 -1
        else :
            count -= 1
        # )가 ( 보다 많으면 올바르지 않은 괄호
        if count < 0:
            answer = False
            break
    # (와 )의 개수가 맞지 않으면 올바르지 않은 괄호
    if count != 0:
        answer = False

    return answer


import cv2,math,time,struct,argparse
from bitstream import BitStream
import numpy as np
from skimage.util.shape import view_as_blocks

parser = argparse.ArgumentParser(description='Converter')
parser.add_argument("file", help="Input video")
parser.add_argument("output", help="Optional output file", nargs='?', default="data.bin")
parser.add_argument("-s", "--show", help="Show dct results", action="store_true")
parser.add_argument("-p", "--play", help="Play video in dct", action="store_true")
parser.add_argument("-d", "--debug", help="Print dct results ", action="store_true")
parser.add_argument("-q", "--quality", help="Scale quantization matrix", dest="quality", type=float, default=1.0)
cmd_args = parser.parse_args()

infile = cmd_args.file
outfile = cmd_args.output

CLEAR = "\033[K"

print("Reading from %s"%infile)
vid = cv2.VideoCapture(infile)
fps = vid.get(cv2.CAP_PROP_FPS)
width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
nbframes = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))
normal_size = nbframes*width*height
duration = nbframes/fps
print("Video: %i frames (%i:%i) @ %ffps (%ix%i)"%(nbframes,duration/60,duration%60,fps,width,height))
print("Writing to file: %s"%outfile)

def img2bin(image):
	gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
	return (gray-128).astype(np.int8)

quant = np.array([[16,11,10,16,24,40,51,61],
				[12,12,14,19,26,58,60,55],
				[14,13,16,24,40,57,69,56],
				[14,17,22,29,51,87,80,62],
				[18,22,37,56,68,109,103,77],
				[24,36,55,64,81,104,113,92],
				[49,64,78,87,103,121,120,101],
				[72,92,95,98,112,100,103,99]])*cmd_args.quality

quant = np.rint(quant).astype(np.uint16)
print(quant)

# 3 -> Duplicate frame
# 2 -> Delta Frame
# 1 -> Huffman Frame
# 0 -> END

gbits = BitStream()
tempbs = BitStream()

symboltable = {}
valsymboltable = {}

frequency = {}
valfrequency = {}

rle_min_same = 16
dc_chunk_size = 8 # needs to divide width&height
dc_chunk_bits = int(math.log((width*height)//(dc_chunk_size*dc_chunk_size),2))
print("DC Chunk size: %i"%(dc_chunk_size))
print("DC Chunk bits: %i"%(dc_chunk_bits))

def addbits(bs,by,nb):
	for i in range(nb):
		bs.write((by >> (nb-1-i)) & 1 == 1)

def huffcomp(dcts,bs):
	bs.read()
	tempbs.read()
	addbits(bs,1,2)
	for dct in dcts:
		bs.write(dct)

def deltacomp(dcts,xdiff,bs):
	bs.read()
	tempbs.read()
	addbits(bs,2,2)
	wd = width//dc_chunk_size
	chunkdiffs = {}

	xdiff_flat = xdiff.flatten()
	for i in range(len(xdiff_flat)):
		if xdiff_flat[i]:
			x = i%width
			y = i//width
			idx = ((y//dc_chunk_size)*wd)+(x//dc_chunk_size)
			if idx not in chunkdiffs:
				chunkdiffs[idx] = 1
			else:
				chunkdiffs[idx] += 1

	addbits(bs,len(chunkdiffs)-1,dc_chunk_bits)
	for idx in chunkdiffs:
		addbits(bs,idx,dc_chunk_bits)
		bs.write(dcts[idx])

nbdup = 0
nbhuff = 0
nbdelta = 0
nboverh = 0
nboverd = 0
ratiohuff = 0
ratiodelta = 0

lastframe = np.zeros((height,width), np.uint8)

rlebs = BitStream()
deltabs = BitStream()

cframe = 0
encodedframes = 0

starttime = time.time()

addbits(gbits,int(fps*1000),16)

def add_freq(freqt, symb):
	if "tot" not in freqt:
		freqt["tot"] = 1
	else:
		freqt["tot"] += 1
	if symb in freqt:
		freqt[symb] += 1
	else:
		freqt[symb] = 1
#(0, 0),
zigzag = [(0, 1), (1, 0),
		(2, 0), (1, 1), (0, 2),
		(0, 3), (1, 2), (2, 1), (3, 0),
		(4, 0), (3, 1), (2, 2), (1, 3), (0, 4),
		(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0),
		(6, 0), (5, 1), (4, 2), (3, 3), (2, 4), (1, 5), (0, 6),
		(0, 7), (1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0),
		(7, 1), (6, 2), (5, 3), (4, 4), (3, 5), (2, 6), (1, 7),
		(2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2),
		(7, 3), (6, 4), (5, 5), (4, 6), (3, 7),
		(4, 7), (5, 6), (6, 5), (7, 4),
		(7, 5), (6, 6), (5, 7),
		(6, 7), (7, 6),
		(7, 7)]

def do_dct(chunk):
	quantized = np.rint(cv2.dct(chunk.astype(np.single))/quant).astype(np.int8)
	output = []
	nbzeros = 0
	lastval = 256
	lastnb = 0
	for pos in zigzag:
		val = quantized[pos[0]][pos[1]]
		if val != lastval:
			while lastnb >= 16:
				lastnb -= 15
				if lastval == 0:
					output.append((0xF0,0))
				else:
					output.append((0xF | ((nbzeros & 0xF) << 4),lastval))
					nbzeros = 0
			if lastval != 256 and lastval != 0:
				output.append(((lastnb & 0xF) | ((nbzeros & 0xF) << 4),lastval))
				nbzeros = 0
			elif lastval == 0:
				nbzeros = lastnb
			lastnb = 1
			lastval = val
		else:
			lastnb += 1
	if lastnb != 0:
		if lastval == 0:
			output.append((0,0))
		else:
			output.append(((lastnb & 0xF) | ((nbzeros & 0xF) << 4),lastval))
	return quantized[0][0],output,quantized

print("Applying DCT & Generating frequency table")
precalc_frames = []
precalc_frames_dct = {}
lastframeflat = np.zeros((height,width), np.uint8)
freqframes = 0
while vid.isOpened():
	r,f = vid.read()
	if not r:
		break
	f = img2bin(f)
	idx = len(precalc_frames)
	precalc_frames.append(f)
	if not (f ^ lastframeflat).any():
		continue
	print(CLEAR+"Frame: %i/%i (%.2f%%)"%(freqframes,nbframes,(freqframes/nbframes)*100),end='\r')

	wd = width//dc_chunk_size
	hd = height//dc_chunk_size

	chunks = view_as_blocks(f,(dc_chunk_size,dc_chunk_size))

	if cmd_args.show:
		dcto = []

		temph = []
		for linechunks in chunks:
			for i,chunk in enumerate(linechunks):
				dct = np.rint(cv2.dct(chunk.astype(np.single))/quant)
				idct = np.clip(cv2.dct(dct*quant,flags=cv2.DCT_INVERSE),-128,127)
				cout = np.rint(idct+128).astype(np.uint8)
				if cmd_args.debug: # and (i%wd) == wd-1:
					print("--------------------")
					print("Chunk:")
					print(chunk)
					print("DCT:")
					print(dct)
					print("IDCT:")
					print(idct)
					print("IDCT RINT:")
					print(np.rint(idct))
					print("Out:")
					print(cout)
				#cout = (np.rint(cv2.dct((np.rint(cv2.dct(chunk.astype(np.single))/quant).astype(np.int8).astype(np.single))*quant,flags=cv2.DCT_INVERSE))+127).astype(np.uint8)
				temph.append(cout)

			dcto.append(np.hstack(temph))
			temph.clear()
		dcto = np.vstack(dcto).astype(np.uint8)

		img = np.concatenate(((f.astype(np.int16)+128).astype(np.uint8),dcto),axis=1)
		cv2.imshow("Image",cv2.resize(img,(width*4*2,height*4),interpolation=cv2.INTER_NEAREST))
		waittime = 0
		if cmd_args.play:
			waittime = round((1/fps)*1000)
		if cv2.waitKey(waittime) == 27:
			cv2.destroyAllWindows()
			exit()

	precalc_frames_dct[idx] = []
	for linechunks in chunks:
		for chunk in linechunks:
			dct = do_dct(chunk)
			precalc_frames_dct[idx].append(dct)
			add_freq(valfrequency,dct[0])
			for i in dct[1]:
				add_freq(frequency,i[0])
				if i[0] != 0xF0 and i[0] != 0:
					add_freq(valfrequency,i[1])

	freqframes += 1
	lastframeflat = f

def get_smallest(nodes):
	s = 1
	n = -1
	for i,k in enumerate(nodes):
		if k["p"] != -1:
			continue
		if k["f"] < s:
			n = i
			s = k["f"]
	return n

# Otherwise C decompressor won't have same tree
tnparr = np.array((1,),dtype=np.single)
def addfloat(f1,f2):
	tnparr[0] = 0
	tnparr[0] += f1
	tnparr[0] += f2
	return tnparr[0]

def huffman(freqs):
	nodes = []
	for i in sorted(freqs, key=freqs.get):
		nodes.append({"s":i,"f":freqs[i],"p":-1,"l":-1,"r":-1})
	rootnode = -1
	while True:
		nm = len(nodes)
		n1 = get_smallest(nodes)
		if n1 == -1:
			rootnode = len(nodes)-1
			break
		nodes[n1]["p"] = nm
		n2 = get_smallest(nodes)
		if n2 == -1:
			nodes[n1]["p"] = -1
			nodes[n1]["f"] = 1
			rootnode = n1
			break
		nodes[n2]["p"] = nm
		nodes.append({"s":0,"f":addfloat(nodes[n1]["f"],nodes[n2]["f"]),"p":-1,"l":n1,"r":n2})
	table = {}
	for i in range(len(freqs)):
		vals = []
		nidx = i
		while True:
			nidxn = nodes[nidx]["p"]
			n = nodes[nidxn]
			if n["l"] == nidx:
				vals.insert(0,False)
			elif n["r"] == nidx:
				vals.insert(0,True)
			if n["p"] == -1:
				break
			nidx = nidxn
		table[nodes[i]["s"]] = vals
	return table

def to_unsigned(val):
	if val < 0:
		return val+256
	return val

def add_table(freqs,bs):
	total = freqs["tot"]
	del freqs["tot"]
	addbits(bs,len(freqs)-1,8)
	for i in sorted(freqs, key=freqs.get):
		freqs[i] = freqs[i]/total
		packed = struct.pack("<f",freqs[i])
		# Make sure same value as in decoder (truncate precision), just in case
		freqs[i] = struct.unpack("<f",packed)[0]

	for i in sorted(freqs, key=freqs.get):
		addbits(bs,to_unsigned(i),8)
		bs.write(struct.pack("<f",freqs[i]))

	return huffman(freqs)

def dct_huffman(dct):
	out = []
	out.extend(valsymboltable[dct[0]])
	for i in dct[1]:
		out.extend(symboltable[i[0]])
		if i[0] != 0xF0 and i[0] != 0:
			out.extend(valsymboltable[i[1]])
	return out

for row in quant:
	for item in row:
		addbits(gbits,item,16)

symboltable = add_table(frequency,gbits)
valsymboltable = add_table(valfrequency,gbits)
"""
def mkst(vals):
	st = ""
	for i in vals:
		if i:
			st += "1"
		else:
			st += "0"
	return st

print("")
print("")
print("Marker:")
for i in sorted(frequency, key=frequency.get):
	print(to_unsigned(i),mkst(symboltable[i]))
print("Values:")
for i in sorted(valfrequency, key=valfrequency.get):
	print(to_unsigned(i),mkst(valsymboltable[i]))
print("")
"""

print(CLEAR+"Done marker:%i,values:%i symbols"%(len(frequency),len(valfrequency)))

for idx,f in enumerate(precalc_frames):
	cframe += 1
	fps = cframe/(time.time()-starttime)
	#if cframe%10 == 0:
	print(CLEAR+"Frame: %i/%i (%.2f%%) %is remaining"%(cframe,nbframes,(cframe/nbframes)*100,(nbframes-cframe)/fps),end='\r')

	diff = f ^ lastframe
	if not diff.any():
		nbdup += 1
		addbits(gbits,3,2) # Duplicate frame
		continue

	frame_size = 2+width*height*8

	dcts = [dct_huffman(dct) for dct in precalc_frames_dct[idx]]

	huffcomp(dcts,rlebs)
	deltacomp(dcts,diff,deltabs)

	if len(rlebs) >= frame_size:
		nboverh += 1
	if len(deltabs) >= frame_size:
		nboverd += 1

	ratiohuff += (len(rlebs)-2)/(frame_size-2)
	ratiodelta += (len(deltabs)-2)/(frame_size-2)
	encodedframes += 1

	if len(rlebs) <= len(deltabs):
		gbits.write(rlebs)
		nbhuff += 1
	else:
		gbits.write(deltabs)
		nbdelta += 1

	lastframe = f

endtime = time.time()

nbbits = len(gbits)
if nbbits%8 != 0:
	for i in range(8-(nbbits%8)):
		gbits.write(False)

size = 0
with open(outfile,"wb") as ofile:
	ofile.write(gbits.read(bytes))
	size = ofile.tell()

print("")
print("----------")
print("Number of frames: %i"%(cframe))
print("Huff frames     : %i (%.2f%%)"%(nbhuff,(nbhuff/nbframes)*100))
print("Delta frames    : %i (%.2f%%)"%(nbdelta,(nbdelta/nbframes)*100))
print("Duplicate frames: %i (%.2f%%)"%(nbdup,(nbdup/nbframes)*100))
print("----------")
print("Huff frames over      : %i (%.2f%%)"%(nboverh,(nboverh/encodedframes)*100))
print("Delta frames over     : %i (%.2f%%)"%(nboverd,(nboverd/encodedframes)*100))
print("Huff frames avg ratio : %.2f%%"%((1-(ratiohuff/encodedframes))*100))
print("Delta frames avg ratio: %.2f%%"%((1-(ratiodelta/encodedframes))*100))
print("----------")
print("Normal    : %i bytes"%normal_size)
print("Compressed: %i bytes"%size)
print("Ratio     : %.2f%%"%((1-(size/normal_size))*100))
print("Speed     : %.2ffps"%(nbframes/(endtime-starttime)))


def prime(i):
    if i == 1:
        return False
    if i == 2:
        return True
    if i%2 ==0 :
        return False
    j = 3
    while j*j <= i:
        if i%j == 0:
            return False
        j +=2
    return True

repeat = int(input())
for x in range(repeat):
    inint = int(input())
    if not prime(inint):
        print(inint, "is not a prime")
    else :
        print(inint, "is a prime")


import json
import requests
import time
import urllib
from datetime import datetime
import pytz

def greetMsg():
    IST = pytz.timezone('Asia/Kolkata')
    datetime_object = datetime.now(IST)
    hour = datetime_object.hour
    if(hour > 0 and hour < 12):
        return 'Good Morning'
    elif(hour >= 12 and hour < 18):
        return 'Good Afternoon'
    elif hour >= 18 and hour < 22:
        return 'Good Evening'
    else:
        return 'I am sleepy, Good Night!!!'

with open('secrets.json') as f:
    data = json.load(f)

# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
# print(data)

TOKEN = data["key"]
URL = "https://api.telegram.org/bot{}/".format(TOKEN)

greetings = ["Hi", "Hello", "Hey"]

def get_url(url):
    response = requests.get(url)
    content = response.content.decode("utf8")
    return content

def get_json_from_url(url):
    content = get_url(url)
    js = json.loads(content)
    return js

def get_updates(offset=None):
    url = URL + "getUpdates?timeout=100"
    if offset:
        url += "&offset={}".format(offset)
    js = get_json_from_url(url)
    return js

def get_last_update_id(updates):
    update_ids = []
    for update in updates["result"]:
        update_ids.append(int(update["update_id"]))
    return max(update_ids)

def echo_all(updates):
    for update in updates["result"]:
        try:
            msgR = update["message"]["text"]
            value = [1 for item in greetings if(item in msgR)]
            if(1 in value):
                firstname = update["message"]["from"]["first_name"]
                message = "Hi {0},\n{1}".format(firstname, greetMsg())
                text = message
            else:
                text = update["message"]["text"]

            chat = update["message"]["chat"]["id"]
            send_message(text, chat)
        except Exception as e:
            print(e)

def get_last_chat_id_and_text(updates):
    num_updates = len(updates["result"])
    last_update = num_updates - 1
    text = updates["result"][last_update]["message"]["text"]
    chat_id = updates["result"][last_update]["message"]["chat"]["id"]
    return (text, chat_id)

def send_message(text, chat_id):
    text = urllib.parse.quote_plus(text)
    url = URL + "sendMessage?text={}&chat_id={}".format(text, chat_id)
    get_url(url)

def main():
    last_update_id = None
    while True:
        updates = get_updates(last_update_id)
        if len(updates["result"]) > 0:
            last_update_id = get_last_update_id(updates) + 1
            echo_all(updates)
        time.sleep(0.5)

if __name__ == '__main__':
    main()


"""A toy Recurent Neural net
to solve brilliant.org's
challanges
"""
import numpy as np

class RNN(object):
	def __init__(self):
		self.Whh = np.array([[0.5, 1],[1, 2]])
		self.Whx = np.array([[1, 0],[-1, 0]])
		self.Why = np.array([[-1, 1],[1, 2]])
		self.H = np.array([1, 1])

	def predict(self, X):
		"""Gets an input vector X
		and returns the prediction
		for it"""
		self.H = np.tanh(np.matmul(self.Whh, self.H) + np.matmul(self.Whx, X))
		return np.matmul(self.Why, self.H)

model = RNN()
print(model.predict(np.array([4, 4])))