# Binarizing numeric variables
df['Binary_Violation'] = 0
df.loc[df['Number_of_violations'] > 0, 'Binary_Violation'] = 1

# Binning numeric variables
import numpy as no
df['Binned_group'] = pd.cut(
    df['Number_of_violations'], bins = [ -np.inf, 0, 2, np.inf], labels = [1,2,3]
)

# EX:
# Create the Paid_Job column filled with zeros
so_survey_df['Paid_Job'] = 0

# Replace all the Paid_Job values where ConvertedSalary is > 0
so_survey_df.loc[so_survey_df['ConvertedSalary']>0, 'Paid_Job'] = 1

# Print the first five rows of the columns
print(so_survey_df[['Paid_Job', 'ConvertedSalary']].head())

# EX:Binning values
# Bin the continuous variable ConvertedSalary into 5 bins
so_survey_df['equal_binned'] = pd.cut(so_survey_df['ConvertedSalary'], bins = 5)

# Print the first 5 rows of the equal_binned column
print(so_survey_df[['equal_binned', 'ConvertedSalary']].head())

# Import numpy
import numpy as np

# Specify the boundaries of the bins
bins = [-np.inf, 10000, 50000, 100000, 150000, np.inf]

# Bin labels
labels = ['Very low', 'Low', 'Medium', 'High', 'Very high']

# Bin the continuous variable ConvertedSalary using these boundaries
so_survey_df['boundary_binned'] = pd.cut(so_survey_df['ConvertedSalary'],
                                         bins = bins, labels = labels)

# Print the first 5 rows of the boundary_binned column
print(so_survey_df[['boundary_binned', 'ConvertedSalary']].head())

Feature Engineering For Machine Learning in Python/Chapter 1  Creating Features/3. Numeric variables.py


def solution(s, e):

    answer = 0
    count = 0

    # 최적화
    # s 와 e 의 관계를 보고 최적화를 해봅시다.

    visited = [False for _ in range(10001)]
    kong = [-1, 1, 5]
    location = [s]
    while location:
        print(count, location)
        for _ in range(len(location)):
            # 방문한적 있는지 없는지 체크한 뒤에 kong 을 해야합니다.
            current = location.pop(0)
            if not visited[current]:
                if current == e:
                    return count
                for k in kong:
                    if not visited[current+k] and current+k > 0:
                        visited[current] = True
                        location.append(current+k)

        count += 1

    return count

print(solution(5, 14))      # 3
print(solution(8, 3))       # -5
print(solution(1,10))       # 2


from ver2 import func
import os
import sys
sys.path.insert(0, os.path.expanduser('/media/bhargav/Windows/Users/bharg/Desktop/PipeCandy/ideacrawler.v0.2.0/pyclient'))
import pyclient
import time

#ans=func('tattly.com')

def main():
    def savePage(ph, ccObj):
        print(ph.success, ph.httpstatuscode, ph.error, ph.url, ph.metaStr)
        print(ph.content)
#        with open("out.file", "wb") as text_file:
#            text_file.write(ph.content)

    z = pyclient.ClientCrawler("127.0.0.1", "2345")
    z.callback           = savePage
    z.seedURL            = ""
    z.follow             = True
    z.unsafeNormalizeURL = True
    z.impolite           = True
    z.followUrlRegexp    = ""
    z.callbackUrlRegexp  = ""
    z.minDelay           = 1
    z.maxDelay           = 3

    z.Start()

    z.AddPage('https://shop.landrover.com/uk/catalogsearch/result/index/?q=1%3D%3D1&product_list_limit=all', "100")
#    z.AddPage("http://milindhg.github.io", "42")
#    z.AddPage("https://github.com/search?q=fullname:Mohammad+Badruzzaman+location:Berlin&type=Users", "42")
    while True:
        if z.IsAlive():
            time.sleep(1)
        else:
            break

main()


import random
from turtle import Turtle, Screen

screen = Screen()
is_race_on = False
# screen.setup helps to set up the width and height of the screen
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter the color:")

y_positions = [-150, -100, -50, 0, 50, 100]
colors = ["red", "yellow", "blue", "green", "orange", "purple"]
all_turtles = []

for turtle_index in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.penup()
    new_turtle.color(colors[turtle_index])
    new_turtle.goto(x=-230, y=y_positions[turtle_index])
    all_turtles.append(new_turtle)

# This if statement makes the compiler to wait until user bets and prevent the code starting prematurely
if user_bet:
    is_race_on = True

while is_race_on == True:

    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
              print(f"You won! The {winning_color} turtle is the winning one!")
            else:
              print("You lost!")

        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

screen.exitonclick()


#!/usr/bin/env python3

import os
import sys

data = []
with open("data.txt",'r') as file:
 for line in file:
  data.append(line.replace("\n", "").split(','))

 for idx in range(len(data)):
    lst = data[idx]

    name = lst[0].strip()
    email = lst[1].strip()
    marketvalue = lst[2].strip()
    role = lst[3].strip()

    print(name)
    print(email)
    print(marketvalue)
    print(role)


import requests
from datetime import datetime
from bs4 import BeautifulSoup
import mysql.connector
import datetime
import mysql.connector

live_challenge_type = []
live_challenge_name = []
live_challenge_url = []

"""
live_challenge_countdown_day = []
live_challenge_countdown_hrs = []
live_challenge_countdown_min = []
"""

upcoming_challenge_type = []
upcoming_challenge_name = []
upcoming_challenge_url = []
upcoming_challenge_date = []

cnx = mysql.connector.connect(user='root', password='',
                                 host='localhost',
                                 database='capstone')

mycursor = cnx.cursor()

# clear_table = "DELETE FROM HACKEREARTH_LIVE";
# mycursor.execute(clear_table)
# cnx.commit()

# clear_table = "DELETE FROM HACKEREARTH_UPCOMING";
# mycursor.execute(clear_table)
# cnx.commit()

months = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05", Jun="06", Jul="07", Aug="08", Sep="09", Oct="10", Nov="11", Dec="12")
url = "https://www.hackerearth.com/challenges/"

data = requests.get(url).text
soup = BeautifulSoup(data,'lxml')

for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for type in live.findAll('div',{"class": "challenge-type light smaller caps weight-600"}):
  live_challenge_type.append(type.text)

for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for name in live.findAll('div',{"class": "challenge-name ellipsis dark"}):
  live_challenge_name.append(name.text)

for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for url in live.findAll('a',{"class": "challenge-card-wrapper challenge-card-link"}):
   link = url['href']
   if link.startswith("https://"):
    live_challenge_url.append(link)
   else:
    link = "https://www.hackerearth.com" + link
    live_challenge_url.append(link)

"""
for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for day1 in live.findAll('div',{"id": "days-1"}):
   print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(day1.text))))
   #print(day1.text+day0.text);
   #live_challenge_countdown_day.append(day1.text+day0.text)

for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for hrs in live.findAll('div',{"id": "date date-countdown"}):
  live_challenge_countdown_hrs.append(hrs.text)

for live in soup.findAll('div',{"class": "ongoing challenge-list"}):
 for min in live.findAll('div',{"id": "date date-countdown"}):
  live_challenge_countdown_min.append(min.text)
"""

for i in range(len(live_challenge_type)):

  live_challenge_type[i].strip()
  sql = "INSERT INTO codechef VALUES(%s, %s, %s, %s, %s)"
  val = (live_challenge_type[i], live_challenge_name[i], "NA", "NA", live_challenge_url[i])
  mycursor.execute(sql, val)
  cnx.commit()

for upcoming in soup.findAll('div',{"class": "upcoming challenge-list"}):
 for type in upcoming.findAll('div',{"class": "challenge-type light smaller caps weight-600"}):
  upcoming_challenge_type.append(type.text)

for upcoming in soup.findAll('div',{"class": "upcoming challenge-list"}):
 for name in upcoming.findAll('div',{"class": "challenge-name ellipsis dark"}):
  upcoming_challenge_name.append(name.text)

for upcoming in soup.findAll('div',{"class": "upcoming challenge-list"}):
 for url in upcoming.findAll('a',{"class": "challenge-card-wrapper challenge-card-link"}):
   link = url['href']
   if link.startswith("https://"):
    upcoming_challenge_url.append(link)
   else:
    link = "https://www.hackerearth.com" + link
    upcoming_challenge_url.append(link)

for upcoming in soup.findAll('div',{"class": "upcoming challenge-list"}):
 for date in upcoming.findAll('div',{"class": "date less-margin dark"}):

  m = months[date.text[0:3]]
  if date.text[4] == ' ':
   d = '0'+date.text[5:6]
  else:
   d = date.text[4:6]
  y = '2021'
  t_d = date.text[8:10]
  t_m = date.text[10:13]
  mrdm = date.text[14:16]

  if mrdm == 'PM':
   t_d = int(t_d) + 12

  t = str(t_d) + t_m + ':00'

  date = y+'-'+m+'-'+d+' '+t
  upcoming_challenge_date.append(date)

for i in range(len(live_challenge_type)):

  sql = "INSERT INTO codechef VALUES(%s, %s, %s, %s, %s)"
  val = ("NA", upcoming_challenge_name[i], upcoming_challenge_date[i], "NA", upcoming_challenge_url[i])
  mycursor.execute(sql, val)
  cnx.commit()

cnx.close()


#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

# import os
import sys
# import simplejson as json
# import shutil
# import sqlite3
import _rightThumb._construct as __
__.appReg = __name__
import _rightThumb._base2 as _
import _rightThumb._vars as _v
import _rightThumb._string as _str

_.switches.register('Table', '-table','_reph_signature_+staff')
_.switches.register('Fields', '-fields','first last')

# _.switches.register('Output', '-o','folder\\appOut.py')
# _.switches.register('Move', '-move','completed_in-folder_name')

_.appInfo[__name__] = {
	'file': 'crud.py',
	'description': 'Changes the world',
	'prerequisite': [],
	'examples': [],
	'columns': [],
	}

_.appInfo[__name__]['examples'].append('p crud -table _reph_signature_+staff -fields first last')

# _.appInfo[__name__]['columns'].append({'name': 'name', 'abbreviation': 'n'})

# def formatColumns(columns):
#     result = ''
#     for c in columns.split(','):
#         for col in _.appInfo[__name__]['columns']:
#             for a in col['abbreviation'].split(','):
#                 if a == c:
#                     c = col['name']
#         result += c + ','
#     result = result[:-1]
#     return result

# _.switches.trigger('Column',formatColumns)

if not __name__ == '__main__':
	_.argvProcess = False

_.switches.process()
appDBA = __.clearFocus( __name__, __file__ )
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
	global appDBA
	f = __.appName( appDBA, parentApp, childApp )
	if reg:
		__.appReg = f
	return f

# pipeData = ''

# if not sys.stdin.isatty():
#     pipeData = sys.stdin.readlines()
#     try:
#         if pipeData[0][0].isalnum() == False:
#             pipeData[0] = pipeData[0][1:]
#     except Exception as e:
#         pass

# if _.switches.isActive('_File_'):
#     _.tables.register('toCheck') # table, rows = []
#     _.switches.fieldSet('_File_','active',True)
#     _.switches.fieldSet('_File_','value','toCheck.json')
#     _.tables.get('toCheck',_.switches.value('_File_'))
#     _.tables.trigger('toCheck','stamp,time,date',_.float2Dated,True)
#     _.tables.sort('toCheck', 'name')

#     _.tables.registerView('test_table','sample3','name,age','age') # table, view, fields, sort
#     _.tables.view('test_table','sample') # table, view

#     _.switches.fieldGet('Column','pos')
#     if _.switches.exists('Column2'):
#         print('This is a valid switch')

#     if _.switches.isActive('Output') == True:

#     if _.switches.isActive('Move') == True:
#             shutil.move(_.ci(_.switches.value('Input')), _.switches.value('Move') + _v.slash + _.ci(_.switches.value('Input')))
#     # if _.showLine(string):
#         # print(line)

########################################################################################
# class TheChildItems:

#     def __init__(self, name, switch):
#         self.name = name
#         self.active = False
#         self.value = None

#     def trigger(self,script):
#         self.script_trigger = script

#     def changeStatus(self,newStatus):
#         self.active = newStatus
# class TheParentItems:

#     def __init__(self):
#         self.childItemRows = []

#     def register(self, name):
#         self.childItemRows.append(TheChildItems(name))
#     def print(self):
#         childItems = []
#         for ci in self.childItemRows:
#             childItems.append({'name':ci.name})
#         _.tables.register('childClassItems',childItems)
#         # tables.trigger('switches','switch,name',test,True)
#         _.tables.print('childClassItems','name')
#     def printStatus(self):
#         childItems = []
#         for ci in self.childItemRows:
#             if ci.active:
#                 active = 'True'
#             else:
#                 active = 'False'
#             value = ci.value
#             if ci.value == True:
#                 value = 'True'
#             elif ci.value == False:
#                 value = 'False'

#             childItems.append({'name':ci.name ,'active':active,'value': value})
#         _.tables.register('childClassItems',childItems)
#         _.tables.print('childClassItems','name,active,value')
#     def status(self,name,newStatus):
#         for i,ci in enumerate(self.childItemRows):
#             if ci.name == name:
#                 self.childItemRows[i].changeStatus(newStatus)

# if _.switches.isActive('Move'):
	# shutil.move(_.ci(_.switches.value('Input')), _.switches.value('Move') + _v.slash + _.ci(_.switches.value('Input')))

########################################

#     json = _.getTable('base64Key.json')
#    books = _.getText(_v.myTables + _v.slash+'bible_books.csv')

# _.saveTable(jsonFile,'file.json')
# _.saveText(convertedFile,_.ci(_.switches.value('Output')))
# _.saveText(convertedFile,'file.txt')
# _.showLine(item)
########################################################################################
def funcname():
	table = _.switches.value('Table')
	# print(table)
	# sys.exit()
	table = table.split('+')[1]
	# print(table)
	table = table.replace('_',' ')
	table = table.title()
	table = table.replace(' ','_')
	return table
def funcfields():
	fields = _.switches.value('Fields')
	field = fields.split(',')
	f = ''
	for fl in field:
		f += '$' + fl + ', '
	f = _str.cleanBE(f,', ')
	return f
def tfields():
	fields = _.switches.value('Fields')
	field = fields.split(',')
	f = ''
	for fl in field:
		f += fl + ', '
	f = _str.cleanBE(f,', ')
	return f
def vfields():
	fields = _.switches.value('Fields')
	field = fields.split(',')
	f = ''
	for fl in field:
		f += "'"+'$' + fl + "'" + ', '
	f = _str.cleanBE(f,', ')
	return f
def readfields():
	fields = _.switches.value('Fields')
	field = fields.split(',')
	b = "\n        'FIELD' => $row['FIELD'],"
	f = ''
	for fl in field:
		f += b.replace('FIELD',fl)
	return f
def thetable():
	table = _.switches.value('Table')
	table = table.replace('+','')
	return table
def updatefields():
	fields = _.switches.value('Fields')
	field = fields.split(',')
	b = "FIELD='$FIELD', "
	f = ''
	for fl in field:
		f += b.replace('FIELD',fl)
	f = _str.cleanBE(f,', ')
	return f
def action():
	crudBase = _.getText(_v.myTables + _v.slash+'crud.php')
	crud = ''

	for i,c in enumerate(crudBase):
		if i > 0:
			crud += c

	funcname0 = '[funcname]'
	funcname1 = funcname()
	crud = crud.replace(funcname0,funcname1)

	funcfields0 = '[funcfields]'
	funcfields1 = funcfields()
	crud = crud.replace(funcfields0,funcfields1)

	tfields0 = '[tfields]'
	tfields1 = tfields()
	crud = crud.replace(tfields0,tfields1)

	vfields0 = '[vfields]'
	vfields1 = vfields()
	crud = crud.replace(vfields0,vfields1)

	readfields0 = '[readfields]'
	readfields1 = readfields()
	crud = crud.replace(readfields0,readfields1)

	table0 = '[table]'
	table1 = thetable()
	crud = crud.replace(table0,table1)

	updatefields0 = '[updatefields]'
	updatefields1 = updatefields()
	crud = crud.replace(updatefields0,updatefields1)

	print(crud)

########################################################################################
if __name__ == '__main__':
	action()

# n %tmpf3%

#  -table _reph_signature_+staff_type -fields label
# -table _reph_signature_+staff -fields first last email availabilityjson addressjson stafftypeid
# -table _reph_signature_+services -fields label durationjson dvalue stafftypeid
# -table _reph_signature_+appointments -fields customerid time_start time_end
# -table _reph_signature_+appointment_items -fields appointmentid serviceid dvalue duration
# -table _reph_signature_+customers -fields first last email availabilityjson addressjson

# n %tmpf4%

# type %tmpf3% | p line --c -make "p crud {} >> %tmpf4% " | p execute


import datetime
import iso8601

from conveyor.tests.unit import fake_constants as fake

DEFAULT_PLAN_NAME = "displayname"
DEFAULT_PLAN_DESCRIPTION = "displaydesc"
DEFAULT_PLAN_TYPE = "clone"
DEFAULT_PLAN_STATUS = "available"
DEFAULT_PLAN_ID = fake.PLAN_ID
DEFAULT_AZ = "fakeaz"

def create_fake_plan(id, **kwargs):
    plan = {
        'id': id,
        'user_id': fake.USER_ID,
        'project_id': fake.PROJECT_ID,
        'availability_zone': DEFAULT_AZ,
        'plan_status': DEFAULT_PLAN_STATUS,
        'name': 'plan_test',
        'display_name': DEFAULT_PLAN_NAME,
        'display_description': DEFAULT_PLAN_DESCRIPTION,
        'updated_at': datetime.datetime(1900, 1, 1, 1, 1, 1,
                                        tzinfo=iso8601.iso8601.Utc()),
        'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1,
                                        tzinfo=iso8601.iso8601.Utc()),
        'plan_type': 'clone',
        'original_resource': '',
        'update_resources': ''
    }

    if kwargs.get('original_resource', None):
        plan['original_resource'] = kwargs.get('original_resource')
    if kwargs.get('update_resources', None):
        plan['update_resources'] = kwargs.get('update_resources')
    if kwargs.get('plan_status', None):
        plan['plan_status'] = kwargs.get('plan_status')
    return plan

def fake_clone_template():
    template = {'template':
                {'heat_template_version': '2013-05-23',
                 'description': 'clone template',
                 'plan_type': 'clone',
                 'parameters': {},
                 'resources': {'volume_0': {'type': 'OS::Cinder::Volume',
                               'properties': {'size': 1,
                                              'availability_zone': 'az01',
                                              'name': 'test-vol-8',
                                              'metadata': {'region': 'az01'}},
                               'extra_properties': {'status': 'in-use',
                                                    'is_deacidized': True,
                                                    'sys_dev_name': 'fake',
                                                    'id': 'fake'}}}}}
    return template

def fake_plan_api_get(self, context, id, **kwargs):
    plan = create_fake_plan(id, **kwargs)
    return plan


import inspect
import re

class Extension:
    """Extension object pretty much
    """
    def __init__(self, **kwargs):
        self.name: str | None = kwargs.get("name")
        self.description: str | None = kwargs.get('description')
        self.ext = kwargs.get("ext")
        self.commands: CommandCollection | None = kwargs.get("commands")
class ExtensionCollection:
    """Extension collection, where extensions are stored into
    """
    def __init__(self, bot):
        self.bot = bot
        self.extensions = {}

    def __iter__(self):
        for cmd in self.extensions.values():
            yield cmd

    def _is_already_registered(self, ext):
        for extension in self.extensions.values():
            if ext.name == extension:
                return True

    def add(self, ext):
        if not isinstance(ext, Command):
            raise ValueError('cmd must be a subclass of Command')
        if self._is_already_registered(ext):
            raise ValueError('A name or alias is already registered')
        self.extensions[ext.name] = ext

    def get(self, alias, prefix=''):
        try:
            return self.extensions[alias]
        except KeyError:
            pass
        for command in self.extensions:
            if command.name in command.aliases:
                return command

class Command:
    """Command Object pretty much
    """
    def __init__(self, **kwargs):
        self.name = kwargs.get("name")
        self.aliases = [self.name] + kwargs.get('aliases', [])
        self.description = kwargs.get('description')
        self.func = kwargs.get("func")
        self.check = inspect.signature(self.func).return_annotation
        self.signature = inspect.signature(self.func).parameters.items()

class CommandCollection:
    """Commands collection, where commands are stored into
    """
    def __init__(self, bot):
        self.bot = bot
        self.commands = {}

    def __len__(self):
        return len(self.commands)
    def __iter__(self):
        for cmd in self.commands.values():
            yield cmd

    def _is_already_registered(self, cmd):
        for command in self.commands.values():
            for alias in cmd.aliases:
                if alias in command.aliases:
                    return True

    def add(self, cmd):
        if not isinstance(cmd, Command):
            raise ValueError('cmd must be a subclass of Command')
        if self._is_already_registered(cmd):
            raise ValueError('A name or alias is already registered')
        self.commands[cmd.name] = cmd

    def get(self, alias, prefix=''):
        try:
            return self.commands[alias]
        except KeyError:
            pass
        for command in self.commands:
            if alias in command.aliases:
                return command

class Context:
    """Context related for commands, and invokation
    """
    def __init__(self, bot, message, http) -> None:
        self.bot = bot
        self.message = message
        self.http = http

    @property
    def author(self):
        return self.message.author

    @property
    def guild(self):
        return self.message.guild

    @property
    def channel(self):
        return self.message.channel

    @property
    def content(self):
        return self.message.content

    @property
    def command(self):
        if self.prefix is None:
            return None
        for command in self.bot.commands:
            for alias in command.aliases:
                if self.content.startswith(self.prefix + alias):
                    return command
        return None

    @property
    def alias(self):
        for command in self.bot.commands:
            for alias in command.aliases:

                if self.content.startswith(self.prefix + alias):
                    return alias
        return None

    @property
    def prefix(self):
        for prefix in self.bot.prefixes:
            if self.content.startswith(prefix):
                return prefix

    @property
    def command_content(self):
        """The content minus the prefix and command name, essentially the args

        Returns:
            str: String of content
        """
        if self.alias == None:
            return
        try:
            cut = len(self.prefix + self.alias)
            return self.content[cut:]
        except:
            return None

    def get_converter(self, param):
        if param.annotation is param.empty:
            return str
        if callable(param.annotation):
            return param.annotation
        else:
            raise ValueError('Parameter annotation must be callable')

    def convert(self, param, value):
        """Attempts to turn x value in y value, using get_converter func for the values

        Args:
            param (_type_): function parameter
            value (_type_): value in message

        Returns:
            Type[str]: The type of parameter
        """
        converter = self.get_converter(param)
        return converter(value)

    async def get_arguments(self):
        """Get arguments by checking function arguments and comparing to arguments in message.

        Returns:
            _type_: _description_
        """
        args = []
        kwargs = {}

        if self.command.signature is not None:
            signature = self.command.signature
        if self.command_content != "":
            splitted = self.command_content.split(" ")[1:]

            for index, item in enumerate(splitted):
                user_regex = re.findall(r"<@[0-9]{18,19}>", item)
                if len(user_regex) > 0:
                    x = re.findall(r"[0-9]{18,19}", item)
                    if len(x) > 0:
                        val = x[0]
                        splitted[index] = val
                break
        else:
            return args, kwargs

        for index, (name, param) in enumerate(signature):
            if index == 0:
                continue

            if param.kind is param.POSITIONAL_OR_KEYWORD:

                arg = self.convert(param, splitted.pop(0))

                args.append(arg)
            if param.kind is param.VAR_KEYWORD:

                for arg in splitted:
                    arg = self.convert(param, arg)
                    args.append(arg)

            if param.kind is param.KEYWORD_ONLY:

                arg = self.convert(param, ' '.join(splitted))
                kwargs[name] = arg

        for key in kwargs.copy():
            if not kwargs[key]:
                kwargs.pop(key)

        return args, kwargs

    async def invoke(self):
        """Used to actually run the command
        """
        if self.command is None:
            return
        if self.message.author.id != self.bot.user.id:
            return
        if self.command_content != None:
            args, kwargs = await self.get_arguments()
            func = self.command.func
            args.insert(0, self)

        await func(*args, **kwargs)

    async def reply(self, content: str, tts=False):
        """Helper function to reply to your own message containing the command

        Args:
            content (str): The message you would like to send
            tts (bool, optional): Whether message should be tts or not. Defaults to False.
        """
        await self.channel.reply(self.message, content, tts)

    async def send(self, content: str, tts=False):
        """Helper function to send message to the current channel

        Args:
            content (str): The message you would like to send
            tts (bool, optional): Whether message should be tts or not. Defaults to False.
        """
        await self.channel.send( content=content, tts=tts)

    async def spam(self, amount: int, content: str):
        """Helper function to spam messages in the current channel (uses asyncio.gather !!!!)

        Args:
            amount (int): Amount of messages to spam
            content (str): The message you would like to send
        """
        await self.channel.spam(amount, content)

    async def purge(self, amount: int=None):
        """Helper function to purge messages in the current channel, uses asyncio gather.

        Args:
            amount (int): The amount of messages to purge, defaults to All.
        """
        await self.channel.purge(amount)


import tensorflow as tf
import numpy as np
import matplotlib
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
'''
一 导入数据
'''
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('MNIST-data',one_hot=True)
print(type(mnist)) #<class 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets'>
print('Training data shape:',mnist.train.images.shape)           #Training data shape: (55000, 784)
print('Test data shape:',mnist.test.images.shape)                #Test data shape: (10000, 784)
print('Validation data shape:',mnist.validation.images.shape)    #Validation data shape: (5000, 784)
print('Training label shape:',mnist.train.labels.shape)          #Training label shape: (55000, 10)
#设置tensorflow对GPU使用按需分配
config = tf.ConfigProto()
config.gpu_options.allow_growth = True

sess = tf.InteractiveSession(config=config)
'''
二 构建网络
'''
'''
初始化权值和偏重
为了创建这个模型，我们需要创建大量的权重和偏置项。这个模型中的权重在初始化时应该加入少量的噪声来
打破对称性以及避免0梯度。由于我们使用的是ReLU神经元，因此比较好的做法是用一个较小的正数来初始化
偏置项，以避免神经元节点输出恒为0的问题（dead neurons）。为了不在建立模型的时候反复做初始化操作
，我们定义两个函数用于初始化。
'''
def weight_variable(shape):
    #使用正太分布初始化权值
    initial = tf.truncated_normal(shape,stddev=0.1)    #标准差为0.1
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1,shape=shape)
    return tf.Variable(initial)
'''
卷积层和池化层
TensorFlow在卷积和池化上有很强的灵活性。我们怎么处理边界？步长应该设多大？在这个实例里，我们会
一直使用vanilla版本。我们的卷积使用1步长（stride size），0边距（padding size）的模板，保证输
出和输入是同一个大小。我们的池化用简单传统的2x2大小的模板做max pooling。为了代码更简洁，我们把
这部分抽象成一个函数。
'''
#定义卷积层
def conv2d(x,W):
    '''默认 strides[0] = strides[3] = 1,strides[1]为x方向步长，strides[2]为y方向步长
     Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
     and a filter / kernel tensor of shape `[filter_height, filter_width, in_channels,
     out_channels]`
    '''
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding = 'SAME')

#pooling层
def max_pooling(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

# 我们通过为输入图像和目标输出类别创建节点，来开始构建计算题  None表示数值不固定，用来指定batch的大小
x_ = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

# 把x转换为卷积所需要的形式  batch_size张手写数字，每张维度为1x28x28
'''
为了用这一层，我们把x变成一个4d向量，其第2、第3维对应图片的高、高，最后一维代表图片的颜色通道数
(因为是灰度图所以这里的通道数为1，如果是rgb彩色图，则为3)。
'''
X = tf.reshape(x_, shape=[-1, 28, 28, 1])

'''
现在我们可以开始实现第一层了。它由一个卷积接一个max pooling完成。卷积在每个5x5的patch中算出
32个特征。卷积的权重张量形状是[5, 5, 1, 32]，前两个维度是patch的大小，接着是输入的通道数目，
最后是输出的通道数目。 而对于每一个输出通道都有一个对应的偏置量。
'''
# 第一层卷积，32个过滤器，共享权重矩阵为1*5*5  h_conv1.shape=[-1,28,28,32]
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(X, w_conv1) + b_conv1)

# 第一个pooling层 最大值池化层2x2 [-1,28,28,28]->[-1,14,14,32]
h_pool1 = max_pooling(h_conv1)

# 第二层卷积，64个过滤器，共享权重矩阵为32*5*5  h_conv2.shape=[-1,14,14,64]
w_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)

# 第二个pooling层 最大值池化层2x2 [-1,14,14,64]->[-1,7,7,64]
h_pool2 = max_pooling(h_conv2)

'''
全连接层
现在，图片尺寸减小到7x7，我们加入一个有1024个神经元的全连接层，用于处理整个图片。我们把池化层输
出的张量reshape成一些向量，乘上权重矩阵，加上偏置，然后对其使用ReLU。
'''
h_poo2_falt = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
# 隐藏层
w_h = weight_variable([7 * 7 * 64, 1024])
b_h = bias_variable([1024])
hidden = tf.nn.relu(tf.matmul(h_poo2_falt, w_h) + b_h)

'''
加入弃权，把部分神经元输出置为0
为了减少过拟合，我们在输出层之前加入dropout。我们用一个placeholder来代表一个神经元的输出在
dropout中保持不变的概率。这样我们可以在训练过程中启用dropout，在测试过程中关闭dropout。
TensorFlow的tf.nn.dropout操作除了可以屏蔽神经元的输出外，还会自动处理神经元输出值的scale。
所以用dropout的时候可以不用考虑scale。
'''
keep_prob = tf.placeholder(tf.float32)  # 弃权概率0.0-1.0  1.0表示不使用弃权
hidden_drop = tf.nn.dropout(hidden, keep_prob)

'''
输出层
最后，我们添加一个softmax层，就像前面的单层softmax regression一样。
'''
w_o = weight_variable([1024, 10])
b_o = bias_variable([10])
output = tf.nn.softmax(tf.matmul(hidden_drop, w_o) + b_o)

'''
三 设置对数似然损失函数
'''
# 代价函数 J =-(Σy.logaL)/n    .表示逐元素乘
cost = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(output), axis=1))

'''
四 求解
'''
train = tf.train.AdamOptimizer(0.0001).minimize(cost)

# 预测结果评估
# tf.argmax(output,1)  按行统计最大值得索引
correct = tf.equal(tf.argmax(output, 1), tf.argmax(y_, 1))  # 返回一个数组 表示统计预测正确或者错误
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))  # 求准确率

# 创建list 保存每一迭代的结果
training_accuracy_list = []
test_accuracy_list = []
training_cost_list = []
test_cost_list = []

# 使用会话执行图
sess.run(tf.global_variables_initializer())  # 初始化变量

# 开始迭代 使用Adam优化的随机梯度下降法
for i in range(5000):  # 一个epoch需要迭代次数计算公式：测试集长度 / batch_size
    x_batch, y_batch = mnist.train.next_batch(batch_size=64)
    # 开始训练
    train.run(feed_dict={x_: x_batch, y_: y_batch, keep_prob: 1.0})
    if (i + 1) % 200 == 0:
        # 输出训练集准确率
        # training_accuracy = accuracy.eval(feed_dict={x_:mnist.train.images,y_:mnist.train.labels})
        training_accuracy, training_cost = sess.run([accuracy, cost],
                                                    feed_dict={x_: x_batch, y_: y_batch, keep_prob: 1.0})
        training_accuracy_list.append(training_accuracy)
        training_cost_list.append(training_cost)
        print('Step {0}:Training set accuracy {1},cost {2}.'.format(i + 1, training_accuracy, training_cost))

# 全部训练完成做测试  分成200次，一次测试50个样本
# 输出测试机准确率   如果一次性全部做测试，内容不够用会出现OOM错误。所以测试时选取比较小的mini_batch来测试
# test_accuracy = accuracy.eval(feed_dict={x_:mnist.test.images,y_:mnist.test.labels})
for i in range(200):
    x_batch, y_batch = mnist.test.next_batch(batch_size=50)
    test_accuracy, test_cost = sess.run([accuracy, cost], feed_dict={x_: x_batch, y_: y_batch, keep_prob: 1.0})
    test_accuracy_list.append(test_accuracy)
    test_cost_list.append(test_cost)
    if (i + 1) % 20 == 0:
        print('Step {0}:Test set accuracy {1},cost {2}.'.format(i + 1, test_accuracy, test_cost))
print('Test accuracy:', np.mean(test_accuracy_list))

'''
图像操作
'''
import matplotlib.pyplot as plt

# 随便取一张图像
img = mnist.train.images[2]
label = mnist.train.labels[2]

# print('图像像素值：{0},对应的标签{1}'.format(img.reshape(28,28),np.argmax(label)))
print('图像对应的标签{0}'.format(np.argmax(label)))

plt.figure()

# 子图1
plt.subplot(1, 2, 1)
plt.imshow(img.reshape(28, 28))  # 显示的是热度图片
plt.axis('off')  # 不显示坐标轴

# 子图2
plt.subplot(1, 2, 2)
plt.imshow(img.reshape(28, 28), cmap='gray')  # 显示灰度图片
plt.axis('off')

plt.show()

'''
显示卷积和池化层结果
'''
plt.figure(figsize=(1.0 * 8, 1.6 * 4))
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
# 显示第一个卷积层之后的结果  (1,28,28,32)
conv1 = h_conv1.eval(feed_dict={x_: img.reshape([-1, 784]), y_: label.reshape([-1, 10]), keep_prob: 1.0})
print('conv1 shape', conv1.shape)

for i in range(32):
    show_image = conv1[:, :, :, 1]
    show_image.shape = [28, 28]
    plt.subplot(4, 8, i + 1)
    plt.imshow(show_image, cmap='gray')
    plt.axis('off')
plt.show()

plt.figure(figsize=(1.2 * 8, 2.0 * 4))
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
# 显示第一个池化层之后的结果  (1,14,14,32)
pool1 = h_pool1.eval(feed_dict={x_: img.reshape([-1, 784]), y_: label.reshape([-1, 10]), keep_prob: 1.0})
print('pool1 shape', pool1.shape)

for i in range(32):
    show_image = pool1[:, :, :, 1]
    show_image.shape = [14, 14]
    plt.subplot(4, 8, i + 1)
    plt.imshow(show_image, cmap='gray')
    plt.axis('off')
plt.show()


#https://www.hackerrank.com/challenges/divisible-sum-pairs/problem
#!/bin/python3

import math
import os
import random
import re
import sys

def divisibleSumPairs(n, k, ar):
    pair = 0

    for i in range(0, n):
        for j in range(i+1, n):
            value = ar[i] + ar[j];
            if((value % k) == 0):
                pair+= 1

    return pair

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

    nk = input().split()

    n = int(nk[0])

    k = int(nk[1])

    ar = list(map(int, input().rstrip().split()))

    result = divisibleSumPairs(n, k, ar)

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

    fptr.close()


def zigzag(matrix):
    for i in range(len(matrix)):
        if i % 2 != 0:
            j = len(matrix[0]) - 1
            while j >= 0:
                print(matrix[i][j])
                j -= 1
        else:
            j = 0
            while j < len(matrix[0]):
                print(matrix[i][j])
                j += 1

if __name__ == '__main__':
    matrix = [[1,2,3,4],
               [8,7,6,5],
               [9,10,11,12],
               [16,15,14,13]]
    zigzag(matrix)


import re

# URL 판단 정규표현
p = re.compile('^https*://([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+(/[a-zA-Z0-9-_.?=]+)*')

print(p.match('http://www.example.com/hello/world.do?key=python'))
print(p.match('https://example/hello/world.html'))

url = input()

def valid_url(url):
    p = re.compile('^https?://([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+(/[a-zA-Z0-9-_.?=]+)*')

    if p.match(url):
        return True
    else:
        return False

print(valid_url(url))


"""
Pass e Ellipsis como placeholders (...) :
São últilizadas para reservar o lugar onde
o programador deveria escrever um cód, mas deixou pra depois.

"""

valor = True

if valor:
    print('oi')
else:
    print('Tchau')


import json
import pandas

def edat(n:int, m:int)->int:
    return abs(n-m)
def hobbies(x: list[str], y: list[str])->int:
    proximitat = 0
    for i in range(len(x)):
        for j in range(len(y)):
            if y[j] == x[i]:
                proximitat -=1
    return proximitat
def emparellament(n:int)->bool:
    if n<=15:
        return True
    else:
        return False
def main()->None:

    #with open('C:/Users/arnau/OneDrive/Documents/AP1/datathon/perfils.json') as file:
    dictperfils = pandas.read_json("perfils.json")
    for row1 in dictperfils.iterrows():
        for row2 in dictperfils.iterrows():
            mitjana = edat(row1['age'],row2['age'])+ hobbies(row1['hobbies'], row2['hobbies'])
    print(emparellament(mitjana))

if __name__ == "__main__":
    main()


import torch
import random

from itertools import islice
from typing import List
from types import SimpleNamespace

class Batcher:
    def __init__(self, max_len:int):
        self.device     = torch.device('cpu')
        self.max_len    = max_len

    def batches(self, data:list, bsz:int, shuffle:bool=False, data_ordering=False):
        """splits the data into batches and returns them"""
        examples = self._prep_examples(data)
        if data_ordering: examples.sort(key=lambda x: len(x.input_ids))
        elif shuffle: random.shuffle(examples)
        batches = [examples[i:i+bsz] for i in range(0,len(examples), bsz)]
        if shuffle and data_ordering: random.shuffle(batches)
        return [self.batchify(batch) for batch in batches]

    def batchify(self, batch:List[list]):
        """each input is input ids and mask for utt, + label"""
        ex_id, input_ids, mask_positions, labels = zip(*batch)
        input_ids, attention_mask = self._get_padded_ids(input_ids)
        labels = torch.LongTensor(labels).to(self.device)

        return SimpleNamespace(
            ex_id=ex_id,
            input_ids=input_ids,
            attention_mask=attention_mask,
            labels=labels
        )

    def _prep_examples(self, data:list):
        """ sequence classification input data preparation"""
        prepped_examples = []
        for ex in data:
            ex_id     = ex.ex_id
            input_ids = ex.input_ids
            label     = ex.label
            mask_position = getattr(ex, 'mask_position', None)

            if self.max_len and len(input_ids) > self.max_len:
                # if truncate, must move mask_position (assumed to be in the final 512 tokens)
                if mask_position:
                    mask_position = mask_position - len(input_ids) + 512
                input_ids = [input_ids[0]] + input_ids[-(self.max_len-1):]

            prepped_examples.append([ex_id, input_ids, mask_position, label])

        return prepped_examples

    def to(self, device:torch.device):
        """ sets the device of the batcher """
        self.device = device

    def _get_padded_ids(self, ids:list, pad_id=0)->List[torch.LongTensor]:
        """ pads ids to be flat """
        max_len = max([len(x) for x in ids])
        padded_ids = [x + [pad_id]*(max_len-len(x)) for x in ids]
        mask = [[1]*len(x) + [0]*(max_len-len(x)) for x in ids]
        ids = torch.LongTensor(padded_ids).to(self.device)
        mask = torch.FloatTensor(mask).to(self.device)
        return ids, mask

    def __call__(self, *args, **kwargs):
        """routes the main method do the batches function"""
        return self.batches(*args, **kwargs)

    #== Debugging Tool to measure Computation time required ===============
    def dummy_batches(self, seq_len, data_len:int=10_000, bsz:int=4, decoder_len=None):
        def random_batch():
            input_ids = torch.randint(low=0, high=1000, size=(bsz, seq_len), dtype=torch.long).to(self.device)
            attention_mask = torch.ones(bsz, seq_len, dtype=torch.long).to(self.device)
            labels =  torch.randint(low=0, high=1, size=(bsz,), dtype=torch.long).to(self.device)

            return SimpleNamespace(
                ex_id=0,
                input_ids=input_ids,
                attention_mask=attention_mask,
                labels=labels
            )

        return [random_batch() for _ in range(int(data_len // bsz))]


import os
import subprocess
import time

from debuglogger import DebugLogger
from driver.instrumentdriver import InstrumentDriver
from config import Config

if os.uname()[4].startswith("arm"):  # Test if the program is running on RPi or not
    # Load modules for
    subprocess.call('modprobe w1-therm', shell=True)
    subprocess.call('modprobe w1-gpio', shell=True)

class TempDS18B20Driver(InstrumentDriver):
    """Driver for 1-Wire BS18B20 temperature sensor"""

    def __init__(self, enabled: bool, debug_logger: DebugLogger, object_id: str, config: Config):
        super(TempDS18B20Driver, self).__init__(enabled, debug_logger, object_id)

        # Initialize config
        self.config = config

        # If the program is not running on RPi, automatically disable the driver
        if not os.uname()[4].startswith("arm"):
            self.set_status_code(1)
            self.debug_logger.info(object_id, "Deactivated: run only on RPi!")
            return
        else:
            self.set_status_code(self.ask_instrument_status())

        # Initialize sensor's file, and check if it exists
        self.sensor_filename = self.__get_sensor_filename__()
        if not os.path.exists(self.sensor_filename):
            self.set_status_code(2)

        # Launch record thread
        self._launch_thread_record_()

    def get_temperature(self):
        """Get the temperature from the sensor."""
        lines = self.__temp_raw__()
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = self.__temp_raw__()

        temp_output = lines[1].find('t=')

        if temp_output != -1:
            temp_string = lines[1].strip()[temp_output+2:]
            temp_c = float(temp_string) / 1000.0
            # temp_f = temp_c * 9.0 / 5.0 + 32.0
            return temp_c

    def __temp_raw__(self):
        """Get the content of the sensor's file"""
        f = open(self.sensor_filename, 'r')
        lines = f.readlines()
        f.close()
        return lines

    def ask_instrument_status(self):
        status = 5
        return status

    def __get_sensor_filename__(self):
        filename = "/sys/bus/w1/devices/" + self.config.read(self.object_id, "sensor_id") + "/w1_slave"
        return filename

    def __update_record__(self):
        self.record["temperature"] = self.get_temperature()

    def _reset_record_(self):
        self.record["temperature"] = -999


def calculate_sum_of_bonus(data):
    exchange_rate = 30
    weight_bonus = []
    set_weight = []

    dict_performance = {"above average" : 2,
                       "average" : 1,
                       "below average:" : 0}
    dict_role = {"CEO" : 2,
                 "Engineer" : 1,
                 "Sales": 1}

    for item in data:
        for index in range(len(data["employees"])):
            performance_level = data["employees"][index]["performance"]
            role = data["employees"][index]["role"]
            salary = data[item][index]['salary']

            if isinstance(salary, str):
                 if "USD" in salary:
                     salary_value = int(salary.replace("USD", ""))
                     salary_usd = salary_value * exchange_rate
                     salary = salary_usd

                 else:
                    salary = int(salary.replace(",",""))

            performance_factor = dict_performance.get(performance_level, 0)
            role_factor = dict_role.get(role, 0)
            base = salary * (role_factor + performance_factor)
            set_weight.append(base)

    sum_set_weight = sum(set_weight)
    weight_value = 10000 / sum_set_weight

    for weight in set_weight:
        bonus = round(weight * weight_value, 0)
        print(bonus)
        weight_bonus.append(bonus)
        sum_bonus = sum(weight_bonus)

    print(sum_bonus)

calculate_sum_of_bonus({
"employees":[
{
"name":"John",
"salary":"1000USD",
"performance":"above average",
"role":"Engineer"
},
{
"name":"Bob",
"salary":60000,
"performance":"average",
"role":"CEO"
},
{
"name":"Jenny",
"salary":"50,000",
"performance":"below average",
"role":"Sales"
}
]
}) # call calculate_sum_of_bonus function


from django.urls import path
from . import views

app_name = 'showcase'

urlpatterns = [
    path('', views.ShowcaseView.as_view(), name='showcase'),
    path('category/<int:category_id>/', views.CategoryPageView.as_view(), name='category_page'),
    path('item/<int:item_id>/', views.ItemPageView.as_view(), name='item_page'),
    path('category/<int:item_id>/sizes/', views.ChooseSizes, name='choose_sizes'),
    path("currency/<str:valuta>/", views.cart_val, name="currency"),
]


def gcd(m, n):

    factor_m = []
    for x in range(1, m+1):
        if (m % x) == 0:
            factor_m.append(x)

    factor_n = []
    for y in range(1, n+1):
        if (n % y) == 0:
            factor_n.append(y)

    high_num = 0
    low_num_list = []
    if m > n:
        high_num = m
        low_num_list = factor_n
    else:
        high_num = n
        low_num_list = factor_m

    common_factor = []
    for z in range(len(low_num_list)):
        if (high_num % low_num_list[z]) == 0:
            common_factor.append(low_num_list[z])

    return max(common_factor)

print("A programme to find Greatest Common Divisor(GCD)/Common Factor")
m = int(input("Enter the First number: "))
n = int(input("Enter the Second number: "))
result = gcd(m, n)
print("The GDC of your given numbers is :", result)


from PyQt5.QtWidgets import QWidget, QMainWindow, QLabel, QGridLayout, QScrollArea
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt
import configparser
import numpy as np

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure, SubplotParams
from tensorflow.keras.models import load_model

# Action Settings
config = configparser.ConfigParser()
config.read('config/action_settings.ini')
SEP = config['ACTION']['SEP']
ADD = config['ACTION']['ADD']
SUB = config['ACTION']['SUB']
DIV = config['ACTION']['DIV']
MUL = config['ACTION']['MUL']

class ModelView(QWidget):
    def __init__(self, nodeflow_main, n, nn, config):
        super(ModelView, self).__init__()

        DATASET = config.get('DATASET')
        MODEL = config.get('MODEL')

        name = nn+'Model_Name'
        dat_dir = nn+'Dataset_Dir'
        dat_ext = nn+'Dataset_Ext'

        mod_dir = nn+'Model_Dir'
        mod_ext = nn+'Model_Ext'

        IMAGES = 30
        ROW = 10
        COL = 10

        nodeflow_main.createAttribute(node=n, name='Model_Name', preset='String', socket=True, plug=True, dataType='str', dataAttr='ImageGirlDataset')
        nodeflow_main.createAttribute(node=n, name='Cmap', preset='String', socket=True, plug=True, dataType='str', dataAttr='Greys_r')
        nodeflow_main.createAttribute(node=n, name='Dataset_Ext', preset='String', socket=True, plug=True, dataType='str', dataAttr='.npz')
        nodeflow_main.createAttribute(node=n, name='Dataset_Dir', preset='String', socket=True, plug=True, dataType='str', dataAttr=DATASET)
        nodeflow_main.createAttribute(node=n, name='Model_Ext', preset='String', socket=True, plug=True, dataType='str', dataAttr='.h5')
        nodeflow_main.createAttribute(node=n, name='Model_Dir', preset='String', socket=True, plug=True, dataType='str', dataAttr=MODEL)
        nodeflow_main.createAttribute(node=n, name='Images', preset='Integer', socket=True, plug=True, dataType='int', dataAttr=IMAGES)
        nodeflow_main.createAttribute(node=n, name='Images_Column', preset='Integer', socket=True, plug=True, dataType='int', dataAttr=COL)
        nodeflow_main.createAttribute(node=n, name='Images_Row', preset='Integer', socket=True, plug=True, dataType='int', dataAttr=ROW)
        nodeflow_main.createAttribute(node=n, name='Dataset_Path', preset='Path', socket=True, plug=True, dataType='str', dataExpr=dat_dir + ADD + name + ADD + dat_ext)
        nodeflow_main.createAttribute(node=n, name='Model_Path', preset='Path', socket=True, plug=True, dataType='str', dataExpr=mod_dir + ADD + name + ADD + mod_ext)

class ModelViewAction(QMainWindow):
    """Model Create"""
    def __init__(self, attrData, config):
        super(ModelViewAction, self).__init__()

        print(attrData)
        self.attrData = attrData

        self.npz_file = attrData.get('Dataset_Path')
        self.mod_file = attrData.get('Model_Path')

        self.img_num = int(attrData.get('Images'))
        self.img_row = int(attrData.get('Images_Row'))
        self.img_col = int(attrData.get('Images_Column'))

        # loading data
        print("Loading previously created data...")
        self.data = np.load(self.npz_file)

        # loading the previous model
        print("Loading Model")
        self.model = load_model(self.mod_file)

        # making a prediction on test dataset
        self.y_pred = self.model.predict(self.data["x_test"])

        self.gridLayout = QGridLayout()
        self.window = QWidget()
        self.window.setContentsMargins(0, 0, 0, 0)
        self.window.setLayout(self.gridLayout)

        self.images = []
        self.buildLayout(self.img_num, self.img_row, self.img_col)
        self.window.update()

    def buildLayout(self, img_num, img_row, img_col):
        for i in range(img_row):
            l = []
            for j in range(img_col):
                img_num += 1

                self.widget = QWidget()
                self.widget.setContentsMargins(0, 0, 0, 0)
                self.label = QLabel(self.widget)
                self.image = self.ColourMap(img_num, "Greys_r")
                self.label.setPixmap(self.image)
                self.label.setContentsMargins(0, 0, 0, 0)
                self.label.setFixedSize(100, 100)
                l.append(self.label)
                self.gridLayout.addWidget(self.label, i, j)
                self.gridLayout.setColumnMinimumWidth(j, 0)
                self.gridLayout.setContentsMargins(0, 0, 0, 0)
                self.gridLayout.setSpacing(0)

            self.images.append(l)
            self.gridLayout.setRowMinimumHeight(i, 0)

        self.scroll = QScrollArea()
        self.scroll.setMinimumHeight(1000)
        self.scroll.setContentsMargins(0, 0, 0, 0)
        self.scroll.setWidget(self.window)
        self.scroll.setWidgetResizable(True)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.update()

        self.setCentralWidget(self.scroll)

    def ColourMap(self, img, cmap):

        sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
        fig = Figure((1, 1), subplotpars=sp)
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(111)

        ax.imshow(self.y_pred[img, img:, img:, 0], cmap=cmap)

        ax.set_axis_off()
        canvas.draw()
        size = canvas.size()
        width, height = size.width(), size.height()
        im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)

        return QPixmap(im)


from random import seed
from random import randrange
from csv import reader
import matplotlib.pyplot as plt

def float_conversion(f, y):          #column = y
    for i in range(len(f)):
        x = f[i]
        a = x[y].strip()
        x[y] = float(a)

def int_conversion(f, y):
    a = []
    for x in f:
        x[y] = float(x[y])
        a = a + [x[y]]
    m1 = float(min(a))
    m2 = float(max(a))

    ax = float(m2 - m1)
    ac = float(ax/3)
    i = float(m1 + ac)
    j = float(m1 + (2*ac))

    for x in f:
        x[y] = float(x[y])
        if x[y] >= m1 and x[y] < i:
            x[y] = 0
        elif x[y] >= i and x[y] < j:
            x[y] = 1
        else:
            x[y] = 2
    return

def tree(f, algo, n, *arguments):
    fs = []
    fs1 = list(f)
    l = len(f)
    size_of_fd = int(l/n)
    for i in range(n):
        fd = []
        while len(fd) < size_of_fd:
            ind = randrange(len(fs1))
            a = fs1.pop(ind)
            fd = fd + [a]
        fs = fs + [fd]

    K_fds = fs
    s = []
    for ij in range(len(K_fds)):
        k_fd = K_fds[ij]
        x_set = list(K_fds)             #train_set = x    test_set = y
        x_set.remove(k_fd)
        x_set = sum(x_set, [])
        y_set = []
        for j in range(len(k_fd)):
            x = k_fd[j]
            x1 = list(x)               #x_copy = x1
            y_set = y_set + [x1]
            x1[-1] = 0
        pred = algo(x_set, y_set, *arguments)
        act = []
        for k in range(len(k_fd)):
            x = k_fd[k]
            act = act + [x[-1]]

        l1 = len(act)
        c1 = 0
        for j in range(l1):
            if act[j] == pred[j]:
                c1 = c1 + 1
        d = float(l1)
        e = (c1/d)*100.0
        acc = e
        s = s + [acc]

    return s

def seperate(f):
    c = []
    for i in range(len(f)):
        x = f[i]
        c= c + [x[-1]]

    bind = 100
    bval = 100
    bsc = 100
    b_gps = 0

    l = len(f[0])
    a = l-1
    for ind in range(a):
        for i in range(len(f)):
            x = f[i]
            u = []
            v = []
            for x1 in f:
                if x1[ind] < x[ind]:
                    u = u + [x1]
                else:
                    v = v + [x1]
            gps = (u,v)
            a1 = []
            for j in range(len(gps)):
                gp = gps[j]
                a1 = a1 + [len(gp)]
            no_of_inst = float(sum(a1))
            gini_ind = 0.0
            for k in range(len(gps)):
                gp = gps[k]
                s1 = float(len(gp))
                if s1 == 0:
                    continue
                sc1 = 0.0
                for m in range(len(c)):
                    class_val = c[m]
                    b = [row[-1] for row in gp].count(class_val)
                    p = b / s1
                    sc1 = sc1 + (p * p)
                x2 = (1.0 - sc1)
                y1 = (s1 / no_of_inst)
                gini_ind = gini_ind + (x2*y1)
            g = gini_ind
            if g < bsc:
                bind = ind
                bval = x[ind]
                bsc = g
                b_gps = gps
    return {'index':bind, 'value':bval, 'groups':b_gps}

def terminal_nd1(gp):
    r = []
    for i in range(len(gp)):
        x = gp[i]
        r = r + [x[-1]]
    a = set(r)
    b = max(a, key=r.count)
    return b

def divide(nd1, md, ms, d):
    g = 'groups'
    lt = 'left'
    rt = 'right'

    l, r = nd1[g]
    del(nd1[g])

    if not l or not r:
        nd1[lt] = terminal_nd1(l + r)
        nd1[rt] = terminal_nd1(l + r)
        return

    if d >= md:
        nd1[lt] = terminal_nd1(l)
        nd1[rt] = terminal_nd1(r)
        return

    if len(l) > ms:
        nd1[lt] = seperate(l)
        divide(nd1[lt], md, ms, d+1)
    else:
        nd1[lt] = terminal_nd1(l)

    if len(r) > ms:
        nd1[rt] = seperate(r)
        divide(nd1[rt], md, ms, d+1)
    else:
        nd1[rt] = terminal_nd1(r)

def prediction(nd, x):
    v = 'value'
    i = 'index'
    l = 'left'
    r = 'right'
    d = dict
    if nd[v] > x[nd[i]]:
        if isinstance(nd[l], d):
            return prediction(nd[l], x)
        else:
            return nd[l]
    else:
        if isinstance(nd[r], d):
            return prediction(nd[r], x)
        else:
            return nd[r]

def bagging(x_t, y_t, md, ms, ss, n_t):
    t = []
    ij = 0
    while ij < n_t:
        ij = ij+1
        s1 = []
        l1 = (len(x_t) * ss)
        n1 = round(l1)          #n = n_sample
        while len(s1) < n1:
            a1 = len(x_t)
            j = randrange(a1)
            s1 = s1 + [x_t[j]]

        s = s1
        r = seperate(s)
        divide(r, md, ms, 1)
        t1 = r
        t.append(t1)
    predict = []
    for j in range(len(y_t)):
        x = y_t[j]
        p = []
        for k in range(len(t)):
            t1 = t[k]
            p = p + [prediction(t1,x)]
        a1 = set(p)
        b1 = max(a1, key= p.count)
        predict = predict + [b1]

    return(predict)

seed(1101)
f = 'C:/Project/hou_all.csv'
data = []
with open(f, 'r') as f1:
    file1 = reader(f1)
    for x in file1:        #row = x
        data = data + [x]

f1 = data
a = len(f1)
f = f1[1:a]

length = len(f[0])

for i in range(0, length-1):
    float_conversion(f, i)

int_conversion(f, length-1)

x = []
y = []

no_of_fds = 5
sample_size_tree = 0.5
size = 2

for depth in [6]:
    for no_of_trees in [1,2]:
        x = x + [no_of_trees]
        accuracy = tree(f, bagging, no_of_fds, depth, size, sample_size_tree, no_of_trees)
        print('Depth: %d' % depth)
        print('Number of Trees: %d' % no_of_trees)
        print('Cross validation Scores: %s' % accuracy)
        a = float(len(accuracy))
        b = sum(accuracy)
        s = (b/a)
        print('Accuracy of Model: %.2f%%' % s)
        y = y + [s]

plt.plot(x,y)
plt.xlabel('Number of trees')
plt.ylabel('Accuracy')


import csv
import os.path
import time
from datetime import datetime
from threading import Thread

from driver.humgendriver import HumgenDriver
from driver.instrumentdriver import InstrumentDriver

class DataLogger:
    """
    Class used to periodically log the values measured by the instruments.
    The object which can be logged must have the following functions (note that this is necessarily the case for
    InstrumentDriver's children classes):
      * get_record(): a dict containing variable:value pairs
      * get_object_id(): the object's string identifyer
      * get_data_logger_header_list(): a list containing all the variables to be logged, in the desired order.
    """

    def __init__(self, filename_root, humgen: HumgenDriver):
        self.filename_root = filename_root
        self.humgen = humgen

        # List of all the instruments whose data should be logged
        self.instruments_to_log = [humgen.pump,
                                   humgen.flowA,
                                   humgen.flowB,
                                   humgen.pressure,
                                   humgen.valve1,
                                   humgen.valve2,
                                   humgen.valve2x3,
                                   humgen.picarro_code]

        # Define columns name
        self.column_names = ["datetime"]
        for instrument in self.instruments_to_log:
            self.column_names += self.__get_formatted_colnames__(instrument)

        # Create and launch write-in-log thread
        log_thread = Thread(target=self.__thread_log__)
        log_thread.daemon = True
        log_thread.start()

    def write(self):
        # Gather and sort the record in a common data list
        data_list = [datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]]
        for instrument in self.instruments_to_log:
            data_list += self.__get_instrument_variable_list__(instrument)

        # Write the data list in file
        if not self.__file_exists__():
            self.__add_header__()
        self.__write_in_file__(data_list)

    def __get_instrument_variable_list__(self, instrument: InstrumentDriver):
        instrument_record = instrument.get_record()
        instrument_data_list = []
        for variable_name in instrument.get_data_logger_header_list():
            variable_value = instrument_record[variable_name]
            variable_value = self.__format_variable__(variable_value)
            instrument_data_list.append(variable_value)
        return instrument_data_list

    def __get_file_name__(self):
        date_string = datetime.now().strftime("%Y-%m-%d")
        filename = "../log/" + date_string + "_" + self.filename_root + ".log"
        return filename

    def __file_exists__(self):
        filename = self.__get_file_name__()
        if os.path.exists(filename):
            return os.path.isfile(filename)
        else:
            return False

    def __add_header__(self):
        self.__write_in_file__(self.column_names)

    def __write_in_file__(self, data_list):
        with open(self.__get_file_name__(), 'a') as datafile:
            writer = csv.writer(datafile, delimiter='\t')
            writer.writerow(data_list)

    def __thread_log__(self):
        """
        Thread which periodically write data log to a file
        """
        while True:
            self.write()
            time.sleep(10)

    def __format_variable__(self, value, digit: int=3) -> str:
        if value is None:
            return "NA"
        elif isinstance(value, int) | isinstance(value, float):
            return str(round(value, digit))
        else:
            return value

    def __get_formatted_colnames__(self, instrument: InstrumentDriver):
        return [instrument.get_object_id() + "_" + colname for colname in instrument.get_data_logger_header_list()]


#!/usr/bin/python3
import sys
import datetime
import smtplib

from email.message import EmailMessage

"""
Lunch Ring

Maintains a ring of the CoBloX devs.  If today is notification_day emails
whomever is at the head of the list to notify them that it is their turn
to pick the lunch spot.  Rotates list head to tail.

Requires an SMTP server to be running on host machine.
Suggested usage: Run this script daily i.e., as a cron job.
"""

ring_path = "./ring.txt"        # The file holding the current lunch ring.
log_file = "./lunch_ring.log"
notification_day = "Wednesday"

# CoBloX hackers listed in alphabetical order.
address_book = [("Daniele", "daniele@coblox.tech"), ("Franck", "franck@coblox.tech"), ("Lucas", "lucas@coblox.tech"), ("Philipp", "philipp@coblox.tech"), ("Thomas", "thomas@coblox.tech"), ("Tobin", "tobin.harding@tenx.tech")]
author = "Tobin"

def main():
   today = day()
   if today == notification_day:
      send_notification()

def day():
   """Returns the current day i.e., Monday"""
   days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
   day = datetime.datetime.today().weekday()
   return days[day]

def send_notification():
   """Reads ring file and sends a notification to the head of the list"""
   who = rotate_ring_file(ring_path)
   notify(who)

def rotate_ring_file(filename):
   """Reads ring file into memory and writes it back to file putting the
   head of the list at the end.  Returns the head of the list"""

   return "Tobin"

   f = open(filename, 'r')
   ring = f.readlines()
   f.close()

   who = ring[0]                # Head of the list.
   who = who[:len(who)-1]       # Remove trailing newline.

   ring = ring[1:] + ring[:1]   # Rotate the list.

   f = open(filename, 'w')
   f.writelines("%s" % item for item in ring)

   return who

def notify(who):
   """Sends an notification to 'who'"""
   body = "Yo %s,\n\nIts your turn to pick the team lunch venue!  Please choose a place and book if necessary.  If we need to leave early to get there please notify the team - we like to eat at 12.\n\nThanks, you rule.\n" % who
   send_email_to(body, address_of(who))

def address_of(who):
   for (name, address) in address_book:
      if name == who:
         return address

   err("failed to get email address for: " + who)

def send_email_to(body, address):
   msg = EmailMessage()
   msg.set_content(body)
   msg['Subject'] = ""
   msg['From'] = "no-reply@lunch-ring.bot"
   msg['To'] = address

   s = smtplib.SMTP('localhost')
   s.send_message(msg)
   s.quit()

   log("sent email to: %s\n" % address)

def err(msg):
   """logs 'msg' and sends an email to the script author"""
   print("error: %s" % msg)
   log(msg)
   sys.exit(1)

def log(msg):
   """Appends 'msg' to end of log file"""
   date = datetime.datetime.today()

   f = open(log_file, 'a')
   f.write("%s: %s" % (date, msg))

if __name__ == "__main__":
    main()


import string

alphabet = string.ascii_lowercase

def init_key(key: str, plain_text: str, repeat: bool) -> str:
    global result
    result = key

    if repeat:
        while len(result) < len(plain_text):
            result += key
        return result[:len(plain_text) + 1]

    return (key + plain_text)[:len(plain_text) + 1]

def encrypt(plain_text: str, k: str) -> str:
    cypher_text = ''
    for i in range(len(plain_text)):
        index_in_alphabet = (alphabet.index(plain_text[i]) + alphabet.index(k[i])) % 26
        cypher_text += alphabet[index_in_alphabet]
    return cypher_text

def decrypt(cypher_text: str, k: str) -> str:
    plain_text = ''
    for i in range(len(cypher_text)):
        index_in_alphabet = (alphabet.index(cypher_text[i]) - alphabet.index(k[i])) % 26
        new_char = alphabet[index_in_alphabet]
        k += new_char
        plain_text += new_char
    return plain_text

if __name__ == '__main__':
    text = 'moneymakesth'
    d_key = init_key('nopain', text, False)

    result = encrypt(text, d_key)
    print(result)
    result2 = decrypt(result, d_key)
    print(result2)


#!/usr/bin/python3
"""DIsplays the X-req-id header var of a req to a given URL.
Using = ./1-hbtn_header.py <URL>
"""
import sys
import urllib.request

if __name__ == "__main__":
    url = sys.argv[1]

    req = urllib.request.Request(url)
    with urllib.request.urlopen(req) as res:
        print(dict(res.headers).get("X-Request-Id"))


#!/usr/bin/python3.9
from math import log10
import random
from matplotlib import pyplot as plt
from esp8266 import *
from methods import (
    methode_partition,
    methode_MonteCarlo,
    methode_gradient,
    apply_method,
)
from graphical import plot_reseau, create_fluctuation_video

def plot_power(signals, real_mean, real_sigma):
    """
    Permet de visualiser la distribution des `signals`
    """

    # just to get a quick view into the shape of the distribution
    # does not act as a proof
    freq = frequencies(signals, margin=0.01)
    plt.plot(freq.keys(), freq.values())
    plt.show()

def main():
    """
    Effectue successivement les différentes visualisations requises pour l'étude.
    """
    print("Running ESP8266 positionning simulation")
    # plot_power(get_measures(4096, -55, 1.6))
    # print(read_csv("config-reseau.csv"))
    esps = read_csv("config-reseau.csv")
    power = signal_moyen(esps[0], esps[1])

    # methods_comparison((0, -3, 8, 8), source_file="config-reseau.csv")
    esps, dims = random_set()
    print(f"Parameters: {len(esps)} ESP8266 nodes on a {dims[2]}x{dims[3]} space.")

    methods_comparison(dims, esps=esps)

    # create_fluctuation_video(reference_nodes(esps)[0])

def random_set():
    """
    Génère un jeu d'ESPs dans un espace aléatoire.
    """
    ref_node_count = random.randrange(3, 20)
    node_count = ref_node_count + random.randrange(1, 10)
    width = random.randrange(10, 50)
    height = random.randrange(10, 50)
    dims = (0, 0, width, height)

    esps = []
    for i in range(ref_node_count):
        esps.append(new_esp(i, (0, 0, 5, 5), ref=True))
    for i in range(ref_node_count, node_count):
        esps.append(new_esp(i, (0, 0, 20, 20)))

    return (esps, dims)

def methods_comparison(dims, source_file=None, esps=[]):
    """
    Applique et visualise successivement toutes les méthodes de géolocalisation.

    Nécessite un jeu d'esps qui peut venir d'un fichier source (`source_file`),
    d'une liste d'`esps` ou d'une combinaison des deux. `dims` est la description de l'espace
    dans lequel la simulation se produit. Pour en savoir plus sur `dims` voir `utils.into_corners`
    """

    if source_file is not None:
        try:
            esps.extend(read_csv(source_file))
        except:
            pass

    ref_esps = reference_nodes(esps)
    calibrage_references(ref_esps)

    distances = {}
    for esp in esps:
        if not esp["reference_node"]:
            distances[esp["id"]] = distances_aux_references(esp, ref_esps)

    fig, axs = plt.subplots(3, 4, figsize=(12, 8))

    # graphiques de références, sans application de méthode de détetection
    plot_reseau(ref_esps, dims, "Capteurs de référence", axs[0][0])
    plot_reseau(ref_esps, dims, "Réseau de noeuds", axs[0][1])

    # méthode de partition
    apply_method(esps, ref_esps, distances, dims, methode_partition)
    plot_reseau(esps, dims, "Méthode par partition", axs[0][2])

    # méthode de Monte-Carlo
    apply_method(esps, ref_esps, distances, dims, methode_MonteCarlo)
    plot_reseau(esps, dims, "Méthode de Monté-Carlo", axs[0][3])

    # méthodes de gradient utilisant les divers méthode de calcul de gradient
    (i, j) = (1, 0)

    for method in (
        "Nelder-Mead",
        "Powell",
        "CG",
        "BFGS",
        "L-BFGS-B",
        "TNC",
        "COBYLA",
        "SLSQP",
    ):
        apply_method(esps, ref_esps, distances, dims, methode_gradient, methode=method)
        plot_reseau(esps, dims, f"Méthode du gradient ({method})", axs[i, j])
        j += 1
        if j == 4:
            j = 0
            i += 1

    plt.tight_layout()
    plt.savefig("localisation.png")
    plt.show()

if __name__ == "__main__":
    main()


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

import pytest
from nba_analytics.skeleton import fib

__author__ = "yotam"
__copyright__ = "yotam"
__license__ = "mit"

def test_fib():
    assert fib(1) == 1
    assert fib(2) == 1
    assert fib(7) == 13
    with pytest.raises(AssertionError):
        fib(-10)


import oracle

class MainMenu(object):

	def __init__(self):
		self.oclient = oracle.OracleQuery()
		self.table_list = 'files/table_lookup.txt'
		self.table_names = 'files/table_names.txt'
		self.table_complete = 'files/table_complete.txt'
		self.options = ('\nOptions: \n\n'
			'   choices                >>>  shows table name choices\n'
			'   <table_name>           >>>  lists columns for specific table\n'
			'   table <table_name>     >>>  alternate way to list table columns\n'
			'   print                  >>>  print table info to text doc\n'
			'   all                    >>>  list all tables\n'
			'   keys <table_name>      >>>  list keys for specific table\n'
			'   relat <table_name>     >>>  lists all relationships for specific table\n'
			'   mod <module_name>      >>>  all tables involved in a module, i.e. sales\n'
			'   exit/quit/cls          >>>  exit program\n\n'
			'  Enter: ')

	def get_table_columns(self, arg):
		#using table <table_name>
		table = ''
		with open(self.table_list, "r") as fp:
			for line in iter(fp.readline, ''):
				# refactor with contains...
				if line[:2] == '++':
					if line.split(',')[0][2:] == arg[1]:
						table = line.split(',')[1]
				if line[:1] == '+':
					if line.split(',')[0][1:] == arg[1]:
						table = line.split(',')[1]
		if table:
			self.oclient.get_table_columns(table)
			return True
		else:
			return False

	def get_table_single(self, arg):
		#using only <table_name>
		table = ''
		with open(self.table_list, "r") as fp:
			for line in iter(fp.readline, ''):
				# refactor with contains...
				if line[:2] == '++':
					if line.split(',')[0][2:] == arg[0]:
						table = line.split(',')[1]
				if line[:1] == '+':
					if line.split(',')[0][1:] == arg[0]:
						table = line.split(',')[1]
		if table:
			self.oclient.get_table_columns(table)
			return True
		else:
			return False

	def view_table_choices(self, arg):
		#open file, print off first before comma
		with open(self.table_list, "r") as fp:
			for line in iter(fp.readline, ''):
				if line[:2] == '++':
					print('    '+line.split(',')[0][2:]+'   [fact]')
				elif line[:1] == '+':
					print('    '+line.split(',')[0][1:])
		return True

	def get_modules(self, arg):
		if arg[1] == 'sales' or arg[1] == 'inventory':
			mod = (input('enter ''"monthly"'', ''"daily"'', or ''"transaction"'': ')).lower()
			mod = (arg[1]+'_'+mod)
		else:
			mod = arg[1]
		with open(self.table_list, "r") as fp:
			flag = False
			for line in iter(fp.readline, ''):
				if not flag and line[:2] == '++' and line.split(',')[0][2:] == mod:
					# found related table for module
					flag = True
					print('  related tables:')
				elif flag and line[1:2] == '-':
					key1 = line.split('[')[1][:-1]
					key2 = line.split('[')[2][:-2]
					print('\t'+line[2:].split('[')[0]+'  '+''.join(['shared key = ' + key1 if key2 =='*' else 'keys = ' + key1 + ', ' + key2]))
				else:
					flag = False
		return True

	def print_all(self, args):
		#take list of tables from table_names, for each, print out columns and column info in table_complete
		table_dict = {}
		with open(self.table_names, "r") as fp:
			for line in iter(fp.readline, ''):
				table_dict = self.oclient.get_table_dict(line)
				#have all columns and info on columns, append to table_completed
				with open(self.table_complete, 'a+') as c:
					c.write('%s\n' % line)
					for key, value in table_dict.items():
						c.write('%s:%s\n' % (key, value))
					c.write('\n')
		return True

	def query_columns(self):
		return 'columns selected'

	def query_keys(self):
		return 'keys selected'

	def query_relationships(self):
		return 'relationships selected'

	def route(self, args):
		switch = {
			'choices': self.view_table_choices,
			'mod': self.get_modules,
			'table': self.get_table_columns,
			'single': self.get_table_single,
			'columns': self.query_columns,
			'keys': self.query_keys,
			'relationships': self.query_relationships,
			'print': self.print_all,
		}

		if args[0] in switch:
			func = switch.get(args[0], lambda: 'invalid choice')
			hastable = func(args)
			if not hastable:
				print('\t***Check spelling and try again***')
			if args[0] == 'choices':
				return True
			else:
				return False
		else:
			func = switch.get('single', lambda: 'invalid choice')
			hastable = func(args)
			if not hastable:
				print('\t***Check spelling and try again***')

	def run(self):
		choices = False
		while True:
			if not choices:
				pick = input(self.options)
			else:
				pick = input('\n  Enter: ')
			pick.lower()
			if pick == 'exit' or pick == 'quit' or pick == 'cls':
				self.oclient.disconnect()
				break
			else:
				print()
				args = pick.split(' ')
				choices = self.route(args)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('romani', '0004_comanda_format'),
    ]

    operations = [
        migrations.CreateModel(
            name='Node',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),
                ('nom', models.CharField(max_length=20)),
                ('carrer', models.CharField(max_length=50)),
                ('poblacio', models.CharField(max_length=20)),
                ('codi_postal', models.IntegerField()),
                ('responsable', models.CharField(max_length=20)),
            ],
        ),
        migrations.AddField(
            model_name='comanda',
            name='lloc_entrega',
            field=models.ForeignKey(to='romani.Node',on_delete=models.CASCADE, default=1),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='userprofile',
            name='lloc_entrega',
            field=models.ForeignKey(to='romani.Node', on_delete=models.CASCADE, default=1),
            preserve_default=False,
        ),
    ]