import pytest
from thefuck.types import Command

from thefuck_contrib_scoop.rules.scoop_unknown_command import get_new_command, match
from thefuck_contrib_scoop.scoop import get_aliases, get_commands

@pytest.mark.parametrize(
    "script, output",
    [
        (
            "scoop bucke add versions",
            "scoop: 'bucke' isn't a scoop command. See 'scoop help'.",
        ),
    ],
)
def test_match(script, output):
    assert match(Command(script, output))

@pytest.mark.parametrize(
    "script",
    [(f"scoop {command}") for command in get_commands() + get_aliases()],
)
def test_not_match(script):
    assert not match(Command(script, ""))

@pytest.mark.parametrize(
    "script, output, new_command",
    [
        (
            "scoop inst thefuck",
            "scoop: 'inst' isn't a scoop command. See 'scoop help'.",
            [
                "scoop install thefuck",
                "scoop uninstall thefuck",
                "scoop list thefuck",
            ],
        ),
        (
            "scoop instaa thefuck",
            "scoop: 'instaa' isn't a scoop command. See 'scoop help'.",
            [
                "scoop install thefuck",
                "scoop uninstall thefuck",
                "scoop list thefuck",
            ],
        ),
    ],
)
def test_get_new_command(script, output, new_command):
    command = Command(script, output)
    assert sorted(get_new_command(command)) == sorted(new_command)


from random import randrange

def main():
    limit = -1

    while limit < 1:
        try:
            limit = int(input("What is the level of this game? "))
        except ValueError:
            print ("Please input a positive integer!")

    guess = ''
    num = randrange(limit)

    while guess != limit:
        try:
            guess = int(input("What is your guess? "))
            print (game(guess, limit))
        except ValueError:
            print ("Please input a positive integer!")

def game(guess, num):

    if guess < num:
        return ("Too small!")
    elif guess > num:
        return ("Too large!")
    elif guess == num:
        return ("Just right!")

main()


# Import the dependencies.
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify

#################################################
# Database Setup
#################################################
# reflects hawaii.sqlite database into a new model
engine = create_engine("sqlite:///Resources/hawaii.sqlite",
                       connect_args={'check_same_thread': False})
base = automap_base()

# reflects the tables
base.prepare(autoload_with=engine)

# Save references to each table, measurement and station
measurement = base.classes.measurement
station = base.classes.station

# Create our session (link) from Python to the DB
session = Session(engine)

#################################################
# Flask Setup
#################################################
app = Flask(__name__)

#################################################
# Flask Routes
#################################################

# Home page - gives list of possible routes
@app.route("/")
def index():
    return (
            f"Available Routes:"
            f"
"
            f"
Precipitation :  /api/v1.0/precipitation
"
            f"
Stations:  /api/v1.0/stations
"
            f"
Temperature:  /api/v1.0/tobs
"
            f"
Insert Start Date (YYYY-MM-DD): /api/v1.0/<start>
"
            f"
Insert Date Range (YYYY-MM-DD): /api/v1.0/<start>/<end>
"
            f"
"
            )

# Precipitation - gives latest year precipitation data in JSON format
@app.route("/api/v1.0/precipitation")
def precipitation():
    # Finds the most recent date in the data
    latest_date = session.query(measurement.date).\
                        order_by(measurement.date.desc()).\
                        first()

    # Converts latest date to datetime format
    latest_date_dt = dt.datetime.strptime(latest_date[0], '%Y-%m-%d').date()
    # Finds the date exactly one year from the latest date
    query_date = latest_date_dt - dt.timedelta(weeks = 52.2)

    # Queries the date and precipitation from the latest year in descending order
    latest_year_data =  session.query(measurement.date, measurement.prcp).\
    filter(measurement.date >= query_date).\
    order_by(measurement.date.desc()).all()

    # Formats data into a dictionary
    latest_year_precip = []
    for date, prcp in latest_year_data:
        dates_precip = {}
        dates_precip["date"] = date
        dates_precip["prcp"] = prcp
        latest_year_precip.append(dates_precip)

    # Returns in json format
    return jsonify(latest_year_precip)

# Stations - gives all distinct stations in json format
@app.route("/api/v1.0/stations")
def stations():
    # Queries all station information
    all_stations_query = session.query(station.id,
                                       station.station,
                                       station.name,
                                       station.latitude,
                                       station.longitude,
                                       station.elevation).\
                        all()

    # Formats data into a dictionary
    all_stations = []
    for id, stn, name, lat, lng, elev in all_stations_query:
        stations_dict = {}
        stations_dict["id"] = id
        stations_dict["station"] = stn
        stations_dict["name"] = name
        stations_dict["lat"] = lat
        stations_dict["long"] = lng
        stations_dict["elevation"] = elev
        all_stations.append(stations_dict)

    # Returns in json format
    return jsonify(all_stations)

@app.route("/api/v1.0/tobs")
def tobs():
    # Finds the most recent date in the data
    latest_date_temp = session.query(measurement.date).\
                        order_by(measurement.date.desc()).\
                        first()

    # Converts latest date to datetime format
    latest_date_temp_dt = dt.datetime.strptime(latest_date_temp[0], '%Y-%m-%d').date()
    # Finds the date exactly one year from the latest date
    query_date_temp = latest_date_temp_dt - dt.timedelta(weeks = 52.2)

    # Queries most active stations and the number of measurements per station
    station_query = session.query(measurement.station, func.count(measurement.station)).\
                            group_by(measurement.station).\
                            order_by(func.count(measurement.station).desc()).\
                            all()

    # Queries temperature from the latest year and from the most active station
    latest_year_temp_query =  session.query(measurement.date, measurement.tobs).\
                                filter(measurement.station == station_query[0][0]).\
                                filter((measurement.date >= query_date_temp)).\
                                order_by(measurement.date).\
                                all()

    # Formats data into a dictionary
    latest_year_temp = []
    for date, temp in latest_year_temp_query:
        dates_temp = {}
        dates_temp["date"] = date
        dates_temp["temp"] = temp
        latest_year_temp.append(dates_temp)

    # Returns in json format
    return jsonify(latest_year_temp)

@app.route("/api/v1.0/<start>")
def start(start):
    # Converts user date input into datetime format
    start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()

    # Queries all temperature measurement from start date to latest date
    start_temp_query = session.query(measurement.date, measurement.tobs).\
                               filter(measurement.date >= start_date).\
                               order_by(measurement.date).\
                               all()

    # Formats data into a dictionary
    start_date_temp = []
    for date, temp in start_temp_query:
        dates_temp = {}
        dates_temp["date"] = date
        dates_temp["temp"] = temp
        start_date_temp.append(dates_temp)

    # Returns in json format
    return jsonify(start_date_temp)

@app.route("/api/v1.0/<start>/<end>")
def end(start, end):
    # Finds the most recent date in the data
    latest_date = session.query(measurement.date).\
                          order_by(measurement.date.desc()).\
                          first()

    # Converts latest date to datetime format
    latest_date_dt = dt.datetime.strptime(latest_date[0], '%Y-%m-%d').date()

    # Converts user date input into datetime format
    start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()
    end_date = dt.datetime.strptime(end, '%Y-%m-%d').date()

    # Queries all temperatures between start and end dates
    start_end_temp_query = session.query(measurement.date, measurement.tobs).\
                               filter(measurement.date >= start_date).\
                               filter(measurement.date <= end_date).\
                               order_by(measurement.date).\
                               all()

    # Formats data into a dictionary
    start_end_date_temp = []
    for date, temp in start_end_temp_query:
        dates_temp = {}
        dates_temp["date"] = date
        dates_temp["temp"] = temp
        start_end_date_temp.append(dates_temp)

    # Returns in json format
    return jsonify(start_end_date_temp)

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


class Solution:
    def letterCombinations(self, digits: str) -> list:
        if not digits: return []

        nums = {'1':('','',''),
                '2':('a','b','c'),
                '3':('d','e','f'),
                '4':('g','h','i'),
                '5':('j','k','l'),
                '6':('m','n','o'),
                '7':('p','q','r','s'),
                '8':('t','u','v'),
                '9':('w','x','y','z')}

        comb = ['']
        for digit in digits:
            tmp = []
            for j in nums[digit]:
                for k in comb:
                    tmp.append(k + j)
            comb = tmp

        return comb

Medium/17. Letter Combinations of a Phone Number.py


# Code source: Jaques Grobler
# License: BSD 3 clause
# Code from https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from joblib import dump, load
from numpy import savetxt

# Load the diabetes dataset
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)

# Use only one feature
#diabetes_X = diabetes_X[:, np.newaxis, 2]

diabetes_X = np.expand_dims(diabetes_X[:, 2], axis=1)

# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]

# Split the targets into training/testing sets
diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)

data_test = np.concatenate((diabetes_X_test, np.expand_dims(diabetes_y_test, axis=1)),axis=1)

savetxt('data_test.csv', data_test, delimiter=',')

#print(type(diabetes_X_test))
#np.save("X_test.npy",diabetes_X_test)

#
dump(regr, 'Model/model.joblib')
#regr_loaded = load('C:/Users/dioge/Desktop/Docker_Machine_Learning/Model/model.joblib')

# Make predictions using the testing set
#diabetes_y_pred = regr_loaded.predict(diabetes_X_test)

diabetes_y_pred = regr.predict(diabetes_X_test)

# The coefficients
print("Coefficients: \n", regr.coef_)
# The mean squared error
print("Mean squared error: %.2f" % mean_squared_error(diabetes_y_test, diabetes_y_pred))
# The coefficient of determination: 1 is perfect prediction
print("Coefficient of determination: %.2f" % r2_score(diabetes_y_test, diabetes_y_pred))

"""Coefficients: [938.23786125]
Mean squared error: 2548.07
Coefficient of determination: 0.47"""


def game(r, c, s):
    grid[r][c] = s
    for i in range(8):
        stack = []
        for l in range(1, N):
            nr = r + delta[i][0] * l
            nc = c + delta[i][1] * l
            if 0 <= nr < N and 0 <= nc < N and not grid[nr][nc]:
                break
            if 0 <= nr < N and 0 <= nc < N and grid[nr][nc] and grid[nr][nc] != s:
                stack.append((nr, nc))
            if 0 <= nr < N and 0 <= nc < N and grid[nr][nc] == s:
                while stack:
                    nr, nc = stack.pop()
                    grid[nr][nc] = s
                break

for tc in range(1, int(input())+1):
    N, M = map(int, input().split())
    grid = [[0] * N for _ in range(N)]
    grid[N//2][N//2] = 2
    grid[N//2-1][N//2] = 1
    grid[N//2][N//2-1] = 1
    grid[N//2-1][N//2-1] = 2
    delta = ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1))
    for _ in range(M):
        x, y, color = map(int, input().split())
        game(x-1, y-1, color)
    white = 0
    black = 0
    for row in grid:
        # print(*row)
        for i in row:
            black += (i == 1)
            white += (i == 2)
    print(f'#{tc}', black, white)


# Exercise 2: Write a program to look for lines of the form:
#
# New Revision: 39772
#
# Extract the number from each of the lines using a regular expression and the
# findall() method. Compute the average of the numbers and print out the average
# as an integer.
#
# Enter file:mbox.txt
# 38549
#
# Enter file:mbox-short.txt
# 39756

from itertools import count
import re

name = input('Enter a file name:')
if len(name) < 1 :
    name = 'mbox.txt'

try :
    handle = open(name)
except :
    print('FILE NOT FOUND')
    quit()

revs = list()
for line in handle :
    line = line.rstrip()
    # I had '^N.+:.([0-9]*)' put it but that one didn't work on mbox.txt -> Changed
    rev = re.findall('^New Revision: ([0-9]*)', line)
    if len(rev) >= 1 :
        revs.append(rev)

int_revs = list()

# x in this case is the whole list (even though its only one index long). To get
# this code to work, I had to specifty which index I wanted to use the int() on.
for x in revs :
    int_revs.append(int(x[0]))

# I kept trying to use the "count" feature for lists. Turns out is "len"
print(int(sum(int_revs)/len(int_revs)))


import math
from statistics import mean,stdev,mode
import os
import pandas as pd

library = pd.read_csv('Z:/Helium_Tan/PTMDIAProject_SpectralLibraries/Pro_12fxnOnly/PTMDIAProject_TimsTOFPro_12fxnOnly.tsv', delimiter= '\t',low_memory = False)
 # print(len(library))
phospho_library = library[library['IntLabeledPeptide'].str.contains('80')]
# print(len(phospho_library))

DIACurve = pd.read_csv('Z:/Helium_Tan/PTMDIAProject_PhosphoBGCurve/Outputs/SpectralLibSearch/Pro_12fxnOnlySearch_LocFilter/20220906_093527_PTMDIAProject_TimsTOFPro_DIACurveAnalysis_12fxnLib0.75Loc_Report.tsv', delimiter= '\t',low_memory = False)
phospho_DIACurve = DIACurve.loc[DIACurve['EG.IntPIMID'].str.contains('80')]

library_peps = set(list(phospho_library['StrippedPeptide']))
DIA_peps = set(list(phospho_DIACurve['PEP.StrippedSequence']))
overlap = library_peps.intersection(DIA_peps)

print('Library contains: ' + str(len(library_peps)) + " peptides")
print('DIA curve contains: ' + str(len(DIA_peps)) + " peptides")
print("There are " + str(len(overlap)) + " peptides in both sets")

DIA_only = DIA_peps - library_peps

scores = {}
for index, row in phospho_DIACurve.iterrows():
    seq = row['PEP.StrippedSequence']
    cscore = row['EG.Cscore']

    if seq in DIA_only:
        if seq not in scores:
            scores[seq] = []
            scores[seq].append(cscore)
        else:
            scores[seq].append(cscore)

print(scores)


import functools
import turtle

import hangman
import words

def write_word(word):
    writer = turtle.Turtle()
    writer.penup()
    writer.goto(100, 200)
    writer.write(word, font=('Arial', 16, 'bold'))
    writer.hideturtle()

# Иницилизация
original_word = words.get_random_word()
word = '_' * len(original_word)
write_word(word)
errors = 0

def on_key_press (key):
    global errors
    global word
    if errors <= hangman.MAX_ERRORS:
        if key in original_word:
            word = words.fill_char(key, word, original_word)
            write_word(word)
            if word == original_word:
                print('You win')
        else:
            errors += 1
            hangman.build_hangman(errors)
    else:
        print('You lost')

# Handle press keys 'a' to 'z'
for i in range(ord('a'), ord('z') + 1):
    key = chr(i)
    turtle.onkey(functools.partial(on_key_press, key), key)

turtle.listen()
turtle.mainloop()


# def solution(gems):
#     size = len(set(gems))
#     dic = {gems[0]:1}
#     temp = [0, len(gems) - 1]
#     start, end = 0, 0
#
#     while(start < len(gems) and end < len(gems)):
#         if len(dic) == size:
#             if end - start < temp[1] - temp[0]:
#                 temp = [start, end]
#             if dic[gems[start]] == 1:
#                 del dic[gems[start]]
#             else:
#                 dic[gems[start]] -= 1
#             start += 1
#
#         else:
#             end += 1
#             if end == len(gems):
#                 break
#             if gems[end] in dic.keys():
#                 dic[gems[end]] += 1
#             else:
#                 dic[gems[end]] = 1
#
#     return [temp[0]+1, temp[1]+1]

def solutions(gems):
    set_gems = set(gems)
    dict_gemcnt = {keys:1 for keys in set_gems}
    start, end = 0, 0
    for gem in set_gems:
        c_lar= gems.index(gem)
        if c_lar > e:
            e = c_lar
    if s > gem:
        s += 1

print(solution(["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"]))
print(solution(["AA", "AB", "AC", "AA", "AC"]))
print(solution(["XYZ", "XYZ", "XYZ"]))
print(solution(["ZZZ", "YYY", "NNNN", "YYY", "BBB"]))


from ast import Interactive
from typing import Collection
import pygame
import logging
from settings import *
from player import Player
from overlay import Overlay
from sprites import GenericSprites, WaterSprites, TreeSprites, WildFlowerSprites, InteractionSprites, ParticleEffects
from pytmx.util_pygame import load_pygame
from support import *
from transition import Transition
from soil import SoilLayer
from sky import Rain, Sky
from random import randint
from menu import Menu

class Level:
    def __init__(self):
        logging.info('The level has started')
        # get the surface for the display
        self.display_surface = pygame.display.get_surface()

        # groups for the sprites
        self.all_sprites = CameraGroup()
        # keep track of things player can collide with
        self.collision_sprites = pygame.sprite.Group()

        # need to know where the trees are relative to player
        self.tree_sprites = pygame.sprite.Group()

        # interaction with objects
        self.interaction_sprites = pygame.sprite.Group()

        # populate soil properties
        self.soil_layer = SoilLayer(self.all_sprites, self.collision_sprites)

        # start it up
        self.setup()
        self.overlay = Overlay(self.player)

        # new transition class
        self.transition = Transition(self.reset_scene, self.player)

        # sky
        self.rain = Rain(self.all_sprites)
        self.raining = randint(0, 10) > 3
        self.soil_layer.raining = self.raining
        logging.info(f'is it raining? {self.raining}')
        self.sky = Sky()

        # shop
        self.menu = Menu(self.player, self.toggle_shop)
        self.shop_active = False

    def setup(self):

        # the map was created in "Tiled" software - mapeditor.org

        # load the map file
        map_file = 'data/map.tmx'
        tmx_data = load_pygame(map_file)

        # import a ton of different things ...

        # house layers need to be separate in pygame
        # bottom (floor) -> walls -> furniture bottom -> furniture top

        # bottom layer in house - order is important, make sure floor is drawn before bottom
        for layer in ['HouseFloor', 'HouseFurnitureBottom']:
            for x, y, surf in tmx_data.get_layer_by_name(layer).tiles():
                GenericSprites((x * TILE_SIZE, y * TILE_SIZE), surf,
                               self.all_sprites, LAYERS['house bottom'])
                if (LOGGINGOPTS == 'DEBUG'):
                    logging.debug(f'layer: {layer} x: {x} y: {y}')

        for layer in ['HouseWalls', 'HouseFurnitureTop']:
            for x, y, surf in tmx_data.get_layer_by_name(layer).tiles():
                GenericSprites((x * TILE_SIZE, y * TILE_SIZE), surf,
                               self.all_sprites, LAYERS['main'])
                if (LOGGINGOPTS == 'DEBUG'):
                    logging.debug(f'layer: {layer} x: {x} y: {y}')

        # fence
        for x, y, surf in tmx_data.get_layer_by_name('Fence').tiles():
            GenericSprites((x * TILE_SIZE, y * TILE_SIZE), surf,
                           [self.all_sprites, self.collision_sprites], LAYERS['main'])
            if (LOGGINGOPTS == 'DEBUG'):
                logging.debug(f'layer: {layer} x: {x} y: {y}')

        # water
        water_folder = 'graphics/water'
        water_frames = import_folder(water_folder)
        for x, y, surf in tmx_data.get_layer_by_name('Water').tiles():
            WaterSprites((x * TILE_SIZE, y * TILE_SIZE),
                         water_frames, self.all_sprites)
            if (LOGGINGOPTS == 'DEBUG'):
                logging.debug(f'frames: {water_frames} x: {x} y: {y}')

        # wildflowers
        # the image layer is slightly different as it was created differently in "Tiled" ...
        # ... but image placement logic is the same
        for obj in tmx_data.get_layer_by_name('Decoration'):
            WildFlowerSprites((obj.x, obj.y), obj.image, [
                              self.all_sprites, self.collision_sprites])
            if (LOGGINGOPTS == 'DEBUG'):
                logging.debug(f'decoration object: {obj} x: {x} y: {y}')

        # trees
        for obj in tmx_data.get_layer_by_name('Trees'):
            TreeSprites(
                pos=(obj.x, obj.y),
                surf=obj.image,
                groups=[
                    self.all_sprites, self.collision_sprites, self.tree_sprites],
                name=obj.name,
                player_add=self.player_add)
            if (LOGGINGOPTS == 'DEBUG'):
                logging.debug(f'tree object: {obj.name} x: {x} y: {y}')

        # collision tiles - these are hard coded in the map layer, not by the objects
        for x, y, surf in tmx_data.get_layer_by_name('Collision').tiles():
            # this is not drawn or updated - just has a non-visible collision surface
            GenericSprites((x * TILE_SIZE, y * TILE_SIZE),
                           pygame.Surface((TILE_SIZE, TILE_SIZE)), self.collision_sprites)

        # player
        # check the map layer and place the player in the 'start' position
        for obj in tmx_data.get_layer_by_name('Player'):
            if obj.name == 'Start':
                self.player = Player(
                    pos=(obj.x, obj.y),
                    group=self.all_sprites,
                    collision_sprites=self.collision_sprites,
                    tree_sprites=self.tree_sprites,
                    interaction=self.interaction_sprites,
                    soil_layer=self.soil_layer,
                    toggle_shop=self.toggle_shop)
            # check map layer and see if player is in 'bed' position
            if obj.name == 'Bed':
                InteractionSprites(
                    pos=(obj.x, obj.y),
                    size=(obj.width, obj.height),
                    groups=self.interaction_sprites,
                    name=obj.name)

            # trader
            if obj.name == 'Trader':
                InteractionSprites(
                    pos=(obj.x, obj.y),
                    size=(obj.width, obj.height),
                    groups=self.interaction_sprites,
                    name=obj.name)

        # create the floor
        floor_image = 'graphics/world/ground.png'
        GenericSprites(
            pos=(0, 0),
            surf=pygame.image.load(floor_image).convert_alpha(),
            groups=self.all_sprites,
            z=LAYERS['ground'])

    def toggle_shop(self):
        self.shop_active = not self.shop_active

    def player_add(self, item):
        self.player.item_inventory[item] += 1
        logging.info(f'inventory: {self.player.item_inventory}')

    def reset_scene(self):

        # plants
        self.soil_layer.update_plant_sprites()

        # soil
        self.soil_layer.remove_water_tiles()

        # rain
        self.raining = randint(0, 10) > 3
        self.soil_layer.raining = self.raining
        if self.raining:
            logging.info(f'is it raining? {self.raining}')
            self.soil_layer.water_all()

        # add apples on trees
        for tree in self.tree_sprites.sprites():
            # look for existing fruit
            for apple in tree.apple_sprites.sprites():
                # remove existing apples
                apple.kill()
            # purged all apples above, now re-add
            tree.create_fruit()

        # reset day/night
        self.sky.start_color = [255, 255, 255]

    def plant_collision(self):
        if self.soil_layer.plant_sprites:
            for plant in self.soil_layer.plant_sprites.sprites():
                if plant.harvestable and plant.rect.colliderect(self.player.hitbox):
                    # 1 add inventory
                    # 2 remove plant
                    # 3 animations
                    # 4 reset grid attribute
                    self.player_add(plant.plant_type)
                    plant.kill()
                    ParticleEffects(plant.rect.topleft, plant.image,
                                    self.all_sprites, z=LAYERS['main'])
                    self.soil_layer.grid[plant.rect.centery //
                                         TILE_SIZE][plant.rect.centerx // TILE_SIZE].remove('P')

    def run(self, dt):
        # remove previous screens and draw new one
        self.display_surface.fill('black')
        # call the new function for the camera group
        self.all_sprites.custom_draw(self.player)

        # updates
        if self.shop_active:
            self.menu.update()
        else:
            self.all_sprites.update(dt)
            self.plant_collision()

        # weather
        self.overlay.display()
        if self.raining and not self.shop_active:
            self.rain.update()

        # day time
        self.sky.display(dt)

        # check if need to change times
        if self.player.sleep:
            self.transition.play()

class CameraGroup(pygame.sprite.Group):
    def __init__(self) -> None:
        super().__init__()
        logging.info('The CameraGroup has started')

        self.display_surface = pygame.display.get_surface()

        # needed to place the player relative to the layers
        self.offset = pygame.math.Vector2()

    def custom_draw(self, player):
        # make the ground offset to the player from the camera pov
        self.offset.x = player.rect.centerx - SCREEN_WIDTH / 2
        self.offset.y = player.rect.centery - SCREEN_HEIGHT / 2

        for layer in LAYERS.values():
            # create a lambda function to sort lower value layers to be drawn below others based on 'y'
            for sprite in sorted(self.sprites(), key=lambda sprite: sprite.rect.centery):
                if sprite.z == layer:
                    offset_rect = sprite.rect.copy()
                    offset_rect.center -= self.offset
                    # changes the sprite's drawing in a position
                    self.display_surface.blit(sprite.image, offset_rect)
                    if (LOGGINGOPTS == 'DEBUG'):
                        logging.debug(f'layer is {sprite.z}')

                    # # find location of target hit
                    if (SPRITEDEBUG=='DEBUG'):
                        if sprite == player:
                            pygame.draw.rect(self.display_surface,'red',offset_rect,5)
                            hitbox_rect = player.hitbox.copy()
                            hitbox_rect.center = offset_rect.center
                            pygame.draw.rect(self.display_surface,'green',hitbox_rect,5)
                            target_pos = offset_rect.center + PLAYER_TOOL_OFFSET[player.status.split('_')[0]]
                            pygame.draw.circle(self.display_surface,'blue',target_pos,5)


# (C) 2021 Victor Suarez Rovere <suarezvictor@gmail.com>

#NOTES:
"""
#test command:
$
$ clang -E -I. ../tr_pipelinec.cpp > tr_pipelinec.E.cpp && python3 cflexc.py tr_pipelinec.E.cpp > tr_pipelinec.gen.cpp && clang -c tr_pipelinec.gen.cpp -o tr_pipelinec.gen.o && clang++ -O3 -I.. -fopenmp=libiomp5 -ffast-math `sdl2-config --cflags --libs` main.cpp -o tr  && ./tr

or for C:

$ clang -E -I. ../tr_pipelinec.cpp > tr_pipelinec.E.cpp && python3 cflexc.py tr_pipelinec.E.cpp > tr_pipelinec.gen.c && clang -c tr_pipelinec.gen.c -include "c_compat.h" -o tr_pipelinec.gen.o && clang++ -O3 -I.. -fopenmp=libiomp5 -ffast-math `sdl2-config --cflags --libs` main.c -o tr  && ./tr

"""
from clangparser import CFlexClangParser, CFlexBasicCPPGenerator

class CFlexCGenerator(CFlexBasicCPPGenerator):
    # surrounds cast for c-style casting
    def generate_cxx_functional_castexpr(self, target_type, expr, expr_type):
        #all C++ style casts to C style
        return self.generate_cstyle_cast_expr(target_type, expr, expr_type)

    def generate_cstyle_cast_expr(self, target_type, expr, expr_type):
        if target_type == expr_type: #same cast: not needed
          return self.generate_expr(expr)
        return super().generate_cstyle_cast_expr(target_type, expr, expr_type)

    def generate_struct(self, keyword, name, fields, hasfields):
        s = "typedef " if name and hasfields else ""
        s += keyword + " " + name  # keyword = struct or union
        if hasfields:
            s += " { " + self.generate_expr(fields) + "} " + name + ";"
        return s #+ ";\n"

    def generate_class(self, name, members):
        return "//CLASS " + name +" (classes not supported)"

    def generate_typedef_decl(self, decltyp, name):
        if "<" in decltyp: return "//typedef does not support for template types: " + decltyp
        return super().generate_typedef_decl(decltyp, name)

    #TODO: add "in/inout", etc

#TODO: be smarter to avoid confusing types like "int_hello_t"
#and make a general function for that
def is_numeric_type(typ):
	return len(typ)>=5 and typ[-2:]=="_t" and (typ[:3]=="int" or typ[:4]=="uint")

class CFlexPipelineCGenerator(CFlexCGenerator):
    def generate_typedef_decl(self, decltyp, name):
        if is_numeric_type(name):
          return "" #numerics are intrisic #super().generate_typedef_decl(decltyp, name)
        if "<" in decltyp: return "//typedef does not support for template types: " + decltyp
        return "#define " + name + " " + decltyp #replace typedef by macro

    def generate_function_decl(self, rettyp, name, argsexpr, stmtexpr):
        s = super().generate_function_decl(rettyp, name, argsexpr, stmtexpr)
        if not stmtexpr: #skip prototypes
            return "//" + s
        return s

    def generate_var_decl(self, decltyp, name, has_value, valueexpr, storage):
        if storage=="static" and decltyp.startswith("const "): #constants are translated to macros
          value = self.generate_expr(valueexpr)
          if not value.startswith("{"): value = "(" + value + ")" #surround, except initializer lists
          return "#define " + name + "\t" + value
        s = super().generate_var_decl(decltyp, name, has_value, valueexpr, storage)
        if storage: #skip all storage types different from ""
          return "//" + s
        return s

    def generate_binary_operator(self, lhs, op, rhs): #replace &&, || by &, |
        if op in ["||", "&&"]:
        	lhs = "((" + lhs + ")!=0)"
        	rhs = "((" + rhs + ")!=0)"
        	op = op[0]
        return lhs + " " + op + " " + rhs

    def generate_member_ref_expr(self, parentexpr, name, parenttyp):
        #this translates vector members ".r/.g/.b" to their alias ".x/.y/.z"
        paren = self.generate_expr(parentexpr)
        if not name: #maybe anonymous
          return paren
        if paren:
          paren += "."
          if parenttyp in ["fixed3", "float3"]:
            if name=="r": name="x"
            if name=="g": name="y"
            if name=="b": name="z"
        return paren + name

    def generate_literal(self, value, typ):
        if typ in ["float", "double"]:
          if value[-1] in ["f", "F"]: value = value[:-1] #remove "f" from literal
          return "(" + typ + ")" + value #do a cast on all defined constants
        return super().generate_literal(value, typ)

import sys
if __name__ == "__main__":
    sourcefile = sys.argv[1]
    cflags = sys.argv[2:]
    parser = CFlexClangParser(sourcefile, cflags)
    parser.comments_enabled = False #comment line to enable comments
    if not parser.print_diagnostics():
        #exit(1) #FIXME: return 1 to indicate error
        pass
    generated = parser.generate(CFlexPipelineCGenerator())
    print(generated)


"""
It is a file that crops the mp3 and srt file by the durations
which is getting from the srt file.
"""
import os
from ..helper.helper import run_bash, parse_time

class CropMp3Srt:
    """
    Gets the mp3 and srt files to crop
    """

    def __init__(self, filepath):
        self._path = filepath

    def crop(self):
        """
        It is a public function which is used from the other packages or files
        to perform main purpose
        """
        dirs = os.listdir(self._path)
        for file in dirs:
            if not file.startswith("crop_"):
                if file.endswith(".srt"):
                    self._crop_mp3_srt(file)

    def _crop_mp3_srt(self, filename):
        # extract video_id from the filename
        _video_id = filename[:-4]
        # read from the given file.
        with open(self._path + "/" + filename, 'r') as _filehandle:
            _filecontent_list = _filehandle.readlines()

            # it starts at index one and increases at adding 4
            for line in range(1, len(_filecontent_list), 4):
                _current_sub_num = _filecontent_list[line - 1][:-1]

                # to split the times (start and end times)
                _split__current_times = _filecontent_list[line].split(' ')

                # crop mp3 by the current times
                # PARSE TIMES
                # before given time, the duration time will get
                # as _split__current_times[:-1],
                # because it has "\n"
                _current_start = parse_time(_split__current_times[0])
                _current_end = parse_time(_split__current_times[2])
                # CALL THE CROPPING MP3 func
                self._crop_mp3(_video_id, _current_sub_num,
                               _current_start, _current_end)

                # CALL the function which WILL SAVE THE CURRENT
                # SUBTITLE to the TXT FILE
                self._save_sub_txt(_video_id, _current_sub_num,
                                   _filecontent_list[line + 1])

    def onetime_save_cropped_mp3_srt(self, video_id, sub_id,
                                     current_sub, start_time, end_time):
        """
        Saves each cropped file and performing cropping of the mp3 file
        :param video_id: is the current video id
        which is using to save cropped files
        :param sub_id: is using for naming to save cropped files
        :param current_sub: it saves to the new cropped text file
        :param start_time: is used to crop the mp3 file
        :param end_time: is used to crop the mp3 file
        """
        _current_start = parse_time(start_time)
        _current_end = parse_time(end_time)
        self._crop_mp3(video_id, str(sub_id), _current_start, _current_end)
        self._save_sub_txt(video_id, str(sub_id), current_sub)

    def _save_sub_txt(self, video_id, sub_id, current_subtitle):
        _new_srt_name = self._path + "/" + video_id\
                        + "_crop_" + sub_id + ".txt"
        with open(_new_srt_name, 'w+') as new_cropped_file:
            new_cropped_file.write(current_subtitle)
        new_cropped_file.close()

    def _crop_mp3(self, video_id, sub_id, start_time, end_time):
        """
        video_id is the video id from the youtube
        sub_id is the index from the subtitle list
        start time the starting point to crop
        """
        input_filename = self._path + "/" + video_id + ".mp3"
        new_file_name = self._path + "/" + video_id+"_crop_" + sub_id + ".mp3"

        # -n means never override
        command = "ffmpeg -n -i " + input_filename + " -ss  " + \
                  start_time + " -to " + end_time + " -c copy " \
                  + new_file_name + " 2> /dev/null"

        run_bash(command)


import logging
import re
from datetime import datetime, timezone
from zipfile import ZipFile
import pandas

from jal.widgets.helpers import g_tr
from jal.db.update import JalDB
from jal.constants import Setup, DividendSubtype, PredefinedCategory, PredefinedAsset

# -----------------------------------------------------------------------------------------------------------------------
class UralsibCapital:
    Header = '  Брокер: ООО "УРАЛСИБ Брокер"'
    PeriodPattern = "  за период с (?P<S>\d\d\.\d\d\.\d\d\d\d) по (?P<E>\d\d\.\d\d\.\d\d\d\d)"
    DividendPattern = "> (?P<DESCR1>.*) \((?P<REG_CODE>.*)\) (?P<DESCR2>.*) налог в размере (?P<TAX>\d+\.\d\d) удержан. НДС не облагается."
    BondInterestPattern = "Погашение купона №( -?\d+)? (?P<NAME>.*)"

    def __init__(self, parent, filename):
        self._parent = parent
        self._filename = filename
        self._statement = None
        self._account_id = 0
        self._settled_cash = {}

    def load(self):
        self._settled_cash = {}
        with ZipFile(self._filename) as zip_file:
            contents = zip_file.namelist()
            if len(contents) != 1:
                logging.error(g_tr('Uralsib', "Archive contains multiple files, only one is expected for import"))
                return False
            with zip_file.open(contents[0]) as r_file:
                self._statement = pandas.read_excel(io=r_file.read(), header=None, na_filter=False)
        if not self.validate():
            return False
        self.load_cash_balance()
        self.load_stock_deals()
        self.load_cash_tranactions()         # FIXME Routing raises errors if section is absent in report
        logging.info(g_tr('Uralsib', "Uralsib Capital statement loaded; Planned cash: ")
                     + f"{self._settled_cash[self._account_id]}")
        return True

    def validate(self):
        if self._statement[2][0] != self.Header:
            logging.error(g_tr('Uralsib', "Can't find Uralsib Capital report header"))
            return False
        account_name = self._statement[2][7]
        parts = re.match(self.PeriodPattern, self._statement[2][2], re.IGNORECASE)
        if parts is None:
            logging.error(g_tr('Uralsib', "Can't parse Uralsib Capital statement period"))
            return False
        statement_dates = parts.groupdict()
        report_start = int(datetime.strptime(statement_dates['S'], "%d.%m.%Y").replace(tzinfo=timezone.utc).timestamp())
        if not self._parent.checkStatementPeriod(account_name, report_start):
            return False
        logging.info(g_tr('Uralsib', "Loading Uralsib Capital statement for account ") +
                     f"{account_name}: {statement_dates['S']} - {statement_dates['E']}")
        self._account_id = self._parent.findAccountID(account_name)
        if self._account_id is None:
            return False
        return True

    def find_section_start(self, header, subtitle, columns, header_height=2) -> (int, dict):
        header_found = False
        start_row = -1
        headers = {}
        for i, row in self._statement.iterrows():
            if not header_found and (row[0] == header):
                header_found = True
            if header_found and ((subtitle == '') or (row[0] == subtitle)):
                start_row = i + 1  # points to columns header row
                break
        if start_row > 0:
            for col in range(self._statement.shape[1]):  # Load section headers from next row
                for row in range(header_height):
                    headers[self._statement[col][start_row+row]] = col
            start_row += header_height
        column_indices = {column: headers.get(columns[column], -1) for column in columns}
        for idx in column_indices:
            if column_indices[idx] < 0:
                logging.error(g_tr('Uralsib', "Column not found: ") + idx)
                start_row = -1
        return start_row, column_indices

    def load_stock_deals(self):
        cnt = 0
        columns = {
            "number": "Номер сделки",
            "date": "Дата сделки",
            "time": "Время сделки",
            "isin": "ISIN",
            "B/S": "Вид сделки",
            "price": "Цена одной ЦБ",
            "qty": "Количество ЦБ, шт.",
            "amount": "Сумма сделки",
            "accrued_int": "НКД",
            "settlement": "Дата поставки, плановая",
            "fee_ex": "Комиссия ТС"
        }

        row, headers = self.find_section_start("СДЕЛКИ С ЦЕННЫМИ БУМАГАМИ",
                                               "Биржевые сделки с ценными бумагами в отчетном периоде", columns)
        if row < 0:
            return False
        asset_name = ''
        while row < self._statement.shape[0]:
            if self._statement[0][row] == '' and self._statement[0][row + 1] == '':
                break
            if self._statement[0][row] == 'Итого по выпуску:' or self._statement[0][row] == '':
                row += 1
                continue
            try:
                deal_number = int(self._statement[0][row])
            except ValueError:
                asset_name = self._statement[0][row]
                row += 1
                continue

            asset_id = self._parent.findAssetID('', isin=self._statement[headers['isin']][row], name=asset_name)
            if self._statement[headers['B/S']][row] == 'Покупка':
                qty = self._statement[headers['qty']][row]
                bond_interest = -self._statement[headers['accrued_int']][row]
            elif self._statement[headers['B/S']][row] == 'Продажа':
                qty = -self._statement[headers['qty']][row]
                bond_interest = self._statement[headers['accrued_int']][row]
            else:
                row += 1
                logging.warning(g_tr('Uralsib', "Unknown trade type: ") + self._statement[headers['B/S']][row])
                continue

            price = self._statement[headers['price']][row]
            fee = self._statement[headers['fee_ex']][row]
            amount = self._statement[headers['amount']][row]
            if abs(abs(price * qty) - amount) >= Setup.DISP_TOLERANCE:
                price = abs(amount / qty)
            ts_string = self._statement[headers['date']][row] + ' ' + self._statement[headers['time']][row]
            timestamp = int(datetime.strptime(ts_string, "%d.%m.%Y %H:%M:%S").replace(tzinfo=timezone.utc).timestamp())
            settlement = int(datetime.strptime(self._statement[headers['settlement']][row],
                                               "%d.%m.%Y").replace(tzinfo=timezone.utc).timestamp())
            JalDB().add_trade(self._account_id, asset_id, timestamp, settlement, deal_number, qty, price, -fee)
            if bond_interest != 0:
                JalDB().add_dividend(DividendSubtype.BondInterest, timestamp, self._account_id, asset_id,
                                     bond_interest, "НКД", deal_number)
            cnt += 1
            row += 1
        logging.info(g_tr('Uralsib', "Trades loaded: ") + f"{cnt}")

    def load_cash_tranactions(self):
        cnt = 0
        columns = {
            "number": "№ операции",
            "date": "Дата",
            "type": "Тип операции",
            "amount": "Сумма",
            "description": "Комментарий"
        }
        operations = {
            'Ввод ДС': self.transfer_in,
            'Вывод ДС': self.transfer_out,
            'Налог': self.tax,
            'Доход по финансовым инструментам': self.dividend,
            'Погашение купона': self.interest
        }

        row, headers = self.find_section_start("ДВИЖЕНИЕ ДЕНЕЖНЫХ СРЕДСТВ ЗА ОТЧЕТНЫЙ ПЕРИОД", '',
                                               columns, header_height=1)
        if row < 0:
            return False

        while row < self._statement.shape[0]:
            if self._statement[0][row] == '' and self._statement[0][row + 1] == '':
                break

            operation = self._statement[headers['type']][row]
            if operation not in operations:   # not supported type of operation
                row += 1
                continue
            number = self._statement[headers['number']][row]
            timestamp = int(datetime.strptime(self._statement[headers['date']][row],
                                              "%d.%m.%Y").replace(tzinfo=timezone.utc).timestamp())
            amount = self._statement[headers['amount']][row]
            description = self._statement[headers['description']][row]

            operations[operation](timestamp, number, amount, description)

            cnt += 1
            row += 1
        logging.info(g_tr('Uralsib', "Cash operations loaded: ") + f"{cnt}")

    def transfer_in(self, timestamp, _number, amount, description):
        currency_name = JalDB().get_asset_name(JalDB().get_account_currency(self._account_id))
        text = g_tr('Uralsib', "Deposit of ") + f"{amount:.2f} {currency_name} " + \
               f"@{datetime.utcfromtimestamp(timestamp).strftime('%d.%m.%Y')}\n" + \
               g_tr('Uralsib', "Select account to withdraw from:")
        pair_account = self._parent.selectAccount(text, self._account_id)
        if pair_account == 0:
            return
        JalDB().add_transfer(timestamp, pair_account, amount, self._account_id, amount, 0, 0, description)

    def transfer_out(self, timestamp, _number, amount, description):
        currency_name = JalDB().get_asset_name(JalDB().get_account_currency(self._account_id))
        text = g_tr('Uralsib', "Withdrawal of ") + f"{-amount:.2f} {currency_name} " + \
               f"@{datetime.utcfromtimestamp(timestamp).strftime('%d.%m.%Y')}\n" + \
               g_tr('Uralsib', "Select account to deposit to:")
        pair_account = self._parent.selectAccount(text, self._account_id)
        if pair_account == 0:
            return                                       # amount is negative in XLS file
        JalDB().add_transfer(timestamp, self._account_id, -amount, pair_account, -amount, 0, 0, description)

    def dividend(self, timestamp, number, amount, description):
        parts = re.match(self.DividendPattern, description, re.IGNORECASE)
        if parts is None:
            logging.error(g_tr('Uralsib', "Can't parse dividend description ") + f"'{description}'")
            return
        dividend_data = parts.groupdict()
        asset_id = self._parent.findAssetID('', reg_code=dividend_data['REG_CODE'])
        if asset_id is None:
            logging.error(g_tr('Uralsib', "Can't find asset for dividend ") + f"'{description}'")
            return
        try:
            tax = float(dividend_data['TAX'])
        except ValueError:
            logging.error(g_tr('Uralsib', "Failed to convert dividend tax ") + f"'{description}'")
            return
        amount = amount + tax   # Statement contains value after taxation while JAL stores value before tax
        shortened_description = dividend_data['DESCR1'] + ' ' + dividend_data['DESCR2']
        JalDB().add_dividend(DividendSubtype.Dividend, timestamp, self._account_id, asset_id,
                             amount, shortened_description, trade_number=number, tax=tax)

    def interest(self, timestamp, number, amount, description):
        parts = re.match(self.BondInterestPattern, description, re.IGNORECASE)
        if parts is None:
            logging.error(g_tr('Uralsib', "Can't parse bond interest description ") + f"'{description}'")
            return
        interest_data = parts.groupdict()
        asset_id = JalDB().find_asset_like_name(interest_data['NAME'], asset_type=PredefinedAsset.Bond)
        if asset_id is None:
            logging.error(g_tr('Uralsib', "Can't find asset for bond interest ") + f"'{description}'")
            return
        JalDB().add_dividend(DividendSubtype.BondInterest, timestamp, self._account_id, asset_id,
                             amount, description, number)

    def tax(self, timestamp, _number, amount, description):
        JalDB().add_cash_transaction(self._account_id, self._parent.getAccountBank(self._account_id), timestamp,
                                     amount, PredefinedCategory.Taxes, description)

    def load_cash_balance(self):
        columns = {
            "settled_cash": "Плановый исходящий остаток"
        }

        row, headers = self.find_section_start("ПОЗИЦИЯ ПО ДЕНЕЖНЫМ СРЕДСТВАМ", '', columns)
        if row < 0:
            return False

        self._settled_cash[self._account_id] = self._statement[headers['settled_cash']][row]


# Capture multiple Faces from multiple users to be stored on a DataBase (dataset directory)
# ==> Faces will be stored on a directory: dataset/ (if does not exist, pls create one)
# ==> Each face will have a unique numeric integer ID as 1, 2, 3, etc

import cv2
from scripts.database_connection import Connection
from tkinter import *

class Photographer:
    def __init__(self, f, i, o="", face_id=None):
        self._face_id = face_id
        _to_database = [self._face_id, f, i, o]

        conn, cursor = Connection.connect("WorkAttendance")
        print (conn, cursor)
        try:
            cursor.execute("""INSERT INTO
                            WorkAttendance.dbo.FIO_Tabels(Табельный_номер, Фамилия, Имя, Отчество)
                            VALUES(?,?,?,?)""", _to_database)
            cursor.commit()
            cursor.close()
            conn.close()
        except Exception as e:
            print("[Ошибка!] " + str(e))
            window = Tk()
            window.wm_title("Ошибка!")
            Label(window, text=str(e),
                  font="arial 14").grid(row=0, column=0)
            window.mainloop()
            cv2.destroyAllWindows()

    def make_photo_set(self):
        cam = cv2.VideoCapture(0)
        cam.set(5, 1900)  # set video width
        cam.set(5, 1000)  # set video height

        face_detector = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')
        eye_detector = cv2.CascadeClassifier('Cascades/haarcascade_eye.xml')

        print("[INFO] Инициализация захвата лица. " +
              "\nСмотрите в камеру и равномерно, медленно поворачивайте лицо по сторонам.")

        # Initialize individual sampling face count
        count = 0

        while True:
            ret, img = cam.read()
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = face_detector.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(20, 20)
            )

            for (x, y, w, h) in faces:
                face_saved = False
                count += 1
                roi_gray = gray[y:y+h, x:x+w]

                eyes = eye_detector.detectMultiScale(
                    roi_gray,
                    scaleFactor=1.1,
                    minNeighbors=5,
                    minSize=(5, 5)
                )

                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
                    cv2.imshow('video', img)
                    if not face_saved:
                        # Save the captured image into the dataset folder
                        cv2.imwrite("dataset/User." + str(self._face_id) + '.' + str(count) + ".jpg",
                                    gray[y:y+h, x:x+w])
                        face_saved = True

            k = cv2.waitKey(100) & 0xff  # Press 'ESC' for exiting video
            if k == 27:
                break
            elif count >= 150:  # Take 150 face sample and stop video
                break

        # Do a bit of clean up
        print("[INFO] Exiting Program and cleaning up stuff")
        cam.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    face_id = input("Введите табельный номер работика и нажмите <Return> ==> ")
    f, i, o = input("Введите ФИО ==> ").split(" ")
    Photographer(f, i, o, face_id).make_photo_set()
else:
    "Вы исользуете frontal_face_dataset_with_database_with_control как библиотеку."


from app import app
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import json

class IneffableStorage(object):

    def __init__(self):
        """ Initialize the class """
        self.connection = None
        self.bucket = None

    def setup_connection(self):
        """ Setup the connection to S3 """
        if self.connection is None:
            self.connection = S3Connection(
                aws_access_key_id=app.config['AWS_ACCESS_KEY_ID'],
                aws_secret_access_key=app.config['AWS_SECRET_ACCESS_KEY']
            )

    def setup_bucket(self):
        """ Setup the connection to the S3 bucket """
        self.setup_connection()
        if self.bucket is None:
            self.bucket = self.connection.get_bucket(app.config['AWS_S3_BUCKET'])

    def get_bucket(self):
        """ Get an S3 bucket """
        self.setup_bucket()
        return self.bucket

    def get_key(self, key_name):
        """ Get a key for a specific bucket """
        self.setup_bucket()

        key = Key(self.bucket)
        key.key = key_name

        return key

ineffable_storage = IneffableStorage()


# -- coding: utf-8 --
import tensorflow as tf
import pandas as pd
import numpy as np
import pymysql
import sys
sys.path.append(sys.path.append('../'))  # 导入上一级目录中的包

from settings import *

# 查询课程信息
# 课程信息查询,例：离散数学及其应用
# 课程编号，课程名称，公司企业名称，课程编码，课程类别，学分，是否考试，上传时间，标签
def courInfo(courseName):
    db = pymysql.connect("10.134.149.182", "F3235631", "3235631", "university")
    cursor = db.cursor()
    cursor.execute(
        "select c.CourseId,c.Name,cp.Name,c.SerialKey,cs.Name,c.CreditValue,c.Exam,c.PublishDate,c.Tags from Course as c, Company as cp,CourseSerial as cs where c.Name = '%s' and c.SerialId = cs.SerialId and c.CompanyId = cp.CompanyId" % (
            courseName))
    data = cursor.fetchall()
    return data[0]

# 构建课程分析提建议所需数据
# 模型需要的数据：课程类型，学分，是否考试，课件数量，课件类型，课件时长，pdf页数
def getCourseData(courseid):
    db = pymysql.connect("10.134.149.182", "F3235631", "3235631", "university")
    cursor = db.cursor()
    cursor.execute(
        "select CourseId,SerialId,CreditValue,Exam from Course where Deleted=0 and CourseId= %d" % (courseid))
    data = list(cursor.fetchall()[0])
    cursor.execute("select count(*),Type,avg(Duration),avg(Page) from CourseWare where CourseId= %d" % (courseid))
    # data.append(list(cursor.fetchall()[0]))
    data = data + list(cursor.fetchall()[0])
    db.close()

    dic = {"s1": [0], "s2": [0], "s3": [0], "s4": [0], "s5": [0], "s6": [0], "s7": [0], "s8": [0], "s9": [0],
           "creditvalue": [data[2]],
           "exam": [data[3]],
           "warenum": [data[4]],
           "type_1": [0], "type_2": [0], "type_3": [0],
           "duration": [float(data[6])],
           "page": [float(data[7])]}
    dataDF = pd.DataFrame(dic)

    dataDF[dataDF.columns[data[1] - 1]] = 1
    if data[5] == 'pdf':
        dataDF[dataDF.columns[12]] = 1
    elif data[5] == 'mp4':
        dataDF[dataDF.columns[13]] = 1
    else:
        dataDF[dataDF.columns[14]] = 1

    return dataDF

def multilayer_perceptron(_X, _w1, _w2, _b1, _b2, _wout, _bout):
    """
    计算课程属于各个列别的可能性大小
    :param _X: 待预测课程的数据
    :param _w1: 从模型读入的参数
    :return: 课程属于各个列别的可能性大小
    """
    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _w1), _b1))
    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _w2), _b2))
    return tf.matmul(layer_2, _wout) + _bout

def courPred(data, MOUDEL_PATH):
    """
    读取模型，预测课程类别
    :param data: 待预测课程的数据
    :param MOUDEL_PATH: 模型存储路径
    :return: 预测课程类别0,1,2,3，分别对应报告中课程类别一，二，三，四
             0 —— 一：需改进
             1 —— 二：较受欢迎
             2 —— 四：非常受欢迎，个例
             3 —— 三：非常受欢迎
    """
    data = np.array(data)
    data = data.astype(np.float32)

    tf.reset_default_graph()
    # 允许参数复用 or 判断是否复用了，已经有了就不再重新创建了
    # tf.get_variable_scope().reuse_variables()
    if "w1" not in vars():
        n_hidden_1 = 256
        n_hidden_2 = 128
        n_input = 17
        n_classes = 4
        w1 = tf.Variable(tf.random_normal([n_input, n_hidden_1]), name="w1"),
        w2 = tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name="w2")
        b1 = tf.Variable(tf.random_normal([n_hidden_1]), name="b1")
        b2 = tf.Variable(tf.random_normal([n_hidden_2]), name="b2")
        wout = tf.Variable(tf.random_normal([n_hidden_2, n_classes]), name="wout")
        bout = tf.Variable(tf.random_normal([n_classes]), name="bout")
        saver = tf.train.Saver()
    else:
        pass

    sess = tf.Session()
    saver.restore(sess, MOUDEL_PATH)
    pred = sess.run(multilayer_perceptron(data, w1[0], w2, b1, b2, wout, bout))
    sess.close()
    return pred.argmax()

# 类别为二，三，四：受欢迎
def courWithoutAdvise():
    return "预测课程受欢迎！"

# 类别为一：需改进
# 维度：是否考试，课件类型、课件数量、时长/页数
def courAdvise(data, STD_COURSE_DATA):
    advice = '该课程仍需改进。\n'
    # 考试
    if data['exam'][0] == 0:
        advice += '课程可增加考试，提升学员对课程的参与度。\n'

    # 课件类型
    if data['type_1'][0] == 0:
        advice += "在受欢迎的课程中，有%s的课程使用了pdf类型的课件，建议课程添加pdf课件便于学员学习复习使用。\n" % (STD_COURSE_DATA['courWarePDFRate'])

    # pdf类，课件少，页码数多
    if data['warenum'][0] < STD_COURSE_DATA['courAvgWareNum'] and data['page'][0] > STD_COURSE_DATA['courAvgPage']:
        advice += "在受欢迎课程中，平均课件数量为%s，平均页码数为%s，本课程有%s的课件数量和%s的平均页码数，建议酌情减少每个课件的\
        页数，增加课件数量，便于学员使用碎片化时间学习。\n" % (
            STD_COURSE_DATA['courAvgWareNum'], STD_COURSE_DATA['courAvgPage'], data['warenum'][0], data['page'][0])

    # MP4类，课件少，平均时间长
    if data['warenum'][0] < STD_COURSE_DATA['courAvgWareNum'] and data['duration'][0] > STD_COURSE_DATA['courAvgTime']:
        advice += "在受欢迎课程中，平均课件数量为%s，视频课程平均时长为%s，本课程有%s个课件数量，每个课件平均时长%s分钟，建议酌情减少每个课件的\
        时长，增加课件数量，便于学员使用碎片化时间学习。\n" % (
            STD_COURSE_DATA['courAvgWareNum'], STD_COURSE_DATA['courAvgTime'], data['warenum'][0],
            round(data['duration'][0] / 60))

    if len(advice) < 10:
        advice = '暂无改进建议'

    return advice

def getAdvise(courseid):
    data = getCourseData(courseid)
    # 2.2 预测课程是否受欢迎
    courTypePred = courPred(data, MOUDEL_PATH)
    # 2.3 如果是受欢迎的类别or不受欢迎的类别分别调用不同函数
    if courTypePred != 0:
        advice = courWithoutAdvise()
    else:
        advice = courAdvise(data, STD_COURSE_DATA)
    return advice

if __name__ == '__main__':
    # 1、查询课程基本信息
    courBasicInfo = courInfo('离散数学及其应用')
    print(courBasicInfo)
    # 2、获得改进建议
    # 2.1 获得需要分析的课程的数据
    data = getCourseData(9477)
    # 2.2 预测课程是否受欢迎
    courTypePred = courPred(data, MOUDEL_PATH)
    # 2.3 如果是受欢迎的类别or不受欢迎的类别分别调用不同函数
    if courTypePred != 0 :
        advice = courWithoutAdvise()
    else :
        advice = courAdvise(data, STD_COURSE_DATA)
    print(advice)


import numpy as np

m1 = (
    (1, -1),
    (1, 2)
)
matrix = np.array(
    m1
)
print(matrix)

output = np.array(
    (0, 8)
)

solve = np.linalg.solve(matrix, output)  # 线性方程组求解 .
print(solve)

X = np.arange(-5, 5, 0.25)
a1 = np.arange(0, 10, 0.5)
print(a1)


from __future__ import absolute_import
import random

from src.event import SignalEvent

class TestRandomStrategy(object):
    def __init__(self, instrument, units, events):
        self.instrument = instrument
        self.units = units
        self.events = events
        self.ticks = 0
        self.invested = False

    def calculate_signals(self, event):
        if event.type == "TICK":
            self.ticks += 1
            if self.ticks % 5 == 0:
                if self.invested == False:
                    signal = SignalEvent(self.instrument, "market", "buy")
                    self.events.put(signal)
                    self.invested = True
                else:
                    signal = SignalEvent(self.instrument, "market", "sell")
                    self.events.put(signal)
                    self.invested = False


from keras.utils import to_categorical
import numpy as np
import pandas as pd
import time

TRAIN_SIZE = 30000
TEST_SIZE = 2

def label_generator(num_of_labels, size):
	"""
	Create a two coloum label set
	:param size1:
	:param size2:
	:return:
	"""
	lab = np.zeros((size, num_of_labels), dtype=np.float)
	length_per_label = int(size / num_of_labels)
	for i in range(num_of_labels):
		lab[(i * length_per_label):((i+1) * length_per_label), i] = 1.0

	return lab

def suffle_data_label(a, b):
	"""
	Utility function to shuffle data and labels
	:param a:
	:param b:
	:return:
	"""
	c = np.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)]
	np.random.shuffle(c)
	a2 = c[:, :a.size // len(a)].reshape(a.shape)
	b2 = c[:, a.size // len(a):].reshape(b.shape)
	return a2, b2

def split_train_test(selex_data, train_size, test_size):
	"""
	split the selex inputs into train and test sets
	:param selex0:
	:param selex1:
	:param train_size:
	:return:
	"""
	split_size = len(selex_data)
	x_train = np.array([])
	x_test = np.array([])
	for selex in selex_data:
		np.random.shuffle(selex)
		if len(x_test) == 0:
			x_train = selex[0:int(train_size/split_size), :, :, :]
			x_test = selex[int(train_size / split_size)+1:int(train_size / split_size)+1+int(test_size/split_size), :, :, :]
			continue
		x_train = np.concatenate((x_train, selex[0:int(train_size/split_size), :, :, :]), axis=0)
		x_test = np.concatenate((x_test, selex[int(train_size / split_size)+1:int(train_size / split_size)+1+int(test_size/split_size), :, :, :]), axis=0)

	y_train = label_generator(split_size, train_size)
	y_test = label_generator(split_size, test_size)

	return x_train, x_test, y_train, y_test

def oneHot(string):
	"""
	One Hot encoding of a DNA sequence ACGT -> 0123 -> [1, 0, 0, 0], [0, 1, 0, 0], ...
	:param string: DNA sequence with A, C, G, or T
	:return: a matrix of the encoded sequence
	"""

	string = string.replace('A', '0')
	string = string.replace('C', '1')
	string = string.replace('G', '2')
	string = string.replace('T', '3')
	data = list(map(int, string))
	return to_categorical(data, 4)

def pbm_dataset_generator(filename):
	"""
	Open a PBM file andtransform it to a numpy encoded list
	:param filename: a PBM file with N lines of DNA sequences
	:return: an Nx4 numpy array
	"""
	f = open(filename, 'r')
	data = []
	for line in f:
		data.append(oneHot(line[0:60]))
	f.close()
	arr = np.array(data)
	return arr

def selex_dataset_generator(filename, data_to_load=TRAIN_SIZE+TEST_SIZE, selex_size=36):
	"""
	Open a selex file and transform it to two numpy lists.
	One for the onehot encoded DNA sequence
	One for the number of occurences
	:param filename:
	:return:
	"""
	t = time.time()
	f = open(filename, 'r')  # pd.read_csv(filename, delimiter='\t', usecols=[0], header=-1)
	dat = f.read().split()[0::2]
	data = []
	n = len(dat)
	idx = np.arange(n)
	# np.random.shuffle(idx)

	for i in range(data_to_load):
		encoded_line = oneHot(dat[idx[i]])
		padding = int((selex_size - len(encoded_line)) / 2)
		encoded_line = np.concatenate((np.concatenate((0.25 * np.ones((padding, 4)), encoded_line)), 0.25 * np.ones((padding, 4))))
		data.append(encoded_line)
		""" Reverse complement"""
		# encoded_line_rev = np.zeros(encoded_line.shape)
		# encoded_line_rev[:, 0] = encoded_line[:, 2]
		# encoded_line_rev[:, 1] = encoded_line[:, 3]
		# encoded_line_rev[:, 2] = encoded_line[:, 0]
		# encoded_line_rev[:, 3] = encoded_line[:, 1]
		# encoded_line_rev = encoded_line_rev[::-1]
		# data.append(encoded_line_rev)

	data = np.asarray(data)
	print('Took ', time.time() - t, ' seconds to encode data, for ', filename)
	return data, None

def save_dataset(x_train, x_test, y_train, y_test):
	import h5py
	hdf5_file = h5py.File('data_tf1.hdf5', mode='w')
	hdf5_file.create_dataset("x_train", data = x_train)
	hdf5_file.create_dataset("y_train", data = y_train)
	hdf5_file.create_dataset("x_test", data=x_test)
	hdf5_file.create_dataset("y_test", data=y_test)
	hdf5_file.close()

def load_dataset():
	import h5py
	f = h5py.File('data_tf1.hdf5', 'r')
	x_train = f["x_train"].value
	y_train = f["y_train"].value
	x_test = f["x_test"].value
	y_test = f["y_test"].value
	return x_train, x_test, y_train, y_test

def generate_data(PBM_FILE, SELEX_FILES, GENERATE_DATASET=True, train_size=100000, SELEX_SIZE=36, test_size=100000):
	"""
	Generate entire dataset
	:param PBM_FILE: PBM file name
	:param SELEX_FILES: SELEX filename list
	:param GENERATE_DATASET: Boolean to load from file dataset or not
	:param train_size: Size of output training data
	:param SELEX_SIZE: To how much to pad the selex sequence
	:param test_size: Size of output testing data
	:return:
	"""
	pbm_data = pbm_dataset_generator(PBM_FILE)
	if GENERATE_DATASET:  # load data and OneHot encode data
		print(pbm_data.shape)
		selex_4, _ = selex_dataset_generator(SELEX_FILES[-1], int((train_size+test_size)/2+1), selex_size=SELEX_SIZE)
		# selex_3, _ = selex_dataset_generator(SELEX_FILES[-2], (train_size+test_size)/5+1, selex_size=SELEX_SIZE)
		# selex_2, _ = selex_dataset_generator(SELEX_FILES[-3], (train_size+test_size)/5+1, selex_size=SELEX_SIZE)
		# selex_1, _ = selex_dataset_generator(SELEX_FILES[-4], (train_size+test_size)/5+1, selex_size=SELEX_SIZE)
		selex_0, _ = selex_dataset_generator(SELEX_FILES[0], int((train_size+test_size)/2+1), selex_size=SELEX_SIZE)

		selex_data = list()
		selex_data.append(selex_0.reshape((len(selex_0), SELEX_SIZE, 4, 1)))
		# selex_data.append(selex_1.reshape((len(selex_1), SELEX_SIZE, 4, 1)))
		# selex_data.append(selex_2.reshape((len(selex_2), SELEX_SIZE, 4, 1)))
		# selex_data.append(selex_3.reshape((len(selex_3), SELEX_SIZE, 4, 1)))
		selex_data.append(selex_4.reshape((len(selex_4), SELEX_SIZE, 4, 1)))

		x_train, x_test, y_train, y_test = split_train_test(selex_data, train_size, test_size)
		save_dataset(x_train, x_test, y_train, y_test)
	else:  # Load from data_tf1.hdf5 file
		t = time.time()
		x_train, x_test, y_train, y_test = load_dataset()
		print('Took ', time.time() - t, ' seconds to load data from h5py file')
	return x_train, x_test, y_train, y_test, pbm_data

import sys

def get_argv():
    """
    Get input from sys.argv
    :return:
    """
    if len(sys.argv) < 3:
        print("Length of input arguments is ", len(sys.argv))
        print("\nUsage:\n python main.py pbm_file SELEX_FILE_0 SELEX_FILE_1 ...")
        print("\nUsage2:\n python main.py pbm_file #of_selex_0 #of_selex_1 ...")
        sys.exit(0)

    PBM_FILE = sys.argv[1]
    SELEX_FILES = [sys.argv[i] for i in range(2, len(sys.argv))]
    if SELEX_FILES[0].isdigit():
        SELEX_FILES = list(map(int, SELEX_FILES))
    return PBM_FILE, SELEX_FILES

def parse_args(PBM_FILE, SELEX_FILES):
    """
    Transform selex numbers to filenames.
    :param PBM_FILE: Required for full path
    :param SELEX_FILES: List of numbers of SELEX cycles, or filenames
    :return: Filenames of everything
    """
    selex = SELEX_FILES
    if len(SELEX_FILES) < 1:
        return None, None
    if type(SELEX_FILES[0]) == int:
        base = PBM_FILE.split('_')[0]
        selex = [base+'_selex_'+str(i)+'.txt' for i in SELEX_FILES]

    return PBM_FILE, selex

if __name__ == '__main__':
	PBM_FILE, SELEX_FILES = 'train/TF1_pbm.txt', [0, 1, 2, 3, 4]  # get_argv()
	print(PBM_FILE)
	print(SELEX_FILES)
	# PBM_FILE, SELEX_FILES =
	PBM_FILE, SELEX_FILES = parse_args(PBM_FILE, SELEX_FILES)
	generate_data(PBM_FILE, SELEX_FILES, test_size=TEST_SIZE, train_size=TRAIN_SIZE)


inp = int(input())
fat = 1
soma = 0

for k in range(inp + 1):
  for i in range( 1, k + 1 ):
    fat = fat * i
  soma = soma + fat
  fat = 1

print (soma)


# Program for array rotation
# Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.
# Input : [1, 2, 3, 4, 5, 6, 7]
# Output : 3 4 5 6 7 1 2

print("==========Calling functions============")

def leftRotate(arr,d,n):
    for i in range(d):
        leftRotateByOne(arr,n)

def leftRotateByOne(arr,n):
    temp = arr[0]
    for i in range(n-1):              # (n-1) array starts from  0 and last filled with temp
        arr[i] = arr[i+1]             # [2,3,4,5,6,7]
    arr[n-1] = temp                   # [3,4,5,6,7,1]

def printArray(arr,n):
    for i in range(n):
        print("%d"%arr[i],end=" ")

arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

print("\n===============One Function=============")

def splitArray(arr,d,n):
    for i in range(d):
        temp = arr[0]
        for j in range(n-1):
            arr[j] = arr[j+1]
        arr[n-1] = temp

arr = [1, 2, 3, 4, 5, 6, 7]
n = len(arr)
splitArray(arr,2,n)

for i in range(n):
    print("%d"%arr[i],end=" ")


#!/usr/bin/python3

from typing import List
import json
from bplib.butil import TreeNode, arr2TreeNode, btreeconnect, aprint

class Solution:
    def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
        intervals = sorted(intervals)
        current_start = -1
        current_end = -1
        for [start, end] in intervals:
            if current_end > start:
                return False
            current_end = end
        return True

arr = json.loads(input())

sol = Solution()
print(sol.canAttendMeetings(arr))


area_side = int(input())
tile_width = float(input())
tile_height = float(input())
bench_width = int(input())
bench_length = int(input())
area_to_cover = area_side*area_side - bench_length*bench_width
tile_area = tile_height*tile_width
tiles_needed = area_to_cover/tile_area
time = tiles_needed*0.2

print(round(tiles_needed, 2))
print(round(time, 2))


india = ["mumbai", "banglore", "chennai", "delhi"]
pakistan = ["lahore","karachi","islamabad"]
bangladesh = ["dhaka", "khulna", "rangpur"]

city_name = input("Enter a city name: ")
city_name = str(city_name)

if city_name in india:
    print("This city is in India!")
elif city_name in pakistan:
    print("This city is in Pakistan!")
elif city_name in bangladesh:
    print("This city is in Bangladesh!")
else:
    print("Sorry I cant identify which area this city is in")


from Supersymmetry_nonBPS_3pt import*
from Supersymmetry_nonBPS_3pt_fourier import*

def etaP_Mul(amplitude, multiplier=sqrt(2)):
    result = 0
    a = multiplier
    for susy in amplitude.arr:
        temp = susy.copy()
        if '01' in susy.etalist:
            temp *= a
        if '02' in susy.etalist:
            temp *= a
        result += temp
    return result

def etaPf_Mul(amplitude, multiplier=sqrt(2)):
    result = 0
    a = multiplier
    for susy in amplitude.arr:
        temp = susy.copy()
        if '01f' in susy.etalist:
            temp *= a
        if '02f' in susy.etalist:
            temp *= a
        result += temp
    return result

factorized = {}
factorized[1] = {}
factorized[2] = {}

factorized[1][1] = FZ*etaP[1]*delta[1]-delta[1]*Ha[1] - \
    (FZ*GZ)*delta[1]*Hb[2]*etaP[1]*etaP[2]+GZ*delta[1]*Ha[1]*Hb[2]*etaP[2]
factorized[1][2] = FZ*etaP[2]*delta[2]-delta[2]*Ha[2] + \
    (FZ*GZ)*delta[2]*Hb[1]*etaP[1]*etaP[2]+(GZ)*delta[2]*Ha[2]*Hb[1]*etaP[1]

factorized[2][1] = FZ*delta[1]*Ha[1]*Hb[1]+delta[1]*etaP[1]*Hb[1]+GZ*delta[1]
factorized[2][2] = FZ*delta[2]*Ha[2]*Hb[2]+delta[2]*etaP[2]*Hb[2]+GZ*delta[2]

factorizedf = {}
factorizedf[1] = {}
factorizedf[2] = {}

factorizedf[1][1] = FZ*etaPf[1]*deltaf[1]-deltaf[1]*Haf[1] - \
    (FZ*GZ)*deltaf[1]*Hbf[2]*etaPf[1] * \
    etaPf[2]+GZ*deltaf[1]*Haf[1]*Hbf[2]*etaPf[2]
factorizedf[1][2] = FZ*etaPf[2]*deltaf[2]-deltaf[2]*Haf[2] + \
    (FZ*GZ)*deltaf[2]*Hbf[1]*etaPf[1]*etaPf[2] + \
    (GZ)*deltaf[2]*Haf[2]*Hbf[1]*etaPf[1]

factorizedf[2][1] = FZ*deltaf[1]*Haf[1] * \
    Hbf[1]+deltaf[1]*etaPf[1]*Hbf[1]+GZ*deltaf[1]
factorizedf[2][2] = FZ*deltaf[2]*Haf[2] * \
    Hbf[2]+deltaf[2]*etaPf[2]*Hbf[2]+GZ*deltaf[2]

if __name__ == '__main__':
    print('FZ = {}\nGZ = {}'.format(FZ, GZ))
    print((factorized[1][1]*factorized[1][2]-solution[1]).vanish(1e-8))
    print(((-x12)*factorized[2][1]*factorized[2][2]-solution[2]).vanish(1e-8))
    print((etaPf_Mul(factorizedf[1][2]) -
          FT1to2(etaP_Mul(factorized[1][1]))).vanish(1e-8))
    print((etaPf_Mul(factorizedf[1][1], -sqrt(2)) -
          FT2to1(etaP_Mul(factorized[1][2]))).vanish(1e-8))


from config import data_db_schema,data_ocr
from repositories import DataRepo
from utilities import LANG_CODES
import logging
from logging.config import dictConfig
log = logging.getLogger('file')

repo = DataRepo()

class OcrModel:
    def __init__(self):
        self.db     =   data_db_schema
        self.col    =   data_ocr

    def compute_ocr_data_filters(self,ocr_data):
        log.info("Updating ocr filter params!")
        try:

            for filter in ocr_data["filters"]:

                if filter["filter"]         ==  "collectionMethod.collectionDescription":
                    collection_method       =   repo.distinct("collectionMethod.collectionDescription",self.db,self.col)
                    filter["values"]        =   self.get_collection_details(collection_method)
                    log.info("collected availabel collection methods")
                elif filter["filter"]       ==  "sorceLanguage":
                    langres                 =   repo.distinct("sourceLanguage",self.db,self.col)
                    filter["values"]        =   self.get_language_filter(langres)
                    log.info("collected available languages")
                else:
                    response                =   repo.distinct(filter["filter"],self.db,self.col)
                    filter["values"]        =   self.get_formated_data(response)
                    log.info(f"collected available {filter['label']}")

            return ocr_data
        except Exception as e:
            log.info(f"Exception on OcrModel :{e}")

    def get_language_filter(self,lang_list):
        log.info("formatting language filter")
        values = []
        for data in lang_list:
            attribute = {}
            attribute["value"] = data
            attribute["label"] = LANG_CODES.get(data)
            values.append(attribute)
        return values

    def get_collection_details(self,collection_methods):
        log.info("formatting collection method,details filter")
        values = []
        for data in collection_methods:
            collection = {}
            collection["value"] = data
            collection["label"] = ' '.join(data.split('-')).title()
            tools =[]
            if data in ['web-scraping-ocr']:
                ocrtools = repo.distinct("collectionMethod.collectionDetails.ocrTool",self.db,self.col)
                tools.append({"OCR Tool" : ocrtools })

            collection["tool/method"] = tools
            values.append(collection)
        return values

    def get_formated_data(self, attribute_data):
        log.info("formatting filter attribute")
        values = []
        for data in attribute_data:
            attribute = {}
            attribute["value"] = data
            attribute["label"] = str(data).title()
            values.append(attribute)
        return values

# Log config
dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] {%(filename)s:%(lineno)d} %(threadName)s %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {
        'info': {
            'class': 'logging.FileHandler',
            'level': 'DEBUG',
            'formatter': 'default',
            'filename': 'info.log'
        },
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'default',
            'stream': 'ext://sys.stdout',
        }
    },
    'loggers': {
        'file': {
            'level': 'DEBUG',
            'handlers': ['info', 'console'],
            'propagate': ''
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['info', 'console']
    }
})


from pyBrainNetSim.generators.network import SensorMoverProperties
from pyBrainNetSim.models.individuals import SensorMover

class SensorMoverEvolutionarySolver(object):
    """
    An Evolutionary solver to find the best 'SensorMover' for the environment. This simulates I individuals at time 0.
    Each individual moves in the environment, using energy, and "trying" to find the food source. An individual must
    find the food or they will perish.

    At a defined time period P, the remaining individuals mate to produce M offspring individuals with a mixture of the
    two mating individual's attributes. The choice/likelihood to mate is determined by internal energy levels of
    individuals.

    In this way, the idea is that the individuals with the "best" configurations eventually emerge from the population.

    """
    def __init__(self, environment, sensormover_distribution=None, num_individuals=100, max_generations = 10,  *args, **kwargs ):
        self.environment = environment
        self.sm_dist = sensormover_distribution if sensormover_distribution is not None\
            else SensorMoverProperties()
        self.n = 0  # iteration number
        self.g = 0  # generation number
        self.num_individuals = num_individuals
        self.max_generations = max_generations
        # Create N individuals @ t0
        self.data = {}

    def solve(self):
        while self.n < self.max_generations:
            self.simulate_generation()
            self.evolve()

    def simulate_generation(self):
        ts, i= [], 0
        while i < self.num_individuals:
            ts.append(SensorMover(self.environment, position=(5, 5),
                                  initial_network=self.sm_dist.create_digraph(),
                                  **{'initial_fire':'prescribed', 'prescribed':['S0']}))
            i += 1
        self.data['G%d' % self.g] = ts

    def evolve(self, *args, **kwargs):
        """
        Defines how individuals evolve from one generation to the next
        :param args:
        :param kwargs:
        :return:
        """
        self.n += 1


__author__ = "Michael Chambers"
__copyright__ = "Copyright 2019, Michael Chambers"
__email__ = "greenkidneybean@gmail.com"
__license__ = "MIT"

from snakemake.shell import shell

log = snakemake.log_fmt_shell(stdout=False, stderr=True)

shell(
    "samtools faidx {snakemake.params} {snakemake.input[0]} > {snakemake.output[0]} {log}"
)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

def trim_fields(apps, schema_editor):
    trim_extra_account(apps, schema_editor, "facebook")
    trim_extra_account(apps, schema_editor, "github")
    trim_extra_account(apps, schema_editor, "twitter")

def trim_extra_account(apps, schema_editor, types):
    Users = apps.get_model('accounts', 'User')
    for user in Users.objects.all():
        field = getattr(user, types)
        if not field:
            continue
        tmpString = field.split("/")[-1]
        if len(field) >= 15:
            setattr(user, types, tmpString[:14])
            user.save()

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_auto_20141218_1755'),
    ]

    operations = [
        migrations.RunPython(trim_fields),
        migrations.AlterField(
            model_name='user',
            name='facebook',
            field=models.CharField(max_length=15, null=True, blank=True),
            preserve_default=True,
        ),

        migrations.AlterField(
            model_name='user',
            name='github',
            field=models.CharField(max_length=39, null=True, verbose_name='github', blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='user',
            name='twitter',
            field=models.CharField(max_length=15, null=True, blank=True),
            preserve_default=True,
        ),
    ]


import math
def secante(x, y):
    #x = Xn
    #y = Xn-1
    for i in range(6):
        aux = x
        x = (y*f(x) - x*f(y))/(f(x) - f(y))
        y = aux
    return x
def f(x):
    return x**2 + 25600/(((240/math.sqrt(900 - x**2)*x)/30) - x)**2 - 20**2

print("Valor de L aproximadamente: " + str(secante(5, 4)))


class Headline:
    '''
    Headlines class to define Headlines Objects
    '''

    def __init__(self,id,title,description,urlToImage,publishedAt,author,content,url):
        self.id =id
        self.title = title
        self.description = description
        self.urlToImage = urlToImage
        self.publishedAt = publishedAt
        self.author = author
        self.content = content
        self.url = url

class News:
    '''
    News class to define News Objects
    '''

    def __init__(self,id,name,description,url):
        self.id =id
        self.name =name
        self.description =description
        self.url = url


from random import randint
import random
age = input('how old are you? ')
age = int(age)

# if condition:
#    "code that runs if condition if true" - typically 4 spaces of indentation

if age >= 21:
    print('Come on in!')
    print('*******')
print('AFTER THE IF STATEMENT')
# this gets printed regardless of True or False as not indented

# elif - Else If (if not the first thing, then try this instead)

# if test:
#     code if true
# elif test 2:
#     code if true

# Can have as many as you want
# elif only runs if nothing before it is true. So if you have 3 statements that are all true, it will print the first thing only then break
color = 'blue'

if color == 'green':
    print('BEGINNER!')
elif color == 'blue':
    print('INTERMEDIATE')
elif color == 'black':
    print('ADVANCED')

# Else - if none of the above were true, do this
# Must be after elif

# if age >= 21:
#     print('Come on in!')
# else:
#     print('Go home kid')

# the order is if, elif (as many as you want) and else

if age < 10:
    print('Your child ticket is $10')
elif age > 65:
    print('Your senior ticket is $12')
else:
    print('Your adult ticket is $14')

# Generating random numbers
# Comes with python, no need to download but need to import

# import random
random.randint(1, 6)  # generates a number between 1,6

# OR...

# from random import randint (this or above works)
randint(2, 10)