import heapq
from collections import Counter

class Node:
    def __init__(self, char, freq):
        self.char = char
        self.freq = freq
        self.left = None
        self.right = None

    def __lt__(self, other):
        return self.freq < other.freq

def build_huffman_tree(text):
    char_freq = Counter(text)
    priority_queue = [Node(char, freq) for char, freq in char_freq.items()]
    heapq.heapify(priority_queue)

    while len(priority_queue) > 1:
        left = heapq.heappop(priority_queue)
        right = heapq.heappop(priority_queue)
        merged = Node(None, left.freq + right.freq)
        merged.left = left
        merged.right = right
        heapq.heappush(priority_queue, merged)

    return priority_queue[0]

def build_huffman_codes(node, current_code="", codes=None):
    if codes is None:
        codes = {}
    if node is not None:
        if node.char is not None:
            codes[node.char] = current_code
        build_huffman_codes(node.left, current_code + "0", codes)
        build_huffman_codes(node.right, current_code + "1", codes)
    return codes

def huffman_encode(text):
    root = build_huffman_tree(text)

    codes = build_huffman_codes(root)
    encoded_text = "".join(codes[char] for char in text)
    print(codes)
    return encoded_text

with open('input.txt', 'r') as file:
    input_string = file.read()

    encoded_result = huffman_encode(input_string)

    with open('output.txt', 'w') as output:
        output.write(encoded_result)
    print(encoded_result)


"""
* File Name:           Day 1 part two: Sonar Sweep.py
* Author:              Deep Shah
* Date:                1st Dec 2022

"""

with open("Day 1 raw_data.txt") as file:
    Arr = [line.strip() for line in file.readlines()]

i, j = 0, 0
res, sum = 0, 0
count = 0

#sliding window technique

while(j < len(Arr)):
            sum = sum + int(Arr[j])
            if j - i + 1 < 3:   #check if window size is hit
                j += 1
            elif j - i + 1 == 3:
                if res == 0:    #this will be the first result (no previous sum)
                    res = sum
                elif sum > res: #compare with previous sum
                    count += 1
                res = sum
                sum = sum - int(Arr[i])
                i += 1          #now slide the window
                j += 1

print(count)


#!/usr/bin/env python3

########### SVN repository information ###########
# $Date$
# $Author$
# $Revision$
# $URL$
# $Id$
########### SVN repository information ###########

'''
The heart of Kevin's monthly-report software.

Connects the interface to the log-file backend.
'''

import xmllog

class ReportLog:
  '''
  Class representing a monthly-report log.

  :param str logFile: file name
  :returns: ReportLog object
  :rtype: complex structure from :meth:`getLog()`

  .. alternate form, use when the "type" is more than one word
  ..  :param other: this is not used
  ..  :type other: list of **objects**
  '''
  def __init__(self, logFile):
    self.definitions()

    # import xml log file?
    self.logFile = self.createLogFileObj(logFile, self.logEntryDef[:])

    # log file in array of entry objs form
    self.entryArray = self.getLog()
    #! self.printLog()

  def createLogFileObj(self, logFile, logEntryDef):
    '''
    Method called by __init__ to create the log file instance. Designed to be overriden without having to reimplement __init__.
    '''
    return xmllog.XmlLog(logFile, logEntryDef)

  def definitions(self):
    '''
    Method called by __init__ to define the fields users will have to input.  Designed to be overridden without having to reimplement __init__.
    '''
    # These must match the fields available in entry.ReportEntry
    # Title is currently dependent on group. Moving title before group in the list will break tab completion in the cli
    self.logEntryDef = [
        "date",
        "duration",
        "activity",
        "group",
        "title",
        "description",
        "payCode"
      ]

  def getLogEntryDef(self):
    '''
    Retuns the log entry definition list.  Called by user interfaces and file-writing modules.
    '''
    return self.logEntryDef[:]

  def _recursiveCollectLabels(self, ent, labels, struct, level=0):
    '''
    A recursive funtion is needed to hand the arbitrary number of levels.

    Creates dictionaries for the higher levels and populates the list at the lowest level.
    '''
    #!print(ent, labels, struct, level)
    getFun, setFun, verifyFun = ent.getFunctions(labels[level])
    label = getFun()

    numLabels = len(labels)
    lastIndex = numLabels - 1

    if level == lastIndex:
      if label not in struct:
        struct.append(label)
    else:
      if level == lastIndex - 1:
        if label not in struct:
          struct[label] = []
      else:
        if label not in struct:
          struct[label] = {}

      self._recursiveCollectLabels(ent, labels, struct[label], level+1)

  def collectLabels(self, labels):
    '''
    Collects the labels on entries from the work log.

    Returns nested dictionaries of labels, with lists at the lowest level.
    '''
    levels = len(labels)
    if levels == 1:
      struct = []
    else:
      struct = {}

    for x in self.entryArray:
      #!print(x)
      self._recursiveCollectLabels(x, labels[:], struct)

    return struct

  def collectGroups(self):
    '''
    Return a list of groups that already exist in the log.

    Used by high-level interfaces for tab-completion.
    '''
    groups = []
    # loop over all entries in the log
    for x in self.entryArray:
      if x.group not in groups:
        groups.append(x.group)

    return groups[:]

  def collectEntries(self, group, field):
    '''
    Return a list of responses to the prompt for field (choice for field are defined in self.logEntryDef) for entries matching the given group.

    group and field are both strings.

    Used by high-level interfaces to tab-complete previously-entered titles based on the chosen group.
    '''
    entries = []
    # loop over all entries in the log
    for x in self.entryArray:
      getFun, setFun, verifyFun = x.getFunctions(field)
      # if the group of an entry matches the desired group...
      if group == x.group or group == "":
        entry = getFun()
        # ...and the text of the desired field isn't already in the list...
        if entry not in entries:
          # add it to the list
          entries.append(entry)

    return entries[:]

  def addEntry(self, entry):
    '''
    Method that actually calls the backend to add the entry.

    entry is an ReportEntry object.
    '''
    #!print(entry)
    self.logFile.addEntry(entry)
    # update the entry array
    self.entryArray = self.getLog()

  def getEntry(self, index):
    '''
    Returns a single ReportEntry object.

    index is an integer (numbering from 0)
    '''
    #!print("INDEX ", index)
    return self.entryArray[index]

  def replaceEntry(self, index, entry):
    '''
    Tells the backend to replace the desired entry and updates the array of entries.

    index is an integer (numbered from 0)
    entry is a ReportEntry object
    '''
    # Sanity check, display the changed entry
    #entry.printEntry()

    self.logFile.replaceEntry(index, entry)
    # update the entry array
    self.entryArray = self.getLog()

  def changeTitle(self, changeList, tag=False):
    '''
    Execute a bulk title change.

    changeList is a list: [oldGroup, oldTitle, newGroup, newTitle]
    '''

    oldGroup, oldTitle, newGroup, newTitle = changeList

    for x in self.entryArray:
      if x.group == oldGroup and x.title == oldTitle:
        groupGetFun, groupSetFun, groupVerifyFun = x.getFunctions('group')
        titleGetFun, titleSetFun, titleVerifyFun = x.getFunctions('title')

        # Is it worth it to test to see if the group or title are different before setting?
        # Should a copy of the object be modified instead of the object itself?
        groupSetFun(newGroup)
        titleSetFun(newTitle)

        if tag == True:
          descGetFun, descSetFun, descVerifyFun = x.getFunctions('description')
          oldDesc = descGetFun()
          newDesc = "(%s/%s) %s" % (oldGroup, oldTitle, oldDesc)
          descSetFun(newDesc)

        # Actually replace the entry with the modified entry
        self.logFile.replaceEntry(int(x.index)-1, x)

    # update the entry array
    self.entryArray = self.getLog()

  def getLog(self):
    '''
    Tell the backend to update the array of entries.
    '''
    return self.logFile.convertLogToObjs()

  def getLogLength(self):
    '''
    Returns the number of entries in the log (Integer).  Useful when validating indices.
    '''
    return len(self.entryArray)

  def isValidIndex(self, index):
    '''
    Returns True if there is a log entry for the desired index.

    index is an integer (numbering from 1)
    '''
    logLength = self.getLogLength()
    if index > 0 and index <= logLength:
      valid = True
    else:
      valid = False
    return valid

  def getAnalysis(self, dayList=None):
    '''
    Do the analysis.

    Returns this tuple
    (details, groupTotals, titleTotals, recordedTotal, theoreticalHours, percent)

    ================  ===================================================================================
    variable          description
    ================  ===================================================================================
    detail            A dictionary of dictionaries. Outer dict keys are groups, inner dict
                      keys are titles, and values of inner dict are ReportEntry objects.
    groupTotals       A dictionary with keys that are groups. Values are recorded hours for that group.
    titleTotals       A dictionary of dictionaries. Outer dict keys are groups, inner dict
                      keys are titles, and values of inner dict are recorded hours for that title.
    recordedTotal     Total recorded hours
    theoreticalHours  Total theoretical hours assuming eight hours per day and at least one entry per day
    percent           recordedTotal / theoreticalHours * 100.0
    ================  ===================================================================================
    '''
    # Make sure there is something to analyze
    if self.getLogLength() == 0:
      #!print("There is nothing to analyze!")
      return None

    if dayList == None:
      entryList = self.entryArray
    else:
      entryList = []
      for x in self.entryArray:
        if x.date[-2:] in dayList:
          entryList.append(x)

    if len(entryList) == 0:
      return None

    # List of days in the log
    days = []
    # Dictionary of dictionaries. Outer level has group keywords, inner dict has title keywords, values of inner dict are duration totals for that group-title combo
    titleTotals = {}
    # Dictionary of dictionaries, similiar to titleTotals.  Instead of totals, it has arrays of entry objects.
    details = {}
    #
    groupTotals = {}

    for x in entryList:
      # Count the days for total work-day calculation
      if x.date not in days:
        days.append(x.date)

      if x.group not in titleTotals:
        titleTotals[x.group] = {}
        details[x.group] = {}

      if x.title not in titleTotals[x.group]:
        titleTotals[x.group][x.title] = 0.0
        details[x.group][x.title] = []

      numDuration = float(x.duration)

      details[x.group][x.title].append(x)
      titleTotals[x.group][x.title] += numDuration

    #!print("titleTotals", titleTotals)
    #!print("groupTotals", groupTotals)

    groups = list(titleTotals.keys())
    groups = sorted(groups)

    # Compute group totals after all groups and titles have been collected.
    recordedTotal = 0.0
    for group in groups:
      titles = titleTotals[group].keys()
      titles = sorted(titles)

      # Loop over titles to get a group total
      groupTotal = 0.0
      for title in titles:
        groupTotal += titleTotals[group][title]

      groupTotals[group] = groupTotal
      recordedTotal += groupTotal

    # Compute theoretical work hours, assuming 8hr days and at least one entry for each work day
    workDays = len(days)
    theoreticalHours = workDays * 8.0
    percent = recordedTotal / theoreticalHours * 100.0

    # Not the best way to return the analysis.  In the future there should probably be an analysis class.
    return (details, groupTotals, titleTotals, recordedTotal, theoreticalHours, percent)

  def getDay(self, day):
    '''
    Returns info for a given day.

    day is a zero-padded, two-character string represting the day of the month.

    Returns the following tuple: (dayArray[:], dayHours, percentRecorded)

    ===============  =======================================================
    variable         description
    ===============  =======================================================
    dayArray         Array of ReportEntry objects matching the specified day
    dayHours         Total hours recorded for the specified day
    percentRecorded  Percent recorded, assuming an eight-hour day
    ===============  =======================================================

    '''
    # day is a zero padded string
    dayArray = []
    dayHours = 0.0
    percentRecorded = 0.0
    for x in self.entryArray:
      if day == x.date[-2:]:
        dayArray.append(x)
        dayHours += float(x.duration)
    percentRecorded = dayHours / 8.0 * 100.0

    return (dayArray[:], dayHours, percentRecorded)

  def getDaySummary(self, day):
    '''
    Returns summary for a given day.

    day is a zero-padded, two-character string represting the day of the month.

    Returns the following tuple: (dayArray[:], dayHours, percentRecorded)

    ===============  =======================================================
    variable         description
    ===============  =======================================================
    groups           Array of groups from the specified day
    totals           Dict of totals with groups as keys
    entries          Dict of lists of entries with groups as keys
    dayHours         Total hours recorded for the specified day
    percentRecorded  Percent recorded, assuming an eight-hour day
    ===============  =======================================================

    '''
    dayArray, dayHours, percentRecorded = self.getDay(day)

    dayArraySorted = sorted(dayArray, key=self._customSortKey)

    runTot = 0.0
    lastGroup = None
    groups = []
    totals = {}
    entries = {}

    for item in dayArraySorted:
      # Add the group to the group list
      if item.group not in groups:
        groups.append(item.group)

      # Keep a running total for the group
      if item.group not in totals:
        totals[item.group] = float(item.duration)
      else:
        totals[item.group] += float(item.duration)

      # Categories the entries
      if item.group not in entries:
        entries[item.group] = [item]
      else:
        entries[item.group].append(item)

    # [[group, hours, [entry1, entry2]], [],
    return (groups[:], totals, entries, dayHours, percentRecorded)

  def _customSortKey(self, entry):
    '''
    Custom sort routine for entry objects
    '''
    return (entry.group, entry.title, entry.index)

  def printLog(self):
    '''
    Prints the entire log
    '''
    #log = self.logFile.convertLogToObjs()
    for x in self.entryArray:
      print("")
      x.printEntry()
    print("")

  def saveLog(self):
    '''
    Tell the backend to save the log file.
    '''
    self.logFile.save()


import argparse
import asyncio
from datetime import datetime, timedelta
import json
import pytz

from dateutil.tz import tzlocal
import requests
import websockets

ARGS = argparse.ArgumentParser(description='Coinbase Exchange Data Collector')
ARGS.add_argument('--m', action='store', dest='minutes', default=5, help='Minutes to run')
args = ARGS.parse_args()

minutes = int(args.minutes)
begin = datetime.now(tzlocal())
end = begin + timedelta(minutes=minutes)

def get_beginning_level_3():
    global beginning_level_3
    beginning_level_3 = requests.get('https://api.pro.coinbase.com/products/BTC-USD/book?level=3').json()

def get_ending_level_3():
    global ending_level_3
    ending_level_3 = requests.get('https://api.pro.coinbase.com/products/BTC-USD/book?level=3').json()

@asyncio.coroutine
def get_websocket_data():
    coinbase_websocket = yield from websockets.connect("wss://ws-feed.pro.coinbase.com")
    yield from coinbase_websocket.send('{"type": "subscribe", "product_id": "BTC-USD"}')
    global messages
    global latencies
    messages = []
    latencies = {}
    while True:
        message = yield from coinbase_websocket.recv()
        message = json.loads(message)
        messages += [message]
        latencies[message['time']] = int((datetime.now(tzlocal()) -
                                              datetime.strptime(message['time'], '%Y-%m-%dT%H:%M:%S.%fZ')
                                              .replace(tzinfo=pytz.UTC)).microseconds)
        if datetime.now(tzlocal()) > end:
            return

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.call_later(10, get_beginning_level_3)
    loop.call_later(minutes*60-10, get_ending_level_3)
    loop.run_until_complete(get_websocket_data())
    global messages
    global beginning_level_3
    global ending_level_3
    global latencies

    first_sequence = beginning_level_3['sequence']
    last_sequence = ending_level_3['sequence']

    messages = [message for message in messages if first_sequence < message['sequence'] <= last_sequence]
    messages = sorted(messages, key=lambda k: k['sequence'])
    for message in messages:
        assert message['sequence'] == first_sequence + 1
        first_sequence = message['sequence']

    with open('latencies.json', 'w') as json_file:
        json.dump(latencies, json_file, indent=4, sort_keys=True)
    with open('messages.json', 'w') as json_file:
        json.dump(messages, json_file, indent=4, sort_keys=True)
    with open('beginning_level_3.json', 'w') as json_file:
        json.dump(beginning_level_3, json_file, indent=4, sort_keys=True)
    with open('ending_level_3.json', 'w') as json_file:
        json.dump(ending_level_3, json_file, indent=4, sort_keys=True)


"""
Class used to parse and update template when tracing is enabled
"""
import logging
from typing import Any

from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap
from ruamel.yaml.representer import RoundTripRepresenter

from samcli.lib.init.template_modifiers.cli_template_modifier import TemplateModifier

LOG = logging.getLogger(__name__)

class XRayTracingTemplateModifier(TemplateModifier):
    FIELD_NAME_FUNCTION_TRACING = "Tracing"
    FIELD_NAME_API_TRACING = "TracingEnabled"
    GLOBALS = "Globals"
    RESOURCE = "Resources"
    FUNCTION = "Function"
    TRACING_FUNCTION = "Tracing"
    ACTIVE_TRACING = "Active"
    API = "Api"
    TRACING_API = "TracingEnabled"
    TRACING_API_VALUE = True
    COMMENT = (
        "# More info about Globals: "
        "https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst\n"
    )

    # set ignore aliases to true. This configuration avoids usage yaml aliases which is not parsed by CloudFormation.
    class NonAliasingRTRepresenter(RoundTripRepresenter):
        def ignore_aliases(self, data):
            return True

    def __init__(self, location):
        self.yaml = YAML()
        self.yaml.Representer = XRayTracingTemplateModifier.NonAliasingRTRepresenter
        super().__init__(location)

    def _get_template(self) -> Any:
        with open(self.template_location) as file:
            return self.yaml.load(file)

    def _update_template_fields(self):
        """
        Add new field to SAM template
        """
        if self.template.get(self.GLOBALS):
            template_globals = self.template.get(self.GLOBALS)

            function_globals = template_globals.get(self.FUNCTION, {})
            if not function_globals:
                template_globals[self.FUNCTION] = {}
            template_globals[self.FUNCTION][self.TRACING_FUNCTION] = self.ACTIVE_TRACING

            api_globals = template_globals.get(self.API, {})
            if not api_globals:
                template_globals[self.API] = {}
            template_globals[self.API][self.TRACING_API] = self.TRACING_API_VALUE

        else:
            self._add_tracing_with_globals()

    def _add_tracing_with_globals(self):
        """Adds Globals and tracing fields"""
        global_section = {
            self.FUNCTION: {self.TRACING_FUNCTION: self.ACTIVE_TRACING},
            self.API: {self.TRACING_API: self.TRACING_API_VALUE},
        }

        self.template = CommentedMap(self.template)
        self.template[self.GLOBALS] = CommentedMap(global_section)
        self.template.yaml_set_comment_before_after_key(self.GLOBALS, before=self.COMMENT)

    def _print_sanity_check_error(self):
        link = (
            "https://docs.aws.amazon.com/serverless-application-model/latest"
            "/developerguide/sam-resource-function.html#sam-function-tracing"
        )
        message = f"Warning: Unable to add Tracing to the project. To learn more about Tracing visit {link}"
        LOG.warning(message)

    def _write(self, template: list):
        """
        write generated template into SAM template

        Parameters
        ----------
        template : list
            array with updated template data
        """
        with open(self.template_location, "w") as file:
            self.yaml.dump(self.template, file)


# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 14:26:01 2019

@author: Tianqi Guo
"""

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # Solution 1 beats 99.66%: binary search on each line
        # deal with trivial cases
        if not matrix or not matrix[0]:
            return False
        # right limit: all numbers on the right of this location on this line is larger than target
        # so all numbers on the right of this location on lines below are also larger than target
        rr = len(matrix[0]) - 1
        # continue searching while there are still numbers from beginning till rr
        # and there are more lines to go
        while rr >= 0 and matrix:
            # pop the top line for current search
            # for some reason it is faster than
            # for row in matrix:
            row = matrix.pop(0)
            # search limits
            l, r = 0, rr
            # binary search in this limit
            while l <= r:
                # mid value
                m = (l + r)/2
                # if found, return YES
                if row[m] == target:
                    return True
                # update left search limit on this line
                elif row[m] < target:
                    l = m + 1
                # update right search limit on this line
                else:
                    r = m - 1
                    # also update the global right limit
                    rr = m - 1
        # if all possibles are searched, then target does not exist
        return False

#        # Solution 2 beats 8.06%: binary search on borders, and update rectangular searching region
#        # subfunction for binary search
#        def b_search(nums,target):
#            h, t = 0, len(nums)
#            while h < t - 1:
#                m = int((h+t)/2)
#                if nums[m] == target:
#                    return m
#                elif nums[m] > target:
#                    t = m
#                else:
#                    h = m
#            return h
#
#        while matrix and matrix[0]:
#
#            x = matrix[0]
#            y = [row[0] for row in matrix]
#            x1 = b_search(x,target)
#            if x[x1] == target:
#                return True
#            y1 = b_search(y,target)
#            if y[y1] == target:
#                return True
#
#            x = matrix[-1]
#            y = [row[-1] for row in matrix]
#            x2 = b_search(x,target)
#            if x[x2] == target:
#                return True
#            y2 = b_search(y,target)
#            if y[y2] == target:
#                return True
#
#            matrix = [row[x2+1:x1+1] for row in matrix[y2+1:y1+1]]
#
#        return False

matrix = [
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
target = 14

test = Solution()
print(test.searchMatrix(matrix,target))
#        # search the closet value to the target
#        head = b_search(heads,target)
#        # determine what interval the target falls in
#        row, rmd = divmod(head, 2)
#        # if target is in heads list
#        if heads[head] == target:
#            # target found
#            return True
#        # if target is larger the last element in one row,
#        # and smaller than the first element in the next row
#        elif rmd == 1:
#            # target is not in the matrix for sure
#            return False
#        # if target falls into the range of one row
#        else:
#            # find its closest position in this row
#            clm = b_search(matrix[row],target)
#            # check if the closest value is equal to the target
#            return matrix[row][clm] == target


import functools as ft, itertools as it, operator as op, collections as co, cmath, math, re, traceback, copy, string

fin = './Short Programming\SimplyIrreducibleIn.txt'
fout = './Short Programming\SimplyIrreducibleOut.txt'
open(fout, 'w').close()

def splitcases(x):
    return x.strip('\n*\n').split('\n*\n')

def solve(x, n):
    x = int(x)

    def irreducible(num, den):
        return math.gcd(num, den) == 1

    s = 0
    for den in range(1, 100):
        for num in range(1, 100):
            if not num / den < x:
                continue
            if not irreducible(num, den):
                continue
            s += num / den
    return f'{s:.3f}'

for num, case in enumerate(splitcases(open(fin).read())):
    print(f'Case {num + 1}:')
    try:
        sol = str(solve(case, num))
        print(sol, '\n')
    except Exception:
        print(f'Input: "{case[:99]}"')
        print(traceback.format_exc())
        sol = ''
    open(fout, 'a').write(sol + '\n*\n')


#!/usr/bin/python
import sys

pagesize = 11
preamble = """
%nodefault,area 90 90, vgap 260, size 8, font "standard", fore "#134d73", back "white", right, newimage -zoom 75 "vu-logo.png"
%size 3

%size 6, vgap 40, left
""".strip()

pagebreak = "%page\n" + preamble

def format(lines):
    iterlines = iter(lines)

    def nextline():
        return next(iterlines, None)

    print(preamble)
    nlines = 0
    line = nextline()
    while line is not None:
        if line.startswith("#"):
            print(line.strip())
            line = nextline()
            continue
        output = []
        if '--' in line:
            a, b = line.split("--", 1)
            output = []
            if a:
                output += ['%font "thick"\n' + a.strip()]
            if b.strip():
                output.append('%font "standard"\n\t' + b.strip())
                line = nextline()
            else:
                while True:
                    line = nextline()
                    if line is None:
                        break
                    if not line.startswith('    '):
                        break
                    line = line[4:]
                    output.append('%font "standard"\n\t' + line.rstrip())
        else:
            output = ['%font "thick"\n' + line.strip()]
            line = nextline()
        if nlines + len(output) > pagesize:
            nlines = 0
            print(pagebreak)
        print("\n".join(output))
        nlines += len(output)

format(sys.stdin)


""" Shooter Functions """
import wpilib
from ctre import *
from wpilib.controller import PIDController

class Shooter:
    def __init__(self):
        """ Shooter """
        # shooter motors and encoders
        self.topShooterEncoder = WPI_TalonSRX(5)
        self.topShooterMotor = WPI_VictorSPX(6)
        self.bottomShooterEncoder = WPI_TalonSRX(7)
        self.bottomShooterMotor = WPI_VictorSPX(8)

        # inverses shooter motors
        self.topShooterMotor.setInverted(True)

        # shooter motor groups
        self.topMotors = wpilib.SpeedControllerGroup(self.topShooterEncoder, self.topShooterMotor)
        self.bottomMotors = wpilib.SpeedControllerGroup(self.bottomShooterEncoder, self.bottomShooterMotor)

        """ Shooter PID """
        # top PID
        self.kPTop = 0.17    # 0.1
        self.kITop = 0.005  # 0.001
        self.kDTop = 0.01      # 0
        self.kFTop = 1.05  # 1.15

        self.integralTop = 0
        self.previousErrorTop = 0
        self.setpointTop = 0

        # bottom PID
        self.kPBottom = 0.3   # 0.105
        self.kIBottom = 0 # 0.001
        self.kDBottom = 0.05     # 0
        self.kFBottom = 0.90 # 0.999

        self.integralBottom = 0
        self.previousErrorBottom = 0
        self.setpointBottom = 0

    def convertVelocityToRPM(velocity):
        """ This method will take in velocity and convert the velocity into rotations per minute

        :param rawVelocity:
        :type rawVelocity: float
        :return rpm:
        :rtype rpm: float
        """
        conversionFactor = 600 / 4096
        RPM = velocity * conversionFactor
        return RPM

    def getShooterRPM(self, motors):
        """ This method will get velocity return rpm of the top or bottom shooter speed controller group
        :return rpm:
        :rtype rpm: float
        """
        if motors == 'Top':
            topEncoderVelocity = self.topShooterEncoder.getSelectedSensorVelocity()
            topShooterRPM = Shooter.convertVelocityToRPM(topEncoderVelocity)
            return topShooterRPM

        elif motors == 'Bottom':
            bottomEncoderVelocity = self.bottomShooterEncoder.getSelectedSensorVelocity()
            bottomShooterRPM = Shooter.convertVelocityToRPM(bottomEncoderVelocity)
            return bottomShooterRPM

    def setSetpoint(self, PID, setpoint):
        """ Sets the setpoints of the top or bottom shooter motors """
        if PID == 'Top':
            self.setpointTop = setpoint
        elif PID == 'Bottom':
            self.setpointBottom = setpoint

    def setVarPID(self, kP, kI, kD, kF, motor):
        """ Sets the variables for PID to be set """
        if motor == 'Top':
            self.kPTop = kP
            self.kITop = kI
            self.kDTop = kD
            self.kFTop = kF
        if motor == 'Bottom':
            self.kPBottom = kP
            self.kIBottom = kI
            self.kDBottom = kD
            self.kFBottom = kF

    def setPID(self, PID):
        """ Method to set two different PIDs for top shooter and bottom shooter with a backspin on bottom shooter """
        if PID == 'Top':
            errorTop = self.setpointTop - self.getShooterRPM('Top')
            self.integralTop = self.integralTop + errorTop

            if self.integralTop > 4400:
                self.integralTop = 4400

            derivative = errorTop - self.previousErrorTop
            self.rcwTop = (self.kPTop * errorTop) + (self.kITop * self.integralTop) + (self.kDTop * derivative) + (self.kFTop * self.setpointTop)
            self.PIDTopOutput = self.rcwTop / 4400
            self.previousErrorTop = errorTop

        elif PID == 'Bottom':
            errorBottom = abs(self.setpointBottom) - abs(self.getShooterRPM('Bottom'))
            self.integralBottom = self.integralBottom + errorBottom

            if self.integralBottom > 4400:
                self.integralBottom = 4400

            derivative = errorBottom - self.previousErrorBottom
            self.rcwBottom = (self.kPBottom * errorBottom) + (self.kIBottom * self.integralBottom) + (self.kDBottom * derivative) + (self.kFBottom * self.setpointBottom)
            self.PIDBottomOutput = self.rcwBottom / 4400
            self.previousErrorBottom = errorBottom

    def execute(self, PID):
        """ Executes the drive-train PID """
        if PID == 'Top':
            self.setPID('Top')
            self.topMotors.set(self.PIDTopOutput)
        elif PID == 'Bottom':
            self.setPID('Bottom')
            self.bottomMotors.set(self.PIDBottomOutput)


def main():

    n = int(input())
    dp = [[1] + [0] * (n-1) for _ in range(n)]
    for i in range(1, n):
        for j in range(1, i+1):
            dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
    for l in dp:
        print(" ".join([str(d) for d in l if d != 0]))

if __name__ == '__main__':
    main()


#training model

import cv2                        #open cv library
import numpy as np                #for mathematical calculation
from os import listdir            #class of os module // when fetching data
from os.path import isfile,join

data_path ="E:/PROJECT/Face-Recognition-Project/Face-Recognition-Project-master/sample"
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path,f))]

Training_Data,Labels = [],[]

for i,files in enumerate(onlyfiles):
    image_path = data_path + onlyfiles[i]
    images = cv2.imread(image_path,cv2.IMREAD_GRAYSCALE)
    Training_Data.append(np.asarray(images,dtype=np.uint8))
    Labels.append(i)

Labels = np.asarray(Labels,dtype=np.int32)

model = cv2.face.LBPHFaceRecognizer_create()

model.train(np.asarray(Training_Data),np.asarray(Labels))

print("Congratulations model is TRAINED ... *_*...")

face_classifier = cv2.CascadeClassifier("C:/Users/AYUSH/AppData/Local/Programs/Python/Python310/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")


import copy
from typing import Generic, Iterable, TypeVar, Optional, Union,List

T = TypeVar('T')

class BSTNode(Generic[T]):
    """
    Your node should permit at least the following
    node.left: get the left child
    node.right: get the right child
    """

    def __init__(self, value: T, children: Optional[List["BSTNode[T]"]] = None,
                 parent: Optional["BSTNode[T]"] = None) -> None:
        # children[1] is the right node, children[0] is the left node.
        self.value = value
        if children == None:
            self.left: Union[None, "BSTNode"] = None
            self.right: Union[None, "BSTNode"] = None
        else:
            self.left = children[0]
            self.right = children[1]
        self.parent: Union[None, "BSTNode"] = parent

    def __iter__(self) -> Iterable["BSTNode[T]"]:
        if self.left is not None:
            yield self.left
        if self.right is not None:
            yield self.right

    # when I do for x in BST node what I return here will be iterated through

    def __deepcopy__(self, memodict) -> "BSTNode[T]":
        """
        I noticed that for some tests deepcopying didn't
        work correctly until I implemented this method so here
        it is for you
        :param memodict:
        :return:
        """
        copy_node = BSTNode(copy.deepcopy(self.value, memodict))
        copy_node.left = copy.deepcopy(self.left, memodict)
        copy_node.right = copy.deepcopy(self.right, memodict)
        copy_node.parent = copy.deepcopy(self.parent, memodict)
        return copy_node

    def __str__(self):
        return self.__dict__

    def __eq__(self, other:"BSTNode")->bool:
        if type(self)!=type(other):
            return False
        elif self.value==other.value:
            return True
        else:
            return False


__author__ = "Matthias Stefan"
__version__ = "1.0.0"

from src.execution import IExecution
from src.model import Asset
from src.manager import Endpoint

class ModelUploadExecutor(IExecution):
    def process_row(self, row):
        """
        Process a single row of data.

        This method processes a row of data to upload a new asset model to the Snipe-IT system.

        :param row: A row of data representing an asset model.
        :type row: dict
        """
        asset = Asset.from_csv(row)
        endpoint = Endpoint()
        endpoint.callback = self._snipe_manager.post
        endpoint.value = '/hardware'
        endpoint.payload = asset.get(validate_not_none=True)
        self._snipe_manager.execute_now(endpoint)


from graphene_django.filter import DjangoFilterConnectionField

class MyChildrenAuditionField(DjangoFilterConnectionField):

    @classmethod
    def resolve_queryset(
            cls, connection, iterable, info, args, filtering_args, filterset_class
    ):
        qs = super(DjangoFilterConnectionField, cls).resolve_queryset(
            connection, iterable, info, args
        )
        filter_kwargs = {k: v for k, v in args.items() if k in filtering_args}
        qs = filterset_class(data=filter_kwargs, queryset=qs, request=info.context).qs

        parent = info.context.user.parent
        students = parent.students.all()
        year = args.get('year', None)
        month = args.get('month', None)
        qs = qs.filter(audition_details__student__in=students,
                       date_audition__year=year,
                       date_audition__month=month
                       ).distinct()

        return qs


import matplotlib.pyplot as plt
import numpy as np
import scipy

fig = plt.figure(figsize=(16, 8))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-5, 5)
y1 = 1/(1 + np.exp(- x))
y2 = np.exp(- x)/(1 + np.exp(- x))**2

plt.subplot(1, 2, 1)
plt.xlabel('x')
plt.ylabel('F(x)')
plt.title(u'$Logistic$ 分布函数')
plt.plot(x, y1, linewidth = 2.0)

plt.subplot(1, 2, 2)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title(u'$Logistic$ 密度函数')
plt.plot(x, y2, linewidth = 2.0)

plt.savefig('../images/821_01.png')
plt.show()


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

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('landing', '0003_auto_20150115_2009'),
    ]

    operations = [
        migrations.CreateModel(
            name='Video',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('file_name', models.CharField(verbose_name='Название видеофайла', max_length=400)),
                ('enabled', models.BooleanField(default=False)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AlterField(
            model_name='metric',
            name='visible',
            field=models.BooleanField(default=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='value',
            name='time',
            field=models.DateTimeField(default=datetime.datetime(2015, 1, 17, 6, 47, 39, 403884)),
            preserve_default=True,
        ),
    ]


# 엘리베이터 알고리즘
def scan(start, requests):
    # 서비스할 요청들을 저장할 변수를 초기화합니다.
    serviced_req = []
    # SCAN 알고리즘은 요청이 없는 방향으로 이동할 때도 이동 거리를 더해주어야 합니다.
    total_distance = abs(start - requests[0])

    # 요청 리스트를 현재 헤드 위치에서 왼쪽과 오른쪽으로 분리합니다.
    left_req = [req for req in requests if req < start]
    right_req = [req for req in requests if req >= start]

    # 왼쪽 요청 리스트와 오른쪽 요청 리스트를 각각 정렬합니다.
    left_req.sort(reverse=True)
    right_req.sort()

    # 오른쪽으로 이동하면서 요청을 서비스합니다.
    for req in right_req:
        serviced_req.append(req)
        total_distance += abs(start - req)
        start = req

    # 가장 끝까지 이동한 후에 다시 방향을 바꿉니다.
    total_distance += abs(start - max(left_req + right_req))
    start = max(left_req + right_req)

    # 왼쪽으로 이동하면서 요청을 서비스합니다.
    for req in left_req:
        serviced_req.append(req)
        total_distance += abs(start - req)
        start = req

    # 서비스된 요청들과 이동 거리의 총합을 반환합니다.
    return serviced_req, total_distance

# 사용 예시
if __name__ == "__main__":
    start = 50
    requests = [98, 183, 37, 122, 14, 124, 65, 67]
    serviced_req, total_distance = scan(start, requests)
    print("서비스된 요청: ", serviced_req)
    print("이동 거리의 총합: ", total_distance)


import sys

from keywords import *
from helpers import *

tweetAckMin = 2

if len(sys.argv) == 2:
	tweetAckMin=int(sys.argv[1])

#API CONNECTION
API = twitter_setup()

#GET REQUIRED DATA FROM TWEETS
processedTweets = []
tweetSet = set()

for keyword in keywords:
	#Look for tweets from a given keyword
	keywordTweets = API.search(q='#'+keyword, tweet_mode='extended')
	#Get tuples with keyword and relevant tweet data tweet
	processedTweetBatch = [ filterTweetData(rawTweet, keyword) for rawTweet in keywordTweets ]
	#Add those tweets to the collections
	processedTweets += processedTweetBatch

linkSet = set( tweet['link'] for tweet in processedTweets if tweet['link'] != None and tweet['acks'] > tweetAckMin  )

for link in linkSet:
	print("Opening link {}".format(link))
	openBrowserTab(link)


import sys

from PyQt5 import QtWidgets,QtGui

def Pencere():
    app = QtWidgets.QApplication(sys.argv)
    pencere = QtWidgets.QWidget()
    etiket  = QtWidgets.QLabel(pencere)
    image = QtWidgets.QLabel(pencere)
    buton = QtWidgets.QPushButton(pencere)

    pencere.setGeometry(200,200,500,800)
    pencere.setWindowTitle("Merhaba Dünya")

    etiket.setText("Mehaba Dünya")
    etiket.move(50,100)

    image.move(75,210)
    image.setPixmap(QtGui.QPixmap("Images/logo.png"))

    buton.setText("Click It!!!")
    buton.move(300,100)
    pencere.show()
    sys.exit(app.exec())

Pencere()


from collections import deque

def bfs(i, j):
    #초기값
    q = deque([(i, j)])
    while q:
        si, sj = q.popleft()
        for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
            ni = si+di
            nj = sj+dj

            if 0<=ni<N and 0<=nj<M and arr[ni][nj] == 1: #이동가능한칸 + 범위내
                q.append((ni, nj))
                arr[ni][nj] += arr[si][sj]

    return arr[N-1][M-1]

N, M = map(int, input().split())
arr = [list(map(int, list(input()))) for _ in range(N)]
print(bfs(0, 0))


import time
from functools import wraps

def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        r = func(*args, **kwargs)
        end = time.perf_counter()
        print('{}.{} : {}'.format(func.__module__,
                                  func.__name__,
                                  end-start))
        return r
    return wrapper


#!/usr/bin/python3.5

#ANN model applied to Corporate Investment Grade Bonds
#Purely for Demonstration purposes

import numpy as np
import pandas as pd
from datetime import datetime
import keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix

def main():

	#input raw bond data
	raw_Bond_data = pd.read_csv('CSV Bond Data File Path')

	#Remove all entries with missing data
	#Done for model demonstration purposes
	#Optional
	bond_data = raw_Bond_data.dropna()

	#Convert 'Maturity' and 'S&P Init Rtg Dt' to datetime
	bond_data['Maturity'] = pd.to_datetime(bond_data['Maturity'])
	bond_data['S&P Init Rtg Dt'] = pd.to_datetime(bond_data['S&P Init Rtg Dt'])

	#Convert 'Maturity' and 'S&P Init Rtg Dt' to ordinal numbers
	bond_data['Maturity'] = bond_data['Maturity'].apply(datetime.toordinal)
	bond_data['S&P Init Rtg Dt'] = bond_data['S&P Init Rtg Dt'].apply(datetime.toordinal)

	#Convert Categorical Ratings
	labelencoder_rate = LabelEncoder()
	bond_data['S&P Rating']=labelencoder_rate.fit_transform(bond_data['S&P Rating'])

	labelencoder_init_rate = LabelEncoder()
	bond_data['S&P Init Rtg'] = labelencoder_init_rate.fit_transform(bond_data['S&P Init Rtg'])

	#Create Binary field to depict change in bond rating
	bond_data['Binary'] = bond_data['S&P Init Rtg'] < bond_data['S&P Rating']
	bond_data['Binary'] = bond_data.Binary.astype(int)

	#Convert 'Maturity Type'
	labelencoder_mat_type = LabelEncoder()
	bond_data['Maturity Type']=labelencoder_mat_type.fit_transform(bond_data['Maturity Type'])

	#Convert 'S&P Outlook'
	labelencoder_outlook = LabelEncoder()
	bond_data['S&P Outlook'] = labelencoder_outlook.fit_transform(bond_data['S&P Outlook'])
	bond_data['S&P Outlook']

	#independent variables
	# dependent variables
	#'Cpn', 'Maturity', 'Maturity Type',
    #'90D Volatility', 'Yld to Mty (Mid)', 'Rev Growth', 'Amount Issued',
    #'Amt Out', 'CDS Recovery Rate', 'CDS Spread (5yr Mid)',
    #'Earnings Assets / Interest Bearing Liabililties', 'S&P Init Rtg Dt',
    #'S&P Outlook',
	x = bond_data.iloc[:,[3,4,5,6,7,8,9,10,11,12,13,16]].values

	#Dependent variable
	# 'S&P Rating'
	y = bond_data.iloc[:,18].values

	#split into training and test partitions
    # .30 = test, .70 = train
	x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.30, random_state = 0)

	#feature scaling
	sc = StandardScaler()
	x_train = sc.fit_transform(x_train)
	x_test = sc.fit_transform(x_test)

	#intialize ANN
	classifier = Sequential()

	# Adding the input layer and the first hidden layer
	classifier.add(Dense(units = 7, kernel_initializer = 'uniform', activation = 'relu', input_dim = 12))

	# Adding the second hidden layer
	classifier.add(Dense(units = 7, kernel_initializer = 'uniform', activation = 'relu'))

	# Adding the output layer
	classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))

	# Compiling the ANN
	classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

	# Fitting the ANN to the Training set
	#batch_size = after number of observations to update wieghts
	classifier.fit(x_train, y_train, batch_size = 10, epochs = 1500)

	# Predicting the Test set results
	y_pred = classifier.predict(x_test)
	print(y_pred)

	# Making the Confusion Matrix
	cm = confusion_matrix(y_test, y_pred.round())
	print(cm)

main()


import json
from datetime import datetime

class Feed:
    data = {
        "status": 0,
        "error": 0,
        "source": {},
        "articles": []
    }
    def __init__(self, status:int, id:int=None):
        self.id = id
        self.data["status"] = status

    def serialize(self) -> str:
        return json.dumps(self.data)

    def set_source(self, link:str, title:str, etag:str, description:str, version:str, updatedAt:str=None):
        self.data["source"] = {
            "title": title,
            "description": description,
        }
        if version:
            self.data["source"]["version"] = version
        if etag:
            self.data["source"]["etag"] = etag
        if updatedAt:
            self.data["source"]["updatedAt"] = updatedAt

    def add_article(self, id:int, link:str, title:str, description:str, publishedAt:str, updatedAt:str):
        self.data["articles"].append({
            "feedId": id,
            "link": link,
            "title": title,
            "description": description,
        })
        if updatedAt:
            self.data["articles"][-1]["updatedAt"] = updatedAt
        if publishedAt:
            self.data["articles"][-1]["publishedAt"] = publishedAt

    def add_link(self, link:str):
        self.data['source']['link'] = link

    @staticmethod
    def format_datetime(parsed_date:str) -> str:
        dt_obj = datetime(*parsed_date[:6])
        return dt_obj.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

    def scrap_data(self, raw_data) -> int:
         # Invalid RSS
        if raw_data.bozo:
            self.data["error"] = 1
            return 1
        # Source title
        self.data["source"]["title"] = raw_data.feed['title']

        # Source description
        if "summary" in raw_data.feed:
            self.data["source"]["description"] = raw_data.feed['summary']
        elif "subtitle" in raw_data.feed:
            self.data["source"]["description"] = raw_data.feed['subtitle']

        # Source etag
        if "etag" in raw_data:
            self.data["source"]["etag"] = raw_data.etag

        # Source version
        if "version" in raw_data:
            self.data["source"]["version"] = raw_data.version

        # Source updated date
        if "updated_parsed" in raw_data:
            self.data["source"]["updatedAt"] = Feed.format_datetime(raw_data["updated_parsed"])

        if "entries" in raw_data:
            entries = raw_data["entries"]
            n = len(entries)
            for i in range(n):

                # Entry id
                entry_id = entries[i].id

                # Entry link
                entry_link = ""
                if "link" in entries[i]:
                    entry_link = entries[i].link
                elif "links" in entries[i]:
                    if type(entries[i]["links"]) == list and len(entries[i]["links"]) > 0:
                        if "href" in entries[i]["links"][0]:
                            entry_link = entries[i]["links"][0]["href"]

                # Entry title
                entry_title = entries[i].title

                # Entry description
                if "summary" in entries[i]:
                    entry_description = entries[i]["summary"]
                elif "description" in entries[i]:
                    entry_description = entries[i]["description"]
                else:
                    entry_description = ""

                # Entry published date and format the datetime object as a string
                entry_published = ""
                if "published_parsed" in entries[i]:
                    entry_published = Feed.format_datetime(entries[i].published_parsed)

                entry_updated = ""
                if "updated_parsed" in entries[i]:
                    entry_updated = Feed.format_datetime(entries[i].updated_parsed)

                self.add_article(id=entry_id, link=entry_link, title=entry_title, description=entry_description,
                                publishedAt=entry_published, updatedAt=entry_updated)
        return 0


#!/usr/bin/env python
# encoding: utf-8
"""
Defines the model classes for 2D and 3D models.
"""
__docformat__ = 'reStructuredText'

import numpy as np
import pandas as pd
import scipy.sparse as sparse

from sajou.materials import Material
from sajou.nodes import Node2D
from sajou.sections import BeamSection
from sajou.elements import (Beam2D, Spring2D)

class Model(object):
    """Defines a model object

    Parameters
    ----------
    name: str
        name of the model
    dimensionality: str
        spacial dimensions used in the model ('2D' or '3D')

    Attributes
    ----------
    nodes: dict
        dictionary with all the nodes of the system
    beams: dict
        dictionary with all the beams of the system
    beam_sections: dict
        dictionary with the beam sections defined in the model
    materials: dict
        dictionary with the materials defined in the model
    n_nodes: int
        number of nodes of the system
    n_elements: int
        number of beams in the system
    n_materials: int
        number of materials defined
    n_dimensions: int
        number of spacial dimensions of the model
    n_dof_per_node: int
        number of degrees of freedom per node
    _name: str
        name of the model
    _dimensionality: str
        spacial dimensions used in the model

    """

    def __new__(cls, name, dimensionality):
        if cls is Model:
            if dimensionality == '2D':
                return super(Model, cls).__new__(Model2D)
            if dimensionality == '3D':
                return super(Model, cls).__new__(Model3D)
        else:
            return super(Model, cls).__new__(cls, name, dimensionality)

    def __init__(self, name, dimensionality):
        self._name = name
        self._dimensionality = dimensionality
        # Node Freedome Allocation Table:
        self.nfat = dict()
        #
        self.nodes = dict()
        self.elements = dict()
        self.beams = dict()
        self.beam_sections = dict()
        self.materials = dict()
        #
        self.n_nodes = 0
        self.n_elements = 0
        self.n_materials = 0
        self._K = None  # global stiffness matrix
        self._P = None  # load matrix
        self._V = None  # global displacement matrix
        # Number of dimensions of the model
        self.n_dimensions = None
        # Number of dof per node. Initialized in the respective models
        self.n_dof_per_node = None
        # Specify dofs that are not active due to border conditions
        self._dof_dirichlet = []
        # Node Freedom Allocation Table
        self._nfat = dict()
        # Node Freedom Map Table:
        # Stores the index of the first used DOF of a node in the global
        # system.
        self._nfmt = dict()

    def material(self, name, data, type='isotropic'):
        """Function used to create a Material instance in the model

        Parameters
        ----------
        name: str
            name of the material
        data:
            data for the material
        type: str
            type of the material

        Returns
        -------
        sajou.Material
            a Material instance

        """
        material = Material(name=name, data=data, type=type)
        # Add the material to the dictionary of materials in the current
        # model
        self.materials[name] = material
        self.n_materials += 1

        return material

    def beam_section(self, name, material, data, type='rectangular'):
        """Function use to create a BeamSection instance in the model

        Parameters
        ----------
        name: str
            name of the section
        material: sajou.Material
            material for the section
        data:
            data (see BeamSection class definition)
        type:
            type of the section (see BeamSection class definition)
        Returns
        -------
        returns
            a beam section instance

        """
        # The material can be passed both as a string, corresponding to
        # a key of the material dictionary of the model, or as a
        # material instance directly.

        if isinstance(material, str):
            material_section = self.materials[material]
        else:
            material_section = material

        section = BeamSection(name=name, material=material_section, data=data,
                              type=type)
        # Add section to the list of beam sections
        self.beam_sections[name] = section

        return section

    def bc(self, node, type='displacement', coord_system='global', **kwargs):
        """Introduces a border condition to the node.

        Parameters
        ----------
        node: sajou.Node
            Node to which the border condition will be applied
        type: str
            type of border condition

            - Options:
                ``'displacement'``, ``...``

        coord_system:
            spcifies the coordinate system to be used when applying the BC
        **kwargs:
            keyword arguments. At least one of the following parameters must
            be supplied

        Keyword Arguments
        -----------------
        v1: float
            displacement in the direction 1
        v2: float
            displacement in the direction 2
        v3: float
            displacement in the direction 3
        r1: float
            rotation in the direction 1
        r2: float
            rotation in the direction 2
        r3: float
            rotation in the direction 3

        Returns
        -------
        bool
            True if successful

        """
        # TODO: currently only in global coordintaes. Implement
        # transformation in other coordinate systems.

        # Get the BC applied
        v1 = kwargs.get('v1', None)
        v2 = kwargs.get('v2', None)
        v3 = kwargs.get('v3', None)
        r1 = kwargs.get('r1', None)
        r2 = kwargs.get('r2', None)
        r3 = kwargs.get('r3', None)

        # For the case of the 2D model
        if self.n_dof_per_node == 3:
            list_dof = [v1, v2, r3]
            for dof, curr_bc in enumerate(list_dof):
                if curr_bc is not None:
                    node.set_BC(dof=dof, val=curr_bc)

        # For the case of the 3D model
        elif self.n_dof_per_node == 6:
            list_dof = [v1, v2, v3, r1, r2, r3]
            for dof, curr_bc in enumerate(list_dof):
                if curr_bc is not None:
                    node.set_BC(dof=dof, val=curr_bc)

        return True

    # TODO: there has to give a 'Load' class to handle the different
    # type of loads.
    def load(self, node, coord_system='global', **kwargs):
        """Introduces a Load in the given direction according to the selected
        coordinate system at the specified node.

        Parameters
        ----------
        node: sajou.Node
            a Node instance
        coordinate:
            coordinate system
        **kwargs:
            keyword arguments. The BC is defined for the different degree of
            freedom (*dof*) available to the node.
            At least one of the following parameters must be supplied:

        Keyword Arguments
        -----------------
        f1: float
            force in direction 1
        f2: float
            force in direction 2
        f3: float
            force in direction 3
        m1: float
            moment in direction 1
        m2: float
            moment in direction 2
        m3: float
            moment in direction 3

        Returns
        -------
        sajou.Load
            the instance of the Load object created

        """
        # TODO: currently only in global coordintaes. Implement
        # transformation in other coordinate systems.

        # Get the BC applied
        f1 = kwargs.get('f1', None)
        f2 = kwargs.get('f2', None)
        f3 = kwargs.get('f3', None)
        m1 = kwargs.get('m1', None)
        m2 = kwargs.get('m2', None)
        m3 = kwargs.get('m3', None)

        # For the case of the 2D model
        if self.n_dof_per_node == 3:
            list_dof = [f1, f2, m3]
            for dof, curr_force in enumerate(list_dof):
                if curr_force is not None:
                    node.set_Load(dof=dof, val=curr_force)

        # For the case of the 3D model
        elif self.n_dof_per_node == 6:
            list_dof = [f1, f2, f3, m1, m2, m3]
            for dof, curr_force in enumerate(list_dof):
                if curr_force is not None:
                    node.set_Load(dof=dof, val=curr_force)

        return None

    def export_model_data(self):
        """Export all the data of the model. This means the nodes, elements,
        border conditions and forces are exported to a ModelData object.

        Returns
        -------
        sajou.model.ModelData
            the data of the whole analyzed model

        """
        model_data = ModelData(self)

        return model_data

    def add_hinge(self, node):
        """Add hinge to the specified node. Also supports list of nodes

        Parameters
        ----------
        node: sajou.Node
            Node instance or list of node instances

        Returns
        -------
        bool
            TODO

        Todo
        ----
        This function still needs work
        """
        #FIXME: not yet implemented!
        if isinstance(node, list):
            for node_i in node:
                node_i.add_hinge()
        else:
            node.add_hinge()

        return True

    def __str__(self):
        """
        Printable string
        """
        return str(
            'Model: Name: {name}, Nodes: {n_nodes}, Elements: {n_elements}'.format(
                name=self._name, n_nodes=self.n_nodes, n_elements=self.n_elements))

    def __repr__(self):
        """
        Returns the printable string for this object
        """
        return str(
            'Model: Name: {name}, Nodes: {n_nodes}, Beams: {n_elements}'.format(
                name=self._name, n_nodes=self.n_nodes, n_elements=self.n_elements))

class Model2D(Model):
    """
    Subclass of the 'Model' class. It is intended to be used for the 2-dimensional
    models of frame structures.

    Allocation of DOFs in each node:

            [1 2 3] = [ux, uy, rz]

    Parameters
    ----------
    name: str
        name of the model

    Attributes
    ----------
    n_dimensions: int
        number of spacial dimensions (2 for Model2D)
    n_dof_per_node: int
        number of degrees of freedom per node

    """

    def __init__(self, name, dimensionality='2D'):
        dimensionality = '2D'
        Model.__init__(self, name, dimensionality)
        # Numer of dimensions
        self.n_dimensions = 2
        # Number of degrees of freedom per node:
        self.n_dof_per_node = 3

    def node(self, x, y):
        """2D implementation of the Node.

        Parameters
        ----------
        x: float
            x position
        y: float
            y position

        Returns
        -------
        sajou.Node
            the node created

        """
        # A coordinate z=0 is passed to initiate the Node Instance
        node = Node2D(x=x, y=y, z=0.0, number=self.n_nodes)
        self.nodes[node.number] = node
        self.n_nodes += 1

        return node

    def beam(self, node1, node2):
        """Define a beam element between two nodes.

        Parameters
        ----------
        node1: sajou.Node
            first node
        node2: sajou.Node
            second node

        Returns
        -------
        sajou.Beam
            the beam element created

        """
        beam = Beam2D(node1=node1, node2=node2, number=self.n_elements)
        self.beams[beam.number] = beam
        # add to the element repository of the model
        self.elements[beam.number] = beam
        # add to the element counter
        self.n_elements += 1

        return beam

    def spring(self, node1, node2, K):
        """Define a spring element between two nodes

        Parameters
        ----------

        node1: Node instance
            first node
        node2: Node instance
            second node
        K: float
            elastic constant of the spring

        Returns
        -------

        sajou.Spring2D:
            A Sprind 2D instance

        """
        spring = Spring2D(node1=node1, node2=node2, number=self.n_elements)
        # assign the elastic constant
        spring.assign_elastic_constant(K)
        # add to the element repository of the model
        self.elements[spring.number] = spring
        # add to the element counter
        self.n_elements += 1

        return spring

    def distributed_load(self, elements, **kwargs):
        """Add a distributed load to a list of beam elements.

        A list of elements has to be supplied for the first variable. The rest of the
        variables are exactly the same as in the 'distributed_load' function of the
        corresponding elements.

        Parameters
        ----------
        elements: list
            list of beam elements
        p1: float
            value of the force at start node
        p2: float
            value of the force at end node
        direction: int
            direction of the applied load (default: *2*)
        coord_system: str
            coordinate system (default: global)

        Returns
        -------
        bool
            TODO

        """
        for curr_elem in elements:
            # Add distributed load
            curr_elem.distributed_load(**kwargs)

        return True

class Model3D(Model):
    """
    Subclass of the 'Model' class. It is intended to be used for the 3-dimensional
    models of frame structures.

    Allocation of DOFs in each node:

            [1 2 3 4 5 6] = [ux, uy, uz, rx, ry, rz]

    """

    def __init__(self, name, dimensionality='3D'):
        dimensionality = '3D'
        Model.__init__(self, name, dimensionality)
        self.n_dof_per_node = 6  # dof per node

    def node(self, x, y, z):
        """
        3D implementation of the Node.

        Parameters
        ----------

        x: float
            x-position of the node
        y: float
            y-position of the node
        z: float
            z-position of the node

        Returns
        -------

        Node: instance of Node

        """
        node = Node(x=x, y=y, z=z, number=self.n_nodes)
        self.nodes[node.number] = node
        self.n_nodes += 1

        return node

    def beam(self, node1, node2):
        """Define a line between two nodes.

        :node1: first node
        :node2: second node

        """
        line = Beam3D(node1=node1, node2=node2, number=self.n_elements)
        self.beams[line.number] = line
        self.n_elements += 1

        return line

class ModelData(object):
    """Object to store the data of a model object. It is used to pass it to the results object"""

    def __init__(self, model):
        """Initializes the ModelData instance

        :model: a Model instance

        """
        from copy import copy

        self._name = model._name
        self._dimensionality = model._dimensionality
        self.nodes = copy(model.nodes)
        self.beams = copy(model.beams)
        self.elements = copy(model.elements)
        self.beam_sections = copy(model.beam_sections)
        self.materials = copy(model.materials)
        self.n_nodes = model.n_nodes
        self.n_elements = model.n_elements
        self.n_dimensions = model.n_dimensions
        self.n_materials = model.n_materials
        # Number of dof per node. Initialized in the respective models
        self.n_dof_per_node = model.n_dof_per_node
        # Specify dofs that are not active due to border conditions
        self._dof_dirichlet = copy(model._dof_dirichlet)

def get_dataframe_of_node_coords(model, nodes='all'):
    """Return a pandas dataframe with coordinates of selected nodes of the model

    Parameters
    ----------

    nodes: list, str
        list of nodes or 'all'

    Returns
    -------

    DataFrame:
        DataFrame with the coordinates of the nodes

    """
    dimensions = model.n_dimensions
    #
    if nodes == 'all':
        nodes = [i for i, n in model.nodes.items()]

    ar_coords = np.zeros((len(nodes), dimensions), dtype=np.float)
    index_nodes = np.zeros(len(nodes), dtype=np.int)

    for ix_node, curr_node in enumerate(nodes):
        node_i = model.nodes[curr_node]
        ar_coords[ix_node, :] = node_i.coords
        index_nodes[ix_node] = curr_node

    # Set coordinate labels according to the model
    if dimensions == 2:
        index_label = ['x', 'y']
    else:
        index_label = ['x', 'y', 'z']

    # Append to the Dta Frame
    df_coords = pd.DataFrame(data=ar_coords, index=index_nodes,
                             dtype=np.float64, columns=index_label)

    return df_coords

def get_node_coords(model, nodes='all'):
    """Return a dictionary with coordinates of selected nodes of the model

    Parameters
    ----------

    nodes: list, str
        list of nodes or 'all'

    Returns
    -------

    DataFrame:
        DataFrame with the coordinates of the nodes

    """
    dimensions = model.n_dimensions
    #
    if nodes == 'all':
        nodes = [n for i, n in model.nodes.items()]

    # initialize empty dictionary to store the coordinates
    dict_coords = dict()

    # loop over every node
    for node_i in nodes:
        dict_coords[node_i.number] = node_i.coords

    return dict_coords


import torch
import numpy as np
import random
from exp.exp_main import Exp_Main
import argparse
import time

fix_seed = 1024
random.seed(fix_seed)
torch.manual_seed(fix_seed)
np.random.seed(fix_seed)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Multivariate Time Series Forecasting')

    # basic config
    parser.add_argument('--is_training', type=int, required=True, default=1, help='status')
    parser.add_argument('--model', type=str, required=True, default='Affine',
                        help='model name, options: [Affine, Linear, STD, TimeFlow]')

    # data loader
    parser.add_argument('--data', type=str, required=True, default='ETTh1', help='dataset type')
    parser.add_argument('--root_path', type=str, default='./dataset/', help='root path of the data file')
    parser.add_argument('--data_path', type=str, default='ETTh1.csv', help='data file')
    parser.add_argument('--features', type=str, default='M',
                        help='forecasting task, options:[M, S]; M:multivariate predict multivariate, S:univariate predict univariate')
    parser.add_argument('--target', type=str, default='OT', help='target feature in S or MS task')
    parser.add_argument('--freq', type=str, default='h',
                        help='freq for time features encoding, options:[s:secondly, t:minutely, h:hourly, d:daily, b:business days, w:weekly, m:monthly], you can also use more detailed freq like 15min or 3h')
    parser.add_argument('--checkpoints', type=str, default='./checkpoints/', help='location of model checkpoints')

    # forecasting task
    parser.add_argument('--seq_len', type=int, default=96, help='input sequence length')
    parser.add_argument('--pred_len', type=int, default=96, help='prediction sequence length')
    parser.add_argument('--individual', action='store_true', default=False, help='DLinear: a linear layer for each variate(channel) individually')
    parser.add_argument('--seg', type=int, default=20, help='prediction plot segments')

    # model
    parser.add_argument('--channel', type=int, default=7, help='num of channel')
    parser.add_argument('--d_model', type=int, default=512, help='dimension of model')
    parser.add_argument('--layers', type=int, default=2, help='num of layers')
    parser.add_argument('--embed', type=str, default='timeF', help='time features encoding, options:[timeF, fixed, learned]')
    parser.add_argument('--do_predict', action='store_true', help='whether to predict unseen future data')
    parser.add_argument('--rev', action='store_true', help='whether to apply RevIN')
    parser.add_argument('--drop', type=float, default=0.1, help='dropout ratio')

    # optimization
    parser.add_argument('--num_workers', type=int, default=10, help='data loader num workers')
    parser.add_argument('--itr', type=int, default=1, help='experiments times')
    parser.add_argument('--train_epochs', type=int, default=15, help='train epochs')
    parser.add_argument('--batch_size', type=int, default=16, help='batch size of train input data')
    parser.add_argument('--patience', type=int, default=10, help='early stopping patience')
    parser.add_argument('--learning_rate', type=float, default=0.001, help='optimizer learning rate')
    parser.add_argument('--lradj', type=str, default='type1', help='adjust learning rate')
    parser.add_argument('--use_amp', action='store_true', help='use automatic mixed precision training', default=False)

    # GPU
    parser.add_argument('--use_gpu', type=bool, default=True, help='use gpu')
    parser.add_argument('--gpu', type=int, default=0, help='gpu')
    parser.add_argument('--use_multi_gpu', action='store_true', help='use multiple gpus', default=False)
    parser.add_argument('--devices', type=str, default='0,1,2,3', help='device ids of multile gpus')

    args = parser.parse_args()

    args.use_gpu = True if torch.cuda.is_available() and args.use_gpu else False

    if args.use_gpu and args.use_multi_gpu:
        args.dvices = args.devices.replace(' ', '')
        device_ids = args.devices.split(',')
        args.device_ids = [int(id_) for id_ in device_ids]
        args.gpu = args.device_ids[0]

    print('Args in experiment:')
    print(args)

    Exp = Exp_Main

    if args.is_training:
        for ii in range(args.itr):
            # setting record of experiments
            setting = '{}_{}_ft{}_sl{}_pl{}_dm{}_eb{}_{}'.format(
                args.model,
                args.data_path[:-4],
                args.features,
                args.seq_len,
                args.pred_len,
                args.d_model,
                args.embed, ii)

            exp = Exp(args)  # set experiments
            print('>>>>>>>start training : {}>>>>>>>>>>>>>>>>>>>>>>>>>>'.format(setting))
            exp.train(setting)

            time_now = time.time()
            print('>>>>>>>testing : {}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.format(setting))
            exp.test(setting)
            print('Inference time: ', time.time() - time_now)

            if args.do_predict:
                print('>>>>>>>predicting : {}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.format(setting))
                exp.predict(setting, True)

            torch.cuda.empty_cache()
    else:
        ii = 0
        setting = '{}_{}_ft{}_sl{}_pl{}_dm{}_eb{}_{}'.format(args.model_id,
            args.model,
            args.data_path[:-4],
            args.features,
            args.seq_len,
            args.pred_len,
            args.d_model,
            args.embed, ii)

        exp = Exp(args)  # set experiments
        print('>>>>>>>testing : {}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.format(setting))
        exp.test(setting, test=1)
        torch.cuda.empty_cache()


"""
Author: Conner Reynolds
Purpose: Use Pytest to check programs, created plural and singular sentences
Date: 10/11/22
"""
import random
from pyparsing import Word

def main():
    quantity = int(input('What is the quantity of your noun (Enter 1 for singular, 2+ for plural). '))
    tense = input("What is the tense of the scenario('past', 'present', or 'future')? ")
    determiner = get_determiner(quantity)
    noun = get_noun(quantity)
    verb = get_verb(quantity, tense)
    prepositional_phrase = get_prepositional_phrase(quantity)
    adjective = get_adjective()
    print(f'{determiner.capitalize()} {adjective} {noun} {verb} {prepositional_phrase}. ')
def get_determiner(quantity):
    """Return a randomly chosen determiner. A determiner is
    a word like "the", "a", "one", "some", "many".
    If quantity == 1, this function will return either "a",
    "one", or "the". Otherwise this function will return
    either "some", "many", or "the".

    Parameter
        quantity: an integer.
            If quantity == 1, this function will return a
            determiner for a single noun. Otherwise this
            function will return a determiner for a plural
            noun.
    Return: a randomly chosen determiner.
    """
    if quantity == 1:
        words = ["a", "one", "the"]
    else:
        words = ["some", "many", "the"]

    # Randomly choose and return a determiner.
    word = random.choice(words)
    return word

def get_noun(quantity):
    """Return a randomly chosen noun.
    If quantity == 1, this function will
    return one of these ten single nouns:
        "bird", "boy", "car", "cat", "child",
        "dog", "girl", "man", "rabbit", "woman"
    Otherwise, this function will return one of
    these ten plural nouns:
        "birds", "boys", "cars", "cats", "children",
        "dogs", "girls", "men", "rabbits", "women"

    Parameter
        quantity: an integer that determines if
            the returned noun is single or plural.
    Return: a randomly chosen noun.
    """
    if quantity == 1:
        nouns = ['bird','boy','car','cat','child','dog','girl','man','rabbit','woman']
    else:
        nouns = ['birds','boys','cars','cats','children','dogs','girls','men','rabbits','women']
    Word = random.choice(nouns)
    return Word

def get_verb(quantity, tense):
    if tense in'past':
        verbs = ["drank", "ate", "grew", "laughed", "thought","ran", "slept", "talked", "walked", "wrote"]
    elif tense in 'present' and quantity == 1:
        verbs = ["drinks", "eats", "grows", "laughs", "thinks","runs", "sleeps", "talks", "walks", "writes"]
    elif tense in 'present' and quantity != 1:
        verbs = ["drink", "eat", "grow", "laugh", "think","run", "sleep", "talk", "walk", "write"]
    elif tense in 'future':
        verbs = ["will drink", "will eat", "will grow", "will laugh","will think", "will run", "will sleep", "will talk","will walk", "will write"]
    Word = random.choice(verbs)
    return Word
def get_adjective():
    adjectives = ['hairy', 'scary', 'sour', 'curly', 'funny', 'strong', 'weak', 'tall', 'short', 'big', 'small']
    word = random.choice(adjectives)
    return word

def get_preposition():
    prepositions = ["about", "above", "across", "after", "along", "around", "at", "before", "behind", "below", "beyond", "by", "despite", "except", "for", "from", "in", "into", "near", "of", "off", "on", "onto", "out", "over", "past", "to", "under", "with", "without"]
    word = random.choice(prepositions)
    return word

def get_prepositional_phrase(quantity):
    if quantity == 1:
        phrase = get_preposition() + ' ' + get_determiner(1) + ' ' + get_noun(1)
    else:
        phrase = get_preposition() + ' ' + get_determiner(2) + ' ' + get_noun(2)
    return phrase
main()


#!/bin/python3

import math
import os
import random
import re
import sys

# https://www.hackerrank.com/challenges/one-month-preparation-kit-flipping-bits/problem
# Complete the 'flippingBits' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts LONG_INTEGER n as parameter.
#

def flippingBits(n):
    bits = f"{n:032b}"
    flipped = ''.join('0' if c == '1' else '1' for c in bits)
    return int(flipped, 2)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(input().strip())

    for q_itr in range(q):
        n = int(input().strip())

        result = flippingBits(n)

        fptr.write(str(result) + '\n')

    fptr.close()


import csv
from datetime import datetime
import json
import os
import random
import subprocess
import sys
import threading

from PIL import Image
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
import numpy as np
from tensorflow.python.client import device_lib

def get_bugs():
    # TODO: Get data from webcompat using issue_parser (https://github.com/webcompat/issue_parser) if the file doesn't exist.
    with open('webcompatdata-bzlike.json', 'r') as f:
        return json.load(f)['bugs']

def mkdir(dir_name):
    try:
        os.mkdir(dir_name)
    except OSError:
        pass

def get_all_images():
    return [f for f in os.listdir('data/') if f.endswith('.png')]

def get_images():
    data = {
        'firefox': [],
        'chrome': [],
    }

    for file_name in get_all_images():
        assert 'firefox.png' in file_name or 'chrome.png' in file_name

        browser = 'firefox' if 'firefox.png' in file_name else 'chrome'

        data[browser].append(file_name[:file_name.index('_' + browser + '.png')])

    return [image for image in data['firefox'] if image in set(data['chrome'])]

def prepare_images():
    try:
        os.mkdir('data_resized')
    except OSError:
        pass

    for f in get_all_images():
        if os.path.exists(os.path.join('data_resized', f)):
            continue

        try:
            orig = Image.open(os.path.join('data', f))
            orig.load()
            channels = orig.split()
            if len(channels) == 4:
                img = Image.new('RGB', orig.size, (255, 255, 255))
                img.paste(orig, mask=channels[3])
            else:
                img = orig

            if img.size[1] > 732:
                img = img.crop((0, 0, img.size[0], 732))
            img = img.resize((192, 256), Image.LANCZOS)
            img.save(os.path.join('data_resized', f))
        except IOError as e:
            print(e)

images = {}

def load_image(fname, parent_dir='data_resized'):
    img = load_img(os.path.join(parent_dir, fname), target_size=(32, 24))
    return img_to_array(img, data_format=keras.backend.image_data_format())

def get_ImageDataGenerator(images, image_shape, parent_dir='data_resized'):
    data_gen = ImageDataGenerator(rescale=1. / 255)
    return data_gen

class CouplesIterator():
    def __init__(self, image_couples_generator, image_shape, image_data_generator, batch_size=32):
        self.image_couples_generator = image_couples_generator
        self.image_shape = image_shape
        self.image_data_generator = image_data_generator
        self.batch_size = batch_size
        self.lock = threading.Lock()

    def __iter__(self):
        return self

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

    def next(self):
        x_batch = [
            np.zeros((self.batch_size,) + self.image_shape, dtype=keras.backend.floatx()),
            np.zeros((self.batch_size,) + self.image_shape, dtype=keras.backend.floatx()),
        ]
        image_couples = [None] * self.batch_size
        y_batch = np.zeros(self.batch_size)

        with self.lock:
            for i in range(self.batch_size):
                image_couple, label = next(self.image_couples_generator)
                image_couples[i] = image_couple
                y_batch[i] = label

        for i, (i1, i2) in enumerate(image_couples):
            x1 = load_image(i1)
            x1 = self.image_data_generator.random_transform(x1.astype(keras.backend.floatx()))
            x1 = self.image_data_generator.standardize(x1)
            x2 = load_image(i2)
            x2 = self.image_data_generator.random_transform(x2.astype(keras.backend.floatx()))
            x2 = self.image_data_generator.standardize(x2)
            x_batch[0][i] = x1
            x_batch[1][i] = x2

        return x_batch, y_batch

def balance(it):
    # Initialise last_label to None so that cur_label != last_label
    # is always True for the first element in it.
    last_label = None

    queue = {
        0: [],
        1: []
    }

    for e in it:
        cur_label = e[1]

        if cur_label != last_label:
            # Maintain relative order.
            # Append element and pop from front.
            queue[cur_label].append(e)
            element = queue[cur_label].pop(0)
            last_label = cur_label
            yield element
        else:
            queue[cur_label].append(e)

    # After every element has been considered, some queue may still be
    # non-empty. If so, and provided the non-empty queue has label other
    # than last label, then take elements from there.
    other_label = 1 if last_label == 0 else 0
    while len(queue[other_label]) != 0:
        element = queue[other_label].pop(0)
        other_label = 1 if other_label == 0 else 0
        yield element

def make_infinite(gen_func, elems):
    while True:
        random.shuffle(elems)
        yield from gen_func(elems)

def read_labels(file_name='labels.csv'):
    if os.stat(file_name).st_size == 0:
        raise Exception('labels file is empty')
    else:
        with open(file_name, 'r', newline='') as f:
            next(f)
            reader = csv.reader(f)
            labels = {row[0]: row[1] for row in reader}
    return labels

CLASSIFICATION_TYPES = ['Y vs D + N', 'Y + D vs N']

def to_categorical_label(label, classification_type):
    if classification_type == 'Y vs D + N':
        if label == 'y':
            return 1
        else:
            return 0
    elif classification_type == 'Y + D vs N':
        if label == 'n':
            return 0
        else:
            return 1

def write_labels(labels, file_name='labels.csv'):
    with open(file_name, 'w', newline='') as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerow(['Image Name', 'Label'])
        for key, values in sorted(labels.items()):
            writer.writerow([key, values])

def read_bounding_boxes(file_name):
    try:
        with open(file_name, 'r') as f:
            bounding_boxes = json.load(f)
    except FileNotFoundError:
        bounding_boxes = {}
    return bounding_boxes

def write_bounding_boxes(bounding_boxes, file_name):
    with open(file_name, 'w') as f:
        print(json.dumps(bounding_boxes), file=f)

def get_all_model_summary(model, model_summary):
    line = []
    model.summary(print_fn=lambda x: line.append(x + '\n'))
    model_summary[model.get_config()['name']] = '\n' + ''.join(line)
    for layer in model.layers:
        if isinstance(layer, keras.engine.training.Model):
            get_all_model_summary(layer, model_summary)

def get_machine_info():
    parameter_value_map = {}
    operating_sys = sys.platform
    parameter_value_map['Operating System'] = operating_sys
    if 'linux' not in operating_sys:
        return parameter_value_map

    for i, device in enumerate(device_lib.list_local_devices()):
        if device.device_type != 'GPU':
            continue
        parameter_value_map['GPU_{}_name'.format(i + 1)] = device.name
        parameter_value_map['GPU_{}_memory_limit'.format(i + 1)] = device.memory_limit
        parameter_value_map['GPU_{}_description'.format(i + 1)] = device.physical_device_desc
    lscpu = subprocess.check_output("lscpu | grep '^CPU(s):\\|Core\\|Thread'", shell=True).strip().decode()
    lscpu = lscpu.split('\n')
    for row in lscpu:
        row = row.split(':')
        parameter_value_map[row[0]] = row[1].strip()
    return parameter_value_map

def write_train_info(information, model, train_history, file_name=None):
    if file_name is None:
        file_name = subprocess.check_output('uname -n', shell=True).strip().decode()
        file_name += datetime.now().strftime('_%H_%M_%Y_%m_%d.txt')
    machine_info = get_machine_info()
    information.update(machine_info)
    os.makedirs('train_info', exist_ok=True)
    with open(os.path.join('train_info', file_name), 'w') as f:
        for key, value in information.items():
            print('%s : %s' % (key, value), file=f)
        print('\n', file=f)
        model_summary = {}
        get_all_model_summary(model, model_summary)
        for key, value in model_summary.items():
            print('%s : %s' % (key, value), file=f)

        print('Sr.No.\t\t', end=' ', file=f)
        train_history_list = []
        for key, value in train_history.items():
            print('%s\t\t' % key, end=' ', file=f)
            train_history_list.append(value)
        train_history_list = np.transpose(np.array(train_history_list))
        for i in range(len(train_history_list)):
            print('\n%d\t\t' % (i + 1), end=' ', file=f)
            row = train_history_list[i]
            for col in row:
                print('%f\t\t' % col, end=' ', file=f)

def create_file_name(bug_id, browser, width=None, height=None, seq_no=None):
    new_file_name_parts = []
    new_file_name_parts.append(bug_id)

    if seq_no is not None:
        new_file_name_parts.append(seq_no)

    if width is not None:
        new_file_name_parts.append('H')
        new_file_name_parts.append(width)

    if height is not None:
        new_file_name_parts.append('V')
        new_file_name_parts.append(height)

    new_file_name_parts.append(browser)
    new_file_name = '_'.join(new_file_name_parts)
    return new_file_name

def parse_file_name(file_name):
    file_name_parts = file_name.split('_')
    file_info = {}
    file_info['bug_id'] = int(file_name_parts[0])

    shift = 0
    if len(file_name_parts) >= 2 and file_name_parts[1].isdigit():
        file_info['seq_no'] = int(file_name_parts[1])
        shift = 1
    if len(file_name_parts) > 2:
        file_info['width'] = int(file_name_parts[shift + 2])
        file_info['height'] = int(file_name_parts[shift + 4])
    return file_info


# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $ MONEY MAKER 6000                              $
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $ Auth: Brandon Belna (bbelna@belnasoft.com)    $
# $ Vrsn: 0.01                                    $
# $ Desc: IT LITERALLY PRINTS MONEY               $
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

import numpy as np
import pandas as pd
from pandas import DataFrame

from freqtrade.strategy.interface import IStrategy

import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib

class MoneyMaker6kStrategy(IStrategy):
    INTERFACE_VERSION = 2
    minimal_roi = {
        "60": 0.02,
        "30": 0.03,
        "0": 0.04
    }
    stoploss = -0.10
    trailing_stop = False
    timeframe = '1m'
    process_only_new_candles = False
    use_sell_signal = True
    sell_profit_only = False
    ignore_roi_if_buy_signal = False
    startup_candle_count = 30
    order_types = {
        'buy': 'limit',
        'sell': 'limit',
        'stoploss': 'market',
        'stoploss_on_exchange': False
    }
    order_time_in_force = {
        'buy': 'gtc',
        'sell': 'gtc'
    }
    plot_config = {
        'main_plot': {
            'tema': {},
            'sar': {'color': 'white'},
        },
        'subplots': {
            "MACD": {
                'macd': {'color': 'blue'},
                'macdsignal': {'color': 'orange'},
            },
            "RSI": {
                'rsi': {'color': 'red'},
            }
        }
    }

    # RSI Hyperoptable Parameters
    rsi_buy_enabled = CategoricalParameter([True, False])
    rsi_sell_enabled = CategoricalParameter([True, False])
    rsi_buy = IntParameter(20, 45, default=30)
    rsi_sell = IntParameter(60, 85, default=70)

    def informative_pairs(self):
        return []

    def populate_indicators(
        self,
        dataframe: DataFrame,
        metadata: dict
    ) -> DataFrame:
        # ADX
        dataframe['adx'] = ta.ADX(dataframe)

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # Bollinger Bands
        bollinger = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=2
        )
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe["bb_percent"] = (
            (dataframe["close"] - dataframe["bb_lowerband"]) /
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"])
        )
        dataframe["bb_width"] = (
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"])
            / dataframe["bb_middleband"]
        )

        # TEMA
        dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)

        return dataframe

    def populate_buy_trend(
        self,
        dataframe: DataFrame,
        metadata: dict
    ) -> DataFrame:
        conditions = []

        # RSI Buy Hyperopt
        if self.rsi_buy_enabled.value:
            conditions.append(
                qtpylib.crossed_above(
                    dataframe['rsi'],
                    self.rsi_buy.value
                )
            )

        # Default Buy Conditions
        conditions.append(dataframe['tema'] <= dataframe['bb_middleband'])
        conditions.append(dataframe['tema'] > dataframe['tema'].shift(1))
        conditions.append(dataframe['volume'] > 0)

        dataframe.loc[
            reduce(lambda x, y: x & y, conditions),
            'buy'
        ] = 1

        return dataframe

    def populate_sell_trend(
        self,
        dataframe: DataFrame,
        metadata: dict
    ) -> DataFrame:
        conditions = []

        # RSI Sell Hyperopt
        if self.rsi_sell_enabled.value:
            conditions.append(
                qtpylib.crossed_below(
                    dataframe['rsi'],
                    self.rsi_sell.value
                )
            )
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe['rsi'], 70))
                & (dataframe['tema'] > dataframe['bb_middleband'])
                & (dataframe['tema'] < dataframe['tema'].shift(1))
                & (dataframe['volume'] > 0)
            ),
            'sell'
        ] = 1
        return dataframe


from app.database.connection import db_connection

def add_template_to_db(templ: dict, con=db_connection):
    print(id(con))
    con.insert(templ)

def construct_template():
    name = input("Enter template name: ")
    form = {"name": name}
    amount_of_fields = int(input("Enter number of fields: "))
    for _ in range(amount_of_fields):
        field_name = input("Enter field's name: ")
        flag = field_name in form
        while flag:
            ovrd = input("Field already exists, override: yes/no?: ").lower()
            if ovrd == "no":
                field_name = input("Enter field's name: ").lower()
                flag = field_name in form
            if ovrd == "yes":
                break
        field_value = input(f"Enter type for {field_name}: ").lower()
        form[field_name] = field_value
    return form

def main():
    starting_prompt = input("Add a template? yes/no: ").lower()
    if starting_prompt == "no":
        return -1
    while True:
        templ = construct_template()
        add_template_to_db(templ)
        cont = input("Add another one? yes/no: ").lower()
        if cont == "no":
            break

if __name__ == "__main__":
    main()