"""
Function Description

Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in strings.

matchingStrings has the following parameters:

string strings[n] - an array of strings to search
string queries[q] - an array of query strings
Returns

int[q]: an array of results for each query

>>> matching_strings(['def', 'de', 'fgh'], ['de', 'lmn', 'fgh'])
[1, 0, 1]
"""
def matching_strings(strings, queries):
    strings_counts = {}
    results_arr=[]
    for string in strings:
        if string in strings_counts.keys():
            strings_counts[string]+=1
        else:
            strings_counts[string]=1
    for query in queries:
        if query in strings_counts.keys():
            results_arr.append(strings_counts[query])
        else:
            results_arr.append(0)
    return results_arr


import token_state
import token as t
import attributes
import re

class Tokeniser(object):

    def __init__(self, reader, errors=None):
        self.reader = reader
        self.errors = errors or []
        self.state = token_state.DATA
        self.tag_pending = None
        self.comment_pending = t.CommentToken()
        self.doctype_pending = t.DoctypeToken()
        self.char_pending = t.CharacterToken()
        self.script_buffer = ''
        self.last_start_tag = None
        self.is_emit_pending = False
        self.emit_pending = None
        self.self_closing_acknow = True
        self.chars_string = ''
        self.code_point_holder = []
        self.multi_point_holder = []

    def tokenise(self):
        tokens = ""
        while True:
            curr_token = self.read()
            normalized = re.sub('\s+|\t+|\n+|\f+|[ ]+', "", curr_token.__str__())
            tokens = "{0}\nToken: {1}".format(tokens, curr_token) if normalized else tokens
            finished = False
            if curr_token.type == t.TokenType.EOF:
                finished = True
            if finished:
                break
        return tokens

    def read(self):
        self.self_closing_acknow = True
        while not self.is_emit_pending:
            self.state.read(self.reader, self)
        if self.chars_string:
            str = self.chars_string
            self.chars_string = ""
            self.char_pending.data = str
            return self.char_pending
        else:
            self.is_emit_pending = False
            return self.emit_pending

    def move_to_state(self, state):
        self.reader.advance()
        self.state = state

    def move(self, state):
        self.state = state

    def emit(self, consumed):
        self.chars_string += consumed

    def emit_token(self, token):
        # validate
        self.emit_pending = token
        self.is_emit_pending = True

        if token.type == t.TokenType.START_TAG:
            self.last_start_tag = token.tag_name
            if token.is_self_closing:
               self.self_closing_acknow = False
        elif token.type == t.TokenType.END_TAG:
            if len(token.attrs.attrs):
                self.error("No attributes allowed on end tag!")

    def emit_string(self, str):
        self.chars_string += str

    def error(self, state):
        print("error in state: {0}".format(state))
        self.errors.append(state)

    def eof_error(self, token):
        self.errors.append("EOF error: " + token)

    def emit_tag_pending(self):
        self.tag_pending.finalise_tag()
        self.emit_token(self.tag_pending)

    def emit_comment_pending(self):
        self.emit_token(self.comment_pending)

    def emit_doctype_pending(self):
        self.emit_token(self.doctype_pending)

    def consume_char_ref(self, additional_char, in_attr):
        if self.reader.empty():  # stopped here TODO
            return None
        if additional_char and additional_char == self.reader.current():
            return None
        if self.reader.current() in ['\t', '\n', '\r', '\f', ' ', '<', '&']:
            return None
        self.reader.mark = self.reader.current_pos
        code_ref = []
        if self.reader.match_seq_consume("#"):
            hex = self.reader.match_seq_ic("X")
            num_ref = self.reader.consume_hex() if hex else self.reader.consume_dig()
            if not num_ref:
                self.reader.current_pos = self.reader.mark
                return None
            if not self.reader.match_seq_consume(";"):
                self.errors.append("Missing semicolon")
            charval = -1
            try:
                base = 16 if hex else 10
                charval = int(num_ref, base)
            except:
                pass
            if charval == -1 or (
                    charval >= 0xD800 and charval <= 0xDFFF) or charval > 0x10FFFF:
                self.errors.append("character outside of valid range")
                code_ref[0] = token_state.REPLACE_CHAR
                return code_ref
            else:
                code_ref[0] = charval
                return code_ref
        else:
            name_ref = self.reader.consume_letter_and_digit_seq()
            legit = self.reader.match(';')
            found = True
            if not found:
                self.reader.current_pos = self.reader.mark
                if legit:
                    self.errors.append("invalid named referenece {0}".format(name_ref))
                return None
            if in_attr and (
                self.reader.match_letter() or self.reader.match_digit() or self.reader.match_any_of('=', '-', '_')):
                self.reader.current_pos = self.reader.mark
                return None
            if not self.reader.match_seq_consume(";"):
                self.errors.append("Missing semicolon")
            num_chars = 1
            if num_chars == 1:
                code_ref[0] = self.multi_point_holder[0]
                return code_ref
            elif num_chars == 2:
                return self.multi_point_holder
            else:
                return self.multi_point_holder

    def create_tag_pending(self, start=False):
        self.tag_pending = t.StartTagToken("", attributes.Attributes()) if start else t.EndTagToken()
        return self.tag_pending

    def create_comment_pending(self):
        self.comment_pending = t.CommentToken()

    def create_doctype_pending(self):
        self.doctype_pending = t.DoctypeToken()

    def approptiate_end_tag_token(self):
        return self.last_start_tag is not None and self.tag_pending.token_name() == self.last_start_tag.lower()

    def approptiate_end_tag_name(self):
        return self.last_start_tag

    def unescape_entities(self, in_attr):
        str = ''
        while not self.reader.empty():
            str += self.reader.consume_to("&")
            if self.reader.match("&"):
                self.reader.consume()
                c = self.consume_char_ref(None, in_attr)
                if not c:
                    str += "&"
                else:
                    str += c[0]
                    if len(c) == 2:
                        str += c[1]
        return str


EXAMPLE_PROJECT = "test-project"
EXAMPLE_NAMESPACE = "hgi"
EXAMPLE_LOCATION = "/my/location"
EXAMPLE_LOCATION_2 = "/my/other/location"
EXAMPLE_URL = "http://gitlab.example.com"
EXAMPLE_TOKEN = "my-token"
EXAMPLE_DOCKER_ARGS = ["run", "-e", "test", "-v", EXAMPLE_LOCATION, "-it", "--rm", "--no-healthcheck", "ubuntu", "bash"]
EXAMPLE_PARAMETER = "MY_SECRET"
EXAMPLE_VALUE="secret123"
EXAMPLE_VARIABLES = {
    "EXAMPLE": "value",
    "HELLO": "hello\nworld",
    "OTHER": "thing"
}


from scenes.nodes import get_story_links
import pytest

link1 = {
            "label":"Choice 1",
            "id":"1"
        }

link2 = {
            "label":"Choice 2",
            "id":"2",
            "requirements":["sword"]
        }

link3 = {
            "label":"Choice 3",
            "id":"3",
            "requirements":["Friend John"]
        }

link4 = {
            "label":"Choice 4",
            "id":"4",
            "requirements":["sword","Friend John"]
        }

sample_scene_node = {
    "id": "single_node",
    "text": "hello world",
    "point_adjust": 100,
    "new_inventory": "Friend Maria",
    "links": [link1,link2,link3,link4]
}

@pytest.mark.parametrize('scene, user_inventory, result', [
    (
        sample_scene_node,
        ["Friend John"],
        [link1, link3, link4]
    ),(
        sample_scene_node,
        ["Friend John","sword"],
        [link1, link2, link3, link4]
    ),(
        sample_scene_node,
        ["sword"],
        [link1, link2, link4]
    ),(
        sample_scene_node,
        ["Friend Maria"],
        [link1]
    ),(
        sample_scene_node,
        [],
        [link1]
    )
])
def test_get_story_links_with_exact_requirements(scene, user_inventory, result):
    assert get_story_links(scene, user_inventory) == result


from project.team import Team
from unittest import TestCase, main

class TeamTests(TestCase):
    def setUp(self) -> None:
        self.team = Team("Test")
        self.other_team = Team("TeamA")

    def test_object_initialized_correctly(self):
        name = "Test"
        team = Team(name)
        self.assertEqual(name, team.name)
        self.assertEqual({}, team.members)

    def test_name_setter_raises_numbers_only(self):
        with self.assertRaises(ValueError) as ex:
            team = Team("12")
        self.assertEqual("Team Name can contain only letters!", str(ex.exception))

    def test_name_setter_raises_numbers_and_letters(self):
        with self.assertRaises(ValueError) as ex:
            team = Team("12as")
        self.assertEqual("Team Name can contain only letters!", str(ex.exception))

    def test_remove_member_that_doesnt_exist(self):
        result = self.team.remove_member("Ivan")
        self.assertEqual(f"Member with name Ivan does not exist", result)
        self.assertEqual({}, self.team.members)

    def test_remove_member_that_exists(self):
        self.team.members = {
            "Ivan": 23,
            "Pavel": 15
        }
        result = self.team.remove_member("Ivan")
        self.assertEqual(f"Member Ivan removed", result)
        self.assertEqual({"Pavel": 15}, self.team.members)

    def test_team_str_returns_correct_string_empty_members(self):
        result = f"Team name: {self.team.name}"

        self.assertEqual(result, str(self.team))

    def test_team_str_returns_correct_string_with_members(self):
        self.team.members = {
            "Ivan": 23,
            "Pavel": 15
        }
        result = [f"Team name: {self.team.name}"]
        members = list(sorted(self.team.members.items(), key=lambda x: (-x[1], x[0])))
        result.extend([f"Member: {x[0]} - {x[1]}-years old" for x in members])
        result = "\n".join(result)
        self.assertEqual(result, str(self.team))

    def test_team_dunder_len_returns_correct(self):
        self.team.members = {
            "Ivan": 23,
            "Pavel": 15
        }
        result = len(self.team)
        self.assertEqual(2, result)

    def test_len_method_zero_length(self):
        result = len(self.team.members)
        self.assertEqual(0, result)

    def test_team_greater_method_equal_lengths(self):
        result = self.team > self.other_team
        self.assertEqual(False, result)

    def test_team_greater_method_self_longer_lengths(self):
        other_team = Team("TeamA")
        self.team.members = {
            "Ivan": 23,
            "Pavel": 15
        }

        result = self.team > other_team
        self.assertEqual(True, result)

    def test_team_greater_method_other_longer_lengths(self):
        self.other_team.members = {
            "Ivan": 23,
            "Pavel": 15
        }

        result = self.team > self.other_team
        self.assertEqual(False, result)

    def test_add_member_new_member_data(self):
        added_members_by_name = ["Ivan", "Pavel"]
        result = self.team.add_member(Ivan=14, Pavel=34)
        self.assertEqual(f"Successfully added: {', '.join(added_members_by_name)}", result)

        expected_members = {
            "Ivan": 14,
            "Pavel": 34
        }
        self.assertEqual(expected_members, self.team.members)

    def test_add_member_semi_new_member_data(self):
        self.team.members = {"Ivan": 14}

        added_members_by_name = ["Pavel"]
        result = self.team.add_member(Ivan=14, Pavel=34)
        self.assertEqual(f"Successfully added: {', '.join(added_members_by_name)}", result)

        expected_members = {
            "Ivan": 14,
            "Pavel": 34
        }
        self.assertEqual(expected_members, self.team.members)

    def test_add_member_with_no_new_data(self):
        expected_members = {
            "Ivan": 23,
            "Pavel": 15
        }
        self.team.members = expected_members
        result = self.team.add_member(Ivan=14, Pavel=34)
        self.assertEqual(f"Successfully added: ", result)
        self.assertEqual(expected_members, self.team.members)

    def test_add_dunder_method_with_empty_members(self):
        new_team = self.team + self.other_team
        self.assertEqual("TestTeamA", new_team.name)
        self.assertEqual({}, new_team.members)

    def test_add_dunder_method_with_repeating_members(self):
        expected_members = {
            "Ivan": 14,
            "Pavel": 34
        }
        self.team.members = expected_members
        self.other_team.members = expected_members
        new_team = self.team + self.other_team
        self.assertEqual("TestTeamA", new_team.name)
        self.assertEqual(expected_members, new_team.members)

    def test_add_method_empty_other_team(self):
        expected_members = {
            "Ivan": 14,
            "Pavel": 34
        }
        self.team.members = expected_members
        new_team = self.team + self.other_team
        self.assertEqual("TestTeamA", new_team.name)
        self.assertEqual(expected_members, new_team.members)

    def test_add_method_empty_self_team(self):
        expected_members = {
            "Ivan": 14,
            "Pavel": 34
        }
        self.other_team.members = expected_members
        new_team = self.team + self.other_team
        self.assertEqual("TestTeamA", new_team.name)
        self.assertEqual(expected_members, new_team.members)

    def test_add_method_with_different_data(self):
        team1_members = {"Berrin": 45, "Nelin": 18}
        self.team.members = team1_members

        team2_members = {"Melek": 16}
        self.other_team.members = team2_members
        new_team = self.team + self.other_team
        self.assertEqual("TestTeamA", new_team.name)

        expected_members = {"Berrin": 45, "Nelin": 18, "Melek": 16}
        self.assertEqual(expected_members, new_team.members)

if __name__ == '__main__':
    main()


"""
Set of functions to compute the gradients Duk of u^k (or its adjoint operator)
on a staggered grid and setting `p^kt += b^k * Duk^t` (or
`u^k -= b^k * div(p^k)`). The "boundary" of p is left untouched.

Example in two dimensions (x are the grid points of u), k fixed:

       |                |
... -- x -- -- v1 -- -- x -- ...
       |                |          v1 and w1 -- the partial x-derivatives at top and bottom
       |                |          v2 and w2 -- the partial y-derivatives at left and right
       v2      Du       w2         Du -- the gradient at the center of the box
       |                |          (Du)_1 -- mean value of v1 and w1
       |                |          (Du)_2 -- mean value of v2 and w2
... -- x -- -- w1 -- -- x -- ...
       |                |

In one dimension there is no averaging, in three dimensions each
derivative is the mean value of four finite differences etc.

The adjoint operator (reading from p and writing to u) is understood to be the
negative divergence -div(p^k) with Dirichlet boundary.
"""

import numpy as np
import itertools

from numba import jit

def staggered_diff_avgskips(imagedims):
    d_image = len(imagedims)
    skips = tuple(int(np.prod(imagedims[(d_image-t):])) for t in range(d_image))
    navgskips =  1 << (d_image - 1)
    avgskips = np.zeros([d_image, navgskips], dtype=np.int64, order='C')
    for t in range(d_image):
        for m, p in enumerate(itertools.product([0, 1], repeat=(d_image - 1))):
            avgskips[t,m] = np.inner(p[:t] + (0,) + p[t:], skips)
    return avgskips

def gradient(pgrad, u, b, avgskips):
    staggered_diff(pgrad, u, b, avgskips, adjoint=False)

def divergence(p, ugrad, b, avgskips):
    staggered_diff(p, ugrad, b, avgskips, adjoint=True)

@jit
def staggered_diff(p, u, b, avgskips, adjoint=False):
    """
    Computes `p^kt += b^k * Duk^t`.

    Args:
        p : array where the result is written as `p^kt += b^k * Duk^t`.
        u : function to be derived
        b : factor such that `p^kt += b^k * Duk^t`
        avgskips : output of staggered_diff_avgskips(u.shape[1:])
        adjoint : (optional) if True, apply the adjoint operator (reading from p
                  and writing to u), i.e. `u^k -= b^k * div(p^k)`.
    """
    l_labels, d_image, n_image = p.shape
    navgskips =  1 << (d_image - 1)
    imagedims = u.shape[1:]

    skips = (1,)
    for t in range(1,d_image):
        skips += (skips[-1]*imagedims[d_image-t],)

    u_flat = u.reshape(l_labels, n_image)
    coords = np.zeros(d_image, dtype=np.int64)

    for k in range(l_labels):
        for t in range(d_image):
            coords *= 0
            for i in range(n_image):
                # ignore boundary points
                in_range = True
                for dc in reversed(range(d_image)):
                    if coords[dc] >= imagedims[dc] - 1:
                        in_range = False
                        break

                if in_range:
                    # regular case
                    pk = p[k]
                    uk = u_flat[k]
                    bk = b[k]/navgskips

                    for avgskip in avgskips[t]:
                        base = i + avgskip
                        if adjoint:
                            uk[base + skips[t]] += bk * pk[t,i]
                            uk[base] -= bk * pk[t,i]
                        else:
                            pk[t,i] += bk * uk[base + skips[t]]
                            pk[t,i] -= bk * uk[base]

                # advance coordinates
                for dd in reversed(range(d_image)):
                    coords[dd] += 1
                    if coords[dd] >= imagedims[dd]:
                        coords[dd] = 0
                    else:
                        break


## CodeEval
## Filename Pattern

import sys
import re

f = open(sys.argv[1], 'r')

for line in f:

    line = line.strip().split(' ')
    pat = '^' + line[0] + '$'
    pat = pat.replace('.', '\.').replace('*', '.*').replace('?', '.')
    pat = re.compile(pat)
    files = line[1:]
    out = [fil for fil in files if pat.match(fil)]
    if out:
        sys.stdout.write(' '.join(out) + '\n')
    else:
        sys.stdout.write('-\n')

f.close()


import requests
from datetime import datetime
import os

def trigger_ifttt_webhook(event, home_team, away_team, venue_name):
    url = f"https://maker.ifttt.com/trigger/{event}/with/key/{os.environ['IFTTT_API_KEY']}"
    payload = {"value1": home_team, "value2": away_team, "value3": venue_name}
    headers = {"Content-Type": "application/json"}

    response = requests.post(url, headers=headers, json=payload)
    return response.status_code == 200

def check_games_for_team(fixtures, team_info):
    team_id, team_name, venue_name = team_info
    for fixture in fixtures:
        if fixture['HomeTeamId'] == team_id:
            home_team = fixture.get('HomeTeamName', 'Unknown Home Team')
            away_team = fixture.get('AwayTeamName', 'Unknown Away Team')

            if trigger_ifttt_webhook("mac_bildirimi", home_team, away_team, venue_name):
                print(f"IFTTT Webhook triggered successfully for the game between {home_team} and {away_team} at {venue_name}.")
            else:
                print(f"Failed to trigger IFTTT Webhook for {team_name}.")
            return
    print(f"No home game today for {team_name}.")

def get_todays_games():
    date = datetime.now().strftime('%Y-%m-%d')
    # Set to a specific date for testing
    # date = "2023-12-21"
    url = f"https://api.sportsdata.io/v3/soccer/scores/json/GamesByDate/{date}"
    headers = {"Ocp-Apim-Subscription-Key": os.environ['SPORTSDATA_IO_API_KEY']}

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error fetching data: {response.text}")
        return None

def main():
    # Team ID, Name, and Venue mapping
    teams = {
        572: ("Fenerbahçe", "Fenerhabçe Şükrü Saraçoğlu Stadyumu"),
        728: ("Beşiktaş", "Beşiktaş İnönü Stadyumu")
    }

    fixtures = get_todays_games()
    if fixtures:
        for team_id, team_data in teams.items():
            team_name, venue_name = team_data
            check_games_for_team(fixtures, (team_id, team_name, venue_name))
    else:
        print("No fixtures data available.")

if __name__ == "__main__":
    main()


import requests
from bs4 import BeautifulSoup

url = "https://www.bfv.de/mannschaften/tv-altoetting/016PMD3330000000VV0AG80NVUT1FLRU"
with requests.get(url) as page:
    soup = BeautifulSoup(page.content, "html.parser")

    team_name = "TV Altötting"

    games = soup.find_all("tr", class_="game")
    for game in games:
        home_team = game.find("td", class_="home").find("span", class_="team-name").get_text()
        away_team = game.find("td", class_="away").find("span", class_="team-name").get_text()
        date = game.find("td", class_="date").get_text()
        if home_team == team_name or away_team == team_name:
            opponent = home_team if away_team == team_name else away_team
            print(f"{team_name} vs {opponent} on {date}")


#记账软件
import os #必须检查是否有csv的档案，不然读取的时候会当掉，所以要用到os里面的功能
products = []  # 将product抓上来当清单  #将空清单移到最外面，才能不管有没有读取道都可以使用他
if os.path.isfile('记账本.csv'): #用这个功能检查档案在不在，并且将读取功能移动到if内部，读取到才执行
    print('您有上次记账的档案')
    # 读取档案 #就是先读取档案后，把读取的内容先装进清单
    # 后续输入新的内容，才不会全部洗掉，这就是读取的作用
    with open('记账本.csv', 'r', encoding='utf-8') as f:  # 不同操作系统会有编码问题，建议还是要加入编码utf-8，可是如果是中文操作系统加入这个可能会出现错误代码
        for line in f:
            if '日期,商品名称,价格' in line:  # 不要让标题重复写入所以加入这行
                continue  # 跟break一样，只是contiue是跳过上面说的东西，就跳过这round，继续下一round
            date, name, price = line.strip().split(',')
            # 记得要先用strip将\n或空格去掉，不然csv会出现在\n在里面，
            # 然后再用split切割档案，并利用逗号做为区隔，这个会有一个顺序(由左而右)
            # 先在新增功能，与下面一样，不要重复写入，而是将data,name,price三个已知名称分别写入，也是一个简写法
            products.append([date, name, price])  # 读取之后，要把他加入product里面，所以用跟下面一样的写法就可以

else:
    print('找不到档案...')
while True:
    date = input('请输入日期：')
    if date == 'q':
        break
    name = input('请输入商品名称：')
    price = input('请输入商品价格：')
    price = int(price) #转换为数值
    products.append([date, name, price]) #直接在大清单中创作小清单，让程式码更少
print(products)

for p in products: #列出细项
    print('这项商品是在', p[0],'买的，商品名称是', p[1], '商品价格为', p[2],'元。') #利用p[0]列出清单中的第一项目达成目的，后面以此列推。

with open('记账本.csv', 'w', encoding='utf-8') as f: #有时候会出现乱码，所以要告诉他，我要使用什么编码，大部分建议使用utf-8，它是世界共通的编码
    f.write('日期,商品名称,价格\n') #要写入每一行的index索引，只要在循环前将标题名称写入即可，这样他就不会一直重复，也能在最上面
    for p in products:
        f.write(p[0] + ',' + p[1] + ',' + str(p[2]) + '\n') #使用CSV档案，必须用逗号分隔，才会分开存取
                                                       #由于把价格转为数值，但是+号的合并只能是字串
                                                       #所以又要把p[1]转换为字串才能合并


from flask_restful import Resource, reqparse, abort

from App.models import UserModel

parse = reqparse.RequestParser()
parse.add_argument("id", type=int, required=True, help="请登录")

def check_permission(permission):
    def receive_permission(func):
        def do_permission(*args, **kwargs):
            parser = parse.parse_args()
            id = parser.get("id")
            user = UserModel.query.get(id)
            if not user:
                abort(401, message="请登录")
            if user.u_permission & permission == permission:
                print("继续做事情")
                return func(*args, **kwargs)
            else:
                abort(403, message="您没有权限，请联系系统管理员进行设置")
        return do_permission
    return receive_permission

READ = 1
WRITE = 2
MANAGE = 4

class OrderResource(Resource):

    @check_permission(WRITE)
    def get(self):
        # parser = parse.parse_args()
        # id = parser.get("id")
        #
        # user = UserModel.query.get(id)
        #
        # if not user:
        #     abort(401, message="请登录")
        #
        # if user.u_permission == 4:
        #     print("我可以阅读帖子")
        #     return {"msg": "读帖子权限"}
        # else:
        #     abort(403, message="你没有权限查看此模块，请联系响应管理员进行设置")
        return {"msg": "ok"}


from libqtile import qtile
from libqtile.config import Group, Match
from libqtile.lazy import lazy

def _go_to_group(name):
    @lazy.function
    def _inner(qtile):
        go_to_group(qtile, name)

    return _inner

def go_to_group(qtile, name):
    old = qtile.current_screen
    group = qtile.groups_map[name]
    screen = group_screen(group)
    group.cmd_toscreen(screen)
    qtile.focus_screen(screen, warp=True)
    if qtile.current_screen != old:
        qtile.warp_to_screen()
    if qtile.current_window:
        qtile.current_window.focus(False)

def group_screen(group):
    screen = 0
    if group.name in "1234567890":
        screen = 0
    elif group.name in "asduio":
        screen = 1
    # elif group.name in "uio":
    #     screen = 2
    return screen % len(qtile.screens)

def switch_group(direction):
    @lazy.function
    def _switch_group(qtile):
        cg = qtile.current_screen.group
        next = cg
        screen = -2
        while screen != group_screen(cg):
            next = next._get_group(direction, False, False)
            screen = group_screen(next)
        next.cmd_toscreen()

    return _switch_group

original_groups = {}

# @lazy.function
# def hide_workspace(qtile):
#     for w in qtile.cmd_windows():
#         window = qtile.windows_map[w["id"]]
#         if window.group.name != "-":
#             original_groups[window.name] = window.group.name
#             window.togroup("0")
#
#
# @lazy.function
# def restore_workspace(qtile):
#     for w in qtile.cmd_windows():
#         window = qtile.windows_map[w["id"]]
#         if window.group.name == "-":
#             if window.name in original_groups:
#                 window.togroup(original_groups[window.name])
#             else:
#                 window.togroup("1")
#     original_groups.clear()

groups_list = [
    Group("1", layout="max", matches=[]),
    Group("2", matches=[]),
    Group("3", matches=[]),
    Group("4", matches=[]),
    Group("5", matches=[]),
    Group("6", matches=[]),
    Group("7", matches=[]),
    Group("8", matches=[]),
    Group("9", matches=[]),
    Group("0", matches=[]),
    Group("a", matches=[Match(wm_class="discord")]),
    Group("s", matches=[]),
    Group("d", matches=[]),
    Group("u", matches=[]),
    Group("i", matches=[]),
    Group("o", matches=[]),
]

group_keys = []
for i in groups_list:
    group_keys.extend(
        [
            # mod1 + key of group = switch to group
            ["M-" + i.name, _go_to_group(i.name), f"Switch to group {i.name}"],
            # mod1 + shift + key of group = move focused window to group
            [
                "M-S-" + i.name,
                lazy.window.togroup(i.name),
                f"Move window to group {i.name}",
            ],
            # mod1 + control + key of group = move focused window and switch to group
            [
                "M-C-" + i.name,
                lazy.window.togroup(i.name),
                _go_to_group(i.name),
                f"Move and switch to group {i.name}",
            ],
        ]
    )

group_keys.extend(
    [
        [
            "M-<period>",
            switch_group(direction=1),
            "Switch to next group",
        ],
        [
            "M-<comma>",
            switch_group(direction=-1),
            "Switch to previous group",
        ],
        # ["M-<backspace>", hide_workspace, "Hide workspace"],
        # ["M-S-<backspace>", restore_workspace, "Restore workspace"],
    ]
)


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

from sys import argv
import subprocess, re
from collections import defaultdict

class Ddict(defaultdict,dict):
    def __init__(self):
            defaultdict.__init__(self, Ddict)
    def __repr__(self):
            return dict.__repr__(self)

def sort_key(s):
    if s:
        try:
            c = re.findall('\d+$', s)[0]
        except:
            c = -1
        return int(c)

def parse_minimap2(strain_name, ref_file, minimap_result_file):
    cmd = f'minimap2 -xasm5 {ref_file} ../../fa_245_sidr_filter_genomes_spades3.15_ntref/{strain_name}_clean.fas > {minimap_result_file}'
    check = subprocess.check_call(cmd, shell=True)
    if check == 0:
        print('minimap2 was run successfully')
    else:
        print('minimap2 was not run successfully')

def generate_identity_perc(minimap2_result_file, identity_file):
    with open(minimap2_result_file, 'r') as f1, open(identity_file, 'w') as f2:
        f2.write('contig_identifier contig_length start_position end_position ref_contig identity_length matching_length identity_perc(%) \n')
        for line in f1:
            line = line.strip().split()
            identity_perc = round(int(line[9])/int(line[10]) * 100, 2)
            if 500 <= int(line[1]) < 1000:
                f2.write(line[0] + '\t' + line[1] + '\t' + line[2] + '\t' + line[3] + '\t'  + line[5] + '\t'+ line[9] + '\t' + line[10] + '\t' + str(identity_perc) + '\n')
    print('generating "' + identity_file + '" file successfully')
    return

def generate_coverage_perc(identity_result_file, candidate_contigs_file):
    len_dir = {}
    position_dir = Ddict()
    with open(identity_result_file, 'r') as f1, open(candidate_contigs_file, 'w') as f2:
        f2.write('contig_identifier\tref_contig\tcoverage_perc\tcoverage_length\tcontig_length\n')
        for line in f1:
            line = line.strip().split()
            if line[1] != 'contig_length' and line[4] != 'mt' and float(line[7]) >= 70:
                len_dir[line[0]] = int(line[1])
                if not line[4] in position_dir[line[0]]:
                    position_dir[line[0]][line[4]] = []
                position_dir[line[0]][line[4]].append([int(line[2]), int(line[3])])
        #print(position_dir)

        for key1 in sorted(position_dir, key=sort_key):
            merged = defaultdict(list)
            for key2 in position_dir[key1]:
                value = position_dir[key1][key2]
                #value.sort(key=lambda x: x[0])
                value.sort()
                for interval in value:
                    if not merged[key2] or merged[key2][-1][-1] < interval[0]:
                        merged[key2].append(interval)
                    else:
                        merged[key2][-1][-1] = max(merged[key2][-1][-1], interval[-1])
            #print(merged)
                #[[2, 4], [6, 8], [7, 13]]
                #[[2, 4], [6, 13]]

            coverage_perc = 0
            cov_len = 0
            for k in merged.keys():
                coverage_len = 0
                for i in merged[k]:
                    #print(key1 + '\t' + k + '\t' + str(i[1]) +'\t' + str(i[0]))
                    single_len = i[1]-i[0]
                    coverage_len += single_len
                perc = coverage_len/len_dir[key1] * 100
                #print(key1 + '\t' + k + '\t' + str(coverage_len) +'\t' + str(perc))
                if perc > coverage_perc:
                    coverage_perc = perc
                    ref_ctg = k
                    cov_len = coverage_len
            f2.write(key1 + '\t' + ref_ctg + '\t'+ str(coverage_perc) + '\t' + str(cov_len) + '\t' + str(len_dir[key1]) + '\n')
        print('generating "' + candidate_contigs_file + '" file successfully')
        return position_dir

def get_gc_content_dir(gc_content_file):
    with open(gc_content_file, 'r') as f:
        gc_content_dir = {}
        for line in f:
            line = line.strip().split()
            if line[0] != 'contig_identifier' and 500 <= int(line[2]) < 1000:
                gc_content_dir[line[0]] = float(line[1])
        return gc_content_dir

def get_lower_identify_perc_nomatching_contigs(position_dir, gc_content_dir):
    lower_identify_perc_nomatching_contigs = []
    for key in gc_content_dir.keys():
        if key not in position_dir.keys():
            lower_identify_perc_nomatching_contigs.append(key)
    return lower_identify_perc_nomatching_contigs

def get_lower_coverage_perc_contigs(candidate_contigs_file, gc_content_dir, coverage_threshold=80, gc_average=48.19, std=12.71):
    lower_coverage_gc_contigs = []
    with open(candidate_contigs_file, 'r') as f:
        for line in f:
            line = line.strip().split()
            if line[2] != 'coverage_perc' and float(line[2]) <= coverage_threshold:
                lower_coverage_gc_contigs.append(line[0])

            elif  line[2] != 'coverage_perc' and float(line[2]) > coverage_threshold:
                min_gc = gc_average - 2*std
                max_gc = gc_average + 2*std
                if gc_content_dir[line[0]] < min_gc or gc_content_dir[line[0]] > max_gc:
                    lower_coverage_gc_contigs.append(line[0])
        return lower_coverage_gc_contigs

def get_short_length_contigs(strain_name):
    cmd = f'fasta_length ../../fa_245_sidr_filter_genomes_spades3.15_ntref/{strain_name}_clean.fas -o > {strain_name}_ctg_contig_length.txt'
    check = subprocess.check_call(cmd, shell=True)
    if check == 0:
        print('contigs length was generated successfully')
    else:
        print('contigs length was not generated')

    contigs_len_all_dir = {}
    short_contigs = []
    with open(strain_name + '_ctg_contig_length.txt', 'r') as f:
        for line in f:
            line = line.strip()
            if line.startswith('>'):
                key = line[1:]
            else:
                contigs_len_all_dir[key] = int(line)
                if contigs_len_all_dir[key] < 500:
                    short_contigs.append(key)
    return short_contigs

def get_mt_contigs(mt_candidate_contigs_file):
    mt_contig = []
    with open(mt_candidate_contigs_file, 'r') as f:
        for line in f:
            line = line.strip().split()
            if line[0] != 'contig_identifier' and float(line[1]) >= 80:
                mt_contig.append(line[0])
        return mt_contig

def get_removed_contigs(lower_identify_perc_nomatching_contigs, lower_coverage_gc_contigs, short_contigs, mt_contig, strain_name):
    print('Success: ' + strain_name + ' lower_identify_perc_nomatching_contigs number is ' + str(len(lower_identify_perc_nomatching_contigs)))
    print('Success: ' + strain_name + ' lower_coverage_gc_contigs number is ' + str(len(lower_coverage_gc_contigs)))
    print('Success: ' + strain_name + ' short_contigs number is ' + str(len(short_contigs)))
    print('Success: ' + strain_name + ' mt_contig number is ' + str(len(mt_contig)))

    removed_contigs = lower_identify_perc_nomatching_contigs + lower_coverage_gc_contigs + short_contigs + mt_contig
    with open(removed_contigs_file, 'w') as f:
        for contig in removed_contigs:
            f.write(contig + '\n')
    return removed_contigs

def filter_genome(removed_contigs, strain_name):
    print('Success: ' + strain_name + ' remove ' + str(len(removed_contigs)) + ' contigs')
    strain_dir = {}
    with open('../../fa_245_sidr_filter_genomes_spades3.15_ntref/' + strain_name + '_clean.fas', 'r') as f1, open('../../fa_245_filtered_genomes/' + strain_name + '.fas', 'w') as f2:
        for line in f1:
            line = line.strip()
            if line.startswith('>'):
                key = line[1:]
            else:
                strain_dir[key] = line
                if key not in removed_contigs:
                    f2.write('>' + key + '\n' + strain_dir[key] + '\n')

if __name__ == "__main__":
    ref_file = argv[2]
    strain_name = argv[1]
    minimap_result_file = strain_name + '_ctg_minimap_results.txt'
    identity_result_file = strain_name + '_ctg_identity_result.txt'
    candidate_contigs_file = strain_name + '_ctg_candidate_contigs.txt'
    gc_content_file = strain_name + '_ctg_GC.txt'
    mt_candidate_contigs_file = strain_name + '_mt_candidate_contigs.txt'
    removed_contigs_file = strain_name + '_removed_contigs_identifiers.txt'

    conducted_minimap2 = parse_minimap2(strain_name, ref_file, minimap_result_file)
    identity_result = generate_identity_perc(minimap_result_file, identity_result_file)
    coverage_result = generate_coverage_perc(identity_result_file, candidate_contigs_file)

    getted_gc_content_dir = get_gc_content_dir(gc_content_file)
    getted_lower_identify_perc_nomatching_contigs = get_lower_identify_perc_nomatching_contigs(coverage_result, getted_gc_content_dir)
    getted_lower_coverage_perc_contigs = get_lower_coverage_perc_contigs(candidate_contigs_file, getted_gc_content_dir, coverage_threshold=80, gc_average=48.19, std=12.71)
    getted_short_length_contigs = get_short_length_contigs(strain_name)
    getted_mt_contigs = get_mt_contigs(mt_candidate_contigs_file)
    getted_removed_contigs = get_removed_contigs(getted_lower_identify_perc_nomatching_contigs, getted_lower_coverage_perc_contigs, getted_short_length_contigs, getted_mt_contigs, strain_name)
    get_filtered_genome = filter_genome(getted_removed_contigs, strain_name)

# python3 remove_ctg.py 160205 180197_pilon4.fas


#!/usr/bin/env python
# coding: utf-8
# reference: https://github.com/mitchelljy/Trending-YouTube-Scraper

import sys
import time
import requests
from google.cloud import storage
from pyspark.sql import SparkSession

snippet_features = ["title",
                    "publishedAt",
                    "channelId",
                    "channelTitle",
                    "categoryId"]
header = ["video_id"] + snippet_features + ["trending_date", "tags", "view_count", "likes", "dislikes",
                                            "comment_count", "thumbnail_link", "comments_disabled",
                                            "ratings_disabled"
                                            ]
unsafe_characters = ['\n', '"']
BUCKET = ''  # enter your bucket name
spark = SparkSession.builder.appName("CommentsScraper").getOrCreate()
api_key = ''  # enter your api key

def prepare_feature(feature):
    for ch in unsafe_characters:
        feature = str(feature).replace(ch, "")
    op = f'"{feature}"'
    return op

def api_request(page_token, country_code):
    global api_key
    request_url = f"https://www.googleapis.com/youtube/v3/videos?part=id,statistics,snippet{page_token}chart=mostPopular&regionCode={country_code}&maxResults=50&key={api_key}"
    request = requests.get(request_url)
    if request.status_code == 403:
        print("excess requests")
        sys.exit()
    return request.json()

def get_tags(tags_list):
    # Takes a list of tags, prepares each tag and joins them into a string by the pipe character
    return prepare_feature("|".join(tags_list))

def get_videos(items):
    lines = []
    for video in items:
        comments_disabled = False
        ratings_disabled = False

        if "statistics" not in video:
            continue

        video_id = prepare_feature(video['id'])

        snippet = video['snippet']
        statistics = video['statistics']

        features = [prepare_feature(snippet.get(feature, "")) for feature in snippet_features]

        thumbnail_link = snippet.get("thumbnails", dict()).get("default", dict()).get("url", "")
        trending_date = time.strftime("%y.%d.%m")
        tags = get_tags(snippet.get("tags", ["[none]"]))
        view_count = statistics.get("viewCount", 0)

        # This may be unclear, essentially the way the API works is that if a video has comments or ratings disabled
        # then it has no feature for it, thus if they don't exist in the statistics dict we know they are disabled
        if 'likeCount' in statistics and 'dislikeCount' in statistics:
            likes = statistics['likeCount']
            dislikes = statistics['dislikeCount']
        else:
            ratings_disabled = True
            likes = 0
            dislikes = 0

        if 'commentCount' in statistics:
            comment_count = statistics['commentCount']
        else:
            comments_disabled = True
            comment_count = 0

        line = [video_id] + features + [prepare_feature(x) for x in [trending_date, tags, view_count, likes, dislikes,
                                                                     comment_count, thumbnail_link, comments_disabled,
                                                                     ratings_disabled
                                                                     ]]
        lines.append(",".join(line))
    return lines

def get_pages(country_code, cursor="&"):
    country_data = []

    while cursor is not None:
        video_data_page = api_request(cursor, country_code)

        cursor = video_data_page.get("nextPageToken", None)
        if cursor is not None:
            cursor = f"&pageToken={cursor}&"

        items = video_data_page.get('items', [])
        country_data += get_videos(items)

    return country_data

def write_to_file(country_code, country_data):
    print(f"Writing {country_code} data to file...")

    client = storage.Client()
    bucket = client.get_bucket(BUCKET)
    target_blob = bucket.blob(f"videos/{time.strftime('%y_%d_%m')}_{country_code}_videos.csv")

    local_tmp_path = f"{country_code}_videos.csv"

    with open(local_tmp_path, "w+") as file:
        for row in country_data:
            file.write(f"{row}\n")

    target_blob.upload_from_filename(local_tmp_path)
    return

def scraper(country_code):
    country_data = [",".join(header)] + get_pages(country_code)
    write_to_file(country_code, country_data)
    return len(country_data)

scraper('US')  # only scraping the videos for US region


"""Integration tests for Yandex Cloud provider"""
from unittest import TestCase

from integration_tests import IntegrationTestsV2

# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# pass, by inheritance from define_tests.TheTests
class YandexCloudProviderTests(TestCase, IntegrationTestsV2):
    """Integration tests for Yandex cloud provider

    Required following environment variables to run:
    LEXICON_YANDEXCLOUD_AUTH_TOKEN
    LEXICON_YANDEXCLOUD_DNS_ZONE_ID
    """

    provider_name = "yandexcloud"
    domain = "example.com"

    def _filter_headers(self):
        return ["Authorization"]

    # filter out data which change on each run
    def _filter_response(self, response):
        if "x-envoy-upstream-service-time" in response["headers"]:
            del response["headers"]["x-envoy-upstream-service-time"]
        if "x-request-id" in response["headers"]:
            del response["headers"]["x-request-id"]
        if "x-server-trace-id" in response["headers"]:
            del response["headers"]["x-server-trace-id"]
        if "grpc-message" in response["headers"]:
            del response["headers"]["grpc-message"]
        if "grpc-status" in response["headers"]:
            del response["headers"]["grpc-status"]
        return response

    def _test_parameters_overrides(self):
        # folder_id only used in test_provider_authenticate_with_unmanaged_domain_should_fail
        # as in other tests, domain id is provided in the environment variable
        # but in case of failure we fall back to retrieving domain ID by cloud ID and folder ID
        return {
            "folder_id": "b1gm2f812hg4h5s5jsgn",
            "dns_zone_id": "dns3a9nospukjt4jlqdm",
        }


import math

class Bits:

    def __init__(self):
        self.b = bytearray()
        self.num_bits = 0
        self.start = 0

    def __init__(self, n, num_bits):
        mbytes = n.to_bytes(math.ceil(num_bits/8), byteorder='big')
        self.start = len(mbytes)*8 - num_bits
        self.b = bytearray(mbytes)
        self.num_bits = num_bits

    def get_bytearray(self):
        return self.b

    def __getitem__(self, i):
        if i >= self.num_bits or i < 0:
            raise IndexError()
        bi = (self.start + i)//8
        offset = (self.start + i) % 8
        mask = 1 << (7 - offset)
        if mask & self.b[bi]:
            return 1
        else:
            return 0

if __name__ == "__main__":
    bits = Bits(300, 13)

    for i in range(13):
        print(bits[i])

    print(bits.get_bytearray())


import unittest
import torch.nn as nn
from torch.nn import functional as F
import hamiltorch.util
import torch

class UtilTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def test_flatten_unflatten(self):
        model = nn.Linear(4, 4)
        flattened_params = hamiltorch.util.flatten(model)

        new_model = nn.Linear(4, 4)
        unflattened_params = hamiltorch.util.unflatten(new_model, flattened_params)
        hamiltorch.util.update_model_params_in_place(new_model, unflattened_params)

        new_model_flattened_params = hamiltorch.util.flatten(new_model)

        hamiltorch.util.eval_print('flattened_params', 'new_model_flattened_params')

        self.assertTrue(torch.all(torch.eq(flattened_params, new_model_flattened_params)))

    def test_model_functional(self):
        model = nn.Linear(4, 4)
        fmodel = hamiltorch.util.make_functional(model)

        x = torch.zeros(1, 4)
        ymodel = model.forward(x)
        params = list(model.parameters())
        yfunctional = fmodel(x, params=params)

        hamiltorch.util.eval_print('ymodel', 'yfunctional')

        self.assertTrue(torch.all(torch.eq(ymodel, yfunctional)))

    def test_differentiable_model_functional(self):
        model = nn.Linear(2, 2)
        params = list(model.parameters())
        params_flattened = hamiltorch.util.flatten(model)
        fmodel = hamiltorch.util.make_functional(model)

        model.zero_grad()
        xmodel = torch.randn(1, 2, requires_grad=True)
        ymodel = model.forward(xmodel).sum()
        ymodel.backward()
        xmodelgrad = xmodel.grad
        pmodelgrad = torch.cat([p.grad.flatten() for p in params])

        model.zero_grad()
        xfunctional = xmodel.detach().clone().requires_grad_()
        yfunctional = fmodel(xfunctional, params=params).sum()
        yfunctional.backward()
        xfunctionalgrad = xfunctional.grad
        pfunctionalgrad = torch.cat([p.grad.flatten() for p in params])

        hamiltorch.util.eval_print('params_flattened', 'xmodel', 'ymodel', 'xmodelgrad', 'xfunctional', 'yfunctional', 'xfunctionalgrad', 'pmodelgrad', 'pfunctionalgrad')

        self.assertTrue(torch.all(torch.eq(xmodelgrad, xfunctionalgrad)))
        self.assertTrue(torch.all(torch.eq(ymodel, yfunctional)))

    def test_conv_model_functional(self):
        class Net(nn.Module):
            def __init__(self):
                super(Net, self).__init__()
                self.layers = nn.Sequential(
                        nn.Conv2d(1, 10, kernel_size=5),
                        nn.MaxPool2d(2),
                        nn.ReLU(),
                        nn.Conv2d(10, 20, kernel_size=5),
                        nn.MaxPool2d(2),
                        nn.ReLU())
                self.fc1 = nn.Linear(320, 50)
                self.fc2 = nn.Linear(50, 10)

            def forward(self, x):
                x = self.layers(x)
                x = x.view(-1, 320)
                x = F.relu(self.fc1(x))
                x = self.fc2(x)
                return F.log_softmax(x, dim=1)

        model = Net()
        model.eval()
        eval_fmodel = hamiltorch.util.make_functional(model)
        model.train()
        train_fmodel = hamiltorch.util.make_functional(model)
        # Verify correctness in eval mode
        model.eval()
        params = list(model.parameters())
        x = torch.randn(10, 1, 28, 28)

        self.assertTrue(torch.all(torch.eq(model(x).sum(), train_fmodel(x, params=params).sum())))

    def test_vanilla_HMC_reversible(self):
        def log_prob(omega):
            mean = torch.zeros(2)
            var = torch.tensor([.10,.10])
            return torch.distributions.MultivariateNormal(mean, torch.diag(var)).log_prob(omega).sum()

        params_init = torch.tensor([1.,1.])
        momentum_init = torch.tensor([1.,1.])
        inv_mass = torch.tensor([1.,1.])
        p,m = hamiltorch.samplers.leapfrog(params_init, momentum_init, log_prob, steps=100, step_size=0.1, jitter=None, normalizing_const=1., softabs_const=1e6, explicit_binding_const=100, fixed_point_threshold=1e-20, fixed_point_max_iterations=6, jitter_max_tries=10, inv_mass=inv_mass, ham_func=None, sampler=hamiltorch.Sampler.HMC, integrator=hamiltorch.Integrator.EXPLICIT, metric=hamiltorch.Metric.HESSIAN, debug=False)
        momentum_reversed = - m[-1].clone()
        p,m = hamiltorch.samplers.leapfrog(p[-1], momentum_reversed, log_prob, steps=100, step_size=0.1, jitter=None, normalizing_const=1., softabs_const=1e6, explicit_binding_const=100, fixed_point_threshold=1e-20, fixed_point_max_iterations=6, jitter_max_tries=10, inv_mass=inv_mass, ham_func=None, sampler=hamiltorch.Sampler.HMC, integrator=hamiltorch.Integrator.EXPLICIT, metric=hamiltorch.Metric.HESSIAN, debug=False)

        self.assertTrue(torch.all(torch.eq(p[-1], params_init)))

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


#!/usr/bin/python
import tkinter as tk
import spectrumPlot
import controlPanel
import spectrumList
import spectro
from config import *
import numpy as np

# Acquisition callback, revceives integration time,
# number of acquisitions per transfer and number of
# transfered acquistions
def acqSpectrumCB(intTime, acqNum, transNum):
    global s, plot, sl
    spectrum = np.zeros(NUMPIXELS)
    for i in range(transNum):
        spectrum += s.getSpectrum(acqNum, intTime)
    # spectrum = spectrum/transNum
    # spectrum = spectrum
    # s.correctImbalance(spectrum)
    wl = s.pixelToWavelength(np.array([i+1 for i in range(NUMPIXELS)]))
    sl.addSpectrum((wl, spectrum), intTime, acqNum, transNum)
    plot.plotSpectrum(wl, spectrum)

def startContinuousAcqCB(intTime, acqNum):
    global gIntTime, gAcqNum, gContAcq
    gIntTime = intTime
    gAcqNum = acqNum
    gContAcq = True
    continuousAcq()

def stopContinuousAcqCB():
    global gContAcq
    gContAcq = False

def continuousAcq():
    global s, plot, sl, gIntTime, gAcqNum
    wl = s.pixelToWavelength(np.array([i+1 for i in range(NUMPIXELS)]))
    spectrum =s.getSpectrum(gAcqNum, gIntTime)
    # plot.clear()
    plot.updateContSpec(wl, spectrum)
    if gContAcq:
        root.after(100, continuousAcq)

# Delete all plotted data
def clearPlotCB():
    global plot
    plot.clear()

# Get dark values
def getDarkCB(intTime, acqNum, transNum):
    global s
    values = np.zeros(NUMPIXELS)
    for i in range(transNum):
        values += s.acqMultSpectrum(acqNum, intTime)
    s.setDark(values)

def spectrumSelectedCB(spectrumList):
    global plot
    plot.clear()
    for s in spectrumList:
        plot.plotSpectrum(*s.data)

def savePlotCB():
    global sl
    sl.saveSelectedPlot()

root = tk.Tk()
root.title("Spectormètre")
root.configure(background='white')

s = spectro.Spectro()
s.connect("/dev/ttyACM0" , 115200)

#create drawing area
plot = spectrumPlot.SpectrumPlot(root)

cp = controlPanel.ControlPanel(root)
cp.acqSpectrumCB = acqSpectrumCB
cp.clearPlotCB = clearPlotCB
cp.getDarkCB = getDarkCB
cp.savePlotCB = savePlotCB
cp.startContinuousAcqCB = startContinuousAcqCB
cp.stopContinuousAcqCB = stopContinuousAcqCB

sl = spectrumList.SpectrumList(root)
sl.spectrumSelectedCB = spectrumSelectedCB

cp.grid(row=0, column=0)
plot.grid(row=0, column=1)
sl.grid(row=0, column=2)

tk.mainloop()

s.disconnect()


from time import sleep

from opentracing.mocktracer import MockTracer
from tornado.ioloop import IOLoop
from opentracing.ext import tags
from threading import Thread
import requests
import tornado
import pytest
import six

from signalfx_tracing.libraries import tornado_config
from signalfx_tracing import instrument
from .app import MyApplication, HelloHandler

endpoint = "http://127.0.0.1:32321/hello/MyName"

def span_callback(span, request):
    span.set_tag("some_tag", True)

class TestTornadoApp(object):

    _app_store = [None]  # pytest doesn't persist attributes set in class-scoped autouse
    _tracer_store = [None]  # fixtures, so use stores as a hack.

    @property
    def app(self):
        return self._app_store[0]

    @property
    def tracer(self):
        return self._tracer_store[0]

    @classmethod
    @pytest.fixture(scope="class", autouse=True)
    def instrumented_app(cls):
        tracer = MockTracer()
        cls._tracer_store[0] = tracer

        tornado_config.start_span_cb = span_callback
        tornado_config.traced_attributes = ["path", "method", "query"]

        instrument(tracer, tornado=True)

        cls._app_store[0] = MyApplication([(r"/hello/(.*)", HelloHandler)])
        app_thread = Thread(target=cls.run_app)
        app_thread.daemon = True
        app_thread.start()

        for i in range(20):  # Wait for application to accept connections.
            try:
                requests.get(endpoint)
                break
            except Exception:
                if i == 19:
                    raise
                sleep(0.25)

        tracer.reset()

        yield

        def stop_ioloop():
            IOLoop.current().stop()

        IOLoop.current().add_callback(stop_ioloop)

    @classmethod
    def run_app(cls):
        if six.PY3 and tornado.version_info >= (5, 0):
            import asyncio

            asyncio.set_event_loop(asyncio.new_event_loop())

        cls._app_store[0].listen(32321)
        IOLoop.current().start()
        IOLoop.current().close()

    @pytest.fixture(autouse=True)
    def reset_tracer(self):
        yield
        self.tracer.reset()

    def test_app_settings(self):
        settings = self.app.settings
        assert settings["opentracing_tracing"].tracer is self.tracer
        assert (
            settings["opentracing_traced_attributes"]
            == tornado_config.traced_attributes
        )
        assert settings["opentracing_start_span_cb"] == tornado_config.start_span_cb
        assert settings["opentracing_trace_all"] == tornado_config.trace_all
        assert settings["opentracing_trace_client"] == tornado_config.trace_client

    @pytest.mark.parametrize(
        "http_method", ("get", "head", "post", "delete", "patch", "put", "options")
    )
    def test_traced_request(self, http_method):
        query = "one=1&two=2"
        method = getattr(requests, http_method)
        method("{}?{}".format(endpoint, query))

        for _ in range(20):  # Tornado's async nature makes this flakey
            if self.tracer.finished_spans():
                break
            sleep(0.25)

        spans = self.tracer.finished_spans()
        assert len(spans) == 1
        span = spans.pop()
        assert span.operation_name == "HelloHandler"
        tagged_method = http_method.upper()
        assert span.tags == {
            "component": "tornado",
            "http.url": "/hello/MyName?one=1&two=2",
            "http.method": tagged_method,
            "http.status_code": 200,
            "method": tagged_method,
            "path": "/hello/MyName",
            "query": query,
            "some_tag": True,
            tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
        }


# 參考標準常態分配表，製作一份更精準的常態分配表
#
# 1. 一般常態分配表是到小數點以下第二位
#
#     例如  P( z < 0.68 )=0.7517
#
#     常態分配表，查表  z 的範圍，小於 0.00 , 0.01, 0.02, 0.03 ......1.00, 1.01, 1.02, 1.03, ......
#
#     表格中， z 的範圍只到小數點後第二位
#
# 2. Hw. 3 要求同學做出來的標準常態分配表，z 的範圍是到小數點後第三位
#
#     例如 P( z < 1.284) 直接查表就可以得到
#
# 3. 這個表格，z 的範圍由 0.000 ~ 4.999
#
# 同學說，聽不懂題目。應該是把常態分配拋到九霄雲外，才不知老師的要求
#
# 建議，先回顧標準常態分配表的意義。慢慢就知道該怎麼作了
import math

from scipy.integrate import quad

from TheNormalDistributionTable.Intergration import intergration

upBound: int = int(1e3)

def probabilityDensityFunction(x: float):
    return (1 / math.sqrt(2 * math.pi)) * math.exp(-1 * (x * x) / 2)

def initTable(intergrateMethod, f):
    table = [[[] for _ in range(101)] for _ in range(55)]
    table[0][0]: float = 0.0
    table[0][1]: float = 0.0
    table[1][0]: float = 0.5
    for i in range(2, 101, 1):
        table[0][i]: float = table[0][i - 1] + 0.01

    for i in range(2, 55, 1):
        table[i][0]: float = table[i - 1][0] + 0.1

    for i in range(1, 55, 1):
        for j in range(1, 101, 1):
            table[i][j] = 0.5 + intergrateMethod(0.0, table[i][0] + table[0][j], f)
    return table

def caculateNormalDistribute(number: float, table: float):
    Xcoodinate: float = float(int(number * 10) / 10)
    Ycoodinate: float = float(int(number * 100) % 100) / 100
    baseX: int = 0
    baseY: int = 0
    while table[baseX + 1][0] <= Xcoodinate:
        baseX += 1
    while table[0][baseY + 1] <= Ycoodinate:
        baseY += 1
    return table[baseX][baseY]

def main():
    HW3 = intergration()
    trapTable: float = initTable(HW3.trapezoidalRule, probabilityDensityFunction)
    simpson13Table: float = initTable(HW3.simpson13Rule, probabilityDensityFunction)
    simpson38Table: float = initTable(HW3.simpson38Rule, probabilityDensityFunction)
    specialSquadTable: float = initTable(HW3.conditionalProbability, probabilityDensityFunction)
    while True:
        X = input("Enter X: ")

        print("P( z <", X, ")=", caculateNormalDistribute(float(X), trapTable), "with trapRule\n")
        print("P( z <", X, ")=", caculateNormalDistribute(float(X), simpson13Table), "with simpson1/3Rule\n")
        print("P( z <", X, ")=", caculateNormalDistribute(float(X), simpson38Table), "with simpson3/8Rule\n")
        print("P( z <", X, ")=", caculateNormalDistribute(float(X), specialSquadTable), "with squadRule\n")

main()


import configparser
import os
import sys
import rauth
import requests

def twitter_like_bot():
    os.system('color')

    config = configparser.RawConfigParser()
    config.read('settings.cfg')

    # get parameters
    try:
        twitter_api_key = config['KEYS']['twitter_api_key']
        twitter_api_secret = config['KEYS']['twitter_api_secret']
        bearer_token = config['KEYS']['bearer_token']
        username = config['PARAMS']['username']
        since_id = config['PARAMS']['since_id']
    except KeyError:
        print(
            "\n\033[91mFailed to load settings!\033[0m"
            "\nCreate a file named 'settings.cfg' with the following content:"
            "\n\n[KEYS]"
            "\ntwitter_api_key = <key>"
            "\ntwitter_api_secret = <secret>"
            "\nbearer_token = <token>"
            "\n\n[PARAMS]"
            "\nusername = <account of which to like tweets>"
            "\nsince_id = 0"
        )
        sys.exit()

    # create session
    try:
        twitter = rauth.OAuth1Service(
            name='twitter',
            consumer_key=twitter_api_key,
            consumer_secret=twitter_api_secret,
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1.1/')
        request_token, request_token_secret = twitter.get_request_token(
            params={'oauth_callback': 'oob'}
        )
        authorize_url = twitter.get_authorize_url(request_token)

        print(
            "\nVisit this URL to authorize the app or type 'q' to quit."
            f"\n\033[94m{authorize_url}\033[0m"
        )
        pin = input("PIN: ")
        if pin == "q":
            sys.exit()

        session = twitter.get_auth_session(
            request_token,
            request_token_secret,
            method='POST',
            data={'oauth_verifier': pin})
    except requests.exceptions.ConnectionError:
        print("\n\033[91mConnection failed!\033[0m")
        sys.exit()
    except KeyError:
        print("\n\033[91mAuthorization failed!\033[0m")
        sys.exit()

    try:
        # get user id
        user_request = requests.get(
            f"https://api.twitter.com/2/users/by/username/{username}",
            headers={"authorization": f"bearer {bearer_token}"})
        user_dict = user_request.json()
        user_request.close()
        user_id = user_dict['data']['id']

        # get ids of new tweets
        tweets_request = session.get(
            f"https://api.twitter.com/2/users/{user_id}/tweets",
            header_auth=True,
            params={'since_id': since_id, 'max_results': '100'})
        tweets_dict = tweets_request.json()
        tweets_request.close()
        newest_tweet_id = tweets_dict['meta']['newest_id']

        tweet_ids = []
        for tweet in tweets_dict['data']:
            tweet_ids.append(tweet['id'])

        while 'next_token' in tweets_dict['meta'] and len(tweet_ids) < 200:
            tweets_request = session.get(
                f"https://api.twitter.com/2/users/{user_id}/tweets",
                header_auth=True,
                params={
                    'since_id': since_id,
                    'max_results': '100',
                    'pagination_token': tweets_dict['meta']['next_token']
                }
            )
            tweets_dict = tweets_request.json()
            tweets_request.close()
            for tweet in tweets_dict['data']:
                tweet_ids.append(tweet['id'])

        # like tweets
        liked_tweets = 0
        limit_reached = False
        for tweet_id in tweet_ids:
            like_request = session.post(
                "https://api.twitter.com/1.1/favorites/create.json",
                header_auth=True,
                data={'id': tweet_id})
            if like_request.status_code == 200:
                liked_tweets += 1
            elif like_request.status_code == 429:
                print("\n\033[91mLimit reached!\033[0m")
                limit_reached = True
                break

    except requests.exceptions.ConnectionError:
        print("\n\033[91mConnection interrupted!\033[0m")
        sys.exit()
    except KeyError:
        print("\nNo Tweets found.")
        sys.exit()

    # set since_id
    print(f"\n\033[92mLiked {liked_tweets} Tweets, Retweets and Replies!\033[0m")
    if not limit_reached:
        config.set('PARAMS', 'since_id', newest_tweet_id)
        with open('settings.cfg', 'w') as configfile:
            config.write(configfile)

if __name__ == '__main__':
    twitter_like_bot()


import requests
import json

def get_API(url, header = None):
    data = requests.get(url, headers= header)
    return json.loads(data.text)

def getCoinInfo(_id):
    data = {}
    base_url = f"https://api.coingecko.com/api/v3"
    path_url = f"/coins/{_id}"
    rsp = get_API(base_url + path_url)
    data["id"] = rsp["id"]
    data["symbol"] = rsp["symbol"]
    data["Website"] = rsp["links"]["homepage"] # Website
    data["twitter"] = "https://twitter.com/" + rsp["links"]["twitter_screen_name"] # Twitter
    data["Source Code"] = rsp["links"]["repos_url"]["github"] # Github
    return data

if __name__ == "__main__":
    id = "ethereum"
    ethereum = getCoinInfo(id)
    print()


#!/usr/bin/env python3

import time
import argparse
import animation as a

from neopixel import *
from threading import Thread

# LED strip configuration:
LED_COUNT      = 270    # Number of LED pixels.
LED_PIN_0      = 12      # GPIO pin connected to the pixels - CHANNEL 0
LED_PIN_1      = 13      # GPIO pin connected to the pixels - CHANNEL 1

LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA        = 10      # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 100     # Set to 0 for darkest and 255 for brightest
LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL_0  = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53
LED_CHANNEL_1  = 1

# Main program logic follows:
if __name__ == '__main__':
    # Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
    args = parser.parse_args()

    # Create NeoPixel object with appropriate configuration.
    strip0 = Adafruit_NeoPixel(LED_COUNT, 18, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0)
    strip1 = Adafruit_NeoPixel(LED_COUNT, 13, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 1)

    # Intialize the library (must be called once before other functions).
    strip0.begin()
    strip1.begin()

    print ('Press Ctrl-C to quit.')
    if not args.clear:
        print('Use "-c" argument to clear LEDs on exit')

    try:
        #a.colorSet(strip0, a.LIME)
        #a.colorSet(strip1, a.LIME)
        while True:
            #a.colorWipe(strip0, a.WHITE)
            #a.rainbowCycle(strip0)
            #a.theaterChaseRainbow(strip0)
            #a.theaterChaseRainbow(strip1)
            #a.randomPixel(strip0, a.CYAN)
            #a.bounce(strip0, Color(0,200,0))
            #a.tetris(strip0)
            #a.tetris(strip1)
            #color = strip0.getPixelColor(strip0.numPixels()/2)
            #color2= strip0.getPixelColor(1)
            #a.bounce_bar(strip0, color, color2)
            #a.bounce_bar(strip1, color, color2)

            #a.colorWipe(strip0, a.RED)
            #a.colorWipe(strip1, a.LIME, True)

            #a.colorWipe(strip0, a.LIME)
            #a.colorWipe(strip1, a.RED, True)

            #a.doubleWipe(strip0, strip1, a.BLUE, a.RED)
            a.police2(strip0, strip1)
            #a.xmas(strip0)
            #a.xmas(strip1)

            #strip0.show()
            #strip1.show()

            #time.sleep(1.0/16.67)

            #a.colorWipe(strip0, a.WHITE)

    except KeyboardInterrupt:
        if args.clear:

            a.colorSet(strip0, a.BLACK)
            a.colorSet(strip1, a.BLACK)


import cld3
import fiona
import geopandas as gpd
from iso639 import languages
import numpy as np
import os
import pandas as pd
import requests
import string
from time import perf_counter
import zipfile

def fetch_data(url):
    r = requests.get(url, stream=True)
    r.raise_for_status()

    print('Downloading data from U.S. Census website')
    with open('us_roads.gdb.zip', 'wb') as handle:
        for block in r.iter_content(1024):
            handle.write(block)

def lid_text(text):
    two_letter = cld3.get_language(text)[0]
    # three_letter = languages.get(alpha2=two_letter).part3
    # name = languages.get(alpha2=two_letter).name
    return two_letter

def load_data(file):
    print('Loading data from geodatabase')
    df = gpd.read_file(file, driver='FileGDB', layer='Roads')
    return df

def lid_data(df, column):
    df = df.apply(lambda x: lid_text(x))
    print(df.head())

def test_lid_speed(num_words, len_words):
    """How long does a LID take on average?"""
    # make a random series of n-grams to LID
    random_ngrams = []
    timings = []
    alpha = list(string.ascii_lowercase)
    i = 0
    while i < num_words:
        j = 0
        word = ''
        while j < len_words:
            word += np.random.choice(alpha)
            print(word)
            j+=1
        random_ngrams.append(word)
        i+=1

    # LID grams and average timing
    for quad in random_ngrams:
        start = perf_counter()
        lid_text(quad)
        stop = perf_counter()
        duration = stop - start
        timings.append(duration)
    print(f'''Per-LID timing for {num_words} words with {len_words} characters \
averages to ~{np.average(timings): 0.6f} seconds.''')
    print(f'''Total time taken is {np.sum(timings)}.''')
    return random_ngrams

def unzip_data(archive):
    print('Unzipping data file')
    if os.path.exists('./data'):
        pass
    else:
        os.mkdir('data')
    with zipfile.ZipFile(archive, 'r') as zip_ref:
        zip_ref.extractall(path='data')


#! /usr/bin/env python3

import argparse
import errno
import glob
import os
import sys
import json
import yaml

import jinja2
import PIL.Image
import numpy

# https://stackoverflow.com/a/600612
def mkdirp(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output', default='output')
    parser.add_argument('index', metavar='FILE')
    parser.add_argument('pages', metavar='PAGE', nargs='*')

    args = parser.parse_args()

    output_dir = args.output
    mkdirp(output_dir)

    js_dir = os.path.join(output_dir, 'js')
    mkdirp(js_dir)

    css_dir = os.path.join(output_dir, 'css')
    mkdirp(css_dir)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
    index_template = env.get_template(args.index)

    with open(os.path.join(output_dir, 'index.html'), 'w') as f:
        f.write(index_template.render(pages=args.pages))

    with open(os.path.join(css_dir, 'style.css'), 'w') as f:
        f.write(env.get_template('css/style.css').render())

    with open(os.path.join(js_dir, 'script.js'), 'w') as f:
        f.write(env.get_template('js/script.js').render())

    textures_dir = os.path.join(output_dir, 'textures', 'common')
    mkdirp(textures_dir)

    for path in glob.glob(os.path.join('common', '*.png')):
        im = PIL.Image.open(path)
        im.save(os.path.join(textures_dir, os.path.basename(path)))

    result = []

    for shader in os.listdir('shaders'):
        if shader in ['common']:
            raise RuntimeError('invalid shader name: {}'.format(shader))

        shader_dir = os.path.join('shaders', shader)

        # returns (input path, output path)
        def search(name):
            path = os.path.join(shader_dir, name)
            if os.path.exists(path):
                return path, os.path.join(shader, name)

            path = os.path.join('common', name)
            if os.path.exists(path):
                return path, path

            raise RuntimeError('File not found: {}'.format(name))

        with open(os.path.join(shader_dir, 'shader.yaml')) as f:
            data = yaml.load(f)

        for buf in data:
            vertex_shader_name = buf.get('vertex', 'vertex.glsl')
            vertex_shader_path, _ = search(vertex_shader_name)
            vertex_shader = open(vertex_shader_path).read()
            buf['vertex'] = vertex_shader

            fragment_shader_name = buf.get('fragment', 'fragment.glsl')
            fragment_shader_path, _ = search(fragment_shader_name)
            fragment_shader = open(fragment_shader_path).read()
            buf['fragment'] = fragment_shader

            textures = buf.setdefault('textures', [])
            for texture in textures[::]:
                name = texture.get('name', 'tex')

                texture_file = texture.get('file')
                texture_buffer = texture.get('buffer')
                texture_choice = texture.get('choice')

                if texture_file is not None:
                    texture_path, texture['file'] = search(texture_file)
                elif texture_buffer is not None:
                    pass
                elif texture_choice is not None:
                    for e in texture_choice:
                        texture_path, e['file'] = search(e['file'])

        textures_dir = os.path.join(output_dir, 'textures', shader)
        mkdirp(textures_dir)

        for path in glob.glob(os.path.join(shader_dir, '*.png')):
            # Premultiply alpha

            # https://stackoverflow.com/a/9146202
            im = PIL.Image.open(path).convert('RGBA')
            premult = numpy.fromstring(im.tobytes(), dtype=numpy.uint8)
            alphaLayer = premult[3::4] / 255.0
            premult[0::4] = premult[0::4] * alphaLayer
            premult[1::4] = premult[1::4] * alphaLayer
            premult[2::4] = premult[2::4] * alphaLayer
            im_out = PIL.Image.frombytes("RGBA", im.size, premult.tostring())
            im_out.save(os.path.join(textures_dir, os.path.basename(path)))

        result.append((shader, data))

    with open(os.path.join(js_dir, 'shaders.js'), 'w') as f:
        print("var shaders = [];", file=f)

        for name, shader in result:
            print("shaders['{}'] = {};".format(name, json.dumps(shader)), file=f)

if __name__ == '__main__':
    main()


# 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/.

__all__ = [
    "gencxx",
    "genipdl",
    "parse",
    "typecheck",
    "writeifmodified",
    "checkSyncMessage",
    "checkFixedSyncMessages",
]

import os
import sys
from io import StringIO

from ipdl.cgen import IPDLCodeGen
from ipdl.lower import LowerToCxx, msgenums
from ipdl.parser import Parser, ParseError
from ipdl.type import TypeCheck
from ipdl.checker import checkSyncMessage, checkFixedSyncMessages

from ipdl.cxx.cgen import CxxCodeGen

def parse(specstring, filename="/stdin", includedirs=[], errout=sys.stderr):
    """Return an IPDL AST if parsing was successful.  Print errors to |errout|
    if it is not."""
    # The file type and name are later enforced by the type checker.
    # This is just a hint to the parser.
    prefix, ext = os.path.splitext(filename)
    name = os.path.basename(prefix)
    if ext == ".ipdlh":
        type = "header"
    else:
        type = "protocol"

    try:
        return Parser(type, name).parse(
            specstring, os.path.abspath(filename), includedirs
        )
    except ParseError as p:
        print(p, file=errout)
        return None

def typecheck(ast, errout=sys.stderr):
    """Return True iff |ast| is well typed.  Print errors to |errout| if
    it is not."""
    return TypeCheck().check(ast, errout)

def gencxx(ipdlfilename, ast, outheadersdir, outcppdir, segmentcapacitydict):
    headers, cpps = LowerToCxx().lower(ast, segmentcapacitydict)

    def resolveHeader(hdr):
        return [
            hdr,
            os.path.join(
                outheadersdir, *([ns.name for ns in ast.namespaces] + [hdr.name])
            ),
        ]

    def resolveCpp(cpp):
        return [cpp, os.path.join(outcppdir, cpp.name)]

    for ast, filename in [resolveHeader(hdr) for hdr in headers] + [
        resolveCpp(cpp) for cpp in cpps
    ]:
        tempfile = StringIO()
        CxxCodeGen(tempfile).cgen(ast)
        writeifmodified(tempfile.getvalue(), filename)

def genipdl(ast, outdir):
    return IPDLCodeGen().cgen(ast)

def genmsgenum(ast):
    return msgenums(ast.protocol, pretty=True)

def writeifmodified(contents, file):
    contents = contents.encode("utf-8")
    dir = os.path.dirname(file)
    os.path.exists(dir) or os.makedirs(dir)

    oldcontents = None
    if os.path.exists(file):
        fd = open(file, "rb")
        oldcontents = fd.read()
        fd.close()
    if oldcontents != contents:
        fd = open(file, "wb")
        fd.write(contents)
        fd.close()


from rest_framework.pagination import PageNumberPagination
from ..models import Post
from ..serializers import PostSerializer
from rest_framework.viewsets import ModelViewSet
from ..permissoes_api import IsOwner
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework import status
from rest_framework.response import Response

class PostAPIv1ViewSet(ModelViewSet):
    queryset = Post.objects.get_published()
    serializer_class = PostSerializer
    pagination_class = PageNumberPagination
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        qs = super().get_queryset()
        categoria_id = self.request.query_params.get('categoria')

        if categoria_id is not None:
            qs = qs.filter(categoria_post=categoria_id)
        qs = qs.filter()
        return qs

    def get_object(self):
        pk = self.kwargs.get('pk')
        obj = get_object_or_404(Post.objects.get_published(), pk=pk)

        self.check_object_permissions(self.request, obj)
        return obj

    def get_permissions(self):
        if self.request.method in ['PATCH', 'DELETE', ]:
            return [IsOwner()]
        return super().get_permissions()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(autor_post=request.user)
        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data,
            status=status.HTTP_201_CREATED,
            headers=headers
        )


import re
from collections import defaultdict

dictionary = defaultdict(int)
def histogram(source_text):

    delimeters = ["\\", ",", ";", ":", "\n", "-", "!", "?", "(", ")", "'s", \
    "'\'", ".", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "/", "}", "{"]

    f = open(source_text, 'r')
    lines = f.readlines()

    for line in lines:
        words = line.strip().translate(None, ''.join(delimeters)).split()
        for word in words:
            dictionary[word] += 1
    return dictionary

def unique_words(histogram):
    total = 0
    for (key, val) in histogram.iteritems():
        total += val
    return total

def frequency(word, histogram):
    return histogram[word]

if __name__ == '__main__':
    histogram_val = histogram("sherlock.rtf")
    print(histogram_val)
    print(unique_words(histogram_val))
    print(frequency("the", histogram_val))


import itertools
from urlextract import URLExtract
from wordcloud import WordCloud
import pandas as pd
from collections import Counter
import emoji

extract = URLExtract()

def remove_unwanted_data(selected_user, df):

    if selected_user != 'Overall':
        df = df[df['user'] == selected_user]

    df = df[df['user'] != 'group_notification']
    df = df[df['message'] != '<Media omitted>\n']
    df = df[df['message'] != 'This message was deleted\n']

    links = []
    for message in df['message']:
        links.extend(extract.find_urls(message))

    for i in range(len(links)):
        df = df[df['message'] != str(links[i]+'\n')]

    return df

def fetch_stats(selected_user,df):

    if selected_user != 'Overall':
        df = df[df['user'] == selected_user]

    # fetch the number of messages
    num_messages = df.shape[0]

    # fetch number of media messages
    num_media_messages = df[df['message'] == '<Media omitted>\n'].shape[0]

    # fetch number of deleted messages
    num_del_mes = df[df['message'] == 'This message was deleted\n'].shape[0]

    # fetch the total number of words
    df = remove_unwanted_data(selected_user, df)
    words = []
    for message in df['message']:
        words.extend(message.split())

    # fetch number of links shared
    links = []
    for message in df['message']:
        links.extend(extract.find_urls(message))

    return num_messages,len(words),num_media_messages,len(links),num_del_mes

def most_busy_users(df):
    x = df['user'].value_counts().head()
    df = round((df['user'].value_counts() / df.shape[0]) * 100, 2).reset_index().rename(columns={'index': 'name', 'user': 'name'})
    return x,df

def most_messages_deleted(df):

    dic = {}
    msg = df['message'].tolist()
    user = df['user'].tolist()
    for i in range(df.shape[0]):
        if msg[i] == 'This message was deleted\n':
            if user[i] not in dic.keys():
                dic[user[i]] = 1
            else:
                dic[user[i]] = dic[user[i]] + 1

    dic = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
    dic = dict(itertools.islice(dic.items(), 5))
    return dic

def most_negative_messages(df):

    f = open('negative_words.txt', 'r')
    neg_words = f.read()
    nl = []
    for word in neg_words.lower().split():
        nl.append(word)
    dic = {}
    msg = df['message'].tolist()
    user = df['user'].tolist()
    for i in range(df.shape[0]):
        message=msg[i].lower().split()
        for j in range(len(message)):
            if message[j] in nl:
                if user[i] not in dic.keys():
                    dic[user[i]] = 1
                else:
                    dic[user[i]] = dic[user[i]] + 1

    dic = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
    dic = dict(itertools.islice(dic.items(), 5))
    return dic

def create_wordcloud(df):

    def wordlist(message):
        y = []
        for word in message.lower().split():
            y.append(word)
        return " ".join(y)

    wc = WordCloud(width=500,height=500,min_font_size=10,background_color='white')
    df['message'] = df['message'].apply(wordlist)
    if df.shape[0]!=0:
        df_wc = wc.generate(df['message'].str.cat(sep=" "))
        return df_wc

def remove_hinglish(df):

    f = open('stop_hinglish.txt', 'r')
    stop_words = f.read()
    sw = []
    for word in stop_words.lower().split():
        sw.append(word)

    words = []
    for message in df['message']:
        for word in message.lower().split():
            if word not in sw:
                words.append(word)

    return words

def most_common_words(df):

    words = remove_hinglish(df)
    most_common_df = pd.DataFrame(Counter(words).most_common(20))
    return most_common_df

def most_neg_words(df):

    words = remove_hinglish(df)
    f = open('negative_words.txt', 'r')
    neg_words = f.read()
    nl = []
    for word in neg_words.lower().split():
        nl.append(word)
    nw = []
    for i in range(len(words)):
        if words[i] in nl:
            nw.append(words[i])
    most_common_df = pd.DataFrame(Counter(nw).most_common(20))
    return most_common_df

def count_negative_words(df):

    words = []
    for message in df['message']:
        for word in message.lower().split():
            words.append(word)

    f = open('negative_words.txt', 'r')
    neg_words = f.read()
    nl = []
    for word in neg_words.lower().split():
        nl.append(word)
    nw=[]
    for i in range(len(words)):
        if words[i] in nl:
            nw.append(words[i])
    if(len(words)!=0):
        return round((len(nw)/len(words)*100),1)
    else:
        return 0

def emoji_helper(df):

    emojis = []
    for message in df['message']:
        emojis.extend([c for c in message if c in emoji.UNICODE_EMOJI['en']])

    emoji_df = pd.DataFrame(Counter(emojis).most_common(len(Counter(emojis))))

    return emoji_df

def monthly_timeline(df):

    timeline = df.groupby(['year', 'month_num', 'month']).count()['message'].reset_index()

    time = []
    for i in range(timeline.shape[0]):
        time.append(timeline['month'][i] + "-" + str(timeline['year'][i]))

    timeline['time'] = time

    return timeline


from PyQt4.QtSql import QSqlQuery
from DataBase.ConexaoSQL import ConexaoSQL

class ClienteDAO:
    def CadastrarCliente(cliente):
        conn = ConexaoSQL
        db = conn.getConexao()
        db.open()

        query = QSqlQuery()
        query.prepare("INSERT INTO Cliente(Nome, CPF, Endereco, Email, Telefone) "
                      "VALUES (?, ?, ?, ?, ?)")
        query.addBindValue(cliente.Nome)
        query.addBindValue(cliente.CPF)
        query.addBindValue(cliente.Endereco)
        query.addBindValue(cliente.Email)
        query.addBindValue(cliente.Telefone)
        query.exec_()
        db.commit()

    def AtualizarCliente(codigoCli, cliente):
        conn = ConexaoSQL
        db = conn.getConexao()
        db.open()

        query = QSqlQuery()
        query.prepare("UPDATE Cliente SET Nome = '"+cliente.Nome+"', CPF = '"+cliente.CPF
                      +"', Endereco = '"+cliente.Endereco+"', Email = '"+cliente.Email
                      +"', Telefone = '"+cliente.Telefone
                      +"' WHERE CodigoCli = "+codigoCli)
        query.exec_()
        db.commit()

    def ExcluirCliente(codigoCli):
        conn = ConexaoSQL
        db = conn.getConexao()
        db.open()

        query = QSqlQuery()
        query.prepare("DELETE FROM Cliente WHERE CodigoCli=:codigoCli")
        query.bindValue(":codigoCli", codigoCli)
        query.exec_()
        db.commit()

    def PesquisarTodosClientes():
        conn = ConexaoSQL
        db = conn.getConexao()
        db.open()

        sql = "SELECT * FROM Cliente"
        query = QSqlQuery(sql)

        return query

    def PesquisarCliente(valor, tipo):
        conn = ConexaoSQL
        db = conn.getConexao()
        db.open()

        if tipo=='Código':
            sql = "SELECT * FROM Cliente where CodigoCli = " + valor
            query = QSqlQuery(sql)
        elif tipo=='Nome':
            sql = "SELECT * FROM Cliente where Nome = '"+valor+"'"
            query = QSqlQuery(sql)
        elif tipo=='CPF':
            sql = "SELECT * FROM Cliente where CPF = '" + valor+"'"
            query = QSqlQuery(sql)

        return query


# Kunal Shah
# Date 02/09/2022

# Problem 1
# Using define
def Equals(a,b):
    # Using If else statement to to check numbers if equal or not
    if a==b:
        print("{} and {} are equal".format(a,b))
    else:
        print("{} and {} are not equal".format(a,b))

#test function

Equals(9,9)

Equals(9,10)

# Problem 2

# Define function
def SumGreater(x,y):
    # Using if statement to check if sum is equal to 10
    if x + y == 10:
        print("Sum is equal to 10")
    # Checking of sum is greater than 10
    elif x + y > 10:
        print("Sum is greater than 10")
    else:
        print("Sum is less than 10")

#test function

SumGreater(5,4)

SumGreater(12,3)

SumGreater(6,4)

# Problem 3

def checkFunction(lst):

#Check if 5 is present in list or not
    if 5 in lst:
        print("Value 5 is present in that list.")
    else:
        print("Value 5 is not present in that list.")

checkFunction([1,2,3,4,5])
checkFunction([2,4,6,8,10,12])

# Problem 4

def checkLeapYear(year):
#Check if the year is evenly divisible by 4
    if (year % 4) == 0:
#Check if the year is evenly divisible by 100
        if (year % 100) == 0:
#Check if the year is evenly divisible by 400
            if (year % 400) == 0:
#Print it is a leap year
                print("{0} is a leap year".format(year))
#Else it is not a leap year
            else:
                print("{0} is not a leap year".format(year))
#if the year is not divisible by 100 then Leap year
        else:
            print("{0} is a leap year".format(year))
    else:
        print("{0} is not a leap year".format(year))

checkLeapYear(2022)
checkLeapYear(2000)

# Problem 5

class character:
    def __init__(self, nickname, weapons, weaknesses):
        self.nickname = nickname
        self.weapons = weapons
        self.weaknesses = weaknesses

    def get_model(self):
        return self.nickname

    def get_year(self):
        return self.weapons

    def get_color(self):
        return self. weaknesses

    def profile(self):
        return self.nickname, self.weapons, self. weaknesses

    def checks(self,p):
        print("Checks function")
        task = input("What task the character are going to perform(Write,climb,cook)")

        # For cooking a dish
        if task == "cook":
            if p.weaknesses == "small":
                print("The character can not cook")

            elif ('pan' in p.weapons) and ('groceries' in p.weapons):
                print("The character can cook")

            else:
             print("The character will not Cook")

        # for climbing a mountain
        elif task == "climb":
            if p.weaknesses != "slow":
                print("The character can not climb the mountain")

            elif ('rope' in p.weapons) and ('coat' in p.weapons) and ("first aid kit") in p.weapons:
                print("The character can climb")

            else:
                print("The character will not climb a mountain")

        # For writing a book
        elif task == "write":
            if p.weaknesses != "confusion":
                print("The character can not write a book")

            elif ('pen' in p.weapons) and ('paper' in p.weapons) and ("idea") in p.weapons:
                print("The character can a write a book")

            else:
                print("The character will not write a book")

player1 = character('','','')
player1.nickname = 'Dragon Slayer'
player1.weapons = ['pan', 'paper', 'idea', 'rope', 'groceries']
player1.weaknesses = ['slow']
for item in player1.weapons:
    print("Item: ", item)

for debuff in player1.weaknesses:
    print("Debuff: ", debuff)

player1.checks(player1)


#!/usr/bin/python3
import csv
import requests
import sys

if __name__ == "__main__":
    tasks_status = []
    tasks_title = []
    user = sys.argv[1]
    url = "https://jsonplaceholder.typicode.com/"

    request_tasks = requests.get(url + "todos/?userid={}".format(user)).json()
    request_user = requests.get(url + "users/{}".format(user)).json()

    username = request_user["username"]
    name = request_user["name"]

    for task in request_tasks:
        if task["userId"] == int(user):
            tasks_status.append(task["completed"])
            tasks_title.append(task["title"])

    with open(user + ".csv", mode='w', encoding='utf-8') as csv_file:
        fieldnames = ["userId", "name", "completed", "title"]
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames,
                                quoting=csv.QUOTE_ALL)
        for i in range(len(tasks_status)):
            writer.writerow({"userId": user, "name": username, "completed":
                            tasks_status[i], "title": tasks_title[i]})


def singleNumber(nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
            return sum(nums)
        nums.sort()
        print(nums)
        if nums[0] != nums[1]: return nums[0]
        for i in range(1,len(nums)-1):
            if nums[i] != nums[i+1] and nums[i-1] != nums[i]: return nums[i]
        return nums[len(nums)-1]

#testing
test = [4,1,5,1,5, 2, 3, 2, 3, 6, 8, 8, 6,9 ,4, 9, 10]
print(singleNumber(test))


"""
2187. 完成旅途的最少时间
给你一个数组 time ，其中 time[i] 表示第 i 辆公交车完成 一趟旅途 所需要花费的时间。
每辆公交车可以 连续 完成多趟旅途，也就是说，一辆公交车当前旅途完成后，可以 立马开始 下一趟旅途。每辆公交车 独立 运行，
也就是说可以同时有多辆公交车在运行且互不影响。
给你一个整数 totalTrips ，表示所有公交车 总共 需要完成的旅途数目。请你返回完成 至少 totalTrips 趟旅途需要花费的 最少 时间。
"""
from typing import *

def minimumTime(time: List[int], totalTrips: int) -> int:
    time.sort()
    left, right = min(time), min(time) * totalTrips
    while left < right:
        mid = (left + right) // 2
        temp = 0
        for t in time:
            temp += mid // t
        if temp < totalTrips:
            left = mid + 1
        else:
            right = mid
    return left

2187. 完成旅途的最少时间.py


# -*- coding: utf-8 -*-
"""
Created on Mon Mar  2 19:41:38 2020
The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function.
@author: Ragib Shahariar Ayon
"""

def format_address(address_string):
    address_list=address_string.split()
    house_number=address_list[0]
    street_name=' '.join(address_list[1:])
    return "house number {} on street named {}".format(house_number,street_name)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"


class TreeNode:
    def __init__(self, val= 0,left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def minDiffbst(self, root):
        prev, res = None, float("inf")

        def dfs(node):
            if not node:
                return
            dfs(node.left)
            nonlocal  prev,res
            if prev:
                res = min(res, node.val-prev.val)
            prev = node
            dfs(node.right)

        dfs(root)

        return res

if __name__ == '__main__':
    root = TreeNode(4)
    root.left = TreeNode(2)
    root.right = TreeNode(6)

    root.left.right = TreeNode(3)
    root.left.left = TreeNode(1)

    solution =  Solution()

    res = solution.minDiffbst(root)

    print(res)


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

""""
@author:Yoann Poupart

File containing an example of conditional GAN training.

"""

# Libraries imports
from dcgan import FLEXI_C_DCGAN

import scipy.stats as sc
import numpy as np
import matplotlib.pyplot as plt
import tikzplotlib

from keras.models import Model, load_model
from keras.layers import Input
from keras.optimizers import Adam
from sklearn.utils import shuffle

# Class definition

# Functions definition

# Constants definition
BLOCK_SIZE = 90
SAMPLING_SIZE = 165
DATA_SET_SIZE = 2 ** 5 * 3 ** 5 * 5 ** 2
FILE_X = './Samples/real_ds_cond_trend_temp_glob.npy'
FILE_Y = './Samples/real_lab_cond_trend_temp_glob.npy'
FILE_GEN_STEP = "./Networks/gan_cond_trend_temp_step_gen"
FILE_DISC_STEP = "./Networks/gan_cond_trend_temp_step_disc"

NUM_EPOCHS = 1  # 50_000
BATCH_SIZE = 2 ** 3 * 3 ** 5
INIT_LR = 4e-4
LAST_ACTI = "linear"
H = 10
FACT_LR = 1
GRAD_NORM = 1
SUB_SET_SIZE = 1000

TYPE = 'student'
SHAPE = 50
SIGMA_NOISE_DATA = 1e-3
W_COND = 2

SIMU_GAN = True
SAVE_STEPS = False
SAVE_FIG = False
SAVE_TEX = False
FS = 30

if __name__ == '__main__':
    if SIMU_GAN:
        X = np.load(FILE_X)
        Y = np.load(FILE_Y)
        if SAMPLING_SIZE == 165:
            print("[INFO] building generator...")
            gen = FLEXI_C_DCGAN.build_generator(w_end=SAMPLING_SIZE, w_start=SAMPLING_SIZE,
                                                w_1=110, s_1=1, w_2=150, final_act=LAST_ACTI, h=H, w_cond=W_COND)
            print("[INFO] building discriminator...")
            disc = FLEXI_C_DCGAN.build_discriminator(w_start=SAMPLING_SIZE,
                                                     w_1=150, w_2=90, w_3=15, h=H, w_cond=W_COND)
        elif SAMPLING_SIZE == 156:
            print("[INFO] building generator...")
            gen = FLEXI_C_DCGAN.build_generator(w_end=SAMPLING_SIZE, w_start=SAMPLING_SIZE,
                                                w_1=100, s_1=1, w_2=140, final_act=LAST_ACTI, h=H, w_cond=W_COND)
            print("[INFO] building discriminator...")
            disc = FLEXI_C_DCGAN.build_discriminator(w_start=SAMPLING_SIZE,
                                                     w_1=140, w_2=80, w_3=15, h=H, w_cond=W_COND)
        else:
            raise NotImplementedError
        try:
            gen = load_model(FILE_GEN_STEP, compile=False)
            disc = load_model(FILE_DISC_STEP, compile=False)
        except:
            pass
        print('[INFO] test...')
        discOpt = Adam(learning_rate=INIT_LR, beta_1=0.999, decay=INIT_LR / NUM_EPOCHS, clipnorm=GRAD_NORM)
        disc.compile(loss="binary_crossentropy", optimizer=discOpt)

        zeros = np.zeros((BATCH_SIZE, SAMPLING_SIZE))
        zeros_coord = np.random.uniform(-90, 90, size=(BATCH_SIZE, 2)) * np.array([2, 1])
        _ = gen.predict((zeros, zeros_coord), verbose=1)
        _ = disc.predict((zeros, zeros_coord), verbose=1)
        print(f"[INFO] discriminator summary : ")
        disc.summary()
        print(f"[INFO] generator summary : ")
        gen.summary()

        print("[INFO] building GAN...")
        disc.trainable = False
        data_input = Input(shape=(SAMPLING_SIZE,))
        coord_input = Input(shape=(2,))
        ganOutput = disc((gen((data_input, coord_input)), coord_input))
        gan = Model((data_input, coord_input), ganOutput)
        ganOpt = Adam(learning_rate=INIT_LR / 4, beta_1=0.5, decay=INIT_LR / 4 / NUM_EPOCHS, clipnorm=GRAD_NORM)
        gan.compile(loss="binary_crossentropy", optimizer=discOpt)

        print("[INFO] starting training...")
        benchmark_noise = np.random.normal(size=(1, SAMPLING_SIZE))
        benchmark_coord = np.random.uniform(-90, 90, size=(1, 2)) * np.array([2, 1])
        disc_losses = []
        gen_losses = []

        for epoch in range(0, NUM_EPOCHS):
            print("[INFO] starting epoch {} of {}...".format(epoch + 1,
                                                             NUM_EPOCHS))
            X, Y = shuffle(X, Y)
            batchesPerEpoch = int(X.shape[0] / BATCH_SIZE)
            for i in range(0, batchesPerEpoch):
                batch_data = X[i * BATCH_SIZE:(i + 1) * BATCH_SIZE, :] + np.random.normal(loc=SIGMA_NOISE_DATA, size=(
                    BATCH_SIZE, SAMPLING_SIZE))
                batch_coord = Y[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]

                noise = np.random.normal(size=(BATCH_SIZE, SAMPLING_SIZE))
                gen_coord = np.random.uniform(-90, 90, size=(BATCH_SIZE, 2)) * np.array([2, 1])
                gen_data = gen.predict((noise, gen_coord), verbose=0)

                X_tr = np.concatenate((batch_data, gen_data))
                y_tr = np.array(([1] * BATCH_SIZE) + ([0] * BATCH_SIZE))
                y_lab_tr = np.concatenate((batch_coord, gen_coord))
                (X_tr, y_tr, y_lab_tr) = shuffle(X_tr, y_tr, y_lab_tr)
                disc_loss = disc.train_on_batch((X_tr, y_lab_tr), y_tr)
                disc_losses.append(disc_loss)

                noise = np.random.normal(size=(BATCH_SIZE, SAMPLING_SIZE))
                gen_coord = np.random.uniform(-90, 90, size=(BATCH_SIZE, 2)) * np.array([2, 1])
                fake_labels = np.array([1] * BATCH_SIZE)
                gen_loss = gan.train_on_batch((noise, gen_coord), fake_labels)
                gen_losses.append(gen_loss)

            if NUM_EPOCHS >= 10:
                if epoch % (NUM_EPOCHS // 10) == 0:
                    gen_sample = gen.predict((benchmark_noise, benchmark_coord), verbose=0)
                    plt.subplot(2, 5, epoch // (NUM_EPOCHS // 10) + 1)
                    plt.plot(gen_sample.mean(axis=0))
            if SAVE_STEPS:
                gen.save(FILE_GEN_STEP, include_optimizer=True)
                disc.save(FILE_DISC_STEP, include_optimizer=True)

        if SAVE_FIG:
            if SAVE_TEX:
                tikzplotlib.save("./Images/states.tex")
            else:
                plt.savefig("./Images/States.png")
            plt.close()
        else:
            plt.show()

        plt.figure(figsize=(15, 15))
        steps = 1 + np.arange(len(gen_losses))
        plt.plot(steps, gen_losses, label="Loss of the generator")
        plt.plot(steps, disc_losses, label="Loss of the discriminator")
        plt.xticks(fontsize=FS)
        plt.yticks(fontsize=FS)
        plt.xlabel("Step", fontsize=FS)
        plt.ylabel(r"Loss", fontsize=FS)
        plt.legend(loc='best', fontsize=FS)
        if SAVE_FIG:
            if SAVE_TEX:
                tikzplotlib.save("Images/Loss.tex")
            else:
                plt.savefig("./Images/Loss.png")
            plt.close()
        else:
            plt.show()