import psycopg2
import requests

import test_helpers
from assert_helpers import assertEqual, assertTrue
from config import TestConfig

class TestSentence(object):

    @classmethod
    def setupClass(cls):

        test_helpers.set_log_levels()
        test_helpers.wait_for_django()

    def setup(self):
        with psycopg2.connect(TestConfig.DATABASE_URL) as conn:
            cur = conn.cursor()
            cur.execute("TRUNCATE TABLE vocab_app_sentence CASCADE ")
            cur.execute("TRUNCATE TABLE vocab_app_tag CASCADE ")
            conn.commit()

        test_helpers.wait_for_django()

    def test_create_sentence_with_tags(self):
        t1_id = test_helpers.create_tag("bob")
        t2_id = test_helpers.create_tag("sam")
        t3_id = test_helpers.create_tag("joe")

        s1_id = test_helpers.create_sentence(
            text_ru="hey",
            text_fr="fr",
            tags=[t1_id,t2_id]
        )

    def test_get_sentences_by_tag(self):
        t1 = test_helpers.create_tag(tag_name="t1")

        t2 = test_helpers.create_tag(tag_name="t2")

        w1 = test_helpers.create_sentence(text_ru="w1", tags=[t1])
        w2 = test_helpers.create_sentence(text_ru="w2", tags=[t1, t2])
        w3 = test_helpers.create_sentence(text_ru="w3", tags=[t1])
        w4 = test_helpers.create_sentence(text_ru="w4", tags=[t2])

        assertEqual(4, len(test_helpers.get_sentences()))
        assertEqual(2, len(test_helpers.get_tags()))

        # Check url results
        sentence_results = test_helpers.get_sentences(tags= ",".join([str(i) for i in [t1, t2]]))
        sentence = sentence_results[0]

        assertEqual(1, len(sentence_results),
                    )

        assertTrue(len(sentence["tags"]) == 2)
        assertTrue(t1 in sentence["tags"])

        assertTrue(t2 in sentence["tags"])

        r = requests.get(url=TestConfig.SENTENCES_URL,
                         params={"tags": [t1, ]}
                         )

        res_json = r.json()

        assertEqual(3, len(res_json["results"]), )

    def test_tag_sentence(self):
        t1 = test_helpers.create_tag(tag_name="t1")

        t2 = test_helpers.create_tag(tag_name="t2")

        w1 = test_helpers.create_sentence(text_ru="w1", tags=[t1])

        sentence = test_helpers.get_sentence(sentence_id=w1)

        assertEqual([t1], sentence["tags"])

        sentence = test_helpers.update_sentence(sentence_id=w1, tags=[t1, t2])

        assertEqual([t1,t2], sentence["tags"])


# -*- coding: UTF-8 -*-
import codecs
import collections
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class Log_manage(object):

	def __init__(self):
		self.file='debug.20170522.0.log'
		self.deep=5

	def list_sort(self,data):
		D=[]
		for d in data:
			d=d.encode('utf-8')
			D.append(d)
		return sorted(D,key=str.lower)

	def log_read(self,file,deep):
		with codecs.open(file,'r','gbk') as fp:
			lines=fp.readlines()
			count=len(lines)
			i=-1
			j=1
			line_list=[]
			while abs(i)<=count:
				m=self.searching_log_input(lines[i])
				if j<=deep:
					if m==True:
						line_list.append(lines[i])
						j+=1
				if j==(deep+1):
					return line_list
				i-=1
			return line_list

	def searching_log_input(self,line):
		if re.search(u'出参：',line):
			return True
		else:
			return False

	def format_str(self,str_dict):
		for i in str_dict:
			for j in range(len(str_dict[i])):
				str_dict[i][j]=self.list_sort(str_dict[i][j].split(", "))
		return str_dict

	def write_to_txt(self,str_dict):
		with codecs.open(u'出参--分析结果.txt','w','gbk') as fp:
			for i in str_dict:
				fp.write('\n'+i+u'出参'+'\n')
				for j in str_dict[i]:
					for l in j:
						fp.write(l.strip()+'\n')
		return

	def extracting_data(self,str_list):
		L=collections.OrderedDict()
		i=0
		for l in str_list:
			a=str(i)+'_'+l[24:30]
			L[a]=l[36:-5]
			i+=1
		return L

	def format_first(self,line_list):
		for i in line_list:
			line_list[i]=line_list[i].split("}, {")
		return line_list

	def main(self):
		line_list=self.log_read(self.file,self.deep)
		line_dict=self.extracting_data(line_list)
		line_dict=self.format_first(line_dict)
		list_dict=self.format_str(line_dict)
		self.write_to_txt(list_dict)

if __name__=='__main__':
	obj_log=Log_manage()
	obj_log.main()


# -*- coding: UTF8 -*-
import os
import sys
import time
import json
import requests
import re
import hashlib
from bs4 import BeautifulSoup

# TODO LIST
# read character encode and save text with same encode
# from meta

#import happybase
#from selenium import webdriver
#webDriver = webdriver.PhantomJS('c:/Python/driver/phantomjs')
#webDriver = webdriver.Chrome('c:/Python/driver/chromedriver.exe')

DATA_SUFFIX ='-data_set.json'
DATA_DIR = '/rawdata'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_STORE = BASE_DIR + DATA_DIR

def checkDataDir(dirpath):
    if not os.path.exists(dirpath):
        os.mkdir(dirpath)

def isExistsUrl(urlStr):
    retVal = ''
    #encodedUrl = hashlib.sha224((urlStr).encode('latin-1')).hexdigest()
    jsonName = DATA_STORE+'/'+urlStr+ DATA_SUFFIX
    print(jsonName)
    if not os.path.exists(jsonName):
        retVal = urlStr
    return retVal

def getDocument(strLink):
    req = requests.get(strLink, allow_redirects=False)

    if req.encoding:
        print("Page Encoding: " + req.encoding)
        print("Page content type: " + req.headers['content-type'])

    if (req.status_code == 200) and (re.search('text/html', req.headers['content-type'])):
        html = req.text
        soup = BeautifulSoup(html, 'html.parser')
    else:
        soup = False
    return soup

def getTitle(soupChunk):
    try :
        if soupChunk.title.string:
            return soupChunk.title.string
    except AttributeError :
        return False

def getAllText(soupChunk):
    cleaned_text = re.sub('[a-zA-Z]','',soupChunk.get_text())
    cleaned_text = re.sub('[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\"]','',cleaned_text)
    return cleaned_text;

def getAllLink(soupChunk):
    tdata = {}
    allLink = soupChunk.find_all('a', string=True)
    for linkSet in allLink:
        p=re.compile('^http')
        linkStr = re.sub(r'<.*?>',' ',linkSet.get('href'))
        linkStr = re.sub(r'{.*?}',' ',linkStr)
        linkStr = re.sub(r'var.*?}',' ',linkStr)
        if p.search(linkStr):
            tdata[linkSet.text] = linkStr

    return tdata

def getCollectStart(urlStr):
    ts = time.time()
    print("Page Url: " + urlStr)
    encodedUrl = hashlib.sha224((urlStr).encode('latin-1')).hexdigest()
    resFile = encodedUrl + DATA_SUFFIX
    data = {}
    chunk = getDocument(urlStr)
    if chunk:
        data['encodedUrl'] = hashlib.sha224((urlStr).encode('latin-1')).hexdigest()
        data['url'] = urlStr
        data['title'] = getTitle(chunk)
        data['text'] = getAllText(chunk)
        data['indexed'] = 0
        data['link'] = getAllLink(chunk)

        with open (os.path.join(DATA_STORE, resFile),'w+') as json_file:
            json.dump(data,json_file)

    else :
        print("no Chunk")

    return resFile

def getCollectJson(JsonFile):
    # open file
    print("File Open : "+JsonFile)
    with open(os.path.join(DATA_STORE ,JsonFile),'r') as data_file:
        data = json.loads(data_file.read())

    for item in data['link']:
        print("ITEM:" + item)
        try:
            res = getCollectStart(data['link'].get(item))
            getCollectJson(res)
        except TypeError:
            print("error: " + data['link'].get(item))
    # get link
    # run getCollect function => jsonfile
    # run getCollectJson(jsonfile)
if __name__ == "__main__":
    if sys.argv[1] :
        checkDataDir(DATA_STORE)
        getCollectStart(sys.argv[1])


"""
@Author : Kokane Ketan
@Description: Program which converts the image from RGB color space to CIE-XYZ color space
"""

import cv2

def convertToCIE(image_name):
    """
    Function which converts the image from RGB to CIE- XYZ color space
    :param image_name: path of the file name to be converted
    :return:  the function does not return anything but prints and saves the file
    """
    img = cv2.imread(image_name) # load the file using Cv2 library
    cie = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # using cvtColor function to change the color space from RGB to CIE XYZ
    cie = cv2.cvtColor(cie, cv2.COLOR_RGB2XYZ) # using cvtColor function to change the color space from RGB to CIE XYZ
    cv2.imshow('Transformed_CIE'+image_name, cie) # showing the
    cv2.imwrite('Transformed_CIE'+image_name, cie)
    cv2.waitKey(0)

if __name__ == '__main__':
    convertToCIE('Lenna.png')


import pdb
import argparse
import sys
import os
from collections import Counter, defaultdict

#from matplotlib.backends.backend_pdf import FigureCanvasPdf, PdfPages
#from matplotlib.figure import Figure
#from matplotlib.patches import Rectangle
#from matplotlib.backends.backend_pdf import PdfPages

from .utils import save_stats

nucleotide = {"A": "R", "G": "R", "C": "Y", "T": "Y"}
REF = 3
ALT = 4
FORMAT = 8
SAMPLE1 = 9

def vcf_stats(vcf_path, stats_file="stats.json", output="vafs.pdf", name=""):

    if not name:
        name = os.path.basename(vcf_path).split(".")[0]

    total = 0
    ti = 0
    tv = 0
    snps = 0
    indels = 0
    vafs = []
    with open(vcf_path, "rt") as f_in:
        for variant in f_in:
            if variant.startswith("#") or variant.startswith('"#'):
                continue

            variant = variant.split("\t")
            total += 1
            try:
                if nucleotide[variant[REF]] == nucleotide[variant[ALT]]:
                    ti += 1
                else:
                    tv += 1
            except KeyError:
                pass

            if len(variant[REF]) != len(variant[ALT]):
                indels += 1
            else:
                snps += 1

            #keys = variant[FORMAT].split(":")
            #vals = variant[SAMPLE1].strip().split(":")
            #vaf = dict(zip(keys, vals))["FREQ"]
            #vafs.append(float(vaf.rstrip("%")) / 100)

    #pdf = PdfPages(output)
    #figure = Figure(figsize=(11.69,8.27))
    #FigureCanvasPdf(figure)
    #ax = figure.gca()

    #ax.hist(vafs, bins=100)
    #ax.get_yaxis().set_visible(False)
    #ax.set_xlabel("Variant Allele Frequency", fontsize=10)
    #ax.set_ylabel("Frequency", fontsize=10)
    #ax.set_title(sample, fontsize=12)

    #pdf.savefig(figure)
    #pdf.close()

    save_stats(stats_file, {"variants": {"total": total,
                                         "snp/indel": float(snps) / (indels or 1),
                                         "ti/tv": float(ti) / (tv or 1)}})

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('vcf_path', help="Input vcf file.")
    parser.add_argument("-s", "--stats", help="Statistics file.", dest="stats_file", default=argparse.SUPPRESS)
    parser.add_argument("-o", "--output", help="Output pdf.", dest="output", default=argparse.SUPPRESS)
    parser.add_argument("-n", "--name", help="Sample name.", default=argparse.SUPPRESS)

    args = parser.parse_args()
    try:
        vcf_stats(**vars(args))
    except OSError as e:
        # File input/output error. This is not an unexpected error so just
        # print and exit rather than displaying a full stack trace.
        sys.exit(str(e))

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing

data = pd.read_csv("dataset.csv",header=0)

X = data.loc[:,["Commune","Etage","Superficie","Piece"]].values
Y = data.loc[:,"Prix"].values

poly = preprocessing.PolynomialFeatures(degree=2)
X =  poly.fit_transform(X)

X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.3)

regressor = LinearRegression()
regressor.fit(X_train,Y_train)
score = regressor.score(X_test,Y_test)
print(score)


#!/usr/bin/env python

"""A tool for provisioning a Khan Academy CloudSearch domain.

Additional information is available at
https://sites.google.com/a/khanacademy.org/forge/for-developers/developing-search/working-with-cloudsearch-domains

WARNING: This script will not currently delete fields. If you remove a field
from the configuration, make sure to remove the field manually by going into
the CloudSearch web console.

Instructions
------------

In order to use this tool you'll need to have the aws command line
tool installed. Get it at
http://docs.aws.amazon.com/cli/latest/userguide/installing.html

Example use: $ ./provision-domain.py khan-academy-dev domain-info.yaml

For a list of possible domains you can use (or to define a new one), see
   https://console.aws.amazon.com/cloudsearch

If you want to update the configs used by prod webapp, use
the domain as part of search_endpoint in <webapp>/search/server.py.
It is probably `khan-academy-prod-2015-8-17`.

After Running the Script
------------------------

You will want to go into the Amazon Cloud Search web console to verify that all
the settings were set as expected.
https://console.aws.amazon.com/cloudsearch/
"""

import json
import logging
import optparse
import os
import pipes
import re
import subprocess
import sys
import urllib2
import yaml

"""A global that is flipped within main if we're in a dry run (not actually
issuing commands to CloudSearch).
"""
dry_run = False

def parse_arguments(raw_args=sys.argv[1:]):
    """Parses any command line arguments."""
    parser = optparse.OptionParser(
        usage="usage: %prog [OPTIONS] DOMAIN_NAME DOMAIN_CONFIG_FILE",
        description="A tool for provisioning a Khan Academy CloudSearch "
            "domain.")

    parser.add_option("-v", "--verbose", action="store_true", default=False,
        help="If specified, DEBUG messages will be printed and more "
            "information will be printed with each log message.")

    parser.add_option("--leave-temp-dir", action="store_true", default=False,
        help="If specified, the created temporary directory will not be "
            "deleted when the script exits.")

    parser.add_option("-n", "--dry-run", action="store_true", default=False,
        help="If specified, no commands will actually be executed.")

    parser.add_option("--no-reindex", action="store_true", default=False,
        help="If specified, will only update the config, without reindexing.")

    options, args = parser.parse_args(raw_args)

    if len(args) != 2:
        parser.error("You must specify the name of the domain and a file "
            "containing the domain configuration.")

    return (options, args[0], args[1])

def maybe_execute_cloudsearch_command(args, error_msg):
    """Runs a CloudSearch command (or not if its a dry run)."""

    command = ["aws", "--region=us-east-1", "cloudsearch"] + args
    pretty_command = command_list_to_str(command)

    # No logging here because we always log
    if dry_run:
        logging.info("Would execute: %s", pretty_command)
        return
    else:
        logging.info("Executing: %s", pretty_command)
        try:
            ret_val = subprocess.check_call(command)
        except subprocess.CalledProcessError:
            logging.exception(error_msg)
            sys.exit(1)
        return ret_val

def setup_logging(verbose):
    # Only print colors if we're working with a terminal
    if sys.stderr.isatty():
        COLOR_START = "\033[1;47m"
        COLOR_END = "\033[1;m"
    else:
        COLOR_START = ""
        COLOR_END = ""

    if verbose:
        log_level = logging.DEBUG
        format = (COLOR_START + "[%(lineno)3s - %(funcName)15s] "
            "%(levelname)5s - %(message)s" + COLOR_END)
    else:
        log_level = logging.INFO
        format = COLOR_START + "%(levelname)s - %(message)s" + COLOR_END

    logging.basicConfig(level=log_level, format=format)

def command_list_to_str(command):
    """Returns the command in such a way that it can be copy and pasted into a
    terminal.

        >>> command_list_to_str(["ls", "/some path"])
        'ls "/some path"'

    This is used in some of the log messages.
    """
    return " ".join(pipes.quote(i) for i in command)

def _ka_language_code(cloudsearch_language_code):
    """Use KA redirects to figure out the ka code for a language code."""
    class NoRedirection(urllib2.HTTPErrorProcessor):
        """Just stop when we get a 302, don't follow it."""
        def http_response(self, request, response):
            return response
        https_response = http_response

    opener = urllib2.build_opener(NoRedirection)
    r = opener.open('http://%s.khanacademy.org/' % cloudsearch_language_code,
                    timeout=5)
    url = r.headers['Location'] or r.url
    host = url.split('/')[2]
    domain = host.split('.')[0]
    if domain == 'www':
        if cloudsearch_language_code == 'en':
            return 'en'
        # A language we don't support.
        return None
    return host.split('.')[0]

def get_disable_flags(field_type, traits):
    """The configure tool enables all available traits by default.

    This function takes a list of desired traits (ex: ["sort", "highlight"])
    and a field_type (ex: "text") and returns a list of arguments to pass to
    define-index-field to make it so (ex: ["--return-enabled", "false",
    "--search-enabled", "false"]).

    An error is logged and `sys.exit` is called if a trait is given that is not
    available for a given field type.
    """

    # Most of the fields have the same available traits so we're going to group
    # the fields into a few categories. Each category will be called a stem.
    # The available traits are listed at
    # http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html
    # They can be verified by playing with the AWS console,
    # selecting each field type and seeing which fields are enabled.
    STEM_TO_FIELD = {
        "plain": {"int", "double", "literal", "date", "latlong"},
        "plain-array": {"int-array", "double-array", "literal-array",
            "date-array"},
        "text": {"text"},
        "text-array": {"text-array"}
    }

    # This gives the available traits for each stem
    STEM_FIELD_AVAILABLE_TRAITS = {
        "plain": {"search", "facet", "return", "sort"},
        "plain-array": {"search", "facet", "return"},
        "text": {"search", "return", "sort", "highlight"},
        "text-array": {"search", "return", "highlight"}
    }

    # Transform the field_type into its corresponding stem
    for stem, field_set in STEM_TO_FIELD.iteritems():
        if field_type in field_set:
            # stem will have the correct value when we break
            break
    else:
        logging.error("Unknown field type %r.", field_type)
        sys.exit(1)

    # Figure out the available traits for field_type
    defaults = STEM_FIELD_AVAILABLE_TRAITS[stem]

    # Make sure that no unavailable traits were specified
    for i in traits:
        if i not in defaults:
            logging.error("Trait %r not available for %r fields.", i,
                field_type)
            sys.exit(1)

    # We're going to disable every default trait that wasn't specified in
    # traits.
    disabled_traits = defaults - set(traits)

    return sum([["--{}-enabled".format(i), "false"]
        for i in disabled_traits], [])

def configure_fields(config, domain, language_codes_with_schemes):
    """Configures all of the fields. Called by main()."""
    # A map from *Khan Academy* locale-name to the cloudsearch scheme name.
    locales = {}
    for language_code in language_codes_with_schemes:
        scheme_name = 'ka_%s' % language_code
        try:
            ka_locale = _ka_language_code(language_code)
        except Exception:
            logging.error('Error fetching KA homepage for %s' % language_code)
            raise
        if not ka_locale:     # Not a language we support at KA
            logging.debug("Ignoring cloudsearch locale '%s': "
                          "it's not yet supported by KA" % language_code)
            continue
        # The CloudSearch field names need to match the regex [a-z0-9_]{3,64}.
        # They include the locale in them, so we convert all non-alnums to
        # _, and lowercse.
        ka_locale = re.sub(r'\W', '_', ka_locale).lower()
        locales[ka_locale] = scheme_name
        logging.debug("Mapping cloudsearch locale '%s' to ka locale '%s'"
                      % (language_code, ka_locale))

    fields = config["fields"]
    logging.debug("Loaded fields: %r", [field["name"] for field in fields])

    # A list of lists where each sublist contains all of the arguments that
    # should be passed to define-index-field to configure that field, with
    # the exception of the --domain flag.
    field_arguments = []

    for field in fields:
        new_arguments = ["--type", field["type"]]

        # Configure the traits we want (if any traits can't be applied to this
        # type of field we'll error).
        new_arguments += get_disable_flags(field["type"], field["traits"])

        # Because of the special "locale_specific" scheme we need to do some
        # fancy processing here.
        analysis_scheme = field.get("analysis_scheme")
        if analysis_scheme == "locale_specific":
            for locale, scheme in locales.iteritems():
                # Make a clone of the current arguments and add the locale
                # specific name and analysis scheme.
                cloned_arguments = list(new_arguments)
                cloned_arguments += [
                    "--analysis-scheme", scheme,
                    "--name", "{}_{}".format(field["name"], locale)
                ]

                field_arguments.append(cloned_arguments)
        else:
            if analysis_scheme:
                new_arguments += ["--analysis-scheme", analysis_scheme]

            new_arguments += ["--name", field["name"]]

            field_arguments.append(new_arguments)

    for i in field_arguments:
        # The name is always the last item in the sublist (hacky)
        name = i[-1]
        logging.info("Configuring field %r.", name)

        command = ["define-index-field", "--domain-name", domain] + i

        maybe_execute_cloudsearch_command(command,
            "Could not configure field {}.".format(name))

def configure_analysis_schemes(config, domain):
    """Configures all of the analysis schemes. Called by main()."""
    # We create an anlaysis scheme for each language that we have both
    # stemming and stopword information for.  See the Configuring Text
    # Analysis Schemes for Amazon CloudSearch document in AWS
    # CloudSearch's documentation for more information.
    with open(config['languages_file']) as f:
        supported_languages = json.load(f)

    with open(config['stemming_file']) as f:
        stemming_data = json.load(f)
    # Get a map from language-code ('en') to stemming scheme ('full')
    stemming_map = {f[1]: f[2] for f in stemming_data}

    language_codes_with_schemes = []

    for language_code in supported_languages:
        try:
            with open('dictionaries/%s-stopwords.json' % language_code) as f:
                stopwords = json.load(f)
        except IOError:
            # We don't have stopword info for this language, skip it.
            logging.warning("Skipping language %s: no stemming information"
                            % language_code)
            continue

        scheme = {
            "AnalysisSchemeName": "ka_%s" % language_code,
            "AnalysisSchemeLanguage": language_code,
            "AnalysisOptions": {
                "Stopwords": json.dumps(stopwords),
            }
        }
        # Only turn on algorithmic stemming for languages where
        # cloudsearch supports that.
        stemming = stemming_map.get(language_code, None)
        if stemming:
            scheme["AnalysisOptions"]["AlgorithmicStemming"] = stemming

        logging.info("Configuring analysis scheme for %r.",
                     scheme["AnalysisSchemeName"])
        logging.debug("Scheme: %r" % scheme)

        command = ["define-analysis-scheme",
                   "--domain-name", domain,
                   "--analysis-scheme", json.dumps(scheme)]

        maybe_execute_cloudsearch_command(command,
            "Could not configure analysis scheme {}.".format(
                scheme["AnalysisSchemeName"]))
        language_codes_with_schemes.append(language_code)

    return language_codes_with_schemes

def reindex(domain, no_reindex):
    if no_reindex:
        logging.info("The index is now in a partial state. Reindex from the "
        "console or by re-running this script.")
        return

    command = ["index-documents", "--domain-name", domain]
    logging.info("Running reindex.")
    maybe_execute_cloudsearch_command(command,
            "Reindex failed.")

def main(options, domain, domain_config_path):
    try:
        with open(domain_config_path, "r") as f:
            config = yaml.load(f)
    except IOError:
        logging.exception("Could not read from file %r.", domain_config_path)
        sys.exit(1)
    except:
        logging.exception("Failed to load configuration from %r.",
            domain_config_path)
        sys.exit(1)

    # From this point onward, all relative paths should be relative from the
    # directory that contains the config file.
    os.chdir(os.path.dirname(os.path.abspath(domain_config_path)))

    global dry_run
    if options.dry_run:
        dry_run = True

    language_codes_with_schemes = configure_analysis_schemes(config, domain)
    configure_fields(config, domain, language_codes_with_schemes)
    reindex(domain, options.no_reindex)

if __name__ == "__main__":
    options, domain, domain_config_path = parse_arguments()

    setup_logging(options.verbose)

    main(options, domain, domain_config_path)

    sys.exit(0)


import datetime
import os

class WeatherEntry:
    """
    WeatherLink Davis Vantage Pro2 Measurement data
    <용어 정리>
    entry : 기상관측기 1회 측정에 해당하는 기상 데이터 집합
    1분 데이터 (기상관측기 Export Record시 한 행) 의미
    entryset : 기상관측기 하루 측정에 해당하는 기상 데이터 집합
    """

    _data = [] # 1분 간격 기상 데이터 json list
    valid = None

    def __init__(self, fname: str, datetostr=False, debug=False):

        try:
            weatherfile = open(fname, 'rt', encoding='utf-8', errors='ignore')
        except (FileNotFoundError, PermissionError):
            self.valid = False
            return

        self.valid = True
        self._map_data(weatherfile, datetostr)

        weatherfile.close()

    def _map_data(self, file, datetostr):

        """ for make key
        json data의 key를 만들기 위하여 전처리
        한 줄 읽고 앞 뒤 공백 제거 후 탭으로 분리 """
        data1 = file.readline().strip().split('\t')
        data2 = file.readline().strip().split('\t')

        # 탭으로 분리된 컬럼 자체의 앞뒤 공백 제거
        for i in range(len(data1)):
            data1[i] = data1[i].strip()
        for i in range(len(data2)):
            data2[i] = data2[i].strip()

        key = []
        key.append("datetime") # 기존 데이터가 date column, time column으로 구분되어 있어 datetime형태로 변경
        for i in range(len(data1)):
            data1[i] = data1[i].replace(' ', '_')
            key.append((data1[i] + "_" + data2[i+2]).strip())

        for i in range(len(key)):
            key[i] = key[i].replace('.','')
            key[i] = key[i].replace('-', '_')
            if key[i][0] == '_':
                key[i] = key[i].replace('_', '', 1)

        # 데이터 시작
        line = file.readline()

        while line: # 존재하는 행 만큼 반복
            line = line.strip().split("\t")

            for i in range(len(line)):
                line[i] = line[i].strip()

            for i in range(2, 8):
                line[i] = float(line[i])
            for i in range(9, 11):
                line[i] = float(line[i])
            for i in range(12, 15):
                line[i] = float(line[i])
            for i in range(16, len(line)):
                line[i] = float(line[i])
            # date, time column을 datetime으로 변환
            datetime_str = line[0] + " " + line[1] + "m"
            if datetostr:
                datetime_str =datetime_str.split(' ')
                str1 = datetime_str[0]
                str2 = datetime_str[1]
                dt = '20'+str1+' '+str2
            else:
                dt = datetime.datetime.strptime(datetime_str, "%y-%m-%d %H:%M %p")

            # date, time column 제거
            del(line[0:2])
            # 가장 처음 인덱스에 datetime insert
            line.insert(0, dt)

            data = {} # 1분 단위의 기상 데이터

            # 1분 단위의 기상 데이터 key, value형태로 저장
            for i in range(len(key)):
                data[key[i]] = line[i]

            self._data.append(data) # entryset에 entry 추가
            line = file.readline() # 다음행

    # entryset 반환
    def get_entryset(self, to_json=False):
        d = self._data
        if to_json: # json 형태로 반환
            import json
            return json.dumps(d, indent=2)
        else:
            return d

    # def get_entry(self, to_json=False):

if __name__ == "__main__":
    import pprint
    import sys
    import os
    fname = sys.path[0] + '/data/190625.txt'
    print(fname)

    entity = WeatherEntry(fname)
    d = entity.get_data()
    pprint.pprint(d)


import os
from typing import Text
from tfx.components.evaluator.component import Evaluator
from tfx.components.example_gen.import_example_gen.component import ImportExampleGen
from tfx.components.example_validator.component import ExampleValidator
from tfx.components.model_validator.component import ModelValidator
from tfx.components.pusher.component import Pusher
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.components.trainer.component import Trainer
from tfx.components.transform.component import Transform
from tfx.orchestration import pipeline
from tfx.orchestration.kubeflow.runner import KubeflowRunner
from tfx.orchestration.kubeflow.kubeflow_dag_runner import KubeflowDagRunnerConfig
from tfx.proto import evaluator_pb2
from tfx.proto import example_gen_pb2
from tfx.proto import pusher_pb2
from tfx.proto import trainer_pb2
from tfx.utils.dsl_utils import external_input
from kfp import onprem

_pipeline_name = 'cifar-10'
_tfx_root = '/mnt/tfx-pv'
_pipeline_root = os.path.join(_tfx_root, _pipeline_name)
_module_file = os.path.join(_pipeline_root, 'utils.py')
_serving_model_dir = os.path.join(_pipeline_root, 'serving_model', _pipeline_name)

def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
                     module_file: Text, serving_model_dir: Text) -> pipeline.Pipeline:
    examples = external_input(data_root)
    input_split = example_gen_pb2.Input(splits=[
        example_gen_pb2.Input.Split(name='train', pattern='train.tfrecord'),
        example_gen_pb2.Input.Split(name='eval', pattern='test.tfrecord')
    ])
    example_gen = ImportExampleGen(input_base=examples, input_config=input_split)
    statistics_gen = StatisticsGen(input_data=example_gen.outputs.examples)
    infer_schema = SchemaGen(stats=statistics_gen.outputs.output, infer_feature_shape=True)
    validate_stats = ExampleValidator(
        stats=statistics_gen.outputs.output,
        schema=infer_schema.outputs.output)
    transform = Transform(
        input_data=example_gen.outputs.examples,
        schema=infer_schema.outputs.output,
        module_file=module_file)
    trainer = Trainer(
        module_file=module_file,
        examples=transform.outputs.transformed_examples,
        schema=infer_schema.outputs.output,
        transform_output=transform.outputs.transform_output,
        train_args=trainer_pb2.TrainArgs(num_steps=1000),
        eval_args=trainer_pb2.EvalArgs(num_steps=500))
    model_analyzer = Evaluator(
        examples=example_gen.outputs.examples,
        model_exports=trainer.outputs.output,
        feature_slicing_spec=evaluator_pb2.FeatureSlicingSpec(specs=[
            evaluator_pb2.SingleSlicingSpec()
        ]))
    model_validator = ModelValidator(
        examples=example_gen.outputs.examples, model=trainer.outputs.output)
    pusher = Pusher(
        model_export=trainer.outputs.output,
        model_blessing=model_validator.outputs.blessing,
        push_destination=pusher_pb2.PushDestination(
            filesystem=pusher_pb2.PushDestination.Filesystem(
                base_directory=serving_model_dir)))

    return pipeline.Pipeline(
        pipeline_name=pipeline_name,
        pipeline_root=pipeline_root,
        components=[
            example_gen, statistics_gen, infer_schema, validate_stats, transform,
            trainer, model_analyzer, model_validator, pusher
        ],
        log_root='/var/tmp/tfx/logs',
    )

if __name__ == '__main__':
    mount_volume_op = onprem.mount_pvc(
        "tfx-pvc",
        "tfx-pv",
        _tfx_root)
    config = KubeflowDagRunnerConfig(
        pipeline_operator_funcs=[mount_volume_op],
        tfx_image='tensorflow/tfx:0.14.0'
    )
    _pipeline = _create_pipeline(
        pipeline_name=_pipeline_name,
        pipeline_root=_pipeline_root,
        data_root=os.path.join(_pipeline_root, 'data'),
        module_file=_module_file,
        serving_model_dir=_serving_model_dir,
        )
    KubeflowRunner(config=config).run(_pipeline)


import mediapipe as mp
import cv2

import math
import numpy as np

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

mpHands = mp.solutions.hands
mpDraw = mp.solutions.drawing_utils

class HandDetector:
    def __init__(self, max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5):
        self.hands = mpHands.Hands(max_num_hands=max_num_hands, min_detection_confidence=min_detection_confidence,
                                   min_tracking_confidence=min_tracking_confidence)

    def findHandLandMarks(self, image, handNumber=0, draw=False):
        originalImage = image
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # mediapipe needs RGB
        results = self.hands.process(image)
        landMarkList = []

        if results.multi_hand_landmarks:  # returns None if hand is not found
            hand = results.multi_hand_landmarks[
                handNumber]  # results.multi_hand_landmarks returns landMarks for all the hands

            for id, landMark in enumerate(hand.landmark):
                # landMark holds x,y,z ratios of single landmark
                imgH, imgW, imgC = originalImage.shape  # height, width, channel for image
                xPos, yPos = int(landMark.x * imgW), int(landMark.y * imgH)
                landMarkList.append([id, xPos, yPos])

            if draw:
                mpDraw.draw_landmarks(originalImage, hand, mpHands.HAND_CONNECTIONS)

        return landMarkList

        results = self.hands.process(image)
        xPos, yPos = int(landMark.x * imgW), int(landMark.y * imgH)
        landMarkList.append([id, xPos, yPos])
        mpDraw.draw_landmarks(originalImage, hand, mpHands.HAND_CONNECTIONS)

handDetector = HandDetector(min_detection_confidence=0.7)
webcamFeed = cv2.VideoCapture(0)

#Volume related initializations
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
print(volume.GetVolumeRange()) #(-65.25, 0.0)

while True:
    status, image = webcamFeed.read()
    handLandmarks = handDetector.findHandLandMarks(image=image, draw=True)

    if(len(handLandmarks) != 0):
        #for volume control we need 4th and 8th landmark
        #details: https://google.github.io/mediapipe/solutions/hands
        x1, y1 = handLandmarks[4][1], handLandmarks[4][2]
        x2, y2 = handLandmarks[8][1], handLandmarks[8][2]
        length = math.hypot(x2-x1, y2-y1)
        print(length)

        volumeValue = np.interp(length, [50, 250], [-65.25, 0.0]) #coverting length to proportionate to volume range
        volume.SetMasterVolumeLevel(volumeValue, None)

        cv2.circle(image, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
        cv2.circle(image, (x2, y2), 15, (255, 0, 255), cv2.FILLED)
        cv2.line(image, (x1, y1), (x2, y2), (255, 0, 255), 3)

    cv2.imshow("Volume", image)
    cv2.waitKey(1)
handLandmarks = handDetector.findHandLandMarks(image=image, draw=True)
x1, y1 = handLandmarks[4][1], handLandmarks[4][2]

length = math.hypot(x2-x1, y2-y1)
volumeValue = np.interp(length, [50, 250], [-65.25, 0.0])
volume.SetMasterVolumeLevel(volumeValue, None)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@爬虫的本事: 请求和响应，一切与数据为导向
@File    : WinXin.py
@Time    : 2020/1/5 8:25
@Author  : 岁月静好
@Email   : 13546465002@163.com
@Desc  : #  调用WinXinMD5.js
"""
import execjs
with open("my.js",'r',encoding='utf-8') as f:
    js = f.read()
    func = execjs.compile(js)
    print(func.call("Winxin",'duanwei112'))


# Train a tensorflow model on the training data

import os

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras
import cv2

CHARLIST = [
    '00', '01', '02', '03', '04', '05', '06', '07', '08', '09',
    '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
    '20', '21', '22', '23', '24', '25', '26', '27', '28', '29'
]

training_images = []
training_answer = []
with open("Training_sample/data.txt") as f:
    for line in f:
        path, value = line.strip().split(" ")

        # Get the number in the image
        value = int(value)
        value = "{:02d}".format(value)

        # Get the image data (20x20)
        image_raw = tf.io.read_file(path)
        image_tf  = tf.image.decode_image(image_raw, dtype=tf.dtypes.uint8)

        training_images.append(image_tf)
        training_answer.append(CHARLIST.index(value))

training_answer = np.asarray(training_answer)
training_images = np.asarray(training_images)

# Scale the images from 0 -> 255 to 0 -> 1
training_images = training_images / 255.0

# The above reads images as (X, Y, COLORS). Even when B/W, the COLORS are a
# list of one. Flatten that out
training_images = np.squeeze(training_images)

# Split the training set into two, for training and testing
n_images = len(training_answer)
sl = int(n_images/2)

train_data = training_images[sl:, ...]
train_keys = training_answer[sl:, ...]

test_data = training_images[:sl, ...]
test_keys = training_answer[:sl, ...]

# Plot a sample of the images
plt.figure(figsize=(4,4))
for i in range(10):
    plt.subplot(2,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_data[i], cmap=plt.cm.binary)
    plt.xlabel(CHARLIST[train_keys[i]])
plt.show()

# Build a model
input_shape = train_data[0].shape
middle_layer = 128
output_shape = len(CHARLIST)
print("Model will have the layers:")
print("{} --> {} --> {}".format(input_shape, middle_layer, output_shape))

model = keras.Sequential([
    keras.layers.Flatten(input_shape=input_shape),
    keras.layers.Dense(middle_layer, activation=tf.nn.relu),
    keras.layers.Dense(output_shape, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Train the model on the data
model.fit(
    train_data,
    train_keys,
    epochs=100,
    verbose=0
)

print("\n\nTESTING ON SECOND DATASET:")
# Let's test it.
test_loss, test_acc = model.evaluate(test_data, test_keys)
print('Test accuracy:', test_acc)
if test_acc != 1.0:
    print("Get more training data!")
    exit()

# The URL to this camera
# http://www.insecam.org/en/view/805350/
URL = "http://210.148.5.180:8084/?action=stream"

# Open a connection to the weird camera
cap = cv2.VideoCapture(URL)

# I need a permanent dir to hold training data for OCR
if not os.path.isdir("Training_sample"):
    os.mkdir("Training_sample")

margin = 180

for _ in range(50):
    ret, image = cap.read()

    # Massage into something the NN can parse
    image = image[margin:-margin, margin:-margin]
    frame = cv2.resize(image, (20,20))
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY)

    img_tf = np.array([frame])
    val = model.predict(img_tf)
    index = np.argmax(val)

    # Get the answer
    num = CHARLIST[index]
    print("I think this image is {}".format(num))

    # show to the user
    cv2.imshow('Grabbed this', image)
    cv2.waitKey(1000)


# -*- coding:utf-8 -*-
"""
author: 15025
time: 2021/1/31 12:04
software: PyCharm

Description:
    T for tutorial

"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QFormLayout
from PyQt5.QtGui import QIntValidator, QDoubleValidator, QRegExpValidator
from PyQt5.QtCore import QRegExp

class LineEditDemo(QWidget):
    def __init__(self, parent=None):
        super(LineEditDemo, self).__init__(parent)
        self.setWindowTitle('QLineEdit例子')

        flo = QFormLayout()
        pIntLineEdit = QLineEdit()
        pDoubleLineEdit = QLineEdit()
        pValidatorLineEdit = QLineEdit()

        flo.addRow('整型', pIntLineEdit)
        flo.addRow('浮点型', pDoubleLineEdit)
        flo.addRow('字母和数字', pValidatorLineEdit)

        pIntLineEdit.setPlaceholderText("整型")
        pDoubleLineEdit.setPlaceholderText("浮点型")
        pValidatorLineEdit.setPlaceholderText("字母和数字")

        # 整型，范围[1, 99]
        pIntValidator = QIntValidator()
        pIntValidator.setRange(1, 99)

        # 浮点型，范围[-360, 360], 精度：小数点后两位
        pDoubleValidator = QDoubleValidator()
        pDoubleValidator.setRange(-360, 360)
        pDoubleValidator.setNotation(QDoubleValidator.StandardNotation)
        pDoubleValidator.setDecimals(2)

        # 字母和数字
        reg = QRegExp("[a-zA-Z0-9]+$")
        pValidator = QRegExpValidator()
        pValidator.setRegExp(reg)

        # 设置验证器
        pIntLineEdit.setValidator(pIntValidator)
        pDoubleLineEdit.setValidator(pDoubleValidator)
        pValidatorLineEdit.setValidator(pValidator)

        self.setLayout(flo)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = LineEditDemo()
    win.show()
    sys.exit(app.exec_())


#!/usr/bin/python3

# Made by Jordan Leich on 6/6/2020, Last updated on 5/11/2021, Version 9.2

# TODO List add multiple players or a.i. to the game

# Imports
import random
import time
from playsound import playsound
import colors
import webbrowser
import json

try:
    with open('data.json', 'r') as user_data_file:
        user_data = json.load(user_data_file)
    user_balance = user_data['ubalance']
    user_score = user_data['uscore']
    dealer_balance = user_data['deal_balance']
except:
    user_balance = 1000
    user_score = 0
    dealer_balance = 5000

# Global Variables
# user_score = 0
# user_balance = 1000
# dealer_balance = 5000
user_bet = 0
user_dealer_money_choice = 0
user_money_choice = 0
player_cards = []
dealer_cards = []

def another_game():
    """
    Used when 1 single round of blackjack has ended. Allows the user to play another game of blackjack or quit playing
    """
    global user_score, user_balance, dealer_balance, user_dealer_money_choice, user_money_choice, user_data_file
    print(colors.green + "Your win count is", user_score, "and your total balance is $" + str(user_balance), "\n",
          colors.reset)
    time.sleep(1)
    print(colors.red + "The dealers total balance is $" + str(dealer_balance), "\n", colors.reset)
    time.sleep(2)
    with open('data.json', 'w') as user_data_file:
        user_data_file.write(json.dumps({'ubalance': user_balance, 'uscore': user_score,
                                         'deal_balance': dealer_balance}))
    if user_balance <= 0:
        print(colors.red + "You don't have any more money to bet... Game Over!\n", colors.reset)
        time.sleep(2)
        user_game_over_choice = input('Would you like to play all over again (yes / no): ')
        print()
        time.sleep(.500)

        if user_game_over_choice.lower() == 'y' or user_game_over_choice.lower() == 'yes':
            print('A brand new game will begin...\n')
            time.sleep(1)
            user_balance = 1000
            user_score = 0
            dealer_balance = 5000
            with open('data.json', 'w') as user_data_file:
                user_data_file.write(json.dumps({'ubalance': user_balance, 'uscore': user_score,
                                                 'deal_balance': dealer_balance}))
            custom_game()
        elif user_game_over_choice.lower() == 'n' or user_game_over_choice.lower() == 'no':
            print(colors.green + 'Thanks for playing! Exiting game now...\n', colors.reset)
            time.sleep(1)
            user_balance = 1000
            user_score = 0
            dealer_balance = 5000
            with open('data.json', 'w') as user_data_file:
                user_data_file.write(json.dumps({'ubalance': user_balance, 'uscore': user_score,
                                                 'deal_balance': dealer_balance}))
            quit()
        else:
            print(colors.red + 'User game over choice selection error found... Restarting game...\n', colors.reset)
            time.sleep(2)
            intro()

    elif user_balance >= 1:

        if dealer_balance <= 0:
            print(colors.green + "Congratulations! You have beat the BlackJack 21 game by defeating the dealers "
                                 "balance!\n", colors.reset)
            time.sleep(2)
        elif dealer_balance <= 2500:
            print(colors.green + "The dealers balance is looking small enough for you to win! You're doing well...\n",
                  colors.reset)
            time.sleep(2)
        restart_action = input("Do you want to play again or cash out your earning or play a brand new game (play "
                               "again / cash out / new game): ")
        print()
        time.sleep(1)
        if restart_action.lower() == "play again" or restart_action.lower() == "y" or restart_action.lower() == 'p' or \
                restart_action.lower() == 'yes':
            restart()
        elif restart_action.lower() == "cash out" or restart_action.lower() == "n" or restart_action.lower() == 'no' or\
                restart_action.lower() == 'c' or restart_action.lower() == 'cash':
            print(colors.green + "You won a total of", user_score, 'games and you walked away with a total of $' +
                  str(user_balance) + str(". Thanks for playing!\n"), colors.reset)
            time.sleep(1)
            quit()
        elif restart_action.lower() == "new" or restart_action.lower() == 'new game':
            print('A brand new game will begin...\n')
            time.sleep(1)
            user_balance = 1000
            dealer_balance = 5000
            user_score = 0
            intro()
        else:
            print(colors.red + "Invalid input... Restarting choice...\n", colors.reset)
            time.sleep(1)
            another_game()
    else:
        print(colors.red + "User Balance Error found...\n", colors.reset)
        time.sleep(1)
        restart()

def restart():
    """
    This restarts the program no matter what if executed
    """
    global user_score
    print("Restarting Blackjack Game...\n")
    time.sleep(1)
    game()

def game():
    """
    This is the main code used for the game entirely
    """
    global user_score, user_balance, user_bet, dealer_balance, player_cards, dealer_cards, user_money_choice, \
        user_dealer_money_choice

    player_cards = []
    dealer_cards = []

    print(colors.green + "Your balance is $" + str(user_balance), "\n", colors.reset)
    time.sleep(1)
    print(colors.red + "The dealers balance is $" + str(dealer_balance), "\n", colors.reset)
    time.sleep(1)

    user_all_in = str(input("Would you like to go all in (yes / no): "))
    time.sleep(.500)

    if user_all_in.lower() == "y" or user_all_in.lower() == "yes":
        user_bet = user_balance
        time.sleep(.500)
    else:
        print()
        user_bet = int(input("How much would you like to bet in dollar amount? "))
        time.sleep(.500)
    if user_bet > user_balance:
        print()
        print(colors.red + "Your total balance cannot make this bet! Your bet is too high for your balance!\n",
              colors.reset)
        time.sleep(2)
        game()
    if user_bet <= 0:
        print()
        print(colors.red + "You cannot make a negative bet! Please place a higher bet than 0!\n",
              colors.reset)
        time.sleep(2)
        game()
    while len(dealer_cards) != 2:
        dealer_cards.append(random.randint(1, 11))
        if len(dealer_cards) == 2:
            print()
            print(colors.red + "The Dealer has ? &", dealer_cards[1], colors.reset, "\n")
            time.sleep(1)
    # Player Cards
    while len(player_cards) != 2:
        player_cards.append(random.randint(1, 11))
        if len(player_cards) == 2:
            print(colors.green + "You have a total of", str(sum(player_cards)), "from these cards", player_cards,
                  colors.reset, "\n")
            time.sleep(1)
    # Total of Dealer cards
    if sum(dealer_cards) == 21:
        game_scoring()
    elif sum(dealer_cards) > 21:
        game_scoring()
    # Total of Player cards
    if len(player_cards) == 5 and sum(player_cards) < 21:
        game_scoring()

    while sum(player_cards) < 21 and len(player_cards) < 5:
        action_taken = str(
            input("Do you want to hit, stay, call help, change song, or quit the game (hit | stay | help | song | quit)"
                  ": "))
        print()
        time.sleep(1)

        if len(player_cards) == 5 and sum(player_cards) < 21:
            game_scoring()
        elif action_taken.lower() == "hit" or action_taken.lower() == "h":
            player_cards.append(random.randint(1, 11))
            print(colors.green + "You now have a total of " + str(sum(player_cards)) + " from these cards",
                  player_cards, colors.reset, "\n")
            time.sleep(1)
        elif action_taken.lower() == 's' or action_taken.lower() == 'stay':
            print(colors.red + 'The Dealer says No More Bets...\n', colors.reset)
            time.sleep(1)
            while sum(dealer_cards) <= 15:
                dealer_cards.append(random.randint(1, 11))
                print(colors.red + "The Dealer has pulled a card...\n", colors.reset)
                time.sleep(1)
                print(colors.red + "The Dealer now has a total of " + str(sum(dealer_cards)) + " from these cards",
                      dealer_cards, colors.reset, "\n")
                time.sleep(1)

                if len(dealer_cards) == 5 and sum(dealer_cards) < 21:
                    game_scoring()

            else:
                game_scoring()

        elif action_taken.lower() == "help" or action_taken.lower() == "help" or action_taken.lower() == 'call help':
            if sum(player_cards) <= 14:
                print(colors.blue + "Since your total is under or equal to a total of 14, we recommend that you hit!\n",
                      colors.reset, )
                time.sleep(1)
            elif sum(player_cards) >= 15:
                print(colors.blue + "Your odds are looking high enough to win, if your card total is closer to 15, "
                                    "we recommend only making 1 hit move and then staying!\n", colors.reset)
                time.sleep(3)
                print(colors.blue + "If your card total is closer to 21, don't risk it! make a stay move!\n",
                      colors.reset)
                time.sleep(3)
            else:
                print(colors.red + "Helping Error Found...\n", colors.reset)
                time.sleep(1)
                quit()
        elif action_taken.lower() == "song" or action_taken.lower() == "change song":
            print("Loading track change...\n")
            time.sleep(1)
            songs()
        elif action_taken.lower() == "q" or action_taken.lower() == "quit" or action_taken.lower() == "end":
            print(colors.green + "Ending game... Thanks for playing!\n", colors.reset)
            time.sleep(1)
            quit()

        else:
            game_scoring()

    # Endgame results
    game_scoring()

def songs():
    """
    Used for the user to able to play songs while playing blackjack
    """
    song_input = str(input("Would you like to play songs from our track list while playing (yes / no): "))
    print()

    if song_input.lower() == "y" or song_input.lower() == "yes":
        song_list = int(
            input("""1. Relax Instrumental
2. Cartoon - On & On
3. Alan Walker - Spectre
4. DEAF KEV - Invincible
5. Different Heaven & EH!DE - My Heart
6. Electro-Light - Symbolism
7. Exit song selection
Which song would you like to play: """))
        print()

        if song_list == 1:
            playsound("songs\\Relax.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 2:
            playsound("songs\\Cartoon - On & On.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 3:
            playsound("songs\\Alan Walker - Spectre.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 4:
            playsound("songs\\DEAF KEV - Invincible.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 5:
            playsound("songs\\Different Heaven & EH!DE - My Heart.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 6:
            playsound("songs\\Electro-Light - Symbolism.mp3", False)
            print("Now proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        elif song_list == 7:
            print("Exiting song list and proceeding to BlackJack 21!\n")
            time.sleep(1)
            custom_game()
        else:
            print(colors.red + "Song input from track list error found!\n", colors.reset)
            time.sleep(1)
            songs()
    elif song_input.lower() == "n" or song_input.lower() == "no":
        print("No song has been selected! Now proceeding to game selection...\n")
        time.sleep(1)
        custom_game()
    else:
        print(colors.red + "Song input error found...\n", colors.reset)
        time.sleep(1)
        songs()

def intro():
    print(colors.green + 'Hello there! Welcome to Blackjack 21, made by Jordan Leich!\n', colors.reset)
    time.sleep(.500)
    print(colors.yellow + '''The goal of this game is to make the dealer go broke and score the most amount of money!
Achieve this by placing your bets and dealing your cards wisely, but carefully...\n''', colors.reset)
    time.sleep(2)

    user_knowledge = input('Do you know how to play Blackjack 21 or would you like to watch a tutorial via youtube or '
                           'skip all setup options to play Blackjack 21 quickly (start / tutorial / express): ')
    print()
    time.sleep(1)

    if user_knowledge.lower() == 'start' or user_knowledge.lower() == 'yes' or user_knowledge.lower() == 's':
        songs()
    elif user_knowledge.lower() == 'no' or user_knowledge.lower() == 'n' or user_knowledge.lower() == 't' or \
            user_knowledge.lower() == 'tutorial':
        print(colors.green + 'A youtube video should now be playing... This game will auto resume once the video has '
                             'been fully played...\n', colors.reset)
        url = "https://www.youtube.com/watch?v=eyoh-Ku9TCI"
        webbrowser.open(url, new=1)
        time.sleep(140)
        songs()
    elif user_knowledge.lower() == 'e' or user_knowledge.lower() == 'express':
        print('Express option has been selected, proceeding to Blackjack 21...\n')
        time.sleep(.500)
        game()
    else:
        print(colors.red + 'User knowledge input error found...', colors.reset)
        time.sleep(1)
        intro()

def game_scoring():
    global player_cards, user_score, user_balance, dealer_balance, dealer_cards

    print(colors.red + "The Dealer has a grand total of", str(sum(dealer_cards)), "from these cards",
          dealer_cards, colors.reset, "\n")
    time.sleep(1)
    print(colors.green + "You have a grand total of " + str(sum(player_cards)) + " with", player_cards,
          colors.reset, "\n")
    time.sleep(1)

    if len(player_cards) == 5 and sum(player_cards) < 21:
        time.sleep(0.500)
        print(colors.green + "You have automatically won since you have pulled a total of 5 cards without busting!"
                             "\n", colors.reset)
        time.sleep(0.500)
        user_score += 1
        user_balance += user_bet
        dealer_balance -= user_bet
        another_game()

    elif len(dealer_cards) == 5 and sum(dealer_cards) < 21:
        print(colors.red + "You have automatically lost since the dealer has pulled a total of 5 cards "
                           "without busting!\n", colors.reset)
        time.sleep(0.500)
        user_score -= 1
        user_balance -= user_bet
        dealer_balance += user_bet
        another_game()

    elif sum(player_cards) > 21:
        print(colors.red + "BUSTED! The Dealer Wins! You lost $" + str(user_bet) + "!\n", colors.reset)
        time.sleep(1)
        user_score -= 1
        user_balance -= user_bet
        dealer_balance += user_bet
        another_game()
    elif sum(dealer_cards) > 21:
        print(colors.green + "The Dealer BUSTED! You win! You won $" + str(user_bet) + "!\n", colors.reset)
        time.sleep(1)
        user_score += 1
        user_balance += user_bet
        dealer_balance -= user_bet
        another_game()
    elif sum(player_cards) == 21:
        print(colors.green + "BLACKJACK! You hit 21! You won $" + str(user_bet) + "!\n", colors.reset)
        time.sleep(1)
        user_score += 1
        user_balance += user_bet
        dealer_balance -= user_bet
        another_game()
    elif sum(dealer_cards) == 21:
        print(colors.red + "BLACKJACK! The Dealer hit 21! You lost $" + str(user_bet) + "!\n", colors.reset)
        time.sleep(1)
        user_score -= 1
        user_balance -= user_bet
        dealer_balance += user_bet
        another_game()
    elif sum(player_cards) > sum(dealer_cards):
        print(colors.green + "You Win! Your cards were greater than the dealers deck, You won $" + str(user_bet) +
              "!\n", colors.reset)
        time.sleep(1)
        user_score += 1
        user_balance += user_bet
        dealer_balance -= user_bet
        another_game()
    elif sum(dealer_cards) > sum(player_cards):
        print(colors.red + "The dealer wins! Your cards were less than the dealers deck, You lost $" + str(user_bet) +
              "!\n", colors.reset)
        time.sleep(1)
        user_score -= 1
        user_balance -= user_bet
        dealer_balance += user_bet
        another_game()
    elif sum(player_cards) == sum(dealer_cards):
        print(colors.yellow + "PUSH! This is a tie! All bet money is refunded!", colors.reset, "\n")
        time.sleep(1)
        another_game()
    else:
        print(colors.red + 'Scoring error found...\n', colors.reset)
        time.sleep(1)
        restart()

def custom_game():
    global user_balance, dealer_balance, user_score, user_dealer_money_choice, user_money_choice
    user_game_picker = input('Would you like to play normal Blackjack 21 or a Custom Game with custom user game '
                             'settings (blackjack / custom): ')
    print()
    time.sleep(1)

    if user_game_picker.lower() == 'b' or user_game_picker.lower() == 'blackjack' or user_game_picker.lower() == \
            'blackjack 21':
        print('Normal Blackjack 21 has been selected...\n')
        time.sleep(.500)
        game()

    elif user_game_picker.lower() == 'c' or user_game_picker.lower() == 'custom' or user_game_picker.lower() == \
            'custom game':
        print('Custom Blackjack 21 has been selected...\n')
        time.sleep(.500)
        user_money_choice = int(input('How much would you like your starting balance to be? '))
        print()
        time.sleep(.500)

        if user_money_choice <= 0:
            print(colors.yellow + 'Invalid starting balance... Please choose a balance greater than 0 dollars!\n',
                  colors.reset)
            time.sleep(2)
            custom_game()

        user_balance = user_money_choice
        user_dealer_money_choice = int(input('How much would you to set the dealers starting balance to? '))
        print()
        time.sleep(.500)
        dealer_balance = user_dealer_money_choice
        user_score_choice = int(input('How much would you like to set your scoring counter to? '))
        print()
        time.sleep(.500)
        user_score = user_score_choice
        print('Now proceeding to Blackjack 21 game with your custom settings...\n')
        time.sleep(1)
        game()

    else:
        print(colors.red + 'User game selection choice error found... Restarting choice selection...\n', colors.reset)
        time.sleep(2)
        custom_game()

intro()


#!/usr/bin/env python
# encoding: utf-8

import uuid

import falcon
from pony import orm
from schema import SchemaError

from models import proto, Diary

def verify_attender(req, resp, resource, params):
    if not params['current_user_identity']:
        raise falcon.HTTPMissingHeader("No 'Authorization' header")
    attender_req = proto.AttenderRequest()
    attender_req.ParseFromString(req.stream)
    attender_resp = proto.AttenderResponse()
    diary_identity = uuid.UUID(attender_req.diary_id)
    with orm.db_session:
        if not Diary.select(lambda d: d.identity == diary_identity).exists():
            raise SchemaError(attender_resp.SerializeToString())
    params['diary_identity'] = diary_identity
    params['attender_req'] = attender_req
    params['attender_resp'] = attender_resp


from django.http import HttpResponseRedirect
from django.contrib import messages
from django.template.loader import render_to_string
from django.conf import settings

import sendgrid

from .banner import BANNER

def sendgrid_messenger(request, mailing_list, subject, context, template):
    """send email using sendgrid"""

    sg = sendgrid.SendGridClient(
        settings.SENDGRID_USERNAME, settings.SENDGRID_PASSWORD)

    message = sendgrid.Mail()
    message.set_subject(subject)
    message.set_html(render_to_string(template, context))
    message.set_text(render_to_string(template, context))
    message.set_from('FunnShopp <no-reply@funnshopp.com>')

    receivers = []

    for mail in mailing_list:
        message.add_to(mail)
        status, msg = sg.send(message)

        if status == 200:
            receivers.append(mail)
        else:
            messages.error(request, msg)

    messages.info(request, f"{BANNER['EMAIL_SUCCESS']} {', '.join(receivers)}")


#!/usr/bin/python

import os
import math
import urllib.request
import logging.config
from logging.handlers import RotatingFileHandler
from logging.handlers import SMTPHandler
import shape2osm

class LandExtractor:

    def __init__(self, data_dir, output_dir, dry_run = False):
        self.logger = logging.getLogger("mapcreator")
        self.data_dir = data_dir
        self.output_dir = output_dir
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
        self.dry_run = dry_run
        # self.landfiles = "land-polygons-complete-4326"  # there seems to be a bug in that data
        self.landfiles = "land-polygons-split-4326"

    def make_sea_polygon_file(self, x, y, z, staging_path):
        self.logger.info("Making sea polygon for %d/%d/%d in %s" % (z, x, y, self.sea_path(staging_path)))
        lllt = self.num2deg(x, y, z)
        llrb = self.num2deg(x+1, y+1, z)
        template = """<osm version='0.6'>
        <node timestamp='1969-12-31T23:59:59Z' changeset='-1' id='32951459320' version='1' lon='{lonmin}'
        lat='{latmin}' />
        <node timestamp='1969-12-31T23:59:59Z' changeset='-1' id='32951459321' version='1' lon='{lonmin}'
        lat='{latmax}' />
        <node timestamp='1969-12-31T23:59:59Z' changeset='-1' id='32951459322' version='1' lon='{lonmax}'
        lat='{latmax}' />
        <node timestamp='1969-12-31T23:59:59Z' changeset='-1' id='32951459323' version='1' lon='{lonmax}'
        lat='{latmin}' />
        <way timestamp='1969-12-31T23:59:59Z' changeset='-1' id='32951623372' version='1'>
        <nd ref='32951459320' />
        <nd ref='32951459321' />
        <nd ref='32951459322' />
        <nd ref='32951459323' />
        <nd ref='32951459320' />
        <tag k='area' v='yes' />
        <tag k='layer' v='-5' />
        <tag k='natural' v='sea' />
        </way>
        </osm>
        """
        with open(self.sea_path(staging_path), "w+") as f:
            f.write(template.format(lonmin=lllt[1], latmin=llrb[0], lonmax=llrb[1], latmax=lllt[0]))

    def download_land_polygons(self):
        import urllib
        import zipfile
        self.logger.info("Retrieving new land files")
        if not self.dry_run:
            path = os.path.join(self.data_dir, self.landfiles + ".zip")
            urllib.request.urlretrieve("http://data.openstreetmapdata.com/" + self.landfiles + ".zip", path)
            zfile = zipfile.ZipFile(path)
            print(self.data_dir)
            zfile.extractall(self.data_dir)
        self.logger.info("Retrieved new land files")

    def extract_land_polygons(self, x, y, z, staging_path, data_path, simplify=0, dry_run=False):
        self.logger.info("Making land polygons for %d/%d/%d in %s" % (z, x, y, self.land_polygon_path(staging_path)))
        output_path = self.land_polygon_dir(staging_path)
        if not os.path.exists(output_path):
            os.makedirs(output_path)
        land_polygon_path = self.land_polygon_path(staging_path)
        if z < 7 and os.path.exists(land_polygon_path):
            self.logger.debug("   shape exists, skip")
            return
        land_path = self.land_path(staging_path)
        if z == 7 and os.path.exists(land_path):
            self.logger.debug("   land exists, skip")
            return
        import subprocess
        if z == 3:
            data_path = os.path.join(self.data_dir, os.path.join(self.landfiles, "land_polygons.shp"))
        else:
            data_path = os.path.join(self.output_dir, self.land_polygon_path(data_path))
        self.logger.info("    from %s" % data_path)
        lllt = self.num2deg(x, y, z)
        llrb = self.num2deg(x+1, y+1, z)
        ogr_call = ["ogr2ogr", "-overwrite", "-skipfailures", "-clipsrc", format(lllt[1], '.4f'), format(llrb[0], '.4f'), format(llrb[1], '.4f'), format(lllt[0], '.4f')]
        if simplify > 0:
            ogr_call += ["-simplify", str(simplify)]
        ogr_call += [output_path, data_path]
        self.logger.debug("calling: %s"," ".join(ogr_call))
        if not dry_run:
            success = subprocess.call(ogr_call)
        if z == 7:
            ogr2osm_call = ["ogr2osm/ogr2osm.py", "--add-version", "--add-timestamp", "-t", "mapsforge", "-f", "-o", land_path, land_polygon_path]
            self.logger.debug("calling: %s"," ".join(ogr2osm_call))
            if not dry_run:
                success = subprocess.call(ogr2osm_call)
            #shape2osm.run(self.land_polygon_path(staging_path), output_location=self.land_path_base(staging_path))

    def land_polygon_dir(self, staging_path):
        return os.path.join(self.output_dir, staging_path)

    def land_polygon_path(self, staging_path):
        """
        path to the shapefile containing the land polygons
        """
        return os.path.join(self.land_polygon_dir(staging_path), "land_polygons.shp")

    def sea_path(self, staging_path):
        return os.path.join(self.output_dir, staging_path + "-sea.osm")

    def land_path_base(self, staging_path):
        """
        returns path to land file but without the numbers and extension
        """
        return os.path.join(self.output_dir, staging_path + '-land')

    def land_path(self, staging_path):
        """
        returns path to land file with first extension, which should be sufficient
        """
        return self.land_path_base(staging_path) + ".osm"

    def num2deg(self, xtile, ytile, zoom):
        n = 2.0 ** zoom
        lon_deg = xtile / n * 360.0 - 180.0
        lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
        lat_deg = math.degrees(lat_rad)
        return (lat_deg, lon_deg)


#!/usr/bin/env python3

import os
import getpass
from pathlib import Path

username = getpass.getuser()

rootDir = str(Path.home()) + '/.world/'
locPath = rootDir + 'loc'
configPath = rootDir + 'config'
roomsPath = rootDir + 'rooms/'
statePath = rootDir + 'state/'
inventoryPath = rootDir + 'inventory'

westDirections = ['l','w','left','west']
eastDirections = ['r','e','right','east']
northDirections = ['u','n','up','north']
southDirections = ['d','s','down','south']
validDirections = westDirections + eastDirections + northDirections + southDirections

class Room:
    def __init__(self):
        self.name = ''
        self.desc = ''
        self.objects = []
        self.exits = []
        self.key = ''
        self.user = ''
        self.x = ''
        self.y = ''

    def setItem(self, key, val):
        if key == 'name': self.name = val
        elif key == 'key': self.key = val
        elif key == 'desc': self.desc = val
        elif key == 'objects': self.objects = val

class Object:
    def __init__(self):
        self.id = ''
        self.name = ''
        self.desc = ''
        self.grab = False
        self.hidden = False
        self.props = []
        self.actions = []

    def setItem(self, key, val):
        if key == 'id': self.id = val
        elif key == 'name': self.name = val
        elif key == 'desc': self.desc = val
        elif key == 'grab': self.grab = val == 'true'
        elif key == 'hidden': self.hidden = val == 'true'
        elif key == 'props': self.props = val
        elif key == 'actions': self.actions = val

class Item:
    def __init__(self):
        self.id = ''
        self.name = ''
        self.desc = ''

class Action:
    def __init__(self):
        self.triggers = []
        self.instructions = []

    def set(self, triggers, instructions):
        self.triggers = triggers
        self.instructions = instructions

class Prop:
    def __init__(self):
        self.key = ''
        self.value = ''

    def set(self, key, val):
        self.key = key
        self.value = val

class State:
    def __init__(self):
        self.room = Room()
        self.locX = 0
        self.locY = 0
        self.inventory = []

def getPropFileName(user, x, y, obj, prop):
    propFileName = statePath
    propFileName += str(x).replace('-','n') + '_'
    propFileName += str(y).replace('-','n') + '_'
    propFileName += obj.id.replace(' ','-') + '_'
    propFileName += prop + '.txt'

    return propFileName

def getInventory():
    inventory = []
    inventoryFile = open(inventoryPath,'r')
    inventoryLines = [x.strip('\n') for x in inventoryFile]
    inventoryFile.close()
    for line in inventoryLines:
        item = Item()
        info = line.split(' : ')
        if len(info) == 3:
            item.id = info[0]
            item.name = info[1]
            item.desc = info[2]
            inventory.append(item)
    return inventory

def getRoom(x, y):
    users = os.listdir('/home')

    room = Room()
    objects = []
    actions = []
    props = []

    for u in users:
        roomPath = roomsPath.replace(username,u) + str(x).replace('-','n') + '_' + str(y).replace('-','n')
        if os.path.exists(roomPath):
            room.user = u
            room.x = x
            room.y = y
            roomData = open(roomPath, 'r')
            roomLines = [x.strip('\n') for x in roomData]
            curObj = Object()
            curProp = Prop()
            curAction = Action()
            inProp = False
            inAction = False
            for line in roomLines:
                if line[0] != ' ':
                    inProp = False
                    inAction = False
                    pieces = line.split(' : ')
                    if len(pieces) == 2:
                        room.setItem(pieces[0].lower(),pieces[1])
                else:
                    if line == '  -':
                        if inAction:
                            curObj.actions.append(curAction)
                            curAction = Action()
                            inAction = False
                        if curObj.name != '':
                            objects.append(curObj)
                        curObj = Object()
                    elif ' : ' in line:
                        pieces = line.strip().split(' : ')
                        curObj.setItem(pieces[0].lower(),pieces[1])
                    elif line.startswith('    PROPS'):
                        if inAction:
                            curObj.actions.append(curAction)
                            inAction = False
                        inProp = True
                    elif line.startswith('    ACTIONS'):
                        if inProp:
                            curObj.props.append(curProp)
                            inProp = False
                        inAction = True
                    elif inProp:
                        pieces = line.strip().split('=')
                        propFileName = getPropFileName(u, x, y, curObj, pieces[0])

                        if os.path.exists(propFileName):
                            propFile = open(propFileName,'r')
                            curProp.set(pieces[0], propFile.read().strip())
                            propFile.close()
                        else:
                            propFile = open(propFileName,'w')
                            curProp.set(pieces[0], pieces[1])
                            propFile.write(pieces[1])
                            propFile.close()
                    elif inAction:
                        if line.startswith('        '):
                            curAction.instructions.append(line[8:])
                        elif line.startswith('      '):
                            if len(curAction.triggers):
                                curObj.actions.append(curAction)
                            curAction = Action()
                            curAction.triggers = line[6:].split('|')
            if inAction:
                curObj.actions.append(curAction)
            if inProp:
                curObj.props.append(curProp)
            if curObj.name != '':
                objects.append(curObj)
            room.setItem('objects',objects)

        if 'north' not in room.exits:
            tmpX = x
            tmpY = y + 1
            northPath = roomsPath.replace(username,u) + str(tmpX).replace('-','n') + '_' + str(tmpY).replace('-','n')
            if os.path.exists(northPath):
                room.exits.append('north')

        if 'south' not in room.exits:
            tmpX = x
            tmpY = y - 1
            southPath = roomsPath.replace(username,u) + str(tmpX).replace('-','n') + '_' + str(tmpY).replace('-','n')
            if os.path.exists(southPath):
                room.exits.append('south')

        if 'east' not in room.exits:
            tmpX = x + 1
            tmpY = y
            eastPath = roomsPath.replace(username,u) + str(tmpX).replace('-','n') + '_' + str(tmpY).replace('-','n')
            if os.path.exists(eastPath):
                room.exits.append('east')

        if 'west' not in room.exits:
            tmpX = x - 1
            tmpY = y
            westPath = roomsPath.replace(username,u) + str(tmpX).replace('-','n') + '_' + str(tmpY).replace('-','n')
            if os.path.exists(westPath):
                room.exits.append('west')
    return room

def updateLoc(x, y):
    locFile = open(locPath, 'r+')
    locFile.truncate(0)
    locFile.write(str(x) + ',' + str(y))
    locFile.close()

def prnt(value):
    if isinstance(value,str):
        print('  ' + value)
    else:
        for x in value:
            print('  ' + x)

def inInventory(key):
    global state
    found = False
    for item in state.inventory:
        if item.id == key:
            found = True
    return found

def addToInventory(obj):
    global state

    owned = inInventory(obj.id)

    if owned:
        prnt('You already have one of these')
    else:
        inventoryFile = open(inventoryPath,'a')
        inventoryFile.write(obj.id + ' : ' + obj.name + ' : ' + obj.desc + "\n")
        inventoryFile.close()
        item = Item()
        item.id = obj.id
        item.name = obj.name
        item.desc = obj.desc
        state.inventory.append(item)
        prnt('You obtain "' + obj.name + '"')

def removeFromInventory(key):
    global state

    owned = inInventory(key)

    if not owned:
        prnt('This item is not in your inventory')
    else:
        inventoryFile = open(inventoryPath,'w')
        for item in state.inventory:
            if item.id == key:
                state.inventory.remove(item)
                prnt('You drop "' + item.name + '"')
            else:
                inventoryFile.write(item.id + ' : ' + item.name + ' : ' + item.desc + "\n")
        inventoryFile.close()

def lookObj(cmd):
    item = cmd[5:]
    found = False
    for obj in state.room.objects:
        if item == obj.id:
            found = True
            desc = obj.desc
            if len(obj.props):
                for prop in obj.props:
                    desc = desc.replace('[' + prop.key + ']', prop.value)
            prnt(desc)
            if len(obj.actions):
                print('')
                actionsOut = ['You can:']
                for actn in obj.actions:
                    actionsOut.append('- ' + actn.triggers[0])
                prnt(actionsOut)

    if not found:
        prnt('Object not found')

def grabObj(cmd):
    item = cmd[5:]
    found = False
    for obj in state.room.objects:
        if item == obj.id:
            found = True
            if obj.grab:
                addToInventory(obj)
            else:
                prnt('This object is not attainable')

    if not found:
        prnt('Object not found')

def dropObj(cmd):
    item = cmd[5:]
    removeFromInventory(item)

def look():
    prnt(state.room.desc)

    if len(state.room.objects):
        print('')

        objOut = ["You see:"]
        for obj in state.room.objects:
            if not inInventory(obj.id) and not obj.hidden:
                objText = '- '
                objText += ('An ' if obj.name[0] in ['a','e','i','o','u'] else 'A ')
                objText += obj.name + ' (' + obj.id + ')'
                objOut.append(objText)
        prnt(objOut)

    if len(state.room.exits):
        print('')
        exitOut = ["Exits:"]
        for exit in state.room.exits:
            exitOut.append('- ' + exit)
        prnt(exitOut)

def inventory():
    if len(state.inventory):
        output = []
        for item in state.inventory:
            output.append('')
            output.append('- ' + item.name + ' (' + item.id + '): ')
            output.append('  ' + item.desc)
        prnt(output)
    else:
        print('')
        prnt("Your inventory is empty")

def go(cmd):
    global state

    # Get the direction
    direction = cmd[3:]

    # Update coords and determine name for message
    if direction in westDirections:
        dirName = 'west'
        tmpX = state.locX - 1
        tmpY = state.locY
    elif direction in eastDirections:
        dirName = 'east'
        tmpX = state.locX + 1
        tmpY = state.locY
    elif direction in northDirections:
        dirName = 'north'
        tmpX = state.locX
        tmpY = state.locY + 1
    elif direction in southDirections:
        dirName = 'south'
        tmpX = state.locX
        tmpY = state.locY - 1

    # Try to get the room
    tmpRoom = getRoom(tmpX,tmpY)

    # Room found
    if tmpRoom.name != '':
        roomKey = tmpRoom.key.split('|')
        if len(roomKey) == 2 and not inInventory(roomKey[0]):
            prnt('The exit is locked. You need "' + roomKey[1]+ '"')
        else:
            state.locX = tmpX
            state.locY = tmpY
            updateLoc(tmpX,tmpY)
            state.room = tmpRoom
            prnt('You go ' + dirName)
            prnt('Current location: ' + state.room.name + ' (' + str(state.locX) + ',' + str(state.locY) + ')')
    # No room found
    else:
        prnt('There is no exit in that direction')

def teleport(cmd):
    global state

    # Get the coords
    tmpCoords = cmd[9:].split(' ')
    tmpX = int(tmpCoords[0])
    tmpY = int(tmpCoords[1])
    if len(tmpCoords) == 2:
        # Try to get the room
        tmpRoom = getRoom(tmpX, tmpY)

        # Room found
        if tmpRoom.name != '':
            state.room = tmpRoom
            state.locX = tmpX
            state.locY = tmpY
            updateLoc(state.locX,state.locY)
            prnt('You teleported to ' + str(state.locX) + ',' + str(state.locY))
            prnt('Current location: ' + state.room.name + ' (' + str(state.locX) + ',' + str(state.locY) + ')')
        # No room found
        else:
            prnt('There is no room at that location')

def objCmd(cmd):
    sp = cmd.split(' ')
    # Look for object commands
    found = False
    if len(state.room.objects) and len(sp) > 1:
        for obj in state.room.objects:
            if obj.id == sp[1]:
                for act in obj.actions:
                    if sp[0] in act.triggers:
                        found = True
                        inIf = False
                        inElse = False
                        for i in act.instructions:
                            if i.startswith('IF'):
                                ifTrue = False
                                inIf = True
                                condition = i[3:].split('=')
                                if condition[0] == 'INVENTORY':
                                    keys = condition[1].split(',')
                                    ifTrue = True
                                    for key in keys:
                                        if not inInventory(key):
                                            ifTrue = False
                                else:
                                    propFileName = getPropFileName(state.room.user, state.room.x, state.room.y, obj, condition[0])
                                    propFile = open(propFileName,'r')
                                    if propFile.read().strip() == condition[1]:
                                        ifTrue = True
                                    propFile.close()
                            if i.startswith('ELSE') and inIf:
                                inElse = True
                            elif i == 'ENDIF':
                                inIf = False
                                inElse = False
                            else:
                                runCmd = True
                                if inIf and not inElse and not ifTrue:
                                    runCmd = False
                                elif inElse and ifTrue:
                                    runCmd = False
                                if runCmd:
                                    if i.startswith('ECHO'):
                                        prnt(i[5:])
                                    elif i.startswith('GRAB'):
                                        for obj in state.room.objects:
                                            if obj.id == i[5:]:
                                                addToInventory(obj)
                                    elif i.startswith('SET'):
                                        info = i[4:].split('=')
                                        propFileName = getPropFileName(state.room.user, state.room.x, state.room.y, obj, info[0])
                                        propFile = open(propFileName,'w')
                                        propFile.write(info[1])
                                        propFile.close()

                                        for prop in obj.props:
                                            if prop.key == info[0]:
                                                prop.value = info[1]
                        break
    if not found:
        prnt('Command not found')

if not os.path.exists(configPath):
    print('')
    print('Welcome traveller! It appears you are new here. I can help you get set up.')
    print('')

    # Ask some questions
    name = input('[?] What is your character\'s name? ')
    desc = input('[?] Describe your character: ')

    # Create new .world dir in the home dir
    if not os.path.exists(rootDir):
        os.makedirs(rootDir)

    # Create the config file
    configFile = open(configPath,'w')
    configFile.write('name=' + name + '\n')
    configFile.write('desc=' + desc + '\n')
    configFile.close()

    # Create loc file
    if not os.path.exists(locPath):
        locFile = open(locPath,'w')
        locFile.write('0,0')
        locFile.close()

    # Create inventory file
    if not os.path.exists(inventoryPath):
        locFile = open(inventoryPath,'w')
        locFile.close()

    # Create rooms dir
    if not os.path.exists(roomsPath):
        os.makedirs(roomsPath)

    # Create state dir
    if not os.path.exists(statePath):
        os.makedirs(statePath)

# Find current room
locFile = open(locPath,'r')
coords = locFile.read().strip().split(',')
locFile.close()
state = State()
state.locX = int(coords[0])
state.locY = int(coords[1])
state.room = getRoom(state.locX, state.locY)

# Load inventory
state.inventory = getInventory()

print('')
print('> Welcome to ~world!')
prnt('Current location: ' + state.room.name + ' (' + str(state.locX) + ',' + str(state.locY) + ')')
print('')

# Keep the program active
active = True
while active == True:

    # Display a prompt
    cmd = input('> ')

    # CMD: look (object)
    if cmd.startswith('look ') and len(cmd) > 5: lookObj(cmd)
    # CMD: grab (object)
    elif cmd.startswith('grab ') and len(cmd) > 5: grabObj(cmd)
    # CMD: drop (object)
    elif cmd.startswith('drop ') and len(cmd) > 5: dropObj(cmd)
    # CMD: look
    elif cmd == 'look': look()
    # CMD: inventory
    elif cmd == 'inventory': inventory()
    # CMD: go
    elif cmd.startswith('go ') and cmd[3:] in validDirections: go(cmd)
    # CMD: teleport
    elif cmd.startswith('teleport'): teleport(cmd)
    # CMD: quit
    elif cmd == 'quit' or cmd == 'exit': active = False
    # CMD: obj commands
    else: objCmd(cmd)

    print('')


# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 17:47:54 2020

@author: lol24
"""

import urllib.request
from bs4 import BeautifulSoup

url=input("Input your url: ")

response = urllib.request.urlopen(url)
data = response.read()
doc = BeautifulSoup(data, 'html.parser')

lists = doc.find_all('ol')
for li in lists:
    i=1
    list_items =li.find_all('li')
    print('\n')
    for l in lists_items:
        print(str(i) + '. '+l.get_text())
        i+=1


# -*- coding: utf-8 -*-
"""
Created on Thu Feb  6 09:30:25 2020

@author: nasredine
"""

import matplotlib.pyplot as plt

from utils import *

def Voltage_parser(source_file,probe_file):
    print ('parsing voltage values . . .')
    file = open (source_file)
    list = file.readlines()
    probe_data=[]
    probe_vect = []
    for line in list:
            probe_data=[]
            temp = split_space(line)
            word = temp[0]
            ff = open (probe_file)
            list2 = ff.readlines()
            for line2 in list2:
                parts = split_semic(line2)
                if (len(parts)>0):
                    if (parts[0]==word):
                        data = split_space(parts[2])
                        for i in data[2:]:
                            probe_data.append(float(i))
            if (len(probe_data) !=0) :
                probe_vect.append(probe_data)
    print ('parsing done')
    return probe_vect

def vectors_def(source_file,probe_file):
    print ('creating time and voltage vectors . . .')
    vect_temp = Voltage_parser(source_file,probe_file)
    time_vect_out = []
    data_vect_out = []
    time_vect = []
    data_vect = []
    for t in vect_temp:
        time_vect=[]
        data_vect=[]
        for c,i in enumerate(t):
            if  (c % 2 == 0):
                time_vect.append(i)

            else:
                data_vect.append(i)
        time_vect_out.append(time_vect)
        data_vect_out.append(data_vect)
    return time_vect_out,data_vect_out

def Diff_Voltage (source_file,probe_file):
    print ('calculating voltage in each segment ...')
    vect = vectors_def(source_file,probe_file)
    time = vect[0]
    time = time [0]
    data = vect[1]
    odd_data = []
    even_data = []
    Voltage_all = []
    for c,i in enumerate(data):
        if  (c % 2 == 0):
            even_data.append(i)

        else:
            odd_data.append(i)
    for i,j in zip((even_data),(odd_data)):
        Voltage = []
        for x,y in zip(i,j):
            Voltage.append(y-x)
        Voltage_all.append(Voltage)

    return Voltage_all

def res_parse(source_file,data_file):
    print ('parsing resistance . . .' )
    res=[]
    f = open (source_file)
    list = f.readlines()
    for line in list:
        temp = split_space(line)
        word = temp[6]
        ff = open (data_file)
        list2 = ff.readlines()
        for line2 in list2:
            temp2 = split_space(line2)
            if (len(temp2)>3):
                if temp2[2] == word:
                    res.append(temp2[1])
    return res

def Current (voltage_source_file,voltage_probe_file,res_source_file,res_probe_file):
     res = res_parse(res_source_file,res_probe_file)
     voltage = Diff_Voltage(voltage_source_file,voltage_probe_file)
     current = []
     print ('calculating current values . . .' )

     for c,i in enumerate(voltage):
         current_temp = []
         for ii in i:
             current_temp.append(ii/float(res[c]))
         current.append(current_temp)
     print ('there are ', len(current) ,' current waveforms')
     print ('each waveform contains ', len(current[0]) ,' point')
     t=max(current[0])
     for c,i in enumerate(current[0]):
         if (i==t):
             max_idx = c
     print ('max current idx for waveform 0 is ',max_idx)
     print ('max_value = ',t)

     tt=min(current[0])
     for c,i in enumerate(current[0]):
         if (i==tt):
             min_idx = c
     print ('min current idx for waveform 0 is  = ',min_idx)
     print ('min_value = ',tt)

     plt.figure("Current [0]")
     plt.plot (current[0])
     plt.show()
     return current


from django.core.exceptions import ValidationError
from django.test import TestCase
from model_mommy import mommy

from saldanprev.core.models import Pessoa
from saldanprev.seguro_auto.models import PrincipalCondutor, SeguroAuto

class TestPrincipalCondutor(TestCase):
    """
    Teste do modelo PrincipalCondutor.
    """
    def setUp(self):
        self.nome = 'Marilena'
        self.cpf = '50411738500'
        self.pessoa = mommy.make(Pessoa, nome=self.nome, cpf=self.cpf)
        self.seguro_auto = mommy.make(SeguroAuto)
        self.cnh = '84052722284'
        self.distancia_trabalho = 'Até 40 km'
        self.tempo_habilitacao = 'De 2 a 10 anos'
        self.profissao = 'Cantora'
        self.relacao_segurado = 'segurado'
        self.tipo_moradia = 'Apartamento ou flat'
        self.principal_condutor = mommy.make(
            PrincipalCondutor,
            cnh=self.cnh,
            distancia_trabalho=self.distancia_trabalho,
            pessoa=self.pessoa,
            relacao_segurado=self.relacao_segurado,
            seguro_auto=self.seguro_auto,
            tempo_habilitacao=self.tempo_habilitacao,
            tipo_moradia=self.tipo_moradia,
        )

    def teste__str__(self):
        """
        Verificar se __str__ do modelo retorna conforme o padrão adicionado:
            [<pessoa.nome> - <pessoa.cpf> | <seguro_auto.uuid>]
        """
        self.assertEqual(
            str(self.principal_condutor),
            '[{0} - {1} | {2}]'.format(
                self.nome,
                self.cpf,
                self.seguro_auto.uuid
            )
        )

    def teste_cnh_tamanho_maximo_invalido(self):
        """
        Verifica a mensagem de erro do atributo cnh caso seja persistido uma
            entrada maior que 11 digitos.
        """
        mensagem = ('CNH inválida. O número da CNH deve conter 11 digitos.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                cnh='84052722284222'
            )

    def teste_cnh_tamanho_minimo_invalid0(self):
        """
        Verifica a mensagem de erro do atributo cnh caso seja persistido uma
            entrada menor que 11 digitos.
        """
        mensagem = ('CNH inválida. O número da CNH deve conter 11 digitos.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                cnh='84052'
            )

    def teste_distancia_trabalho_opcao_invalida(self):
        """
        Verifica a mensagem de erro do atributo distancia_trabalho caso seja
            persistido uma entrada inválida.
        """
        mensagem = ('Selecione uma opção válida. "distância inválida" não é '
                    'uma das opções disponíveis.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                distancia_trabalho='distância inválida'
            )

    def teste_meta_verbose_name(self):
        """
        Verifica se o PrincipalCondutor.Meta.verbose_name corresponde com o
            nome da classe.
        """
        self.assertEqual(
            str(PrincipalCondutor._meta.verbose_name), 'PrincipalCondutor')

    def teste_meta_verbose_name_plural(self):
        """
        Verifica se o PrincipalCondutor.Meta.verbose_name_plural corresponde
            com o nome da classe no plural.
        """
        self.assertEqual(
            str(PrincipalCondutor._meta.verbose_name_plural),
            'PrincipaisCondutores'
        )

    def teste_ordernacao(self):
        """
        Verifica se a ordem de filtro corresponde ao definido no modelo:
            ('pessoa', )
        """

        pessoa_1 = mommy.make(
            Pessoa,
            cpf='25345842353',
            nome="Amanda",
            sobrenome='da Fonseca'
        )
        pessoa_2 = mommy.make(
            Pessoa,
            cpf='64766450132',
            nome="Julio",
            sobrenome='Ribeiro'
        )
        pessoa_3 = mommy.make(
            Pessoa,
            cpf='51867267705',
            nome="Amanda",
            sobrenome='Pires'
        )

        principal_condutor_1 = mommy.make(PrincipalCondutor, pessoa=pessoa_1)
        principal_condutor_2 = mommy.make(PrincipalCondutor, pessoa=pessoa_2)
        principal_condutor_3 = mommy.make(PrincipalCondutor, pessoa=pessoa_3)

        principais_condutores = PrincipalCondutor.objects.all()

        self.assertTrue(principais_condutores.ordered)
        self.assertEqual(principais_condutores[0], principal_condutor_1)
        self.assertEqual(principais_condutores[1], principal_condutor_3)
        self.assertEqual(principais_condutores[2], principal_condutor_2)
        self.assertEqual(principais_condutores[3], self.principal_condutor)

    def teste_relacao_segurado_opcao_invalida(self):
        """
        Verifica a mensagem de erro do atributo relacao_segurado caso seja
            persistido uma entrada inválida.
        """
        mensagem = ('Selecione uma opção válida. "relacao segurado inválida" '
                    'não é uma das opções disponíveis.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                relacao_segurado='relacao segurado inválida'
            )

    def teste_related_name_e_related_query_name_pessoa(self):
        """
        Garantir se o related_name e related_query_name no atributo
            pessoa retornam valores corretos.
        """

        qs = Pessoa.objects.get(principal_condutor__cnh=self.cnh)
        self.assertEqual(qs, self.pessoa)
        self.assertIn(self.principal_condutor, qs.principais_condutores.all())

    def teste_related_name_e_related_query_name_seguro_auto(self):
        """
        Garantir se o related_name e related_query_name no atributo
            seguro_auto retornam valores corretos.
        """

        qs = SeguroAuto.objects.get(principal_condutor__cnh=self.cnh)
        self.assertEqual(qs, self.seguro_auto)
        self.assertEqual(self.principal_condutor, qs.principal_condutor)

    def teste_tempo_habilitacao_opcao_invalida(self):
        """
        Verifica a mensagem de erro do atributo tempo_habilitacao caso seja
            persistido uma entrada inválida.
        """
        mensagem = ('Selecione uma opção válida. "tipo moradia inválida" não '
                    'é uma das opções disponíveis.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                tempo_habilitacao='tipo moradia inválida'
            )

    def teste_tipo_moradia_opcao_invalida(self):
        """
        Verifica a mensagem de erro do atributo tipo_moradia caso seja
            persistido uma entrada inválida.
        """
        mensagem = ('Selecione uma opção válida. "tipo moradia inválida" não '
                    'é uma das opções disponíveis.')

        with self.assertRaisesMessage(ValidationError, mensagem):
            mommy.make(
                PrincipalCondutor,
                pessoa__cpf='25345842353',
                tipo_moradia='tipo moradia inválida'
            )


import json
import requests
import threading
import socket

link_file = open("./other_files/links.txt", "r")

def check_urls_from_file(url, data):
    try:
        request = requests.get(url)
        payload = {
                     "url": url,
                     "is_ok": request.status_code == requests.codes.ok,
                     "status_code": request.status_code
                }
        data.append(payload)
    except:
        faield_payload = {
            "url": url,
            "is_ok": False,
            "status_code": None
        }
        data.append(faield_payload)

def write_data_in_json_file(results):
    with open('./other_files/data.json', 'w', encoding='utf-8') as f:
        json.dump(results, f, ensure_ascii=False, indent=4)

results = []
file_line = link_file.read().splitlines()
threads = [threading.Thread(target=check_urls_from_file, args=(url, results))
           for url in
           file_line]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

for result in results:
    print(result)

write_data_in_json_file(results)