from unittest import TestCase
import blockchain
from blockchain import node_identifier
import json
import itertools

class TestRoutes(TestCase):
    def setUp(self):
        """""Define the setup app that uses a new blockchain in every test method."""
        _app = blockchain.app
        blockchain.blockchain = blockchain.Blockchain()
        self.app = _app.test_client()

    def test_get_genesis_chain(self):
        response = self.app.get('/chain')

        data = json.loads(response.data)
        assert response.status_code == 200
        assert 'chain' in data
        assert 'length' in data
        assert data['length'] == 1

    def test_first_block_mined(self):
        response = self.app.get('/mine')

        data = json.loads(response.data)
        assert response.status_code == 200
        assert 'message' in data
        assert 'index' in data
        assert 'transactions' in data
        assert 'proof' in data
        assert 'previous_hash' in data
        assert data['index'] == 2

    def test_mining_blocks_increases_index(self):
        response = self.app.get('/mine')
        data_first = json.loads(response.data)
        response = self.app.get('/mine')
        data_second = json.loads(response.data)
        assert data_first['index'] == 2
        assert data_second['index'] == 3

    def test_mining_blocks_rewards_miner(self):
        for _ in range(3):
            response = self.app.get('/mine')
            data = json.loads(response.data)
            assert len(data['transactions']) == 1
            last_transaction = data['transactions'][-1]
            assert last_transaction['sender'] == '0'
            assert last_transaction['recipient'] == node_identifier
            assert last_transaction['amount'] == 1

    def test_add_new_transactions_in_one_block(self):
        for _ in range(3):
            response = self.app.post('/transactions/new', data=json.dumps({
                'sender': 'X',
                'recipient': 'Y',
                'amount': 100.0
            }), content_type='application/json')
            assert response.status_code == 201
            data = json.loads(response.data)
            assert 'message' in data
            assert 'Block 2' in data['message']

    def test_add_new_transactions_in_more_blocks(self):
        for i in range(1, 4):
            # New transaction
            response = self.app.post('/transactions/new', data=json.dumps({
                'sender': 'X',
                'recipient': 'Y',
                'amount': 100.0
            }), content_type='application/json')
            assert response.status_code == 201
            data = json.loads(response.data)
            assert 'message' in data
            assert f'Block {i + 1}' in data['message']

            # New block
            response = self.app.get('/mine')
            assert response.status_code == 200
            data = json.loads(response.data)
            # 1 for transaction, 1 for reward
            assert len(data['transactions']) == 2

    def test_adding_incomplete_new_transaction(self):
        complete_data = (('sender', 'x'), ('recipient', 'y'), ('amount', 100.0))
        for missing_data in itertools.combinations(complete_data, len(complete_data) - 1):
            response = self.app.post(
                '/transactions/new',
                data=json.dumps(dict(missing_data)),
                content_type='application/json')
            assert response.status_code == 400

    def test_register_nodes(self):
        response = self.app.post('/nodes/register', data=json.dumps({
            'nodes': ['http://localhost:5001'],
        }), content_type='application/json')
        assert response.status_code == 201
        data = json.loads(response.data)
        assert 'message' in data
        assert len(data['total_nodes']) == 1
        assert 'localhost:5001' in data['total_nodes'][0]

    def test_register_invalid_nodes(self):
        response = self.app.post('/nodes/register', data=json.dumps({
            'wrong_key': None
        }), content_type='application/json')
        assert response.status_code == 400

    def test_no_nodes_to_resolve_conflict(self):
        response = self.app.get('/nodes/resolve')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert data['message'] == 'Our chain is authoritative'
        assert 'chain' in data

    def test_response_of_mocking_resolving_conflicts_between_nodes(self):
        # Mokeypatch blockchain's method
        blockchain.blockchain.resolve_conflicts = lambda: True
        response = self.app.get('/nodes/resolve')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert data['message'] == 'Our chain was replaced'
        assert 'new_chain' in data


#!/usr/bin/python
from __future__ import print_function
from datetime import date
from money import Money
from dateutil.relativedelta import relativedelta
from decimal import Decimal
import findates
from Contract import LoanContract
import LoanCalculator

calculator = LoanCalculator.LoanCalculator()
calculator.test_wrapper()
exit

print("Standard Payments")
my_contract = LoanContract()
my_contract.set_events({"kickstarter_success":True,
                        "kickstarter_start_date": date(2015,1,1),
                        "kickstarter_payment_date":date(2015,1,15),
                        "kickstarter_revenue":50000,
                        "early_payments":[]})
calculator = LoanCalculator.LoanCalculator()
calculator.calculate(my_contract)
print()

print ("Kickstarter success #1")
my_contract.set_events({"kickstarter_success":True,
                        "kickstarter_start_date": date(2015,1,1),
                        "kickstarter_payment_date":date(2015,1,15),
                        "kickstarter_revenue":100000,
                        "early_payments":[]})
calculator = LoanCalculator.LoanCalculator()
calculator.calculate(my_contract)
print ()
print ("Kickstarter success #2")
my_contract.set_events({"kickstarter_success":True,
                        "kickstarter_start_date": date(2015,1,1),
                        "kickstarter_payment_date":date(2015,1,15),
                        "kickstarter_revenue":60000,
                        "early_payments":[]})
calculator = LoanCalculator.LoanCalculator()
calculator.calculate(my_contract)


##########################################################
# pdf-to-csv
import tabula

for year in [2016,2017,2018]:
    print('Processing year ' + str(year))
    pdf = './data/bieg-' + str(year) + '.pdf'
    csv = './data/bieg-' + str(year) + '.csv'
    df = tabula.read_pdf(pdf, lattice=True, pages='all', area = [20, 0, 100, 100], relative_area = True, pandas_options={'header': None})
    df.columns = ['place', 'id', 'name', 'surname', 'location', 'team', 'birthYear', 'category', 'place2', 'M', 'K', 'half-time', 'time', 'netto-time']
    if (year == 2017):
        df = df[:-4] # In 2017 there were 3 disqualified participants and they had place 'DSQ' which is not of type int
    else:
        df = df[:-1]
    df = df.fillna({'place': -1, 'id': -1, 'name': '', 'surname': '', 'location': '', 'team': '',
                   'birthYear': -1, 'category': '', 'place2': -1, 'M': -1, 'K': -1,
                    'half-time': '', 'time': '', 'netto-time': ''})
    df = df.astype({'place': int, 'id': int, 'name': str, 'surname': str, 'location': str, 'team': str, 'birthYear': int, 'category': str, 'place2': int, 'M': int, 'K': int, 'half-time': str, 'time': str, 'netto-time': str})
    df.to_csv(csv, ';', index=False)

    # Replacing new-lines in cell on spaces
    file = open(csv, 'rb')
    content = file.read()
    content = content.replace(b'\r', b' ')
    content = content.replace(b' \n', b'\r\n')
    file.close()
    file = open(csv, 'wb')
    file.write(content)
    file.close()

##########################################################
# read dataset to numpy structured array
import pandas
df = pandas.read_csv('./data/bieg-2018.csv', ';')
df = df.astype({'place': int, 'id': int, 'name': str, 'surname': str, 'location': str, 'team': str, 'birthYear': int, 'category': str, 'place2': int, 'M': int, 'K': int, 'half-time': str, 'time': str, 'netto-time': str})
data = df.to_records(index=False)


import machine
import numpy as np
def measureSensor():
    #measure some samples, remove the biggest deviations, and take the average
    measurements = np.array([])
    for i in range(10):
        reading = adc.read()  # read the value
        np.hstack((measurements, reading)) #stack the readings in an array
    val = np.mean(measurements) #take the average value
    devi = np.std(measurements) #take the standard deviation

    return(val,devi)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 22:34:32 2017

@author: Ray
"""

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x ** 2 for x in x_values]

plt.title("Squared list of a Range between 1 and 1000.\n", fontsize = 18)
plt.xlabel("Value", fontsize = 14)
plt.ylabel("Square of Value", fontsize = 14)

plt.scatter(x_values, y_values)

plt.axis([0, 1100, 0, 1100000])

# remove the outlines from data points
plt.scatter(x_values, y_values, edgecolor='none', s=40)

plt.scatter(x_values, y_values, c = (0.4, .7, 0.8), edgecolor='none', s=40)


from spacetrack import SpaceTrackClient

def main():
	st = SpaceTrackClient('user', 'pw')
	ids = [20580, 27540, 28485, 31135, 33053, 36577, 25544, 37820, 41765]
	for i in ids:
		lines = st.tle_latest(iter_lines=True, epoch='>now-30', limit=1, orderby='epoch', norad_cat_id=i, format='tle')
		with open('satellites/' + str(i) + '.dat', 'w') as fp:
			for line in lines:
				fp.write(line + "\n")

if __name__ == "__main__":
	main()


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
random_walk.py

Created by Ernesto Costa on 2008-04-19.
Copyright (c) 2008 University of Coimbra. All rights reserved.
"""

import sys
import os

from time import sleep
from random import *
from xturtle import *

def random_walk(size, steps, xi=0,yi=0):
	reset()
	pu()
	x=xi
	y=yi
	goto((x,y))
	pd()
	for step in range(steps):
		delta_x=choice([-size,0,size])
		delta_y=choice([-size,0,size])
		x=x + delta_x
		y=y + delta_y
		goto(x,y)
	ht()

if __name__ == '__main__':
	size,steps,x,y=eval(input("tamanho, passos,x e y: "))
	random_walk(size,steps,x,y)
	sleep(10)


# -*- coding: utf8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab

'''Call python3.4 setup.py build_ext --inplace

Creates _nvm.cpython-34m.so
'''

from distutils.core import setup, Extension

include_pba = '../../lib/pba/include/'

swig_mod = Extension(
    '_nvm',
    include_dirs=[include_pba],
    # pba generates quiet a few warnings that I won't address, though
    extra_compile_args=[
        '-Wno-array-bounds',
        '-Wno-aggressive-loop-optimizations',
        '-Wno-maybe-uninitialized',
    ],
    sources=['nvm.i'],
    swig_opts=['-c++', '-py3', '-I{}'.format(include_pba)]
)

setup(
    ext_modules=[swig_mod]
)


import logging
import time
from StringIO import StringIO

try:
    import pygal
except:
    pygal = None

from openerp import api, models, fields

_logger = logging.getLogger(__name__)

class TelegramCommand(models.Model):

    _inherit = "telegram.command"

    @api.multi
    def _get_globals_dict(self):
        res = super(TelegramCommand, self)._get_globals_dict()
        res['pygal'] = pygal
        return res

    @api.multi
    def _eval(self, *args, **kwargs):
        locals_dict = kwargs.get('locals_dict') or {}
        locals_dict['charts'] = []
        kwargs['locals_dict'] = locals_dict
        return super(TelegramCommand, self)._eval(*args, **kwargs)

    def _render(self, template, locals_dict, tsession):
        res = super(TelegramCommand, self)._render(template, locals_dict, tsession)
        t0 = time.time()
        photos = []

        for obj in locals_dict.get('charts', []):
            f = StringIO(obj.render_to_png())
            f.name = 'chart.png'
            photos.append(f)

        render_time = time.time() - t0
        _logger.debug('Render Charts in %.2fs\n locals_dict: %s', render_time, locals_dict)
        res['photos'] += photos
        return res


from django.utils.functional import empty, LazyObject

class LazySettings(LazyObject):

    def _setup(self):
        from django.conf import settings

        settings_dict = getattr(settings, "GITVIEW", {})

        settings_dict["name"] = settings_dict.get("name", "GitView")

        self._wrapped = settings_dict

    def __getattr__(self, name):
        """
        Allow dictionary keys to be accessed as attributes.
        """

        if self._wrapped is empty:
            self._setup()

        return self._wrapped[name]

settings = LazySettings()


#coding=utf-8

# 写入数据的工具类
class FileManager(object):

	# 保存文件的名称
	filename = 'student.txt'

	# 写一个写入数据的接口
	@classmethod
	def write(cls,content,split='\n'):
		'''
		:param content: 要写入的数据
		:param split: 每条数据之间的分隔符
		:return:
		'''
		# 判断传入的参数是否为字符串类型，如果是就写入，如果不是就抛出异常
		if isinstance(content,str):
			# 1.打开文件
			f = open(cls.filename, 'a')
			# 2.写入数据
			f.write(content)
			f.write(split)
			# 3.关闭文件
			f.close()
		else:
			raise TypeError('content must be a str')

	# 写入多行数据
	@classmethod
	def writelines(cls,str_list,split='\n'):

		# 判断某个对象是否是个类型,如果是返回True，如果不是返回False
		rs = isinstance(str_list,list)
		# 如果为True
		if rs:
			# for循环遍历列表，取出每一个数据，判断数据类型是否为字符串
			for content in str_list:
				# 如果不是字符串类型，抛出异常
				if isinstance(content,str) == False:
					raise TypeError('000')
			# 如果没有抛出异常，就可以写入数据了
			# 1.打开文件
			f = open(cls.filename,'a')
			# 2.写入数据 str1\str2\str3
			string = split.join(str_list)
			f.write(string)
			# 3.关闭文件
			f.close()
		else:
			# 如果传入的不是列表，抛出异常
			raise TypeError('str_list must be a list of "str"')

# 日期格式化类，用类执行一个函数，返回一个对象，对象分别有year\month\day
'''
    2018-2-1  2018.2.1  2018 2 1
    date.year = 2018
    date.month = 2
    date.day = 1
'''
class DateTool(object):

	def __init__(self, year=1970, month=1, day=1):
		self.year = year
		self.month = month
		self.day = day
	#类函数，传递进来一个日期，返回一个该类的对象

	@classmethod
	def get_date(cls, date):
		# 判断date是否为str类型
		if not isinstance(date,str):
			# 不是str类型，直接触发异常
			raise TypeError('date must be a str!')
		# 转换
		# 判断是- 还是. 还是空格
		if '-' in date:
			# 相当于year,month,day = [2018,2,1]
			# 分别将2018赋值给year，2赋值给month，1赋值给day
			year,month,day = list(map(int,date.split('-')))
		elif '.' in date:
			year, month, day = list(map(int, date.split('.')))
		elif ' ' in date:
			year, month, day = list(map(int, date.split(' ')))

		# 创建对象
		# 相当于obj = DateTool(year,month,day)
		obj = cls(year, month, day)
		# 返回对象
		return obj

# 只有在当前文件直接运行时，才会运行以下代码
if __name__ == '__main__':

	# 指定写入文件的名称
	FileManager.filename = 'all_student.txt'

	# 执行写入功能函数
	FileManager.write('hello')

	FileManager.writelines(['hello','world','鸡帆'])

	# 开始进行日期转换
	# 转换之后 返回一个结果对象
	date = DateTool.get_date('2020-2-22')
	# date 有三个属性，分别为year month day
	print(date.year)
	print(date.month)
	print(date.day)


# Remote Control - Transmit
#   for use in the Sparkfun Thing Plus RP2040 board
#
# Default transmitter settings:
#   power level: 0 dB (maximum)
#   transmit address: b"1Node"
#   receive address:  b"2Node"
#
# nm3210@gmail.com
# Date Created:  April 17th, 2021
# Last Modified: October 10th, 2021

# Import modules
import board, bitbangio, digitalio, struct, time, random # circuitpython built-ins
from math import atan2, acos, sqrt, pi # necessary math calls
import adafruit_mpu6050 # also requires adafruit_register
import neopixel # also requires adafruit_pypixelbuf
from circuitpython_nrf24l01.rf24 import RF24
from lib.ColorDescriptors.ColorDescriptors import *
from lib.EasyStreamNrf24.EasyStreamNrf24 import sendPayload
print("Finished importing modules")

### Initialize nRF24L01
# Configure pinouts
ce = digitalio.DigitalInOut(board.D0)
csn = digitalio.DigitalInOut(board.D1)
spi = board.SPI() # init spi bus w/ pins D[2,3,4]
# irq = digitalio.DigitalInOut(board.D6) # optional IRQ pin to listen to interrupts

# Initialize object
nrf = RF24(spi, csn, ce)

# Configure settings
# irq.switch_to_input()  # make sure its an input object
nrf.pa_level = 0 # maximum

# Select tx/rx addresses
txAddress = b"1Node" # transmit module tx pipe = '1Node'
rxAddress = b"2Node" # transmit module rx pipe = '2Node'
nrf.open_tx_pipe(txAddress)
nrf.open_rx_pipe(1, rxAddress)

# Set default state to 'off'
nrf.listen = False
nrf.power = False
print("Finished initializing nRF24 module")

### Initialize neopixel output
ledPin = board.NEOPIXEL
pixelMain = neopixel.NeoPixel(ledPin, 1, pixel_order=neopixel.GRB)
pixelMain.fill((0,0,0)) # turn off on startup
print("Finished initializing neopixel")

### Initialize MPU6050 sensor
i2c = board.I2C();

# Initialize MPU6050 object
sensor = adafruit_mpu6050.MPU6050(i2c)
sensor.cycle_rate = adafruit_mpu6050.Rate.CYCLE_40_HZ # update cycle rate
sensor.cycle = True # only periodically update sensor (saves power!)
print("Finished initializing mpu6050")

# Setup calibrated accel values
numAvgValues = 7
listAccelX = [None] * numAvgValues
listAccelY = [None] * numAvgValues
listAccelZ = [None] * numAvgValues
listFaceIdx = [0] * numAvgValues

### Other things
# Setup some storage vars
lastFace = 0

# Configure timers
timeCheck_faceIdx = time.monotonic_ns()
updateTime_faceIdx = 1.1/40 # seconds, enough time for the 40 Hz to update

timeCheck_changes = time.monotonic_ns()
updateTime_changes = 0.01 # seconds

timeCheck_autosend = time.monotonic_ns()
updateTime_autosend = 1.0 # always send an update every once in a while

### Set up colors (preallocate)
# Solid colors
solidRed     = ColorMethod(ModeStationary, ColorRed)
solidYellow  = ColorMethod(ModeStationary, ColorYellow)
solidGreen   = ColorMethod(ModeStationary, ColorGreen)
solidCyan    = ColorMethod(ModeStationary, ColorCyan)
solidBlue    = ColorMethod(ModeStationary, ColorBlue)
solidMagenta = ColorMethod(ModeStationary, ColorMagenta)
solidWhite   = ColorMethod(ModeStationary, ColorWhite)
solidOff     = ColorMethod(ModeStationary, ColorOff)

# Gradients
gradientRainbowShort = ColorGradient([ColorRed, ColorYellow, ColorGreen, ColorCyan, ColorBlue, ColorMagenta, ColorSolid(hue=360)])
rainbowShort = ColorMethod(ModeStationary, gradientRainbowShort)
gradientRainbowMedium = ColorGradient([ColorRed, ColorYellow, ColorGreen, ColorCyan, ColorBlue, ColorMagenta, ColorSolid(hue=360)],1)
rainbowMedium = ColorMethod(ModeStationary, gradientRainbowMedium)

### Private functions
def getDownwardFaceIndex():
    # Collect sensor updates
    theta, phi = getAccelTiltAngle() # in degrees

    # Determine sides of the platonic cube
    angleCheck = 20
    return getPlatonicCubeFaceIdx(theta, phi, angleCheck)

def getPlatonicCubeFaceIdx(theta, phi, angleCheck):
    # Determine sides of the platonic cube
    faceIdx = 0 # invalid face
    angleDiff = lambda start, stop : ((start-stop)+180)%360 - 180
    if   abs(angleDiff(theta,  0)) <= angleCheck and abs(angleDiff(phi, 90)) <= angleCheck: # Down
        faceIdx = 1
    elif abs(angleDiff(theta,180)) <= angleCheck and abs(angleDiff(phi, 90)) <= angleCheck: # Up
        faceIdx = 2
    elif abs(angleDiff(theta,-90)) <= angleCheck and abs(angleDiff(phi, 90)) <= angleCheck: # Side 1
        faceIdx = 3
    elif abs(angleDiff(theta, 90)) <= angleCheck and abs(angleDiff(phi, 90)) <= angleCheck: # Side 2
        faceIdx = 4
    elif abs(angleDiff(phi,    0)) <= angleCheck: # Side 3, no theta check necessary because it's in a singularity
        faceIdx = 5
    elif abs(angleDiff(phi,  180)) <= angleCheck: # Side 4, no theta check necessary because it's in a singularity
        faceIdx = 6
    else:
        pass
    return faceIdx

def getAccelTiltAngle():
    # via https://www.analog.com/en/app-notes/an-1057.html eq 9 & 10
    x, y, z = getSmoothedAccel()
    theta = atan2(y, x) # (-180,180)
    phi = acos(z / sqrt(x*x + y*y + z*z)) # (0,180)
    return theta*180/pi, phi*180/pi # -> deg

def getSmoothedAccel():
    preallocateAccelList() # first time only, via simply none check

    # Update the sensor
    updateAccelList()

    # Calculate the 'moving' average
    x = sum(listAccelX) / len(listAccelX)
    y = sum(listAccelY) / len(listAccelY)
    z = sum(listAccelZ) / len(listAccelZ)
    return x, y, z

def updateAccelList():
    """
    Updates the acceleration lists with a new sensor value
    """
    # Get new sensor update/s
    x, y, z = getSensorAccel()

    # Pop out old values (idx 0)
    listAccelX.pop(0) # ignore outgoing value
    listAccelY.pop(0) # ignore outgoing value
    listAccelZ.pop(0) # ignore outgoing value

    # Append the new values
    listAccelX.append(x)
    listAccelY.append(y)
    listAccelZ.append(z)

def getSmoothedFaceIdx():
    if not all(ele == listFaceIdx[0] for ele in listFaceIdx):
        return 0 # ALL elements need to be identical to return a valid value
    return listFaceIdx[0]

def updateFaceIdx():
    _faceIdx = getDownwardFaceIndex()
    listFaceIdx.pop(0) # remove an entry (ignore outgoing value)
    listFaceIdx.append(_faceIdx) # add the new index

def preallocateAccelList():
    # Check if there are any none's to replace
    while (None in listAccelX or None in listAccelY or None in listAccelY):
        updateAccelList()
        time.sleep(1.1/40) # wait for the sensor to update

def getSensorAccel():
    x, y, z = sensor.acceleration
    return x, y, z

def anyChanges():
    global lastFace
    currentFace = getSmoothedFaceIdx()
    if currentFace != 0 and currentFace != lastFace:
        lastFace = currentFace
        return True
    return False

def lookupFaceMethod(faceVal):
    if   faceVal == 1: # TOP Die Val = '2'
        return solidRed
    elif faceVal == 2: # TOP Die Val = '5'
        return solidYellow
    elif faceVal == 3: # TOP Die Val = '4'
        return solidGreen
    elif faceVal == 4: # TOP Die Val = '3'
        return solidCyan
    elif faceVal == 5: # TOP Die Val = '1'
        return solidBlue
    elif faceVal == 6: # TOP Die Val = '6'
        return solidMagenta
    else:
        return None

def getPayload():
    global lastFace
    faceMethod = lookupFaceMethod(lastFace)
    if faceMethod is None: return None
    return faceMethod.toString()

###
# Main LOOP
print("Starting main loop for Remote Control - Transmit...")
while True:
    ### Check timers
    # Update FaceIdx
    if abs(time.monotonic_ns() - timeCheck_faceIdx) > updateTime_faceIdx*1e9:
        timeCheck_faceIdx = time.monotonic_ns() # reset timer
        updateFaceIdx()

    # Check for any face index changes
    detectedChanges = False
    if abs(time.monotonic_ns() - timeCheck_changes) > updateTime_changes*1e9:
        timeCheck_changes = time.monotonic_ns() # reset timer
        detectedChanges = anyChanges()

    # Send an update if any changes or a timeout has been reached
    if lastFace != 0 and (detectedChanges or abs(time.monotonic_ns() - timeCheck_autosend) > updateTime_autosend*1e9):
        timeCheck_autosend = time.monotonic_ns() # reset timer
        curPayload = getPayload()
        if curPayload is not None:
            sendPayload(nrf, getPayload(), debugPrint=False)


from PyQt5.QtCore import Qt, pyqtSignal, QObject
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QDialog, QBoxLayout, QGridLayout, QLabel, QLineEdit, QPushButton, QProgressBar, QFileDialog, \
    QGroupBox, QCheckBox, QHBoxLayout, QSpacerItem

class NTFSLogFileDialog(QDialog, QObject):
    complete = pyqtSignal()

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        QObject.__init__(self)
        self.selectedPartition = -1
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Import File System Log File")
        # self.setFixedSize(570, 300)
        self.setFixedSize(self.sizeHint())
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.spacerItem1 = QSpacerItem(10, 5)
        self.layout.addItem(self.spacerItem1)
        self.setLayout(self.layout)

        # First Group
        self.diskRawChkBox = QCheckBox("In this case, it's possible to carve some files.", self)
        self.diskRawChkBox.stateChanged.connect(lambda: self.selectedType(self.diskRawChkBox))
        self.diskRawGroupBox = QGroupBox(self)
        self.diskRawGroupBox.setStyleSheet("margin-top: 0;")
        self.diskRawGroupBox.setDisabled(True)
        diskRawGroupBoxLayout = QHBoxLayout(self.diskRawGroupBox)
        self.diskRawGroupBox.setLayout(diskRawGroupBoxLayout)

        self.diskRawLabel = QLabel("Disk Raw: ", self)
        self.diskRawTextBox = QLineEdit()
        self.diskRawTextBox.setReadOnly(True)
        self.diskRawTextBox.setFixedWidth(400)

        self.browseDiskRawBtn = QPushButton("...", self)
        self.browseDiskRawBtn.setFixedWidth(50)
        self.browseDiskRawBtn.clicked.connect(self.btnClicekd)
        self.browseDiskRawBtn.setCursor(QCursor(Qt.PointingHandCursor))

        diskRawGroupBoxLayout.addWidget(self.diskRawLabel)
        diskRawGroupBoxLayout.addWidget(self.diskRawTextBox)
        diskRawGroupBoxLayout.addWidget(self.browseDiskRawBtn)

        self.layout.addWidget(self.diskRawChkBox)
        self.layout.addWidget(self.diskRawGroupBox)

        # Second Group
        self.ntfsLogFileChkBox = QCheckBox("In this case, NTFS Log analysis only supported.", self)
        self.ntfsLogFileChkBox.stateChanged.connect(lambda: self.selectedType(self.ntfsLogFileChkBox))

        self.ntfsLogGroupBox = QGroupBox(self)
        self.ntfsLogGroupBox.setStyleSheet("margin-top: 0;")
        self.ntfsLogGroupBox.setDisabled(True)
        ntfsLogGroupBoxLayout = QGridLayout(self)
        self.ntfsLogGroupBox.setLayout(ntfsLogGroupBoxLayout)

        self.mftLabel = QLabel("$MFT: ", self)
        self.mftPathTextBox = QLineEdit(self)
        self.mftPathTextBox.setReadOnly(True)
        self.mftPathTextBox.setFixedWidth(400)
        self.browseMFTBtn = QPushButton("...", self)
        self.browseMFTBtn.setFixedWidth(50)
        self.browseMFTBtn.clicked.connect(self.btnClicekd)
        self.browseMFTBtn.setCursor(QCursor(Qt.PointingHandCursor))

        self.usnjrnlLabel = QLabel("$UsnJrnl: ", self)
        self.usnjrnlPathTextBox = QLineEdit(self)
        self.usnjrnlPathTextBox.setReadOnly(True)
        self.usnjrnlPathTextBox.setFixedWidth(400)
        self.browseUsnJrnlBtn = QPushButton("...", self)
        self.browseUsnJrnlBtn.setFixedWidth(50)
        self.browseUsnJrnlBtn .clicked.connect(self.btnClicekd)
        self.browseUsnJrnlBtn.setCursor(QCursor(Qt.PointingHandCursor))

        self.logfileLabel = QLabel("$LogFile: ", self)
        self.logfilePathTextBox = QLineEdit(self)
        self.logfilePathTextBox.setReadOnly(True)
        self.logfilePathTextBox.setFixedWidth(400)
        self.browseLogFileBtn = QPushButton("...", self)
        self.browseLogFileBtn.setFixedWidth(50)
        self.browseLogFileBtn .clicked.connect(self.btnClicekd)
        self.browseLogFileBtn.setCursor(QCursor(Qt.PointingHandCursor))

        ntfsLogGroupBoxLayout.addWidget(self.mftLabel, 0, 0)
        ntfsLogGroupBoxLayout.addWidget(self.mftPathTextBox, 0, 1)
        ntfsLogGroupBoxLayout.addWidget(self.browseMFTBtn, 0, 2)
        ntfsLogGroupBoxLayout.addWidget(self.usnjrnlLabel, 1, 0)
        ntfsLogGroupBoxLayout.addWidget(self.usnjrnlPathTextBox, 1, 1)
        ntfsLogGroupBoxLayout.addWidget(self.browseUsnJrnlBtn, 1, 2)
        ntfsLogGroupBoxLayout.addWidget(self.logfileLabel, 2, 0)
        ntfsLogGroupBoxLayout.addWidget(self.logfilePathTextBox, 2, 1)
        ntfsLogGroupBoxLayout.addWidget(self.browseLogFileBtn, 2, 2)

        self.submitBtn = QPushButton("Submit", self)
        self.submitBtn.setFixedSize(100, 40)
        self.submitBtn.setCursor(QCursor(Qt.PointingHandCursor))

        self.loggingLabel = QLabel("Loading...", self)
        self.loggingLabel.setFixedHeight(20)
        self.loggingLabel.setAlignment(Qt.AlignCenter)
        self.loggingLabel.hide()

        self.loadingBar = QProgressBar(self)
        self.loadingBar.setFixedHeight(10)
        self.loadingBar.setTextVisible(False)
        self.loadingBar.hide()

        from modules.UI.LoadingScreen import LoadingBarThread
        self.barThread = LoadingBarThread(self)
        self.barThread.change_value.connect(self.loadingBar.setValue)

        self.spacerItem2 = QSpacerItem(10, 15)
        self.spacerItem3 = QSpacerItem(10, 20)
        self.layout.addItem(self.spacerItem2)
        self.layout.addWidget(self.ntfsLogFileChkBox)
        self.layout.addWidget(self.ntfsLogGroupBox)
        self.layout.addItem(self.spacerItem3)
        self.layout.addWidget(self.submitBtn, alignment=Qt.AlignHCenter)

        self.setWindowModality(Qt.WindowModal)
        self.show()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()

    def selectedType(self, b):
        if b is self.diskRawChkBox:
            if b.isChecked():
                self.ntfsLogFileChkBox.setChecked(False)
                self.ntfsLogGroupBox.setDisabled(True)
                self.diskRawGroupBox.setDisabled(False)
            else:
                self.diskRawGroupBox.setDisabled(True)
        else:
            if b.isChecked():
                self.diskRawChkBox.setChecked(False)
                self.diskRawGroupBox.setDisabled(True)
                self.ntfsLogGroupBox.setDisabled(False)
            else:
                self.ntfsLogGroupBox.setDisabled(True)

    def btnClicekd(self):
        sender = self.sender()
        fileName = QFileDialog.getOpenFileName(self)
        if sender is self.browseDiskRawBtn:
            self.diskRawTextBox.setText(fileName[0])
        elif sender is self.browseMFTBtn:
            self.mftPathTextBox.setText(fileName[0])
        elif sender is self.browseUsnJrnlBtn:
            self.usnjrnlPathTextBox.setText(fileName[0])
        elif sender is self.browseLogFileBtn:
            self.logfilePathTextBox.setText(fileName[0])

    def ready(self):
        self.submitBtn.hide()
        self.layout.removeWidget(self.submitBtn)
        self.layout.addWidget(self.loggingLabel, alignment=Qt.AlignBottom | Qt.AlignHCenter)
        self.layout.addWidget(self.loadingBar)
        self.loggingLabel.show()
        self.loadingBar.show()
        self.barThread.start()

    def resume(self):
        if self.barThread.cnt < 50:
            self.barThread.cnt = 100
            return
        self.barThread.toggle_status()

    def changeInterface(self, contents):
        from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem

        self.layout.removeWidget(self.diskRawChkBox)
        self.diskRawChkBox.hide()
        self.layout.removeWidget(self.diskRawGroupBox)
        self.diskRawGroupBox.hide()
        self.layout.removeItem(self.spacerItem2)
        self.layout.removeWidget(self.ntfsLogFileChkBox)
        self.ntfsLogFileChkBox.hide()
        self.layout.removeWidget(self.ntfsLogGroupBox)
        self.ntfsLogGroupBox.hide()
        self.layout.removeItem(self.spacerItem3)
        self.layout.removeWidget(self.submitBtn)

        self.diskNameLabel = QLabel("Image Name:\t" + contents[0][0], self)
        self.diskSizeLabel = QLabel("Image Size:\t{} Bytes".format(contents[0][1]), self)
        self.diskSizeLabel.setFixedHeight(20)
        self.diskSizeLabel.setAlignment(Qt.AlignVCenter)
        self.diskPartLabel = QLabel("Partition:", self)
        self.diskPartLabel.setFixedHeight(20)
        self.diskPartLabel.setAlignment(Qt.AlignBottom)

        self.partitionTree = QTreeWidget(self)
        self.partitionTree.setHeaderLabels(
            ["Order", "File System", "Active", "Starting Offset", "Total Sector", "Size"])
        self.partitionTree.itemChanged.connect(self.itemChanged)
        self.partitionTree.resizeColumnToContents(2)
        self.partitionTree.resizeColumnToContents(3)
        self.partitionTree.resizeColumnToContents(4)
        self.partitionTree.headerItem().setTextAlignment(0, Qt.AlignCenter)
        self.partitionTree.headerItem().setTextAlignment(1, Qt.AlignCenter)

        self.partitionItems = []
        for row in range(1, 5):
            self.partitionTree.headerItem().setTextAlignment(row + 1, Qt.AlignCenter)
            item = QTreeWidgetItem(self.partitionTree)
            item.setText(0, str(row))
            item.setTextAlignment(0, Qt.AlignLeft)
            if not contents[row]:
                item.setText(1, "None")
                item.setCheckState(0, Qt.Unchecked)
                item.setDisabled(True)
                continue
            for col in range(5):
                item.setText(col + 1, contents[row][col])
                item.setTextAlignment(col + 1, Qt.AlignCenter)
            item.setTextAlignment(1, Qt.AlignLeft)
            item.setCheckState(0, Qt.Unchecked)
            self.partitionItems.append(item)

        self.layout.addWidget(self.diskNameLabel)
        self.layout.addWidget(self.diskSizeLabel)
        self.layout.addWidget(self.diskPartLabel)
        self.layout.addWidget(self.partitionTree)
        self.layout.addItem(QSpacerItem(10, 10))
        self.layout.addWidget(self.submitBtn, alignment=Qt.AlignCenter)

    def itemChanged(self, changedItem, p_int):
        if changedItem.checkState(0) == Qt.Checked:
            self.selectedPartition = int(changedItem.text(0))
            for item in self.partitionItems:
                if item is not changedItem:
                    item.setCheckState(0, Qt.Unchecked)

if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication
    import sys
    import qdarkstyle
    app = QApplication(sys.argv)
    w = NTFSLogFileDialog()
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    sys.exit(app.exec_())


# Copyright 2016 Markus D. Herrmann, University of Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''Jterator module for registering objects. Registration allows subsequent
measurements of the objects (feature extraction) and automatically persist them
on disk.
'''
import collections
import logging
from jtlib.utils import label

logger = logging.getLogger(__name__)

VERSION = '0.1.0'

Output = collections.namedtuple('Output', ['objects'])

def main(mask):
    '''Registers objects (connected pixel components) in an image for use by
    other (measurement) modules downstream in the pipeline. In case a binary
    mask is provided the image is automatically labeled.

    Parameters
    ----------
    mask: numpy.ndarray[Union[numpy.bool, numpy.int32]]
        binary or labeled mask

    Returns
    -------
    jtmodules.register_objects.Output

    See also
    --------
    :class:`tmlib.workflow.jterator.handles.SegmentedObjects`
    '''
    if mask.dtype == 'bool':
        label_image = label(mask)
    else:
        label_image = mask
    return Output(label_image)


from math import log2

# Pasted letter_freq here, did not see it in ex01 folder.
def letter_freq(txt):
    dictionary = {}
    for letter in txt:
        character = letter.lower()
        if character in dictionary:
            dictionary.update({character: dictionary[character] + 1})
        else:
            dictionary.update({character: 1})
    return dictionary

def entropy(message):
    """This function will use the message as input.
    ----
    The output will be a sum calculated from the entropy function.
    """
    # Defining variables
    bit_entropy = 0
    n = len(message)
    # Using the for loop to run for each unique character.
    for occurrence in letter_freq(message).values():
        # Finding the occurrence rate for the given letter
        p_i = occurrence / n
        # Using the function given to us in order to sum it up.
        bit_entropy -= p_i * log2(p_i)
    return bit_entropy

if __name__ == "__main__":
    for msg in '', 'aaaa', 'aaba', 'abcd', 'This is a short text.':
        print('{:25}: {:8.3f} bits'.format(msg, entropy(msg)))


from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools.mask import decode
from pycococreatortools.pycococreatortools import binary_mask_to_polygon
import os
import os.path as osp
import json
import argparse
import ipdb
from tqdm import tqdm

def pred2hard(ann_file, pred_file, output, fp_th=0.8):

    #load GT and Detections
    cocoGt = COCO(ann_file)
    cocoDt = cocoGt.loadRes(pred_file)
    #Eval Detections
    cocoEval = COCOeval(cocoGt,cocoDt)
    cocoEval.evaluate()

    #number of instances
    num_train_inst = len(cocoGt.catToImgs[1])

    # Load previous file
    new_anns = json.load(open(ann_file))

    #Find the FPs given a threshold
    print('Finding FP...')
    num_fp = 0
    for key in tqdm(cocoDt.imgToAnns.keys()):
        # ipdb.set_trace()
        ious = cocoEval.ious[(key,1)]
        for i,iou in enumerate(ious):
            max_overlap = max(iou)
            if max_overlap <= fp_th:
                num_fp += 1
                fp = cocoDt.imgToAnns[key][i]
                fp['width'] = fp['segmentation']['size'][1]
                fp['height'] = fp['segmentation']['size'][0]
                fp_segm = decode(fp['segmentation'])
                fp['segmentation'] = binary_mask_to_polygon(fp_segm, tolerance=2)
                # ipdb.set_trace()
                fp.pop('score')
                fp['category_id'] = 2
                fp['id'] += num_train_inst
                fp['area'] = int(fp['area'])
                fp['bbox'] = fp['bbox'].tolist()
                new_anns['annotations'].append(fp)
    print('{} FPs found'.format(num_fp))
    # ipdb.set_trace()
    new_anns['categories'].append({'id':2, 'name': 'Three Leaf Clover', 'supercategory': 'Clover'})
    with open(output, 'w') as f:
        json.dump(new_anns, f)

    print('Hard negatives annotation file saved in {}'.format(output))
if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Predictions to hard negatives")
    parser.add_argument(
        "--ann_file",
        default="",
        help="path to ann file",
        required=True,
        type=str,
    )
    parser.add_argument(
        "--pred_file",
        default="",
        help="path to pred file",
        required=True,
        type=str,
    )
    parser.add_argument(
        "--out_file",
        default="",
        help="name and path of out file",
        required=True,
        type=str,
    )
    parser.add_argument(
        "--th",
        default=0.8,
        help="FP threshold",
        required=False,
        type=float,
    )

    args = parser.parse_args()
    print('Function called with args {}'.format(args))
    #ann_file = 'examples/instances_test_pos.json'
    #pred_file = 'examples/segm.json'
    #output = 'examples/instances_test_hard_negatives.json'
    pred2hard(args.ann_file, args.pred_file, args.out_file)


# A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:

# S is empty;
# S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
# S has the form "VW" where V and W are properly nested strings.
# For example, the string "{[()()]}" is properly nested but "([)()]" is not.

# Write a function:

# def solution(S)

# that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

# For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.

# Write an efficient algorithm for the following assumptions:

# N is an integer within the range [0..200,000];
# string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".

def solution(S):
    # write your code in Python 3.6
    # queue and pop as pass through
    # characters stored in hashmap
    # TC:O(N)

    dic = {'}': '{', ']': '[', ')': '('}
    que = []

    for c in S:
        if c in dic and que:
            if que[-1] == dic[c]:
                que.pop()
            else:
                return 0
        elif c in dic and not que:
            return 0
        else:
            que.append(c)

    if que:
        return 0
    else:
        return 1


"""Python Cookbook 2nd ed.

Chapter 12, recipe 1.
"""
import json
import random
from typing import (
    List,
    Dict,
    Iterator,
    Any,
    Callable,
    Union,
    Optional,
    Tuple,
    Iterable,
    cast,
    overload,
    TYPE_CHECKING,
    Text,
    Protocol,
)

class Card:
    """
    >>> c = Card(1, "\\u2660")
    >>> repr(c)
    "Card(rank=1, suit='♠')"
    >>> c.to_json()
    {'__class__': 'Card', 'rank': 1, 'suit': '♠'}
    """

    __slots__ = ("rank", "suit")

    def __init__(self, rank: int, suit: str) -> None:
        self.rank = int(rank)
        self.suit = suit

    def __repr__(self):
        return f"Card(rank={self.rank!r}, suit={self.suit!r})"

    def to_json(self):
        return {"__class__": "Card", "rank": self.rank, "suit": self.suit}

class Deck:
    SUITS = (
        "\N{black spade suit}",
        "\N{white heart suit}",
        "\N{white diamond suit}",
        "\N{black club suit}",
    )
    """
    Create deck or shoe.

    >>> random.seed(2)
    >>> deck = Deck()
    >>> cards = deck.deal(5)
    >>> cards  # doctest: +NORMALIZE_WHITESPACE
    [Card(rank=4, suit='♣'), Card(rank=8, suit='♡'),
     Card(rank=3, suit='♡'), Card(rank=6, suit='♡'),
     Card(rank=2, suit='♠')]
    >>> json_cards = list(card.to_json() for card in deck.deal(5))
    >>> print(json.dumps(json_cards, indent=2, sort_keys=True))
    [
      {
        "__class__": "Card",
        "rank": 2,
        "suit": "\u2662"
      },
      {
        "__class__": "Card",
        "rank": 13,
        "suit": "\u2663"
      },
      {
        "__class__": "Card",
        "rank": 7,
        "suit": "\u2662"
      },
      {
        "__class__": "Card",
        "rank": 6,
        "suit": "\u2662"
      },
      {
        "__class__": "Card",
        "rank": 7,
        "suit": "\u2660"
      }
    ]
    """

    def __init__(self, n: int = 1) -> None:
        self.n = n
        self.create_deck(self.n)

    def create_deck(self, n: int = 1) -> None:
        self.cards = [
            Card(r, s) for r in range(1, 14) for s in self.SUITS for _ in range(n)
        ]
        random.shuffle(self.cards)
        self.offset = 0

    def deal(self, hand_size: int = 5) -> List[Card]:
        if self.offset + hand_size > len(self.cards):
            self.create_deck(self.n)
        hand = self.cards[self.offset : self.offset + hand_size]
        self.offset += hand_size
        return hand

    def __len__(self) -> int:
        return len(self.cards)

    @overload
    def __getitem__(self, position: int) -> Card:
        ...

    @overload
    def __getitem__(self, position: slice) -> List[Card]:
        ...

    def __getitem__(self, position: Union[int, slice]) -> Union[Card, List[Card]]:
        return self.cards[position]

    def __iter__(self) -> Iterator[Card]:
        return iter(self.cards)

# Copy-Pasta from wsgiref/types.pyi
class StartResponse(Protocol):
    def __call__(
        self,
        status: str,
        headers: List[Tuple[str, str]],
        exc_info: Optional[Tuple] = ...,
    ) -> Callable[[bytes], Any]:
        ...

WSGIEnvironment = Dict[Text, Any]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]]

from http import HTTPStatus

deck: Optional[Deck] = None

def deal_cards(
    environ: Dict[str, Any], start_response: StartResponse
) -> Iterable[bytes]:
    global deck
    if deck is None:
        random.seed(environ.get("DEAL_APP_SEED"))
        deck = Deck()
    hand_size = int(environ.get("HAND_SIZE", 5))
    cards = deck.deal(hand_size)
    status = f"{HTTPStatus.OK.value} {HTTPStatus.OK.phrase}"
    headers = [("Content-Type", "application/json;charset=utf-8")]
    start_response(status, headers)
    json_cards = list(card.to_json() for card in cards)
    return [json.dumps(json_cards, indent=2).encode("utf-8")]

class DealCards:
    def __init__(self, hand_size: int = 5, seed: Optional[int] = None) -> None:
        self.hand_size = hand_size
        random.seed(seed)
        self.deck = Deck()
        self.offset = 0

    def __call__(
        self, environ: Dict[str, Any], start_response: StartResponse
    ) -> Iterable[bytes]:
        if self.offset + self.hand_size >= len(self.deck):
            self.deck = Deck()
            self.offset = 0
        cards = self.deck[self.offset : self.offset + self.hand_size]
        self.offset += self.hand_size
        status = f"{HTTPStatus.OK.value} {HTTPStatus.OK.phrase}"
        headers = [("Content-Type", "application/json;charset=utf-8")]
        start_response(status, headers)
        json_cards = list(card.to_json() for card in cards)
        return [json.dumps(json_cards, indent=2).encode("utf-8")]

from urllib.parse import parse_qs

class JSON_Filter:
    def __init__(self, json_app: WSGIApplication) -> None:
        self.json_app = json_app

    def __call__(
        self, environ: Dict[str, Any], start_response: StartResponse
    ) -> Iterable[bytes]:
        if "HTTP_ACCEPT" in environ:
            if "json" in environ["HTTP_ACCEPT"]:
                environ["$format"] = "json"
                return self.json_app(environ, start_response)
        decoded_query = parse_qs(environ["QUERY_STRING"])
        if "$format" in decoded_query:
            if decoded_query["$format"][0].lower() == "json":
                environ["$format"] = "json"
                return self.json_app(environ, start_response)
        status = f"{HTTPStatus.BAD_REQUEST.value} {HTTPStatus.BAD_REQUEST.phrase}"
        headers = [("Content-Type", "text/plain;charset=utf-8")]
        start_response(status, headers)
        return [
            "Request doesn't include ?$format=json or Accept:application/json header".encode(
                "utf-8"
            )
        ]

if __name__ == "__main__":
    from wsgiref.simple_server import make_server

    # dealer = DealCards()
    json_wrapper = JSON_Filter(deal_cards)

    httpd = make_server("", 8080, json_wrapper)  # type: ignore
    httpd.serve_forever()


#!/usr/bin/env python

import os
import argparse
from typing import Optional, Sequence
from pathlib import Path
from dotenv import load_dotenv
from project_init import local_project as lp, remote_project as rp

def main(argv: Optional[Sequence[str]] = None) -> int:

    # Intilaize argparser and set arguments
    parser = argparse.ArgumentParser(
        description="Necessary GitHub arguments for new Remote and local repo"
        )

    parser.add_argument(
        "-v", "--view",
        default="public",
        choices=("private", "public"),
        type=str,
        help="GitHub view status Public vs Private. (default: %(default)s).",
        )

    parser.add_argument(
        "-n", "--projectname",
        required=True,
        type=str,
        help="Your project Name for Remote and local creation.",
        )

    # Get argparse arguments
    args = parser.parse_args(argv)
    view = args.view
    pn = args.projectname

    # Get base directory this file is in
    env_path = Path(".", ".env")

    # Join path with file name and load_dotenv
    load_dotenv(dotenv_path=env_path)

    # Get .env variables
    un      = os.getenv("NAME")
    fp      = os.getenv("FILEPATH")
    api_url = os.getenv("API_URL")
    token   = os.getenv("TOKEN")
    key     = os.getenv("KEY")

    # Concat Project name to path
    #path = fp + "\\" + pn
    path = f"{fp}/{pn}"

    # Create remote repo on GitHub and return repo information local repo
    repo = rp(un, api_url, token, pn, view, key)

    # Create local repo in Python folder and connect to remote repo.
    lp(path, repo, pn)

if __name__ == '__main__':
    main()


import numpy as np
import argparse
import cv2

# Parse the command line arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# Load the image, then split it into R, G, B channels
# Remember that OpenCV stored RGB images as NumPy arrays in reverse
# channel order
image = cv2.imread(args["image"])
(B, G, R) = cv2.split(image)

cv2.imshow("Red", R)
cv2.imshow("Green", G)
cv2.imshow("Blue", B)
cv2.waitKey(0)

# Merge the channels back together with the cv2.merge function
# With the following code we can show the actual colour of the channel
zeros = np.zeros(image.shape[:2], dtype="uint8")
cv2.imshow("Red", cv2.merge([zeros, zeros, R]))
cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))
cv2.waitKey(0)


from numpy import linspace, zeros,sign,array
import matplotlib.pyplot as plt

def f(x):
    return -x**2+6.0*x-5.0
a=-2.0
b=3.0
n=14
c=zeros(n)
error = zeros(n)
xrange = array(range(1,15))
for i in range(n):
    c[i] = (a+b)/2.0
    if(sign(f(c[i]))==sign(f(a))):
        a=c[i]
    else:
        b=c[i]

for i in range(n-1):
    error[i+1]=abs(((c[i+1]-c[i])/c[i+1]))*100

print("%5s %8s %8s" % ('k','c','E'))
for k in range(n):
    print("%5d %9.4f %9.4f" % (k+1,c[k],error[k]))

plt.plot(xrange,c,'k--',label='c')
plt.plot(xrange,error,'ro-',label='E(%)')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('focus', '0032_auto_20161119_1126'),
    ]

    operations = [
        migrations.CreateModel(
            name='ChartData',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
                ('title', models.CharField(max_length=40)),
                ('width', models.IntegerField(default=400)),
                ('height', models.IntegerField(default=400)),
                ('x_data', models.TextField(null=True, blank=True)),
                ('y_data', models.TextField(null=True, blank=True)),
                ('fill_val', models.BooleanField(default=True)),
                ('color_val', models.CharField(blank=True, max_length=10, default=True)),
                ('bg_color_val', models.CharField(blank=True, max_length=10, default=True)),
                ('line_tension', models.FloatField(default=0.0)),
                ('border_width', models.FloatField(default=0.5)),
                ('point_border_width', models.FloatField(default=1.0)),
                ('point_hover_radius', models.FloatField(default=5.0)),
                ('point_hover_radius_width', models.FloatField(default=1.0)),
                ('point_radius', models.FloatField(default=1.0)),
                ('point_hit_radius', models.FloatField(default=10.0)),
                ('chart_type', models.CharField(max_length=40, choices=[('_type_full_history', 'Full History'), ('_type_resampled_avg_m', 'Average Resampled by Month'), ('_type_resampled_sum_w', 'Total Resampled by Week'), ('_type_dual_moving_avg', 'Dual Moving Average'), ('_type_moving_env', 'Moving Envelope'), ('_type_this_month', 'This Month'), ('_type_year_weekly_sum', 'Year Total Resampled by Week')], default='_type_full_history')),
            ],
        ),
        migrations.CreateModel(
            name='Dataset',
            fields=[
                ('chartdata_ptr', models.OneToOneField(primary_key=True, to='focus.ChartData', serialize=False, parent_link=True, auto_created=True)),
            ],
            bases=('focus.chartdata',),
        ),
        migrations.AddField(
            model_name='chartdata',
            name='parent',
            field=models.ForeignKey(to='focus.Task'),
        ),
        migrations.AddField(
            model_name='dataset',
            name='chart',
            field=models.ForeignKey(related_name='+', to='focus.ChartData'),
        ),
    ]


# -*- coding: utf-8 -*-
"""
# @Author  : huxw
# @Update  : 2018/10/16 14:02
# @Software: PyCharm
"""

# 爬取内容：
#     a、最新电竞信息
import json

from new_word_md.utils import format_str
from utils import download_page

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'}

def esportsCrawler(path):
    for i in range(1,10):
        url = 'http://www.dadianjing.cn/index.php?m=Index&a=xhrList&cid=1&page='+str(i)
        try:
            result = download_page.download_html_waitting(url, headers, 1)
            result = json.loads(result,strict=False)
            items = result["data"]["list"]
            # 写入文件
            file = open(path, "a",encoding="utf-8")
            file.write("抓取电竞内容")
            for item in items:
                title = item['title']
                summary = item['summary']
                file.write(format_str((title+":"+summary))+'\n')
                print(title + "---" + summary)
            file.close()
        except Exception as e:
            print ("Except - 电竞:" + url,e)
    return 'success'


# Routines for visualizing a tokamak.

from DREAM.DREAMSettings import DREAMSettings
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

def plotSignal(ax, x, y, name, xlabel=False):
    """
    Plot the given signal nicely.

    :param ax: Axes to plot the signal on.
    :param x:  X coordinates.
    :param y:  Y coordinates.
    """
    ax.plot(x, y, linewidth=2, color=(87/255, 117/255, 144/255))
    if xlabel:
        ax.set_xlabel(r'Minor radius (m)')
    ax.set_ylabel(name)

    ax.set_xlim([x[0], x[-1]])
    ax.set_ylim([0, np.amax(y)*1.2])

def visualize(tokamak, nticks=None, Tticks=None):
    """
    Visualize the given tokamak module.

    :param tokamak: Module reference for the tokamak to visualize.
    """
    fig = plt.figure(figsize=(10,4))
    gs  = gridspec.GridSpec(3, 2)

    gs.update(wspace=0.22, hspace=0, left=0.13, top=0.95, right=0.95, bottom=0.14)

    # Magnetic field
    ds = DREAMSettings()
    tokamak.setMagneticField(ds)

    ax = fig.add_subplot(gs[:,0])
    ds.radialgrid.visualize(ax=ax, ntheta=100)

    #

    # Density
    r, ne0 = tokamak.getInitialDensity()
    axn = fig.add_subplot(gs[0,1])
    plotSignal(axn, r, ne0/1e19, name=r'$n_e$ ($10^{19}\,$m$^{-3}$)')

    if nticks:
        axn.set_yticks(nticks)

    # Temperature
    r, Te0 = tokamak.getInitialTemperature()
    axT = fig.add_subplot(gs[1,1])
    plotSignal(axT, r, Te0/1e3, name=r'$T_e$ (keV)')

    if Tticks:
        axT.set_yticks(Tticks)

    # Current density
    r, j0 = tokamak.getCurrentDensity()
    axj = fig.add_subplot(gs[2,1])
    plotSignal(axj, r, j0, name=r'$j/j_0$', xlabel=True)

    axj.set_yticks(np.linspace(0.2, 1, 3))

    xticks = np.linspace(0, 1, 6)
    if ds.radialgrid.a == 0:
        xticks *= ds.radialgrid.r_f[-1]
    else:
        xticks *= ds.radialgrid.a

    tickparams = {'direction': 'in', 'length': 5, 'top': True, 'right': True, 'labelsize': 13}
    axn.set_xticks(xticks)
    axn.set_xticklabels([])
    axn.tick_params(**tickparams)
    axT.set_xticks(xticks)
    axT.set_xticklabels([])
    axT.tick_params(**tickparams)
    axj.set_xticks(xticks)
    axj.tick_params(**tickparams)

    def settxt(ax, x, y, txt, direction='tl', **kwargs):
        if 'l' in direction: xdir = 0
        else: xdir = 1
        if 'b' in direction: ydir = 0
        else: ydir = 1

        ax.text(ax.get_xlim()[xdir]*x, ax.get_ylim()[ydir]*y, txt, **kwargs)

    #ax.text(ax.get_xlim()[0]*1.04, ax.get_ylim()[1]*0.92, '(a)')
    #axn.text(
    settxt(ax,  0.86, 0.87, '(a)')
    settxt(axn, 0.88, 0.81, '(b)', 'tr')
    settxt(axT, 0.88, 0.81, '(c)', 'tr')
    settxt(axj, 0.88, 0.81, '(d)', 'tr')

    plt.show()


#faulty calculator gives correct output except for 45*3 , 56/6 and 56+9
line1=" is = "
input1=input("Enter the operator = ")
var1=int(input("enter the first number = "))
var2=int(input("enter the second number = "))
if input1=='+':
    if var1==56 and var2==9:
        print(var1,"+",var2,"=77")
    else:
        print("Addition of ",var1,"+",var2,line1,var1+var2)
elif input1=='-':
    print("Substracion of ",var1,"-",var2,line1,var1-var2)
elif input1=='*':
    if var1==45 and var2==3:
        print(var1,"*",var2,"=555")
    else:
        print("Multipication of ",var1,"*",var2,line1,var1*var2)
elif input1=='/':
    if var1==56 and var2==6:
        print(var1,"/",var2,"=4")
    else:
        print("Division of ",var1,"/",var2,line1,var1/var2)
else:
    print("please eneter valid choice")


# 파일명 및 함수명을 변경하지 마시오.
def can_divide(numbers, divisor):
    """
    아래에 코드를 작성하시오.
    numbers는 0이 아닌 양의 정수가 담긴 리스트입니다.
    divisor는 0이 아닌 양의 정수입니다.
    numbers에 담겨있는 숫자들 중, divisor로 나누어 떨어지는 숫자들을 오름차순으로 정렬한 리스트를 반환합니다.
    """

    # 방법 1 (정석)
    result = []
    # divisor 로 나눴을 때 나머지가 0이면, result 에 해당 숫자 추가.
    for number in numbers:
        if number % divisor == 0:
            result.append(number)

    # 모든 numbers 의 요소들을 나눠본 이후, result 가 비었는지 확인.
    if result == []:
        result.append(-1)

    # 정렬하기
    result.sort()
    return result  # sorted(result)

    # 방법 2 (부가적인 로직)
    # list comprehension ==  나머지가 0인 숫자들 뽑기
    result = [number for number in numbers if not number % divisor]

    return sorted(result) if result else [-1]

# 실행 결과를 확인하기 위한 코드입니다. 수정하지 마시오.
if __name__ == '__main__':
    print(can_divide([20, 3, 5, 7], 5))
    print(can_divide([4, 3, 2, 1], 1))
    print(can_divide([7, 11, 13], 3))


import copy

class Stock:

    def __init__(self, products):
        self.products = copy.deepcopy(products) # 'głęboka' kopia słownika
        pass

    def resupply(self, product, count):
        if count <= 0:
            raise ValueError("Can resupply only with positive count.")
        self.products[product] = self.products.get(product, 0) + count
        pass

    def withdraw(self, product, count):
        if count <= 0:
            raise ValueError
        if product not in self.products:
            raise ValueError("Unknown product: " + product)
        if self.products[product] < count:
            raise ValueError("Insufficient number of items in stock.")
        self.products[product] -= count

    def available_items(self):
        items = {}
        for product, count in self.products.items():
            if count > 0:
                items[product] = count
        return items

#Zadanie 8:

    def save(self, file_obj):
        for product, count in self.products.items():
            file_obj.write(product + "," + str(count) + '\n')

    def save2(self, file_obj):
        lines = [prod + ',' + str(count) + '\n' for prod, count in self.products.items()]
        file_obj.writelines(lines)

    @staticmethod
    def load(file_obj):
        data = {}
        for line in file_obj:
            record = line.rstrip('\r\n').split(',')
            data[record[0]] = int(record[1])

        return Stock(data)

stock = Stock({"banana": 3, "orange": 2, "apple": 5, "lemon": 4})

print()
print(stock.available_items())

# prawie mi sie udalo (vide def save):
lista = []
slownik = stock.available_items()
for key,value in slownik.items():
    lista.append((str(key) + "," + str(value))) #zamiast do listy, od razu zapis do pliku: plik.write

with open("magazyn.csv", "wt") as data_file:
    stock.save(data_file)

with open("magazyn2.csv", "wt") as data_file:
    stock.save2(data_file)

with open("magazyn.csv", "rt") as data_file:
    stock2 = Stock.load(data_file)
    print(stock2.available_items())


import os
import subprocess

def cmd(c):
    process = subprocess.Popen(c, stdout=subprocess.PIPE, shell=True)
    output, error = process.communicate()

cmd("mkdir converted")

i = 0

for f in [f for f in os.listdir('.') if os.path.isfile(f)]:
    bash = ("ffmpeg -i '" + f + "' -vf scale=640:-1 -map 0 '_" +
            f + "'")

    cmd(bash)
    cmd("mv '_" + f + "' converted/'" + f + ".mkv'")

    i = i + 1

cmd("exit;exit")


from flask_restful import Resource, abort
from flask import jsonify
from project.parsers import Parser
from project.schema import User, Task
import sqlalchemy
from flask_jwt_extended import (jwt_required, get_jwt_identity)

class CreateTask(Resource):
    """
    Given a request with params {"heading", "description"}
    Endpoint is jwt protected
    """

    @jwt_required
    def post(self):
        task_parser = Parser.get_tasks_parser(id_req=False, heading_req=True, desc_req=True)
        task_data = task_parser.parse_args()
        username = get_jwt_identity()
        user = User.get_user_by_name(username=username)

        task = Task(
            user_id=user.id,
            heading=task_data['heading'],
            description=task_data['description'],
            is_completed=False
        )
        try:
            task.save()
            return {
                'message': 'Task was created successfully',
                'id': task.id
            }
        except:
            abort(500, description="Failed to create task")

class GetTask(Resource):
    """
    Retrieve a task given "id" of task in params
    Endpoint is jwt protected
    """

    @jwt_required
    def get(self, id):
        try:
            task = Task.get_task_by_id(id)
            if task == None:
                raise KeyError
            return {
                'id': task.id,
                'heading': task.heading,
                'description': task.description,
                'is_completed': str(task.is_completed)
            }
        except KeyError:
            abort(409, description='Task %d does not exist' % id)
        except:
            abort(500, description="Unknown exception occured")

class ListTasks(Resource):
    """
    Lists all the tasks for the user logged in.
    Endpoint is jwt protected
    """

    @jwt_required
    def get(self):
        username = get_jwt_identity()
        user = User.get_user_by_name(username=username)
        tasks = user.tasks
        list_of_tasks = []
        for task in tasks:
            list_of_tasks.append({
                'id': task.id,
                'heading': task.heading,
                'description': task.description,
                'is_completed': str(task.is_completed)
            })
        return jsonify(list_of_tasks)

class UpdateTask(Resource):
    """
    Updates a given task. Params may include any of {"heading", "description", "is_completed"}
    Endpoint is jwt protected
    """

    @jwt_required
    def post(self, id):
        task_parser = Parser.get_tasks_parser(id_req=False)
        task_data = task_parser.parse_args()
        task = Task.get_task_by_id(id=id)
        heading = task.heading if ('heading' not in task_data or task_data['heading'] == None) else task_data[
            'heading']
        description = task.description if ('description' not in task_data or task_data['description'] == None) else \
        task_data['description']
        is_completed = task.is_completed if (
                    'is_completed' not in task_data or task_data['is_completed'] == None) else task_data[
            'is_completed']

        try:
            Task.update_task(id=id, heading=heading, description=description, is_completed=bool(is_completed))
            return {
                'message': 'Task updated successfully',
                'id': id,
                'heading': heading,
                'description': description,
                'is_completed': is_completed
            }
        except:
            abort(500, description="Failed to updated task %d" % id)

class DeleteTask(Resource):
    """
    Deletes a task given the task id
    Endpoint is jwt protected
    """

    @jwt_required
    def post(self, id):
        try:
            Task.delete_task(id=id)
            return {
                'message': 'Task Deleted Successfully'
            }
        except sqlalchemy.orm.exc.UnmappedInstanceError:
            abort(409, description="Task %d does not exist" % id)
        except:
            abort(500, description="Failed to delete task %d" % id)


from pykdtree.kdtree import KDTree
import time
import trimesh
import numpy as np

def filter_mesh_significant_outside_pieces(unfiltered_mesh,main_mesh,significance_threshold=2000,n_sample_points=3):
    """
    Purpose; will take in a full, unfiltered mesh and find the biggest mesh piece, and then return a list of that mesh
    with all of the other mesh fragments that are both above the significance_threshold AND outside of the biggest mesh piece

    Pseudocode:
    1) split the meshes to unconnected pieces
    2) Filter the meshes for only those above the significance_threshold
    3) find the biggest mesh piece
    4) Iterate through all of the remaining pieces:
        a. Determine if mesh inside or outside main mesh
        b. If outside add to final list to return

    Returns:
    1) list of significant mesh pieces that are not inside of main mesh

    """

    print("------Starting the mesh filter for significant outside pieces-------")

    mesh_pieces = unfiltered_mesh.split(only_watertight=False)

    print(f"There were {len(mesh_pieces)} pieces after mesh split")

    significant_pieces = [m for m in mesh_pieces if len(m.faces) > significance_threshold]

    print(f"There were {len(significant_pieces)} pieces found after size threshold")
    if len(significant_pieces) <=0:
        print("THERE WERE NO MESH PIECES GREATER THAN THE significance_threshold")
        return []

    final_mesh_pieces = []

    #final_mesh_pieces.append(main_mesh)
    for i,mesh in enumerate(significant_pieces):
        #get a random sample of points
        # points = np.array(mesh.vertices[:n_sample_points,:]) # OLD WAY OF DOING THIS
        idx = np.random.randint(len(mesh.vertices), size=n_sample_points)
        points = mesh.vertices[idx,:]

        start_time = time.time()
        signed_distance = trimesh.proximity.signed_distance(main_mesh,points)
        #print(f"Total time = {time.time() - start_time}")

        outside_percentage = sum(signed_distance <= 0)/n_sample_points
        if outside_percentage > 0.9:
            final_mesh_pieces.append(mesh)
            #print(f"Mesh piece {i} OUTSIDE mesh")
        else:
            #print(f"Mesh piece {i} inside mesh :( ")
            pass

    return final_mesh_pieces

def neuron_boolean_difference(main_mesh_verts,
                             main_mesh_faces,
                             child_mesh_verts,
                             child_mesh_faces,
                             distance_threshold=5,
                             significance_threshold=1000,
                             n_sample_points=3):
    """
    returns the boolean difference of two meshes passed. Only returns meshes pieces that
    are greater than the size threshold and outside of the main mesh

    Function operation: child_mesh - main_mesh

    Parameters:
    main_mesh_verts (np.array): array of the reference mesh vertices
    main_mesh_faces (np.array): array of the reference mesh faces
    child_mesh_verts (np.array): array of the child mesh vertices that is to be compared to the main mesh
    child_mesh_faces (np.array): array of the child mesh faces that is to be compared to the main mesh

    Optional parameters:
    -- for controlling the mesh returned --
    distance_threshold (int) : distance away from the reference mesh that vertices from the child
                                mesh will considered distinct and part of the difference mesh
                                (default=5)
    significance_threshold (int) : number of faces necessary for any distinct/unconnected part of the
                                    difference mesh to be considered relevant and included in the difference mesh
                                (default=1000)
    n_sample_points (int) : number of vertices to check to see if submesh is a mesh located inside of the main mesh.
                            The less there are the quicker the speed for filtering the difference mesh
                            (default=3)

    Returns:
    difference_mesh_verts (np.array): array of vertices from the mesh boolean operation of child - main mesh
    difference_mesh_faces (np.array): array of faces from the mesh boolean operation of child - main mesh
    """

    #Create the kdtree from main mesh and run the queries

    import time
    global_time = time.time()
    start_time = time.time()
    mesh_tree = KDTree(main_mesh_verts)
    distances,closest_node = mesh_tree.query(child_mesh_verts)
    print(f"Total time for KDTree creation and queries: {time.time() - start_time}")

    print("Original number vertices in child mesh = " + str(len(child_mesh_verts)))
    vertex_indices = np.where(distances > distance_threshold)[0]
    print("Number of vertices after distance threshold applied =  " + str(len(vertex_indices)))

    start_time = time.time()
    set_vertex_indices = set(list(vertex_indices))
    face_indices_lookup = np.linspace(0,len(child_mesh_faces)-1,len(child_mesh_faces)).astype('int')
    face_indices_lookup_bool = [len(set_vertex_indices.intersection(set(tri))) > 0 for tri in child_mesh_faces]
    face_indices_lookup = face_indices_lookup[face_indices_lookup_bool]

    print(f"Total time for finding faces after distance threshold applied: {time.time() - start_time}")

    start_time = time.time()
    trimesh_original = trimesh.Trimesh(child_mesh_verts,child_mesh_faces,process=False)
    new_submesh = trimesh_original.submesh([face_indices_lookup],only_watertight=False,append=True)

    pymesh_mesh = trimesh.Trimesh(main_mesh_verts,main_mesh_faces)

    #filter the mesh for only significant pieces on the outside
    returned_mesh = filter_mesh_significant_outside_pieces(new_submesh,pymesh_mesh,significance_threshold,n_sample_points=n_sample_points)

    total_returned_mesh = trimesh.Trimesh()
    for r in returned_mesh:
        total_returned_mesh = total_returned_mesh + r

    print(f"Total time for filtering: {time.time() - start_time}")
    return total_returned_mesh.vertices,total_returned_mesh.faces

    print(f"Total time for boolean difference: {time.time() - global_time}")


#！/usr/bin/evn python
# _*_ coding:utf-8 _*_

from time import sleep
from threading import current_thread, Thread, RLock

lock = RLock()

def show():
    with lock:
        print(current_thread().name, i)
        sleep(0.1)

def test():
    with lock:
        for i in range(3):
            show()

for i in range(2):
    Thread(target=test).start()


import ptah
from pyramid.testing import DummyRequest
from pyramid.httpexceptions import HTTPNotFound

from base import Base

class TestLayoutPreview(Base):

    def setUp(self):
        self._setup_pyramid()

    def test_layout_preview_notfound(self):
        from ptah.manage.layout import LayoutPreview

        request = DummyRequest()

        v = LayoutPreview(None,request)
        self.assertRaises(HTTPNotFound, v.update)

    def test_layout_preview_notfound2(self):
        from ptah.manage.layout import LayoutPreview

        class Context(object):
            """ """

        global View
        class View(object):
            ptah.view.pview('', Context)
            def render(self):
                return 'test' # pragma: no cover

        self._init_ptah()

        request = DummyRequest()

        v = LayoutPreview(Context(), request)
        self.assertRaises(HTTPNotFound, v.update)

    def test_layout_preview(self):
        from ptah.manage.layout import LayoutPreview

        class Context(object):
            """ """
            __name__ = 'test'

        global View
        class View(ptah.view.View):
            ptah.view.pview('', Context)
            def render(self):
                return 'test' # pragma: no cover

        global Layout
        class Layout(ptah.view.Layout):
            ptah.view.layout('', Context, parent=None)

            def render(self, content):
                return '
%s
'%content

        self._init_ptah()

        request = DummyRequest()

        v = LayoutPreview(Context(), request)
        v.update()
        res = v.render()

        self.assertIn('
', res)
        self.assertIn('ptah.manage.tests.test_layout.Layout', res)
        self.assertIn('ptah.manage.tests.test_layout', res)


from django.http import HttpResponse
from django.shortcuts import render
import pandas as pd
import re

def home(request):
    return render(request,'home.html')

def count(request):
    user_text = request.GET['text']
    user_text1 = request.GET['text']
    user_text = re.findall('[\u4e00-\u9fa5]', user_text, re.S)
    total_count=len(user_text)

    word_dict = {}
    for word in user_text:
        if word not in word_dict:
            word_dict[word] = 1

        else:
            word_dict[word] += 1

    dataframe = pd.DataFrame(list(word_dict.keys()), columns=['字'])
    dataframe['频次'] = pd.DataFrame(list(word_dict.values()))
    dataframe.sort_values('频次', inplace=True, ascending=False)
    old_width = pd.get_option('display.max_colwidth')
    pd.set_option('display.max_colwidth', -1)
    dataframe = dataframe.to_html(escape=False, index=False, sparsify=True, border=0, index_names=False, header=False)
    pd.set_option('display.max_colwidth', old_width)

    return render(request , 'count.html',{'count':total_count , 'text':user_text1,'dict':dataframe})

def about(request):
    return render(request ,'about.html')

if __name__ == '__main__':
    home()
    count()
    about()


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^reg_process$', views.reg, name='reg'),
    url(r'^log_process$', views.log),
    url(r'^success$', views.success),
    url(r'^logout$', views.logout),
]


# Copyright (C) 2018 Red Hat, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import fixtures
import mock

from nova.tests.functional import fixtures as func_fixtures
from nova.tests.functional import test_servers as base
from nova.tests.unit.virt.libvirt import fake_imagebackend
from nova.tests.unit.virt.libvirt import fake_libvirt_utils
from nova.tests.unit.virt.libvirt import fakelibvirt

class ServersTestBase(base.ServersTestBase):

    def setUp(self):
        super(ServersTestBase, self).setUp()

        # Replace libvirt with fakelibvirt
        self.useFixture(fake_imagebackend.ImageBackendFixture())
        self.useFixture(fixtures.MonkeyPatch(
            'nova.virt.libvirt.driver.libvirt_utils',
            fake_libvirt_utils))
        self.useFixture(fixtures.MonkeyPatch(
            'nova.virt.libvirt.driver.libvirt',
            fakelibvirt))
        self.useFixture(fixtures.MonkeyPatch(
            'nova.virt.libvirt.host.libvirt',
            fakelibvirt))
        self.useFixture(fixtures.MonkeyPatch(
            'nova.virt.libvirt.guest.libvirt',
            fakelibvirt))
        self.useFixture(fakelibvirt.FakeLibvirtFixture())
        self.useFixture(func_fixtures.PlacementFixture())

        # Mock the 'get_connection' function, as we're going to need to provide
        # custom capabilities for each test
        _p = mock.patch('nova.virt.libvirt.host.Host.get_connection')
        self.mock_conn = _p.start()
        self.addCleanup(_p.stop)

    def _setup_compute_service(self):
        # NOTE(stephenfin): We don't start the compute service here as we wish
        # to configure the host capabilities first. We instead start the
        # service in the test
        self.flags(compute_driver='libvirt.LibvirtDriver')

    def _get_connection(self, host_info, pci_info=None):
        fake_connection = fakelibvirt.Connection(
            'qemu:///system',
            version=fakelibvirt.FAKE_LIBVIRT_VERSION,
            hv_version=fakelibvirt.FAKE_QEMU_VERSION,
            host_info=host_info,
            pci_info=pci_info)
        return fake_connection


class Node:

    def __init__(self, value):
        self.value = str(value)
        self.next = None

    def __repr__(self):
        return f'{self.value} - {repr(self.next)}'

    # def __str__(self):
    #     return f'The current node has a value {self.value}, and the next node is {self.next}'

    def get_value(self):
        return self.value

    def get_next(self):
        return self.next

    def set_value(self, value):
        self.value = value

class LinkedList:

    def __init__(self, head=None):
        self.head = head

    def insert(self, value):
        node = Node(value)
        node.next = self.head
        self.head = node

    def includes(self, value):
        if not self.head:
            return False
        current = self.head

        while current:
            if current.get_value() == value:
                return True
            current = current.get_next()
        return False

    def __str__(self):
        output = ''
        node = self.head

        while node != None:
            output += f'{node.get_value()}'
            node = node.get_next()

        return output.strip()

    def return_list(self):
        current = self.head
        collection_of_values = []
        while current:
            collection_of_values.append(str(current))
            current = current.next
        return collection_of_values

def merge_lists(ll_one, ll_two):
    current_one = ll_one.head
    current_two = ll_two.head
    if current_one ==None:
        current_one = current_two
    else:
        while current_one !=None and current_two !=None:

            one_next = current_one.next
            two_next = current_two.next

            current_one.next = current_two
            if one_next == None:
                break
            current_two.next = one_next

            current_one = one_next
            current_two = two_next
        return ll_one.head


import sys
import operator
import socket
import re

from collections import defaultdict, deque
from calvin.runtime.north.reliability_calculator_factory import get_reliability_calculator
from calvin.runtime.north.task_scheduler_factory import get_task_scheduler

from calvin.utilities import calvinconfig
from calvin.utilities.calvinlogger import get_logger

_conf = calvinconfig.get()
_log = get_logger(__name__)

DEFAULT_HISTORY_SIZE = 20
DEFAULT_REPLICATION_HISTORY_SIZE = 5
DEFAULT_REPLICATION_TIME = 2.0
DEFAULT_NODE_RELIABILITY = 0.8
LOST_NODE_TIME = 0.5
MAX_PREFERRED_USAGE = 80

class ResourceManager(object):
    def __init__(self, history_size=DEFAULT_HISTORY_SIZE):
        self.history_size = history_size
        self.usages = defaultdict(lambda: deque(maxlen=self.history_size))
        rc = _conf.get('global', 'reliability_calculator')
        self.reliability_calculator = get_reliability_calculator(rc)
        ts = _conf.get('global', 'task_scheduler')
        self.task_scheduler = get_task_scheduler(ts, self)
        _log.info("Starting resource manager using reliability calculator {} and task scheduler {}".format(rc, ts))
        self.node_uris = {}
        self.node_ids = {}
        self.test_sync = 2
        self._lost_nodes = set()
        self._rep_times = {}

    def register_uri(self, node_id, uri):
        _log.debug("Registering uri: {} - {}".format(node_id, uri))
        if isinstance(uri, list):
            uri = uri[0]

        if uri:
            uri = uri.replace("calvinip://", "").replace("http://", "")
            addr = uri.split(":")[0]
            port = int(uri.split(":")[1])

            is_ip = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", addr)
            if not is_ip:
                addr = socket.gethostbyname(addr)

            uri = "{}:{}".format(addr, port)
            self.node_uris[node_id] = uri
            self.node_ids[uri] = node_id

    def get_id(self, uri):
        uri = uri.replace("calvinip://", "").replace("http://", "")
        addr = uri.split(":")[0]
        port = int(uri.split(":")[1])

        is_ip = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", addr)
        if not is_ip:
            addr = socket.gethostbyname(addr)

        return self.node_ids.get("{}:{}".format(addr, port))

    def register(self, node_id, usage, uri):
        _log.debug("Registering resource usage for node {}: {} with uri {}".format(node_id, usage, uri))
        self.register_uri(node_id, uri)

        if usage:
            self.usages[node_id].append(usage['cpu_percent'])

    def lost_node(self, node_id):
        if node_id in self._lost_nodes:
            return
        self._lost_nodes.add(node_id)
        del self.usages[node_id]
        _log.debug("Registering lost node: {}".format(node_id))

    def _average_usage(self, node_id):
        return sum(self.usages[node_id]) / max(len(self.usages[node_id]), 1)

    #Only used for evaluation
    def get_avg_usages(self):
        usages = {}
        for node_id in self.usages.keys():
            uri = self.node_uris.get(node_id)
            if uri:
                usages[uri] = self._average_usage(node_id)
        return usages

    def least_busy(self):
        """Returns the id of the node with the lowest average CPU usage"""
        min_usage, least_busy = sys.maxint, None
        for node_id in self.usages.keys():
            average = self._average_usage(node_id)
            if average < min_usage:
                min_usage = average
                least_busy = node_id

        return least_busy

    def most_busy(self):
        """Returns the id of the node with the highest average CPU usage"""
        min_usage, most_busy = - sys.maxint, None
        for node_id in self.usages.keys():
            average = self._average_usage(node_id)
            if average > min_usage:
                min_usage = average
                most_busy = node_id

        return most_busy

    def get_reliability(self, node_id, replication_times, failure_info):
        _log.info("Getting reliability for {}".format(node_id))
        uri = self.node_uris.get(node_id)
        if uri:
            replication_time = self.replication_time(replication_times)
            if uri in failure_info:
                failure_info = failure_info[uri]
            else:
                failure_info = []
            rel = self.reliability_calculator.calculate_reliability(failure_info, replication_time)
            _log.info("Returning reliability for {}: {}".format(node_id, rel))
            return rel
        else:
            _log.info("Returning default reliability: {}".format(DEFAULT_NODE_RELIABILITY))
            return DEFAULT_NODE_RELIABILITY

    def replication_time(self, replication_times):
        if not replication_times:
            return DEFAULT_REPLICATION_TIME

        key = "".join([str(t) for t in replication_times])
        if key in self._rep_times:
            return self._rep_times[key]

        value = self.reliability_calculator.replication_time(replication_times) + LOST_NODE_TIME
        self._rep_times[key] = value
        return value

    def get_preferred_nodes(self, node_ids):
        preferred = []
        for node_id in node_ids:
            if self._average_usage(node_id) < MAX_PREFERRED_USAGE:
                preferred.append(node_id)
        return preferred

    def _update_deque(self, new_values, old_values):
        for tup in new_values:
            if tup[0] > old_values[-1][0]:
                old_values.append(tup)

    def sort_nodes_reliability(self, node_ids, replication_times, failure_info):
        return self.task_scheduler.sort(node_ids, replication_times, failure_info)

    def current_reliability(self, current_nodes, replication_times, failure_info):
        current_nodes = list(set(current_nodes))
        _log.debug("Calculating reliability for nodes: {}".format(current_nodes))
        failure = []
        for node_id in current_nodes:
            f = 1 - self.get_reliability(node_id, replication_times, failure_info)
            _log.debug("Failure for {}: {}".format(node_id, f))
            failure.append(f)

        p = 1 - reduce(operator.mul, failure, 1)
        _log.info("Reliability for nodes {} is {}".format(current_nodes, p))
        return p

    def sync_info(self, usages=None):
        if usages:
            self._sync_usages(usages)

        usages = {}
        for (node_id, usage_list) in self.usages.iteritems():
            usages[node_id] = [usage for usage in usage_list]

        return usages

    def _sync_usages(self, usages):
        """
        Sync the usages for each node_id stored on another node.
        usages is a dict of lists but stored as a dict with deques
        """
        _log.debug("\n\nSyncing usages {} with usages {}".format(self.usages, usages))
        for (node_id, usage_list) in usages.iteritems():
            if (not node_id in self.usages.keys() or len(usage_list) > self.usages[node_id]) and not node_id in self._lost_nodes:
                usage_deq = deque(maxlen=self.history_size)
                for u in usage_list:
                    usage_deq.append(u)
                self.usages[node_id] = usage_deq


# coding: utf-8

# In[2]:

f = open('Chenbei_primers.txt','r')
primer_list = dict()
for line in f:
    token = line.strip().split('\t')
    name = token[0].split('-')[0]
    name = name.split('_')[0]
    if len(token) < 3:
        primer_for = token[1]
    elif len(token) > 2:
        primer_rev = token[1]
        bp = token[2]
        if name not in primer_list:
            primer_list[name] = [primer_for+' '+primer_rev,bp]
        else:
            primer_list[name.lower()] = [primer_for+' '+primer_rev,bp]
f.close()
f_out = open('Chenbei_LD.txt','w')
for gene in sorted(primer_list):
    f_out.write('%s %s '%(gene,primer_list[gene][0]))
    if 'or' in primer_list[gene][1]:
        temp = primer_list[gene][1].split()
        length_former = int(temp[0].rstrip('bp'))
        length_latter = int(temp[2].rstrip('bp'))
        if length_former > length_latter:
            f_out.write('%d %d\n'%(length_latter-5,length_former+5))
        else:
            f_out.write('%d %d\n'%(length_former-5,length_latter+5))
    else:
        f_out.write('%d %d\n'%(int(primer_list[gene][1].rstrip('bp'))-5,int(primer_list[gene][1].rstrip('bp')))+5)
f_out.close()

# In[25]:

# In[ ]:


from datetime import datetime as dt
from datetime import timedelta
from unittest import TestCase

from src.plugins.plugin_filter_day import plugin_filter_day
from src.plugins.plugin_filter_date import plugin_filter_date

class TestPlugins(TestCase):
    def test_plugin_repeat(self):
        today = dt.today()
        delta = timedelta(days=2)
        day = today.strftime('%d').replace('0', '')
        month = today.strftime('%m').replace('0', '')

        params_1 = {
            'from_date': (today - delta).strftime('%Y-%m-%d'),
            'to_date': (today + delta).strftime('%Y-%m-%d'),
            'days': day,
            'months': month
        }
        result = plugin_filter_date(**params_1)
        self.assertTrue(result)

        params_2 = {
            'to_date': (today + delta).strftime('%Y-%m-%d'),
            'days': '1-31',
            'months': str(int(month) - 2)
        }
        result = plugin_filter_date(**params_2)
        self.assertFalse(result)

    def test_plugin_day(self):
        test_all = 'Sun,Mon-Fri,Sat'
        test_any = 'any'
        test_wrong = 'wro'

        self.assertTrue(plugin_filter_day(test_all))
        self.assertTrue(plugin_filter_day(test_any))
        self.assertFalse(plugin_filter_day(test_wrong))


# -*- coding: cp1252 -*-
import nltk
from nltk.tokenize import word_tokenize

def res():
# Step 1 – Training data
 train = [

    ("Nifty India,ONGC and gail marginally higher","Positive"),
    ("Nifty ends marginally up on BSE","Positive"),
    ("Modest Monday Nifty ends above 7500 mark in choppy session","Positive"),
    ("Nifty zooms 10%","Positive"),
    ("Nifty declares interim dividend; stock zooms 7%","Positive"),
    ("Daily Market Strategy Holding on! Sensex, Nifty to start upbeat","Positive"),
    ("Top 18 stocks in focus today: SBI, Tata Motors, SpiceJet","Positive"),
    ("Sensex, Nifty extend gains to 2nd week in a row","Positive"),
    (" Nifty Dividend delight! Bharat Forge, Welspun India others declare dividend","Positive"),
    ("Nifty, Welspun India among 15 scrips that hit 52-week high","Positive"),
    ("Skipper soars after winning order from Power Grid","Positive"),

    '''("Oil stocks end mixed; cabinet approves policy on hydrocarbon exploration","Positive"),
    ("Dalmia Bharat Sugar,Kellton Tech among 10 stocks that hit 52-week high","Positive"),
    ("Godrej Consumer acquires 39% additional stake in DGH Owned Style Industries; stock down","Positive"),
    ("Pipavav Defence rallies 11%","Positive"),
    ("Marsons gallops 10% on bagging EPC contract","Positive"),
    ("Va Tech Wabag gallops 7% on order win","Positive"),
    ("Mphasis rises 2.9%; BSE seeks clarification on Mint report","Positive"),
    ("VA Tech Wabag bags order worth Rs. 594 crore","Positive"),
    ("Strides Shasun to acquire 3 brands from Moberg Pharma for USD 10 Million","Positive"),
    ("HMT gallops 14.6%","Positive"),
    ("Daily Market Strategy - Another fine Friday start! Indices to open in green","Positive"),
    ("European indices gain as EU, UK reach deal in Brexit talks","Positive"),("Indian ADRs end higher on positive global cues","Positive"),("Nasdaq closes higher led by gains in tech shares","Positive"),("Major Asian indices inch higher","Positive"),("European indices rebound as profit booking wanes","Positive"),("Japan's Nikkei rebounds in the early trade","Positive"),("Dow Jones closes at record high","Positive"),("US Fed nominee comments and strong consumer data aid US indices to close at record highs","Positive"),("US Indices end higher; gold prices slip","Positive"),
    ("Indian ADRs end higher tracking strong US markets","Positive"),

    ("US benchmark Indices end lower","Negative"),
    ("US indices end off-lows; tax bill nears passage","Negative"),
    ("Asian markets subdued following tepid US close","Negative"),
    ("Most US indices end lower as FOMC indicates dovish stance","Negative"),
    ("Coal India crashes 7% despite hefty dividend; plans to buyback 5%","Negative"),
    ("Sasken gallops 20%; settles Protocol Stack IP dispute","Negative"),
    ("Falling low! Jammu & Kashmir Bank, Prestige Estates among 11 stocks that hit 52-week lows","Negative"),
    ("High value stocks tumble since January 2016","Negative"),
    ("Ramky Infrastructure, Sequent Scientific among 10 stocks that hit 52-week high","Negative"),
    ("Hot stocks: Reliance slumps 3%, Golden Tobacco gallops 11%","Negative"),
    ("Syndicate Bank ends flat; reports a Rs. 1000 crore scam","Negative"),
    ("Despite late recovery Metal stocks end in red; Vedanta dips 3%","Negative"),
    ("ICRA, Visagar Polytex among 15 scrips that hit 52-week low","Negative"),
    ("Mindtree slumps 9%; issues Q4 revenue warning","Negative"),
    ("Nifty slips below 7500 mark","Negative"),
    ("SBI releases Rs. 1465 crores to defence pensioners","Neutral"),
    ("Timing, rhyming and relative calm in the equity markets","Neutral"),
    ("Sebi bars wilful defaulters from raising public funds","Neutral"),
    ("Fine Friday finally! Nifty settles above 7500","Neutral"),
    ("JSPL tumbles 5%; Franklin Temp MF sells bonds","Negative"),
    ("Crompton Greaves accepted revised offer for sale of T&D assets","Neutral"),
    ("Why CONCOR is in the news today?","Neutral"),
    ("Yes Bank ends flat; appoints former CCI chairman Ashok Chawla","Neutral"),
    ("Sensex, Nifty end flat; BoB, SBI top Nifty losers","Neutral"),
    ("Thomas Cook signs strategic alliance with Western Union Business Solutions and DCB Bank","Neutral"),
    ("Asian indices end mixed; China Shanghai Composite slips","Neutral"),
    ("Asian indices mixed tracking weak cues from US markets","Neutral"),
    ("European Markets trade mixed on Thursday","Neutral"),
    ("Asian indices mixed ahead of key economic data","Neutral"),
    ("US shares end on a mixed note","Neutral"),
    ("Indian ADRs end on a mixed note on Friday","Neutral"),
    ("SpiceJet plunges 4%","Negative"),
    ("SpiceJet crashes 4.5% over court battle","Negative"),
    ("Pfizer plunges 7% after discontinuing Corex sale; Mcap erodes by Rs. 821 cr","Negative"),
    ("IDBI Bank dips by 1.44%, Moody's affirmed its rating","Negative"),
    (  "United Spirits slips 2%; plans to sell 13 residential properties","Negative"),
    ("Sensex, Nifty to open flat with negative bias","Negative"),
    ("Nifty hits 52 week high","Positive") ,
    ("Nifty hits 52 week low","Negative")'''
 ]

 # Step 2
 dictionary = set(word.lower() for passage in train for word in word_tokenize(passage[0]))

 # Step 3
 t = [({word: (word in word_tokenize(x[0])) for word in dictionary}, x[1]) for x in train]

 # Step 4 – the classifier is trained with sample data
 classifier = nltk.NaiveBayesClassifier.train(t)

 test_data = "Nifty "
 test_data_features = {word.lower(): (word in word_tokenize(test_data.lower())) for word in dictionary}

 result=(classifier.classify(test_data_features))
 return result
res()


import os

backend_vcl = """
backend {0} {{
    .host = "{1}";
    .port = "{2}";
    .probe = {{
        .url = "{3}";
        .timeout = 1s;
        .interval = 30s;
        .window = 3;
        .threshold = 2;
    }}
}}
"""

probe_urls = {
    "lists": "/404.html",
    "things": "/404.html",
    "utilities": "/404.html",
    "bandiera": None
}

class Backend(object):

    def __init__(self, name, data, url):
        self.name = name
        self.ip = data['ip']
        self.ports = data['ports']
        self.url = url

    def get_vcl(self):
        vcl = ''
        for port in self.ports:
            vcl += backend_vcl.format(self.name, self.ip, port, self.url)
        return vcl

class Director(object):

    def __init__(self, name):
        self.name = name
        self.backends = []

    def add_backend(self, data):
        index = len(self.backends) + 1
        backend_name = self.name + '_' + str(index)
        url = probe_urls.get(self.name, '/')
        if url:
            backend = Backend(backend_name, data, url)
            self.backends.append(backend)

    def get_vcl(self):
        vcl = []
        vcl.append(
            '    new {0} = directors.round_robin();'.format(self.name)
        )
        for backend in self.backends:
            vcl.append('    {0}.add_backend({1});'.format(self.name, backend.name))
        return os.linesep.join(vcl)

class VclFile(object):

    def __init__(self):
        self.directors = {}

    def add_backend(self, data):
        name = data['service']
        director = self.directors.get(name)
        if not director:
            director = Director(name)
            self.directors[name] = director
        director.add_backend(data)

    def get_vcl(self):
        vcl = [
            'import directors;',
            '',
        ]

        for director in self.directors.values():
            for backend in director.backends:
                vcl.append(backend.get_vcl())

        vcl.append('')
        vcl.append('sub init_backends {')

        for director in self.directors.values():
            vcl.append(director.get_vcl())

        vcl.append('}')
        return os.linesep.join(vcl)