from direct.showbase.ShowBase import ShowBase   # Para usar panda
from direct.actor.Actor import Actor
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.OnscreenText import OnscreenText, Point3, Vec3
from direct.interval.MetaInterval import Parallel, Sequence
from panda3d.core import PandaNode, NodePath, Camera, TextNode
import sys

# Función para añadir Instrucciones a la pantala
def addInstructions(pos, msg):
    return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), scale=.05,
                        shadow=(0, 0, 0, 1), parent=base.a2dTopLeft,
                        pos=(0.08, -pos - 0.04), align=TextNode.ALeft)

class Parcial(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()

        # Instrucciones en pantalla
        self.Salir = addInstructions(.06, "[ESC]: Para Salir")
        self.Camara = addInstructions(.12, "[A]: Para Mover Cabeza")
        self.CabezaL = addInstructions(.18, "[S]: Para Mover Brazo Derecho")
        self.CabezaL = addInstructions(.24, "[D]: Para Mover Brazo Izquierdo")
        self.CaderaL = addInstructions(.30, "[F]: Para Mover Cadera")
        self.CaderaL = addInstructions(.36, "[G]: Para Mover Tronco")
        self.CaderaL = addInstructions(.42, "[H]: Para Girar")
        self.CaderaL = addInstructions(.48, "[Z]: Cabeza Cadera")
        self.CaderaL = addInstructions(.54, "[X]: Brazos")
        self.CaderaL = addInstructions(.60, "[C]: Giro Tronco")
        self.CaderaL = addInstructions(.66, "[V]: Todos a la vez")

        # Carga de un Actor
        self.Ralph = Actor("models/ralph",
                                {"run": "models/ralph-run",
                                 "walk": "models/ralph-walk"})

        self.Ralph.setScale(.5, .5, .5)
        self.Ralph.setPos(0, 10, -1)        #(x   -IZQ  +DER   ,y   PROFUNDIDAD  ,z   +ARRIBA -ABAJO   )
        self.Ralph.reparentTo(self.render)

        # Giro de ralph
        self.GiroTotal = self.Ralph.hprInterval(1.5, Point3(0,359,0))

        # Declaración de partes del cuerpo
        self.Cabeza = self.Ralph.controlJoint(None, 'modelRoot', 'Neck')
        self.BrazoDerecho = self.Ralph.controlJoint(None, 'modelRoot', 'RightShoulder')
        self.BrazoIzquierdo = self.Ralph.controlJoint(None, 'modelRoot', 'LeftShoulder')
        self.CaderaDerecha = self.Ralph.controlJoint(None, 'modelRoot', 'RightHip')
        self.CaderaIzquierda = self.Ralph.controlJoint(None, 'modelRoot', 'LeftHip')
        self.Tronco = self.Ralph.controlJoint(None, 'modelRoot', 'Chest')

        # Movimiento de Cabeza
        self.CabezaAbajo = self.Cabeza.hprInterval(0.5, Point3(0, 0, 0))
        self.CabezaArriba = self.Cabeza.hprInterval(0.5, Point3(20, 0, 0))

        # Movimientos de brazo derecho
        self.BrazoDerechoAbajo = self.BrazoDerecho.hprInterval(1.0, Point3(72.2059, 106.186, -45))
        self.BrazoDerechoArriba = self.BrazoDerecho.hprInterval(1.0, Point3(72.2059, 76.186, 6.02231))

        # Movimientos de brazo izquierdo
        self.BrazoIzquierdoAbajo = self.BrazoIzquierdo.hprInterval(1.0, Point3(160.1401, -22.1706, 6.55722))
        self.BrazoIzquierdoArriba = self.BrazoIzquierdo.hprInterval(1.0, Point3(80.1401, -52.1706, 6.55722))

        # Movimientos de cadera derecha
        self.CaderaDerechaDerecha = self.CaderaDerecha.hprInterval(0.5, Point3(4.9762, 0, 120))
        self.CaderaDerechaNormal = self.CaderaDerecha.hprInterval(0.5, Point3(4.9762, 0, 90))

        # Movimientos de cadera derecha
        self.CaderaIzquierdaIzquierda = self.CaderaIzquierda.hprInterval(0.5, Point3(5.02118, -0.862563, 62.9857))
        self.CaderaIzquierdaNormal = self.CaderaIzquierda.hprInterval(0.5, Point3(5.02118, -0.862563, 92.9857))

        # Movimientos del tronco
        #self.Tronco.setHpr(0, 50, 0)
        self.TroncoIzquierda = self.Tronco.hprInterval(0.5, Point3(0, 50, 0))
        self.TroncoDerecha = self.Tronco.hprInterval(0.5, Point3(0, -50, 0))
        self.TroncoNormal = self.Tronco.hprInterval(0.5, Point3(0, 0, 0))

        # Secuencias de movimientos
        self.MoverCabeza = Sequence(self.CabezaArriba, self.CabezaAbajo)
        self.MoverBrazoDerecho = Sequence(self.BrazoDerechoAbajo, self.BrazoDerechoArriba)
        self.MoverBrazoIzquierdo = Sequence(self.BrazoIzquierdoAbajo, self.BrazoIzquierdoArriba)
        self.MoverCaderaDerechaIzquierda = Sequence(self.CaderaDerechaDerecha, self.CaderaDerechaNormal,
                                                    self.CaderaIzquierdaIzquierda, self.CaderaIzquierdaNormal)
        self.MoverTronco = Sequence( self.TroncoDerecha, self.TroncoNormal, self.TroncoIzquierda)
        self.Giro = Sequence(self.GiroTotal)

        # Paralelos
        self.CaderaCabeza = Parallel(self.MoverCabeza, self.MoverCaderaDerechaIzquierda)
        self.Brazos = Parallel(self.MoverBrazoDerecho, self.MoverBrazoIzquierdo)
        self.GiroTronco = Parallel(self.Giro, self.MoverTronco)
        self.Todos = Parallel(self.MoverCabeza, self.MoverCaderaDerechaIzquierda, self.MoverBrazoDerecho, self.MoverBrazoIzquierdo, self.Giro, self.MoverTronco)

        self.accept("escape", sys.exit)
        self.accept("a", self.eCabeza)
        self.accept("s", self.eBrazoDerecho)
        self.accept("d", self.eBrazoIzquierdo)
        self.accept("f", self.eCadera)
        self.accept("g", self.eTronco)
        self.accept("h", self.eGiro)
        self.accept("z", self.eCadCab)
        self.accept("x", self.eBrazos)
        self.accept("c", self.eGiroT)
        self.accept("v", self.eTodos)

    def eCabeza(self):
        self.MoverCabeza.start()

    def eBrazoDerecho(self):
        self.MoverBrazoDerecho.start()

    def eBrazoIzquierdo(self):
        self.MoverBrazoIzquierdo.start()

    def eCadera(self):
        self.MoverCaderaDerechaIzquierda.start()

    def eTronco(self):
        self.MoverTronco.start()

    def eGiro(self):
        self.Giro.start()

    def eCadCab(self):
        self.CaderaCabeza.start()

    def eBrazos(self):
        self.Brazos.start()

    def eGiroT(self):
        self.GiroTronco.start()

    def eTodos(self):
        self.Todos.loop()

app = Parcial()
app.run()


# -*- coding: utf-8 -*-
#!/usr/bin/python2.6

import sys
import os
import csv
import pymongo
import json
from datetime import datetime
from copy import deepcopy
from pprint import pprint

path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.insert(0, path)
sys.path.insert(0, path + "/sefaria")
from texts import *

parashiot_file = "/var/data/Sefaria-Data/misc/parshiot.csv"

def parse_span(ref):
	ref = ref.split(" | ")[0]
	ref = ref.replace(" - ", "-")
	return ref

def parse_haftara(ref):
	ref = parse_span(ref)
	refs = ref.split("; ")
	for i in range(len(refs)):
		if refs[i][0] in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
			refs[i] = parse_ref(refs[i-1])["book"] + " " + refs[i]

	return refs

def parse_shabbat_name(ref):
	ref = ref.split(" | ")
	return ref[1] if len(ref) > 1 else None

p = []
with open(parashiot_file, 'rb') as csvfile:
	parashiot = csv.reader(csvfile)
	parashiot.next()
	parasha = {"date": None}
	for row in parashiot:
		if not len(row): continue

		# Continuation
		if datetime.strptime(row[0], "%d-%b-%Y") == parasha["date"]:
			if row[2] == "Haftara":
				parasha["haftara"] = parse_haftara(row[3])
				parasha["shabbat_name"] = parse_shabbat_name(row[3])
			else:
				parasha["aliyot"].append( parse_span(row[3]) )

		# New Parasha
		else:
			if parasha["date"] is not None:
				# clean up last object
				start = parse_ref(parasha["aliyot"][0])
				end   = parse_ref(parasha["aliyot"][7])
				start["toSections"] = end["toSections"]
				parasha["ref"] = make_ref(start)
				p.append(deepcopy(parasha))

			parasha = {
				"date": datetime.strptime(row[0], "%d-%b-%Y"),
				"parasha": row[1],
				"aliyot": [ parse_span(row[3]) ]
			}

db.parshiot.remove()
for parasha in p:
	db.parshiot.save(parasha)
db.parshiot.ensure_index("date")


from robot.errors import ExecutionFailed, PassExecution
from robot.model import TagPatterns
from robot.utils import html_escape, py3to2, unic, test_or_task

@py3to2
class Failure(object):

    def __init__(self):
        self.setup = None
        self.test = None
        self.teardown = None
        self.setup_skipped = None
        self.test_skipped = None
        self.teardown_skipped = None

    def __bool__(self):
        return bool(
            self.setup or self.test or self.teardown or
            self.setup_skipped or self.test_skipped or self.teardown_skipped
        )

@py3to2
class Exit(object):

    def __init__(self, failure_mode=False, error_mode=False,
                 skip_teardown_mode=False):
        self.failure_mode = failure_mode
        self.error_mode = error_mode
        self.skip_teardown_mode = skip_teardown_mode
        self.failure = False
        self.error = False
        self.fatal = False

    def failure_occurred(self, failure=None):
        if isinstance(failure, ExecutionFailed) and failure.exit:
            self.fatal = True
        if self.failure_mode:
            self.failure = True

    def error_occurred(self):
        if self.error_mode:
            self.error = True

    @property
    def teardown_allowed(self):
        return not (self.skip_teardown_mode and self)

    def __bool__(self):
        return self.failure or self.error or self.fatal

class _ExecutionStatus(object):

    def __init__(self, parent=None, *exit_modes):
        self.parent = parent
        self.children = []
        self.failure = Failure()
        self.exit = parent.exit if parent else Exit(*exit_modes)
        self.skipped = False
        self._teardown_allowed = False
        self._rpa = False
        if parent:
            parent.children.append(self)

    def setup_executed(self, failure=None):
        if failure and not isinstance(failure, PassExecution):
            if failure.skip:
                self.failure.setup_skipped = unic(failure)
                self.skipped = True
            elif self._skip_on_failure():
                msg = self._skip_on_failure_message(
                    'Setup failed:\n%s' % unic(failure))
                self.failure.test = msg
                self.skipped = True
            else:
                self.failure.setup = unic(failure)
            self.exit.failure_occurred(failure)

        self._teardown_allowed = True

    def teardown_executed(self, failure=None):
        if failure and not isinstance(failure, PassExecution):
            if failure.skip:
                self.failure.teardown_skipped = unic(failure)
                # Keep the Skip status in case the teardown failed
                self.skipped = self.skipped or failure.skip
            elif self._skip_on_failure():
                msg = self._skip_on_failure_message(
                    'Setup failed:\n%s' % unic(failure))
                self.failure.test = msg
                self.skipped = True
            else:
                self.failure.teardown = unic(failure)
            self.exit.failure_occurred(failure)

    def failure_occurred(self):
        self.exit.failure_occurred()

    def error_occurred(self):
        self.exit.error_occurred()

    @property
    def teardown_allowed(self):
        return self.exit.teardown_allowed and self._teardown_allowed

    @property
    def failed(self):
        return bool(self.parent and self.parent.failed or
                    self.failure or self.exit)

    @property
    def status(self):
        if self.skipped or (self.parent and self.parent.skipped):
            return 'SKIP'
        if self.failed:
            return 'FAIL'
        return 'PASS'

    def _skip_on_failure(self):
        return False

    def _skip_on_failure_message(self, failure):
        return ("%s failed but its tags matched '--SkipOnFailure' and it was "
                   "marked skipped.\n\nOriginal failure:\n%s"
                   % (test_or_task('{Test}', self._rpa), unic(failure)))

    @property
    def message(self):
        if self.failure or self.exit:
            return self._my_message()
        if self.parent and self.parent.failed:
            return self._parent_message()
        return ''

    def _my_message(self):
        raise NotImplementedError

    def _parent_message(self):
        return ParentMessage(self.parent).message

class SuiteStatus(_ExecutionStatus):

    def __init__(self, parent=None, exit_on_failure_mode=False,
                 exit_on_error_mode=False,
                 skip_teardown_on_exit_mode=False):
        _ExecutionStatus.__init__(self, parent, exit_on_failure_mode,
                                  exit_on_error_mode,
                                  skip_teardown_on_exit_mode)

    def _my_message(self):
        return SuiteMessage(self).message

class TestStatus(_ExecutionStatus):

    def __init__(self, parent, test, skip_on_failure=None, critical_tags=None,
                 rpa=False):
        _ExecutionStatus.__init__(self, parent)
        self.exit = parent.exit
        self._test = test
        self._skip_on_failure_tags = skip_on_failure
        self._critical_tags = critical_tags
        self._rpa = rpa

    def test_failed(self, failure):
        if hasattr(failure, 'skip') and failure.skip:
            self.test_skipped(failure)
        elif self._skip_on_failure():
            msg = self._skip_on_failure_message(failure)
            self.failure.test = msg
            self.skipped = True
        else:
            self.failure.test = unic(failure)
            self.exit.failure_occurred(failure)

    def test_skipped(self, reason):
        self.skipped = True
        self.failure.test_skipped = unic(reason)

    def skip_if_needed(self):
        if not self.skipped and self.failed and self._skip_on_failure():
            msg = self._skip_on_failure_message(self.failure.test)
            self.failure.test = msg
            self.skipped = True
            return True
        return False

    def _skip_on_failure(self):
        critical_pattern = TagPatterns(self._critical_tags)
        if critical_pattern and critical_pattern.match(self._test.tags):
            return False
        skip_on_fail_pattern = TagPatterns(self._skip_on_failure_tags)
        return skip_on_fail_pattern and \
            skip_on_fail_pattern.match(self._test.tags)

    def _my_message(self):
        return TestMessage(self).message

class _Message(object):
    setup_message = NotImplemented
    setup_skipped_message = NotImplemented
    teardown_skipped_message = NotImplemented
    teardown_message = NotImplemented
    also_teardown_message = NotImplemented

    def __init__(self, status):
        self.failure = status.failure
        self.skipped = status.skipped

    @property
    def message(self):
        message = self._get_message_before_teardown()
        return self._get_message_after_teardown(message)

    def _get_message_before_teardown(self):
        if self.failure.setup_skipped:
            return self._format_setup_or_teardown_message(
                self.setup_skipped_message, self.failure.setup_skipped)
        if self.failure.setup:
            return self._format_setup_or_teardown_message(
                self.setup_message, self.failure.setup)
        return self.failure.test_skipped or self.failure.test or ''

    def _format_setup_or_teardown_message(self, prefix, message):
        if message.startswith('*HTML*'):
            prefix = '*HTML* ' + prefix
            message = message[6:].lstrip()
        return prefix % message

    def _get_message_after_teardown(self, message):
        if not (self.failure.teardown or self.failure.teardown_skipped):
            return message
        if not message:
            if self.failure.teardown:
                prefix, msg = self.teardown_message, self.failure.teardown
            else:
                prefix, msg = self.teardown_skipped_message, self.failure.teardown_skipped
            return self._format_setup_or_teardown_message(prefix, msg)
        return self._format_message_with_teardown_message(message)

    def _format_message_with_teardown_message(self, message):
        teardown = self.failure.teardown or self.failure.teardown_skipped
        if teardown.startswith('*HTML*'):
            teardown = teardown[6:].lstrip()
            if not message.startswith('*HTML*'):
                message = '*HTML* ' + html_escape(message)
        elif message.startswith('*HTML*'):
            teardown = html_escape(teardown)
        if self.failure.teardown:
            return self.also_teardown_message % (message, teardown)
        return self.also_teardown_skip_message % (teardown, message)

class TestMessage(_Message):
    setup_message = 'Setup failed:\n%s'
    teardown_message = 'Teardown failed:\n%s'
    setup_skipped_message = '%s'
    teardown_skipped_message = '%s'
    also_teardown_message = '%s\n\nAlso teardown failed:\n%s'
    also_teardown_skip_message = 'Skipped in teardown:\n%s\n\nEarlier message:\n%s'
    exit_on_fatal_message = 'Test execution stopped due to a fatal error.'
    exit_on_failure_message = \
        'Failure occurred and exit-on-failure mode is in use.'
    exit_on_error_message = 'Error occurred and exit-on-error mode is in use.'

    def __init__(self, status):
        _Message.__init__(self, status)
        self.exit = status.exit

    @property
    def message(self):
        message = super(TestMessage, self).message
        if message:
            return message
        if self.exit.failure:
            return self.exit_on_failure_message
        if self.exit.fatal:
            return self.exit_on_fatal_message
        if self.exit.error:
            return self.exit_on_error_message
        return ''

class SuiteMessage(_Message):
    setup_message = 'Suite setup failed:\n%s'
    setup_skipped_message = 'Skipped in suite setup:\n%s'
    teardown_skipped_message = 'Skipped in suite teardown:\n%s'
    teardown_message = 'Suite teardown failed:\n%s'
    also_teardown_message = '%s\n\nAlso suite teardown failed:\n%s'

class ParentMessage(SuiteMessage):
    setup_message = 'Parent suite setup failed:\n%s'
    setup_skipped_message = 'Skipped in parent suite setup:\n%s'
    teardown_skipped_message = 'Skipped in parent suite teardown:\n%s'
    teardown_message = 'Parent suite teardown failed:\n%s'
    also_teardown_message = '%s\n\nAlso parent suite teardown failed:\n%s'

    def __init__(self, status):
        while status.parent and status.parent.failed:
            status = status.parent
        SuiteMessage.__init__(self, status)


from django.conf import settings
from adjuntos.models import Attachment

class Command(BaseCommand):

    def handle(self, *args, **options):

        for a in Attachment.objects.filter(probema__isnull=False):
            print(f'*** {settings.ALLOWED_HOSTS} ***')
            print(a.id, a.problema)
            print('')


#------------------------------------------------------------------------------#

# Allow print statement to be compatible between Python 2 and 3
from __future__ import print_function

# Import pyCAPS class
from pyCAPS import capsProblem

# Import os
import os

#------------------------------------------------------------------------------#

# Initialize capsProblem object
myProblem = capsProblem()

# Load CSM file
filename = os.path.join("..","EGADS","CFDInviscid_Wing.egads")
transport = myProblem.loadCAPS(filename)

# Load AFLR4 AIM
aflr4 = myProblem.loadAIM(aim = "aflr4AIM",
                          analysisDir = "workDir_AFLR4")

# Mark capsGroup="Farfield" with a Farfield bcType
aflr4.setAnalysisVal("Mesh_Sizing", ("Farfield", {"bcType":"Farfield"}))

# Use 5 segments on farfield face edges
aflr4.setAnalysisVal("ff_nseg", 5)

# Scaling factor to compute AFLR4 'ref_len' parameter via
# ref_len = capsMeshLength * Mesh_Length_Factor
aflr4.setAnalysisVal("Mesh_Length_Factor", 5)

# Relative scale of maximum spacing bound relative to ref_len
# max_spacing = max_scale * ref_len
aflr4.setAnalysisVal("max_scale", 0.1)

# Relative scale of minimum spacing bound relative to ref_len
# min_spacing = min_scale * ref_len
aflr4.setAnalysisVal("min_scale", 0.01)

# Absolute scale of minimum spacing bound for proximity
# abs_min_spacing = abs_min_scale * ref_len
aflr4.setAnalysisVal("abs_min_scale", 0.01)

# Use mesh length factor to make a series of meshes (not a family)
for Mesh_Length_Factor in [1, 4, 20]:
    aflr4.setAnalysisVal("Mesh_Length_Factor", Mesh_Length_Factor)

    # Run AIM pre-/post-analysis
    aflr4.preAnalysis()
    aflr4.postAnalysis()

    # View the surface tessellation
    aflr4.viewGeometry()


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

# In[1]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# In[2]:

data=pd.read_csv("https://raw.githubusercontent.com/Mounika-Kajjam/Datasets/master/claimants.csv")
data.head()

# In[3]:

data.drop(['CASENUM'],axis=1,inplace=True)
data

# In[4]:

data.isnull().sum()

# In[5]:

def fill_na(col):
    col.fillna(col.value_counts().index[0],inplace=True)
    return col
data.apply(lambda col:fill_na(col))

# In[6]:

data.isnull().sum()

# In[7]:

X = data.iloc[:,1:]
X.head()

# In[8]:

y=data.ATTORNEY
y.head()

# In[9]:

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=2)

# In[10]:

# Training Data
from  sklearn.linear_model import LogisticRegression
reg=LogisticRegression()
reg.fit(X_train,y_train)

# In[11]:

y_train_pred = reg.predict(X_train)
y_train_pred

# In[12]:

from sklearn.metrics import confusion_matrix,accuracy_score
conf = confusion_matrix(y_train,y_train_pred)
conf

# In[13]:

sns.heatmap(confusion_matrix(y_train,y_train_pred),annot=True,fmt='3.0f',annot_kws={'size':'20'})

# In[14]:

# Testing Data
from  sklearn.linear_model import LogisticRegression
reg=LogisticRegression()
reg.fit(X_test,y_test)

# In[15]:

y_test_pred = reg.predict(X_test)
y_test_pred

# In[16]:

from sklearn.metrics import confusion_matrix,accuracy_score
conf = confusion_matrix(y_test,y_test_pred)
conf

# In[17]:

sns.heatmap(confusion_matrix(y_test,y_test_pred),annot=True,fmt='3.0f',annot_kws={'size':'20'})

# In[18]:

from sklearn.metrics import classification_report
# Syntax: classification_report(actualValues,predictedValues)
print(classification_report(y_train,y_train_pred))
print(classification_report(y_test,y_test_pred))

# In[19]:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Scaling for training data
scaled_X_train = pd.DataFrame(scaler.fit_transform(X_train),columns=X_train.columns)
scaled_X_train

# In[20]:

scaled_X_test = pd.DataFrame(scaler.fit_transform(X_test),columns=X_test.columns)
scaled_X_test

# In[21]:

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
scores =[]
for k in range(1,20):
    knn_model = KNeighborsClassifier(n_neighbors=k)#,metric='euclidean')
    knn_model.fit(scaled_X_train,y_train)
    pred_test = knn_model.predict(scaled_X_test)
    scores.append(accuracy_score(y_test,pred_test))
scores

# In[22]:

plt.plot(range(1,20),scores,marker='o',markerfacecolor='r',linestyle='--')

# In[23]:

final_model = KNeighborsClassifier(n_neighbors=7,metric='euclidean')
final_model.fit(scaled_X_train,y_train)

# In[24]:

final_train_pred = final_model.predict(scaled_X_train)
final_train_pred

# In[25]:

from sklearn.metrics import confusion_matrix
sns.heatmap(confusion_matrix(y_train,final_train_pred),annot=True,fmt='d')

# In[27]:

print(classification_report(y_train,final_train_pred))

# In[28]:

# Prediction on Test Data
final_test_pred = final_model.predict(scaled_X_test) #y_test
final_test_pred

# In[29]:

sns.heatmap(confusion_matrix(y_test,final_test_pred),annot=True,fmt='d')

# In[30]:

print(classification_report(y_test,final_test_pred))

# In[31]:

y_test_prob=final_model.predict_proba(scaled_X_test)
y_test_prob=pd.DataFrame(y_test_prob)
y_test_prob

# In[32]:

# Logistic Regression
y_test_prob1=reg.predict_proba(X_test)
y_test_prob1=pd.DataFrame(y_test_prob1)
y_test_prob1

# In[33]:

y_test

# In[34]:

from sklearn.metrics import roc_auc_score,roc_curve
m_prob = final_model.predict_proba(scaled_X_test)[:,1]
#m_prob
fpr,tpr,threshold = roc_curve(y_test,m_prob,pos_label=1)
print(fpr)
print(tpr)
print(threshold)
print(pd.DataFrame(threshold))

# In[35]:

# Logistic Regression
m_prob1 = reg.predict_proba(scaled_X_test)[:,1]
fpr1,tpr1,threshold1 = roc_curve(y_test,m_prob1,pos_label=1)

# In[36]:

plt.plot(fpr,tpr)

# In[37]:

# Logistic Regression
plt.plot(fpr1,tpr1)

# In[38]:

roc_auc_score(y_test,m_prob)

# In[39]:

# Logistic Regression
roc_auc_score(y_test,m_prob1)

# In[ ]:


#!/ust/bin/env python3
# -*- coding: utf-8 -*-

#Python的函数定义非常简单，但灵活度却非常大。除了正常定义的必选参数外，还可以使用默认参数、可变参数和关键字参数，
#使得函数定义出来的接口，不但能处理复杂的参数，还可以简化调用者的代码。

#1.位置参数

#我们先写一个计算x2的函数：
def power(x):
	return x*x

#现在，如果我们要计算x3怎么办？可以再定义一个power3函数，但是如果要计算x4、x5……怎么办？我们不可能定义无限多个函数。
#你也许想到了，可以把power(x)修改为power(x, n)，用来计算xn，说干就干：
def power2(x, n):
	s = 1
	while n > 0:
		n = n - 1
		s = s * x
	return s
#修改后的power(x, n)函数有两个参数：x和n，这两个参数都是位置参数，调用函数时，传入的两个值按照位置顺序依次赋给参数x和n。

#2.默认参数
def power3(x, n=2):
	s = 1
	while n > 0:
		n = n - 1
		s = s * x
	return s
#这样我们调用power3(5),相当于调用power3(5,2)

#设置默认参数时，有几点要注意：
#一是必选参数在前，默认参数在后，否则Python的解释器会报错（思考一下为什么默认参数不能放在必选参数前面）；
#二是如何设置默认参数。
#当函数有多个参数时，把变化大的参数放前面，变化小的参数放后面。变化小的参数就可以作为默认参数。

#使用默认参数有什么好处？最大的好处是能降低调用函数的难度。
#举个例子，我们写个一年级小学生注册的函数，需要传入name和gender两个参数：
def enroll(name, gender):
	print('name:', name)
	print('gender', gender)
#如果要继续传入年龄、城市等信息怎么办？这样会使得调用函数的复杂度大大增加。
#我们可以把年龄和城市设为默认参数：
def enroll2(name, gender, age=6, city='郑州'):
	pass

#有多个默认参数时，调用的时候，既可以按顺序提供默认参数，比如调用enroll('Bob', 'M', 7)，意思是，
#除了name，gender这两个参数外，最后1个参数应用在参数age上，city参数由于没有提供，仍然使用默认值。
#也可以不按顺序提供部分默认参数。当不按顺序提供部分默认参数时，需要把参数名写上。比如调用enroll2('Adam', 'M', city='Tianjin')，
#意思是，city参数用传进去的值，其他默认参数继续使用默认值。

#默认参数很有用，但使用不当，也会掉坑里。默认参数有个最大的坑，演示如下：
def add_end(L=[]):
	L.append('END')
	return L
print(add_end([1,2]))
#[1, 2, 'END']
print(add_end())
#['END']

#坑来了
print(add_end())
#['END', 'END']

#原因
#Python函数在定义的时候，默认参数L的值就被计算出来了，即[]，因为默认参数L也是一个变量，它指向对象[]，
#每次调用该函数，如果改变了L的内容，则下次调用时，默认参数的内容就变了，不再是函数定义时的[]了。

#所以，定义默认参数要牢记一点：默认参数必须指向不变对象！

#要修改上面的例子，我们可以用None这个不变对象来实现：
def add_end2(L=None):
	if L is None:
		L = []
	L.append('END')
	return L

#3.可变参数

#在Python函数中，还可以定义可变参数。顾名思义，可变参数就是传入的参数个数是可变的，可以是1个、2个到任意个，还可以是0个。
#我们以数学题为例子，给定一组数字a，b，c……，请计算a2 + b2 + c2 + ……。
#要定义出这个函数，我们必须确定输入的参数。由于参数个数不确定，
#我们首先想到可以把a，b，c……作为一个list或tuple传进来，这样，函数可以定义如下：
def calc(numbers):
	sum = 0
	for n in numbers:
		sum = sum + n*n
	return sum
#但是调用的时候，需要先组装出一个list或tuple：
calc([1,2,3])
calc((1,2,3,5))

#如果利用可变参数，调用函数的方式可以简化成这样：
def calc2(*numbers):
	sum = 0
	for n in numbers:
		sum = sum + n*n
	return sum
#定义可变参数和定义一个list或tuple参数相比，仅仅在参数前面加了一个*号。在函数内部，
#参数numbers接收到的是一个tuple，因此，函数代码完全不变。但是，调用该函数时，可以传入任意个参数，包括0个参数：
calc2(1,2)
calc2()
#如果已经有一个list或者tuple，要调用一个可变参数怎么办？可以这样做：
nums = [1, 2, 3]
calc2(nums[0], nums[1], nums[2])
#这种写法当然是可行的，问题是太繁琐，所以Python允许你在list或tuple前面加一个*号，把list或tuple的元素变成可变参数传进去：
nums2 = [1,2,3]
calc2(*nums2)
#*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用，而且很常见。

#4.关键字参数

#关键字参数允许你传入0个或任意个含参数名的参数，这些关键字参数在函数内部自动组装为一个dict。请看示例：
def person(name, age, **kw):
	print('name:', name, 'age:', age, 'other:', kw)
#函数person除了必选参数name和age外，还接受关键字参数kw。在调用该函数时，可以只传入必选参数：
person('han', 25)
#name: han age: 25 other: {}

#也可以传入任意个数的关键字参数：
person('Bob', 35, city='Beijing')
#name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer')
#name: Adam age: 45 other: {'job': 'Engineer', 'gender': 'M'}

#关键字参数有什么用？
#它可以扩展函数的功能。比如，在person函数里，
#我们保证能接收到name和age这两个参数，但是，如果调用者愿意提供更多的参数，
#我们也能收到。试想你正在做一个用户注册的功能，除了用户名和年龄是必填项外，
#其他都是可选项，利用关键字参数来定义这个函数就能满足注册的需求。

#和可变参数类似，也可以先组装出一个dict，然后，把该dict转换为关键字参数传进去：
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
#name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

#当然，上面复杂的调用可以用简化的写法：

extra2 = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra2)
#name: Jack age: 24 other: {'job': 'Engineer', 'city': 'Beijing'}
#**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数，kw将获得一个dict，
#注意kw获得的dict是extra的一份拷贝，对kw的改动不会影响到函数外的extra。

#5.命名关键字参数

#对于关键字参数，函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些，就需要在函数内部通过kw检查。
#仍以person()函数为例，我们希望检查是否有city和job参数：
def person2(name, age, **kw):
	if 'city' in kw:
		#有city参数
		pass
	if 'job' in kw:
		#有job参数
		pass
	print('name:', name, 'age:', age, 'other:', kw)
#但是调用者仍可以传入不受限制的关键字参数：
person2('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456)
#name: Jack age: 24 other: {'addr': 'Chaoyang', 'city': 'Beijing', 'zipcode': 123456}

#如果要限制关键字参数的名字，就可以用命名关键字参数，例如，只接收city和job作为关键字参数。这种方式定义的函数如下：
def person3(name, age, *, city, job):
	print(name, age, city, job)
#和关键字参数**kw不同，命名关键字参数需要一个特殊分隔符*，*后面的参数被视为命名关键字参数。
person('Jack', 24, city='Beijing', job='Engineer')
#name: Jack age: 24 other: {'job': 'Engineer', 'city': 'Beijing'}

#如果函数定义中已经有了一个可变参数，后面跟着的命名关键字参数就不再需要一个特殊分隔符*了：
def person4(name, age, *args, city, job):
	print(name, age, args, city, job)
#命名关键字参数必须传入参数名，这和位置参数不同。如果没有传入参数名，调用将报错：

#命名关键字参数可以有缺省值，从而简化调用：
#由于命名关键字参数city具有默认值，调用时，可不传入city参数：
def person5(name, age, *, city="beijing", job):
	print(name, age, city, job)
person5('Jack', 24, job='Engineer')
#Jack 24 beijing Engineer

#使用命名关键字参数时，要特别注意，如果没有可变参数，就必须加一个*作为特殊分隔符。如果缺少*，Python解释器将无法识别位置参数和命名关键字参数

#6.参数组合

#在Python中定义函数，可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数，这5种参数都可以组合使用。
#但是请注意，参数定义的顺序必须是：必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

def fl(a, b, c=0, *args, **kw):
	print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

fl(1, 2)
#a = 1 b = 2 c = 0 args = () kw = {}

fl(1, 2, c=3)
#a = 1 b = 2 c = 3 args = () kw = {}

fl(1, 2, 3, 'a', 'b')
#a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}

fl(1, 2, 3, 'a', 'b', x=99)
#a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

f2(1, 2, d=99, ext=None)
#a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

#最神奇的是通过一个tuple和dict，你也可以调用上述函数：

args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
fl(*args, **kw)
#a = 1 b = 2 c = 3 args = (4,) kw = {'x': '#', 'd': 99}

args2 = (1,2,3)
kw2 = {'d': 88, 'x': '#'}
f2(*args2, **kw2)
#a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
#所以，对于任意函数，都可以通过类似func(*args, **kw)的形式调用它，无论它的参数是如何定义的。


#07_05_kitchen_sink.py

from tkinter import *

class App:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        Label(frame, text='Label').grid(row=0, column=0)
        Entry(frame, text='Entry').grid(row=0, column=1)
        Button(frame, text='Button').grid(row=0, column=2)
        check_var = StringVar()
        check = Checkbutton(frame, text='Checkbutton', variable=check_var, onvalue='Y', offvalue='N')
        check.grid(row=1, column=0)
        #Listbox
        listbox = Listbox(frame, height=3, selectmode=SINGLE)
        for item in ['red', 'green', 'blue', 'yellow', 'pink']:
            listbox.insert(END, item)
        listbox.grid(row=1, column=1)
        #Radiobutton set
        radio_frame = Frame(frame)
        radio_selection = StringVar()
        b1 = Radiobutton(radio_frame, text='portrait',
            variable=radio_selection, value='P')
        b1.pack(side=LEFT)
        b2 = Radiobutton(radio_frame, text='landscape',
            variable=radio_selection, value='L')
        b2.pack(side=LEFT)
        radio_frame.grid(row=1, column=2)
        #Scale
        scale_var = IntVar()
        Scale(frame, from_=1, to=10, orient=HORIZONTAL,
              variable=scale_var).grid(row=2, column=0)
        Label(frame, textvariable=scale_var,
              font=("Helvetica", 36)).grid(row=2, column=1)
        #Message
        message = Message(frame,
              text='Multiline Message Area')
        message.grid(row=2, column=2)
        #Spinbox
        Spinbox(frame, values=('a','b','c')).grid(row=3)
root = Tk()
root.wm_title('Kitchen Sink')
app = App(root)
root.mainloop()


from rest_framework import serializers
from .models import midi_data

class firstappSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(
    read_only=True,
    default=serializers.CurrentUserDefault()
    )
    class Meta:
        model = midi_data
        fields = ('user', 'description', 'completed')


# Using a Python dictionary to act as an adjacency list
graph = {
    'A' : ['B','C'],
    'B' : ['D', 'E', 'B', 'A'],
    'C' : ['F'],
    'D' : ['F'],
    'E' : ['F'],
    'F' : ['G'],
    'G' : ['B', 'Ds'],
    'Ds': ['G']
}

visited = set() # Set to keep track of visited nodes
def dfs(visited, graph, node, target):

    if not graph.get(node):
        return False

    if node == target:
        return True

    if node not in visited:
        visited.add(node)

        for neigbor in graph[node]:
            if dfs(visited, graph, neigbor, target):
                return True

    return False
# Driver Code
found = dfs(visited, graph, 'Ds', 'A')

print(found)


import pygame
import sys
#custom object for copys of walls
class bckgrnd1(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        img = pygame.image.load("invade.png")
        self.image = pygame.transform.scale(img, (1000, 700))
        self.mask  = pygame.mask.from_surface(self.image)
        self.rect = self.image.get_rect(topleft=(0,0))


import pandas as pd
from joblib import load
from gensim.models import Word2Vec
from nltk.corpus import wordnet
from nltk.sentiment.vader import SentimentIntensityAnalyzer
#sklearn
def score_predictor(review: str):
    doc2vec_model = Word2Vec.load('./feed/word2vec_student.model')
    rf_model = load("./feed/rfmodel_teacher.joblib")
    def get_wordnet_pos(pos_tag):
        if pos_tag.startswith('J'):
            return wordnet.ADJ
        elif pos_tag.startswith('V'):
            return wordnet.VERB
        elif pos_tag.startswith('N'):
            return wordnet.NOUN
        elif pos_tag.startswith('R'):
            return wordnet.ADV
        else:
            return wordnet.NOUN

    import string
    from nltk import pos_tag
    from nltk.corpus import stopwords
    from nltk.tokenize import WhitespaceTokenizer
    from nltk.stem import WordNetLemmatizer

    def clean_text(text):
        # lower text
        text = text.lower()
        # tokenize text and remove puncutation
        text = [word.strip(string.punctuation) for word in text.split(" ")]
        # remove words that contain numbers
        text = [word for word in text if not any(c.isdigit() for c in word)]
        # remove stop words
        stop = stopwords.words('english')
        text = [x for x in text if x not in stop]
        # remove empty tokens
        text = [t for t in text if len(t) > 0]
        # pos tag text
        pos_tags = pos_tag(text)
        # lemmatize text
        text = [WordNetLemmatizer().lemmatize(t[0], get_wordnet_pos(t[1])) for t in pos_tags]
        # remove words with only one letter
        text = [t for t in text if len(t) > 1]
        # join all
        text = " ".join(text)
        return(text)

    clean_review = clean_text(review)
    df = pd.DataFrame(data = {'Review': review,'review_clean': clean_review},index = [0])
    sid = SentimentIntensityAnalyzer()
    df["sentiments"] = df["Review"].apply(lambda x: sid.polarity_scores(x))
    df = pd.concat([df.drop(['sentiments'], axis=1), df['sentiments'].apply(pd.Series)], axis=1)
    df["nb_chars"] = df["Review"].apply(lambda x: len(x))

    df["nb_words"] = df["Review"].apply(lambda x: len(x.split(" ")))

    doc2vec_df = df["review_clean"].apply(lambda x: doc2vec_model.infer_vector(x.split(" "))).apply(pd.Series)
    doc2vec_df.columns = ["doc2vec_vector_" + str(x) for x in doc2vec_df.columns]
    df = pd.concat([df, doc2vec_df], axis=1)
    ignore_cols = ["Review", "review_clean"]
    features = [c for c in df.columns if c not in ignore_cols]

    y_pred = rf_model.predict_proba(df[features])
    return(1 - y_pred[0][1])

if __name__ == "__main__":
    review = "It was great !"
    print(score_predictor(review))


from __future__ import annotations

import uuid

from aiogram import Router
from aiogram.types import CallbackQuery
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from likeinterface import Interface
from likeinterface.exceptions import LikeInterfaceError
from likeinterface.methods import AddGame
from redis.asyncio.client import Redis

from callback_data import CreateGameCallbackData
from enums import Game
from filters import As
from keyboards import join_inline_keyboard_builder
from logger import logger
from schemas import Settings

router = Router()

async def create_texas_holdem_poker(
    callback_query: CallbackQuery,
    redis: Redis,
    interface: Interface,
    settings: Settings,
    scheduler: AsyncIOScheduler,
) -> None:
    access = uuid.uuid4().hex
    redis_callback_data_key = uuid.uuid4().hex

    await redis.set(name=redis_callback_data_key, value=access)

    try:
        await interface.request(
            method=AddGame(
                access=access,
                sb_bet=settings.small_blind,
                bb_bet=settings.small_blind * 2,
                bb_mult=settings.big_blind_multiplication,
                min_raise=settings.small_blind * 2,
            ),
        )
    except LikeInterfaceError as e:
        logger.exception(e)

        return await callback_query.answer(text="Failed to create game")

    await callback_query.bot.edit_message_text(
        inline_message_id=callback_query.inline_message_id,
        text=f"Texas Holdem Poker\n\n"
        f"Stack: {settings.small_blind * 2 * settings.big_blind_multiplication}\n\n"
        f"SB/BB: {settings.small_blind}/{settings.small_blind * 2}",
        reply_markup=join_inline_keyboard_builder(
            bot=callback_query.bot,
            redis_callback_data_key=redis_callback_data_key,
            game=Game.TEXAS_HOLDEM_POKER.value,
        ).as_markup(),
    )
    return None

@router.callback_query(
    CreateGameCallbackData.filter(),
    As(Settings, "settings"),
)
async def create_game_handler(
    callback_query: CallbackQuery,
    callback_data: CreateGameCallbackData,
    redis: Redis,
    interface: Interface,
    settings: Settings,
    scheduler: AsyncIOScheduler,
) -> None:
    if callback_data.game == Game.TEXAS_HOLDEM_POKER.value:
        return await create_texas_holdem_poker(
            callback_query=callback_query,
            redis=redis,
            interface=interface,
            settings=settings,
            scheduler=scheduler,
        )

    return await callback_query.answer(text="Sorry, Game Not Supported Yet!")


from Node import Node

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, value):
        node = Node(value)

        if self.head == None:
            self.head = node
            self.tail = node
            return

        self.tail.next = node
        self.tail = node

    def isPalindrome(self, list: Node):
        vector = []

        while list != None:
            vector.append(list.val)
            list = list.next

        first_pointer = 0
        last_pointer = len(vector) - 1

        for i in vector:
            if vector[first_pointer] != vector[last_pointer]:
                return False

            if last_pointer <= first_pointer:
                return True

            first_pointer += 1
            last_pointer -= 1

    def print(self, node):

        current_node = node

        while current_node != None:
            print(current_node.val)
            current_node = current_node.next

    def get_root(self):
        return self.head

list = LinkedList()

list.add(1)
list.add(0)
list.add(0)
list.add(1)

node = list.get_root()

list.isPalindrome(node)


T = int(input())
for test in range(1,1+T):
    bit = input()
    ans = 0
    if bit[0] == '1': ans += 1

    for i in range(0,len(bit)-1):
        if bit[i] != bit[i+1]:
            ans += 1
    print(f'#{test} {ans}')

1289_원재의_메모리_복구하기.py


import random

def play():
    user = input("guess any ??? 'r' for rock ,'p' for paper, 's' for scissors:\n ")[0].lower()
    if user.isdigit():
        print("please enter letter not digit")
    com = random.choice(['r','p','s'])
    print(com)

    if user == com:
        return  "it is a tie"
    if is_win(user,com):
        return  'you won'
    else:
        return "you lose"

def is_win(player,oppent):

    if(player== 'r' and oppent == 's') or (player== 's' and oppent == 'p') or (player== 'p' and oppent == 'r'):
        return True

print(play())


N, M, K = map(int, input().split())
nodes = [[] for _ in range(N+1)]
for _ in range(M):
	s, e = map(int, input().split())
	nodes[s].append(e)
	nodes[e].append(s)

visit = [0]*(N+1)
visit[K] = 1
n = 1
pre = -1
while pre != K:
	if nodes[K]:
		nodes[K].sort()
		m = 0
		for k in nodes[K]:
			if visit[k] == 0:
				m = k
				visit[m] = 1
				n += 1
				pre = K
				K = m
				break
		else:
				break
	else:
		break

print(n, K)


import numpy as np
from sklearn.metrics import ndcg_score
from src.constants import lm

def hit_att(ascore, labels, ps = [100, 150]):
	res = {}
	for p in ps:
		hit_score = []
		for i in range(ascore.shape[0]):
			a, l = ascore[i], labels[i]
			a, l = np.argsort(a).tolist()[::-1], set(np.where(l == 1)[0])
			if l:
				size = round(p * len(l) / 100)
				a_p = set(a[:size])
				intersect = a_p.intersection(l)
				hit = len(intersect) / len(l)
				hit_score.append(hit)
		res[f'Hit@{p}%'] = np.mean(hit_score)
	return res

def ndcg(ascore, labels, ps = [100, 150]):
	res = {}
	for p in ps:
		ndcg_scores = []
		for i in range(ascore.shape[0]):
			a, l = ascore[i], labels[i]
			labs = list(np.where(l == 1)[0])
			if labs:
				k_p = round(p * len(labs) / 100)
				try:
					hit = ndcg_score(l.reshape(1, -1), a.reshape(1, -1), k = k_p)
				except Exception as e:
					return {}
				ndcg_scores.append(hit)
		res[f'NDCG@{p}%'] = np.mean(ndcg_scores)
	return res


# import time, This file/module read the user file

import datetime  # Import all?
filename = 'DefaultUser.txt'

def create_attention_lists(userphoneandmail):
    users = []  # List [
    phones = []  # List of alarms
    status_phones = []   #  List of Status :
    to_mail_list = []   #  List of mail
    status_mail = []   #  Mail status
    user_log = [] # Build list of string to report, Each warning and error should be a line.
      # Or use a file reference and add new string? One log for each start session.
      # Possible to copy a file with open session with contents included?
      # HeaderOnTable= "User" "/t" "Acesslevel" "/t" "Celluar phones" "/t" "Voice phone" "/t" "Mail adress" "/t"
      # "Created" "/t" "Valid until" "/t" "User password" Vände jag på / \?
    logstring = ""
    start = "StartOfTable"
      # EndOfF *undantag*
    try:
        user_file = open(userphoneandmail,'r') # The reference to file? Not the  name!?
        row = 0
        for line in user_file:
            row = row+1
            if line.strip() == (start): # Sort out where the table starts
                found_table_start = True
                break # Jump to read line. Header infromation is not used from text file
            else:
                found_table_start=False # Use false to create an error log if wrong file o
                #  user_log.append("Didn't find file ", userphoneandmail)
                # logstring = logstring +"Didn't find file ", userphoneandmail)
        for line in user_file:
            users.append(line)  #Skip this line?
            row = row+1
            line = line.strip()  #tar bort radslut?
            try:
                acess_level, user_phone,e_mail,valid_until = line.split (',') # The pattern must match. replace with try?
                # Should be  possible to ignore if more fields are added? Check how CSV modules work
                #What happens if blankrow are added?
                try :
                    Year,Month,Day =valid_until.split ('-') # If format doesn't match on the string it assume there should be no limit
                    Year= int(Year) # Convert to integer to use in date function
                    Month= int(Month)
                    Day= int(Day)
                    AcessUntil = datetime.datetime (Year,Month,Day)
                    CurrentTime =datetime.datetime.now ()
                    if AcessUntil > CurrentTime: # Don't add guest user which date have passed to  the list
                        use_line =True
                    else:
                        use_line =False # The user that have pass date should be removed from list
                except ValueError:
                    use_line = True
                if use_line : # Create list of phone and mail to inform with alarm as bugler or  fire
                    phone_check = list(user_phone)
                    phone_number_length = len (user_phone)
                    pc2 = phone_check[:1]  # 0 didn't work contain 0 or + , (Capital letter? ignored for the  moment)
                    # print (pc2)
                    pc1 = ''.join(phone_check[1:])
                    # print (pc1) Skippa felsökning lägg det på format vid inmatning stora bokstäver. #*- finns också
                    phones.append (user_phone) # phone number with capital letter exist in US and UK.
                    # No check for insane  number yet
                    use_mail = e_mail.find ('@') > 0  # Do a simple check that @ is included.
                                                    # Use variabel since bad mail can be added in both mail list
                    if use_mail:
                        to_mail_list.append(e_mail) # No sanity check on mail yet. Wiki have a defintion of unvalid e-mail adress
                    else:
                        mailwithnosnabel = 'Time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())+'Bad mail in line'+str(row)+" "+str(line)+'in file '+str(userphoneandmail)
                        user_log.append(mailwithnosnabel) #Varför ger inte denna rad fel?
                    if acess_level== '3': # Create  list of  phone  for  status  or  just larm (Enum with string?)
                        status_phones.append (user_phone) # Some phone numbee will be in two  list
                        if use_mail:
                            status_mail.append (e_mail)  # Status mail adress is also larm no need to add twice
            except ValueError:
                # user_log.append("Row ",row," ",line,'in file ',userphoneandmail," bad format")
                add_this_string = 'Time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())+"row "+str(row)+str(line)+" in file "+str(userphoneandmail)+" bad format(empty value error?)"
                user_log.append(add_this_string)
                # 'in file ', user_file, " bad format")
                # print ("Row ",row," ",line,'in file ',user_file," bad format")
            except TypeError:
                badline = 'Time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())+"row "+str(row)+": "+str(line)+" in file "+str(userphoneandmail)
                #  print ('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
                user_log.append (badline)
        user_file.close ()
        if found_table_start :
            phones = set (phones) # Delete  phone used twice. Set changes the order but is not important
            to_mail_list =set (to_mail_list)
            status_mail = set (status_mail)
            status_phones = set (status_phones)
        else:
            missingstartrow = 'Time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())+" Didn't found "+str(start)+' in file '+str(userphoneandmail)
            user_log.append (missingstartrow)#Hur hittar jag path?
            # Och hur ser den ut i byggd miljö?
    except FileNotFoundError:
        user_log.append ("Didn't find file ",userphoneandmail)

    # print (user_log)
    return phones, to_mail_list,status_phones, status_mail, user_log

AlarmPhones,AlarmMail,StatusP,StatusM,Log = create_attention_lists(filename) # Order from defs, Create new list drop error/warninng

print (Log)
LarmMessages = (AlarmMail, AlarmPhones) #create new tupples of phone an mail to use depending on use case to different user
StatusMessages = (StatusM, StatusP)
print (LarmMessages),
print (StatusMessages)
# print (create_attention_lists(filename))


import copy

alist = [2, 4, 5, 6, 8, 7, 7, 7, 7]
# # 第一种方法
blist = copy.deepcopy(alist)
for i in alist:
    if i % 2 == 0:
        blist.remove(i)
print(blist)
#
# # 第二种方法
b = [i for i in alist if i % 2 != 0]
print(b)
#
# # 第三种方法
for i in alist[::-1]:
    if i % 2 == 0:
        alist.remove(i)
print(alist)
# 第四种方法
while 7 in alist:
    alist.remove(7)
print(alist)

"""
引用/深拷贝/浅拷贝
先分为：
    不可变对象：number（数字）string（字符串） tuple（元组）:number和string在 a = 1,b =1 ,a=b=1,内存地址一样。
                                                        tuple a=b=1地址一样,a =1 b=1时候地址不一样
    可变对象：list[],dict{},set()
"""
a, b, c = 14325243532452143214, "aa", ("aa",)
a1, b1, c1 = a, b, c

#


import socket
import time
import threading

UDP_IP = "192.168.0.120"
UDP_PORT = 7191
spray_off_msg = b"0-Off"
spray_on_msg = b"1-On"
lighting_msg = "L="
thread_run = True

def listen_for_udp(sock):
    global thread_run
    sock.connect((UDP_IP, UDP_PORT))
    sock.settimeout(2)
    while thread_run:
        try:
            data, addr = sock.recvfrom(1024)
            print("received message:", data, addr)
        except socket.timeout:
            pass

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
listen_UDP = threading.Thread(target=listen_for_udp, args=(sock,))
listen_UDP.start()
for i in range(2):

    if i % 2 == 0:
        sock.sendto(spray_off_msg, (UDP_IP, UDP_PORT))
        print("UDP {}:{} {}".format(UDP_IP, UDP_PORT, spray_off_msg))
    else:
        sock.sendto(spray_on_msg, (UDP_IP, UDP_PORT))
        print("UDP {}:{} {}".format(UDP_IP, UDP_PORT, spray_on_msg))

    light_lev_msg = bytes(lighting_msg + str(i*10), 'utf-8')
    sock.sendto(light_lev_msg, (UDP_IP, UDP_PORT))
    print("UDP {}:{} {}".format(UDP_IP, UDP_PORT, light_lev_msg))

    time.sleep(5.0)

thread_run = False
time.sleep(5.0)


# Add element to a list

# Concatenation
c = [1, 2] + [3, 4]
assert c == [1, 2, 3, 4]

# Append a list
c = [1, 2]
c += [3, 4]
assert c == [1, 2, 3, 4]

# Append an element
# noinspection PyListCreation
app = [1, 2]
app.append(3)
assert app == [1, 2, 3]


import random
import time
from team import teams
from innings import innings
import os

rows, columns = os.popen('stty size', 'r').read().split()
columns = int(columns)

class gameplay:
    def __init__(self):
        self.team1_name = input('\nEnter your team1 name: \n')
        self.team2_name = input('Enter your team2 name: \n')
        self.order = [None, None]
        self.inning1_stats = None
        self.inning2_stats = None

    def preplay(self):
        self.team1, self.team2 = teams().generate_team()

        def toss():
            team1_toss = input('Choose Heads(h) or Tails(t): ').lower()
            toss_result = str(random.choice('ht'))

            if team1_toss == toss_result and team1_toss in 'ht':
                self.order = [self.team1_name, self.team2_name]
            elif team1_toss != toss_result and team1_toss in 'ht':
                self.order = [self.team2_name, self.team1_name]
            else:
                return toss()

            team1_toss = 'Heads' if team1_toss == 'h' else 'Tails'
            toss_result = 'Heads' if toss_result == 'h' else 'Tails'
            print('-'*int(columns))
            print('\n',  self.team2[0][0] + ' spins the coin and ' + self.team1[0][0] + ' calls ' + team1_toss + '. ' + toss_result + ' it is.', '\n')
            print('\n', self.order[0] + ' win and decide to bat first')
            print('-'*int(columns))

        toss()

    def play(self):

        bat = self.team1 if self.order[0] == self.team1_name else self.team2
        bowl = self.team1 if self.order[1] == self.team1_name else self.team2

        self.first_innings, self.inning1_stats = innings(self.order[0] , bat, bowl, 1)
        print('\n\n','End of First Innings...')
        print('Second Innings will begin in a minute...','\n\n')
        time.sleep(30)
        self.second_innings, self.inning2_stats = innings(self.order[1], bowl, bat, 2, int(self.first_innings[0]))

    def postplay(self):
        inning1_bat = self.inning1_stats[0]
        inning1_bowl = self.inning1_stats[1]
        inning1_bat_top3 = sorted(inning1_bat, key= lambda x: x[1])[::-1]
        inning1_bowl_top3 = sorted(inning1_bowl, key= lambda x: x[3])[::-1]

        inning2_bat = self.inning2_stats[0]
        inning2_bowl = self.inning2_stats[1]
        inning2_bat_top3 = sorted(inning2_bat, key= lambda x: x[1])[::-1]
        inning2_bowl_top3 = sorted(inning2_bowl, key= lambda x: x[3])[::-1]

        print('\n\n')
        print('-'*columns)
        print(self.order[0].ljust(columns-25), str(self.first_innings[2]) + ' OVERS','  ', self.first_innings[0], '-', self.first_innings[1])
        print('-'*columns)
        print('\n')
        print(str(inning1_bat_top3[0][0]).ljust(20),'  ', str(inning1_bat_top3[0][1]).ljust(5), '(',str(inning1_bat_top3[0][2]).ljust(3),')', '\t\t', str(inning1_bowl_top3[0][0]).ljust(20), '  ',str(inning1_bowl_top3[0][2]).ljust(5),'-',str(inning1_bowl_top3[0][3]).ljust(2))
        print('\n')
        print(str(inning1_bat_top3[1][0]).ljust(20),'  ', str(inning1_bat_top3[1][1]).ljust(5), '(',str(inning1_bat_top3[1][2]).ljust(3),')', '\t\t', str(inning1_bowl_top3[1][0]).ljust(20), '  ',str(inning1_bowl_top3[1][2]).ljust(5),'-',str(inning1_bowl_top3[1][3]).ljust(2))
        print('\n')
        print(str(inning1_bat_top3[2][0]).ljust(20),'  ', str(inning1_bat_top3[2][1]).ljust(5), '(',str(inning1_bat_top3[2][2]).ljust(3),')')
        print('-'*columns)
        print('\n')

        print('-'*columns)
        print(self.order[1].ljust(columns-25), str(self.second_innings[2]) + ' OVERS','  ', self.second_innings[0], '-', self.second_innings[1])
        print('-'*columns)
        print('\n')
        print(str(inning2_bat_top3[0][0]).ljust(20),'  ', str(inning2_bat_top3[0][1]).ljust(5), '(',str(inning2_bat_top3[0][2]).ljust(3),')', '\t\t', str(inning2_bowl_top3[0][0]).ljust(20), '  ',str(inning2_bowl_top3[0][2]).ljust(5),'-',str(inning2_bowl_top3[0][3]).ljust(2))
        print('\n')
        print(str(inning2_bat_top3[1][0]).ljust(20),'  ', str(inning2_bat_top3[1][1]).ljust(5), '(',str(inning2_bat_top3[1][2]).ljust(3),')', '\t\t', str(inning2_bowl_top3[1][0]).ljust(20), '  ',str(inning2_bowl_top3[1][2]).ljust(5),'-',str(inning2_bowl_top3[1][3]).ljust(2))
        print('\n')
        print(str(inning2_bat_top3[2][0]).ljust(20),'  ', str(inning2_bat_top3[2][1]).ljust(5), '(',str(inning2_bat_top3[2][2]).ljust(3),')')
        print('-'*columns)
        if self.first_innings[0] > self.second_innings[0]:
            m = self.order[0] + ' wins by ' + str(self.first_innings[0] - self.second_innings[0]) + ' runs.'
        elif self.first_innings[0] < self.second_innings[0]:
            m = self.order[1] + ' wins by ' + str(10 - self.second_innings[1]) + ' wickets.'
        else:
            m = 'Match draw.'
        print(m.center(columns))
        print('-'*columns)
        print('\n')

match = gameplay()
match.preplay()
match.play()
match.postplay()


from django.shortcuts import redirect, render
from django.urls import is_valid_path
from .forms import QuestionForm, CommentForm
from .models import Question, Comment

# Create your views here.
def index(request):
    questions = Question.objects.all()
    context = {
        'questions': questions,
    }
    return render(request, 'eithers/index.html', context)

def create(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save()
            return redirect('eithers:index')
    else:
        form = QuestionForm()
    context = {
        'form':form
    }
    return render(request, 'eithers/create.html', context)

def detail(request, pk):
    question = Question.objects.get(pk=pk)
    comment_form = CommentForm()
    comments = question.comment_set.all()
    context = {
        'question': question,
        'comment_form': comment_form,
        'comments': comments,
    }
    return render(request, 'eithers/detail.html', context)

def comments_create(request, pk):
    question = Question.objects.get(pk=pk)
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.question = question
        comment.save()
    return redirect('eithers:detail', pk)


import bpy, time, struct, json, math, mathutils
from bpy.props import *

bl_info = {
    "name": "Export fake.grav map",
    "author": "literallyvoid",
    "blender": (2, 78, 0),
    "location": "File > Export > FGM",
    "description": "pls",
    "category": "Import-Export"
    }

class ExportFGM(bpy.types.Operator):
    bl_idname = "export.fgm"
    bl_label = "Export FGM"

    filepath = StringProperty(subtype = "FILE_PATH", name = "File Path", description = "Filepath for exporting", maxlen = 1024, default = "")

    def execute(self, context):

        def t(x, y = None):
            if y == None:
                y = x.y
                x = x.x
                return mathutils.Vector([x, -y])
            else:
                return (x, -y)

        data = []
        objects = []
        for i in range(20):
            objects.append([])
            for o in context.scene.objects:
                if o.layers[i]:
                    objects[-1].append(o)
        for layer in range(20):
            layerData = {"objects": []}
            for obj in objects[layer]:
                if obj.type == "MESH":
                    if "arc" in obj.name.lower():
                        matrix = obj.matrix_world
                        x, y = (matrix * mathutils.Vector([0, 0, 0]))[:2]
                        x2, y2 = (matrix * mathutils.Vector([1, 0, 0]))[:2]
                        x, y = t(x, y)
                        x2, y2 = t(x2, y2)
                        r = math.degrees(math.atan2(y2 - y, x - x2))

                        size = 0
                        for i in range(8):
                            for j in range(3):
                                size = max(size, obj.bound_box[i][j])

                        angles = []
                        for v in obj.data.vertices:
                            nang = math.degrees(math.atan2(t(v.co).y, t(v.co).x)) + r
                            for o in angles:
                                while nang < o - 180:
                                    nang += 360
                                while nang > o + 180:
                                    nang -= 360
                            angles.append(nang)
                        angles = list(sorted(angles))
                        layerData["objects"].append(["arc", t(obj.location).x, t(obj.location).y, size, angles[0] + 180, angles[-1] + 180])
                    else:
                        for e in obj.data.edges:
                            v1 = t(obj.matrix_world * obj.data.vertices[e.vertices[0]].co)
                            v2 = t(obj.matrix_world * obj.data.vertices[e.vertices[1]].co)
                            layerData["objects"].append(["line", v1.x, v1.y, v2.x, v2.y])
                elif obj.type == "CURVE":
                    mesh = obj.to_mesh(context.scene, True, "RENDER")
                    properties = {}
                    if "lava" in obj.name.lower():
                        properties = {"onTouch": "restartLevel"}
                    for e in mesh.edges:
                        v1 = t(obj.matrix_world * mesh.vertices[e.vertices[0]].co)
                        v2 = t(obj.matrix_world * mesh.vertices[e.vertices[1]].co)
                        layerData["objects"].append(["line", v1.x, v1.y, v2.x, v2.y, properties])
                    bpy.data.meshes.remove(mesh)
                elif obj.type == "EMPTY":
                    if "spawn" in obj.name.lower():
                        matrix = obj.matrix_world
                        x, y = (matrix * mathutils.Vector([0, 0, 0]))[:2]
                        x2, y2 = (matrix * mathutils.Vector([1, 0, 0]))[:2]
                        x, y = t(x, y)
                        x2, y2 = t(x2, y2)
                        r = -math.degrees(math.atan2(y2 - y, x - x2)) + 180
                        layerData["objects"].append(["playerSpawn", x, y, r])
                    elif "portal" in obj.name.lower():
                        layerData["objects"].append(["portal", t(obj.location).x, t(obj.location).y])
                elif obj.type == "FONT":
                    matrix = obj.matrix_world
                    x, y = (matrix * mathutils.Vector([0, 0, 0]))[:2]
                    x2, y2 = (matrix * mathutils.Vector([1, 0, 0]))[:2]
                    x, y = t(x, y)
                    x2, y2 = t(x2, y2)
                    r = -math.degrees(math.atan2(x2 - x, y2 - y)) + 90
                    layerData["objects"].append(["text", obj.data.body, obj.data.size, t(obj.location).x, t(obj.location).y, r])
            if len(layerData["objects"]):
                data.append(layerData)
        fi = open(self.properties.filepath, "w")
        fi.write(json.dumps(data))
        fi.close()

        return {"FINISHED"}

    def invoke(self, context, event):
        wm = context.window_manager
        wm.fileselect_add(self)
        return {'RUNNING_MODAL'}

def menu_func(self, context):
    self.layout.operator(ExportFGM.bl_idname, text = "FGM", icon = "BLENDER")

def register():
    bpy.utils.register_class(ExportFGM)
    bpy.types.INFO_MT_file_export.append(menu_func)

def unregister():
    bpy.utils.unregister_class(ExportFGM)
    bpy.types.INFO_MT_file_export.remove(menu_func)

if __name__ ==  "__main__":
    register()


import boto3

# getting the dynamodb resource
dynamodb = boto3.resource('dynamodb')

table_name = 'songs'
# resource representing a dynamodb table
table = dynamodb.Table(table_name)

song_id = '5'

def update_item():
    print('Updating item id = {} from the dB\n'.format(song_id))

    # get_item(...)
    # get the item from the table.
    response = table.get_item(
        Key={
            'song_id': song_id
        }
    )

    if 'Item' in response:
        # update_item(...)
        # update an item from the table based on the key.
        response = table.update_item(
            Key={
                'song_id': song_id
            },
            UpdateExpression="set artist = :g",
            ExpressionAttributeValues={
                ':g': "Butterfly"
            }
        )

        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print('Item updated with status code = {} OK'.format(response['ResponseMetadata']['HTTPStatusCode']))
        else:
            print('Some error occurred while updating the item from the dB')
    else:
        print('Item id = {} not found in the dB'.format(song_id))

update_item()


from apibase import AbstractTxnHost, MakeArgs
import asyncio
import logging
import zmq

logger = logging.getLogger('apipeer.hardhash')

#----------------------------------------------------------------#
# ServiceA
#----------------------------------------------------------------#
class ServiceA(AbstractTxnHost):
  def __init__(self, connector, brokerId, *args, **kwargs):
    super().__init__(connector, brokerId)
    self.__dict__['NOTIFY'] = self._NOTIFY
    self.__dict__['TESTX'] = self._TESTX

  @classmethod
  def make(cls, context, actorId, packet):
    logger.info(f'{cls.__name__}, creating hardhash service, packet : {str(packet)}')
    connector = context.get(packet.taskId)
    if not connector:
      makeArgs = MakeArgs(
          sockType=zmq.DEALER,
          sockKw={zmq.IDENTITY:packet.taskId},
          conn=[context.hhDb])
      connector = context.addConn(packet.taskId, makeArgs)
      logger.info(f'!!! ServiceA, {packet.taskId}, added connector {connector.cid}')
    return cls(connector, context.hhId, actorId)

  def __getitem__(self, key):
    if key in self.__dict__:
      return self.__dict__[key]
    return getattr(self, key)

  # -------------------------------------------------------------- #
  # __call__
  # __call__ returns coroutine serve, which is intended to be final
  # This enables a descendent class to override __call__ with special
  # options
  # ---------------------------------------------------------------#
  async def __call__(self):
    logger.info(f'### {self.hostname} is starting ...')
    self.active.set()
    await self.serve()

  #----------------------------------------------------------------#
  # perform
  #----------------------------------------------------------------#
  async def perform(self, request, *args):
    logger.info(f'{self.hostname}, got request : {request}')
    response = await self[request](*args)
    if response:
      await self.send(response,self.name)

  #----------------------------------------------------------------#
  # _TESTX - end of transmission
  #----------------------------------------------------------------#
  async def _TESTX(self, packet):
    logger.info(f'{self.hostname}, TESTX called : {str(packet)} ...')
    await asyncio.sleep(0.1)
    return [201,{'message':'TESTX is successful'}]

  #----------------------------------------------------------------#
  # _NOTIFY - end of transmission
  #----------------------------------------------------------------#
  async def _NOTIFY(self, taskId):
    logger.info(f'{self.hostname}, notified ...')
    await asyncio.sleep(0.1)
    self.active.clear()


""" Counter를 매 루프마다 생성하는 것은 매우 비효율적이다.
편의성을 위해 Counter(a) - Counter(b)와 같은 형태로 연산을 수행하려면
각각의 객체를 생성해야하는데 시간초과를 할 가능성이 높다.

"""
from collections import Counter

def solution(gems):
    kinds = len(set(gems))
    n = len(gems)
    left = right = 0
    answer = [-1, 1_000_000]
    cache = Counter([gems[left]])
    while left <= right and right < n:
        if len(cache) < kinds:
            right += 1
            if right == n:
                break
            cache[gems[right]] += 1

        elif len(cache) == kinds:
            if answer[1] - answer[0] > right - left:
                answer = [left + 1, right + 1]
            cache[gems[left]] -= 1
            if cache[gems[left]] <= 0:
                del cache[gems[left]]
            left += 1
    return answer

print(solution(["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"]))


class Solution:
    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
        pairs = [(n1,n2) for n1,n2 in zip(nums1,nums2)]
        pairs.sort(key=lambda x: x[1], reverse=True)

        minHeap = []
        sm = 0
        ans = 0

        for n1,n2 in pairs:
            sm += n1
            heapq.heappush(minHeap, n1)
            if len(minHeap) > k:
                n1Pop = heapq.heappop(minHeap)
                sm -= n1Pop
            if len(minHeap) == k:
                ans = max(ans, sm*n2)

        return ans

# intuition:
# 1. Here DP won't work because the constraints are too high and we won't get too many overlapping subproblems.
# 2. A greedy approach with respect to the first array would be sufficient if we sort the second array in descending order.
# 3. We need to maximize the sum of the first array and the product of the second array. So first of all we will sort the 2nd array in descending order and keep checking what is the maximum sum possible if we take the current element of the 2nd array as minimum.
# 4. For keeping only k elements, we will use a min heap so that whenever the size of the heap becomes greater than k, we will pop the minimum element from the heap.
# 5. We will keep a running sum of the elements in the heap and multiply it with the current element of the 2nd array and update the answer.

# solution:
# 1. Create an array of pairs of nums1 and nums2 and sort it in descending order of nums2.
# 2. Create a min heap and a variable sm to keep track of the sum of the elements in the heap. Also create a variable ans to keep track of the answer.
# 3. Iterate over the array of pairs and add the current element of nums1 to sm and push it to the heap. If the size of the heap becomes greater than k, pop the minimum element from the heap and subtract it from sm.
# 4. If the size of the heap becomes equal to k, update the answer by multiplying sm with the current element of nums2.
# 5. Return the answer.

# Time Complexity: O(nlogn)

# Space Complexity: O(n)


import os

from filetypes import *
import filetypes

class FileGrouper(object):
    def __init__(self, dir="", prefix_len=5, types=[]):
        self.directory = dir
        self.prefix_len = prefix_len
        self.type_map = {}
        self.outlier_dict = dict() #String (prefix) : list[file if type not in types or group already full]
        #For each prefix; do you already have a group with that prefix
        #Is the file already in the group

        for filetype in types:
            self.type_map[filetype.typename] = filetype.comp_func

        self.groups_ = dict()
        self.walk_directory()

    def walk_directory(self):
        #curr_group = FileGroup(self.type_map.keys())

        #while not curr_group.full:
        for root, dirs, files in os.walk(self.directory):
            for file in files:
                if file.startswith("."):
                    continue
                pref = file[:self.prefix_len]
                if pref not in self.groups_:
                    self.groups_[pref] = FileGroup(self.type_map.keys())
                curr_group = self.groups_[pref]
                curr_group.prefix = pref
                if pref in self.groups_:
                    if self.group_full(curr_group):
                        curr_group.outliers_extra.append(file)
                    if not self.group_full(curr_group):
                        self.add_file(curr_group, os.path.join(root, file))

    def outliers(self):
        return [x for x in self.groups_.values() if x.outliers_extra or not self.group_full(x)]

    def group_full(self, group):
        found_empty = False
        group_vars = vars(group)
        for x in self.type_map.keys():
            if not group_vars[x]:
                found_empty = True
        if found_empty:
            return False
        else:
            group.full = True
        return True

    def add_file(self, group, file):
        for type, func in self.type_map.items():
            if func(file):
                vars(group)[type] = file
                group.empty = False
                self.group_full(group)
                return

    def prefix_in_groups(self, prefix):
        for group in self.groups_:
            if group.prefix == prefix:
                return True
        return False

    def groups(self):
        return self.groups_.items()

class FileGroup(object):
    def __init__(self, file_types=[], prefix=""):
        for x in file_types:
            setattr(self, x, "")

        self.prefix = prefix
        self.full = False
        self.empty = True
        self.outliers_extra = []

    def prefix_match(self, input):
        if input[:len(self.prefix)] == self.prefix:
            return True
        return False


import time;
import hashlib;
import logging;

from resources.lib.modules import utils;

try:
    from sqlite3 import dbapi2 as database;

except:
    from pysqlite2 import dbapi2 as database;

logger = logging.getLogger('funimationnow');

def getToken(system):

    try:

        dbcon = database.connect(utils.tokensFile);
        dbcur = dbcon.cursor();

    except:

        return None;

    try:

        dbcur.execute("SELECT * FROM tokens WHERE system IN ('%s')" % system);

        match = dbcur.fetchone();

        if match is not None:

            return match;

        else:
            return None;

    except Exception as inst:
        logger.error(inst);

        return None;

def setToken(system, user, token):

    logger.debug('Attempting to update tokens DB.');

    try:

        logger.debug('Validating DB file exists.');

        utils.makeFile(utils.dataPath);

        dbcon = database.connect(utils.tokensFile);
        dbcur = dbcon.cursor();

        logger.debug('Creating tokens table if it does not exist.');

        dbcur.execute("CREATE TABLE IF NOT EXISTS tokens (""system TEXT, ""user TEXT, ""token TEXT"", ""UNIQUE(system)"");");

        try:

            logger.debug('Attempting to delete tokens entry.');

            dbcur.execute("DELETE FROM tokens WHERE system IN ('%s')" % (system));

        except Exception as inst:
            logger.error(inst);

        try:

            logger.debug('Attempting to insert tokens entry.');

            dbcur.execute("INSERT INTO tokens Values (?, ?, ?)", (system, user, token));

        except Exception as inst:
            logger.error(inst);

        logger.debug('Commiting DB change.');

        dbcon.commit();

        return True;

    except Exception as inst:

        logger.error(inst);

        return False;


import zmq
import json

def main():
    zc = zmq.Context()
    zs = zc.socket(zmq.PULL)
    zs.connect('ipc:///var/run/bluewalker-gateway/relay.zmq')
    while True:
        print(json.dumps(zs.recv_json()))

if __name__ == '__main__':
    main()


'''
Given a graph, return the number of strongly connected components.
'''

def build_graph(n: int, edges: list[tuple[int, int]]) -> dict[int, list[int]]:
    graph: dict[int, list[int]] = {v: [] for v in range(n)}
    for u, v in edges:
        graph[u].append(v)
    return graph

def transpose_graph(graph: dict[int, list[int]]) -> dict[int, list[int]]:
    tgraph: dict[int, list[int]] = {v: [] for v in range(len(graph))}

    for u, adj in graph.items():
        for v in adj:
            tgraph[v].append(u)

    return tgraph

def dfs(graph: dict[int, list[int]], vertex: int, visited: set[int], r: list[int] | None) -> None:
    for adj in graph[vertex]:
        if adj not in visited:
            visited.add(adj)
            dfs(graph, adj, visited, r)

    if r is not None:
        r.append(vertex)

def strongly_connected_components(n: int, edges: list[tuple[int, int]]) -> int:
    graph = build_graph(n, edges)

    # DFS to save finish time by appending to r
    visited: set[int] = set()
    r: list[int] = []
    for vertex in range(n):
        if vertex not in visited:
            dfs(graph, vertex, visited, r)

    # Transpose the graph
    graph = transpose_graph(graph)

    # DFS in ascending order of finish time
    visited = set()
    roots: list[int] = []
    for vertex in r[::-1]:
        if vertex not in visited:
            dfs(graph, vertex, visited, None)
            roots.append(vertex)

    # Roots of the strongly connected components
    return len(roots)

if __name__ == '__main__':
    tests = [
        (
            3,
            [(0, 1), (1, 0), (0, 2)],
            2
        ),
        (
            8,
            [(0, 4), (1, 0), (2, 1), (2, 3), (3, 2), (4, 1),
             (5, 1), (5, 6), (6, 5), (6, 2), (7, 6), (7, 3)],
            4
        ),
    ]

    for n_test, (n, edges, expected) in enumerate(tests):
        result = strongly_connected_components(n, edges)
        if result != expected:
            raise Exception(f'Test #{n_test} failed:'
                            f' result={result}, expected={expected}')
    print('Success!')


import os
from werkzeug.utils import secure_filename
import logging
from logging.handlers import RotatingFileHandler
import random
from flask import Flask, request, jsonify
from spu import SpeechProcessingUnit

current_dir = os.path.dirname(os.path.realpath(__file__))
log_path = os.path.join(current_dir, "log")
if not os.path.exists(log_path):
    os.mkdir(log_path)
LOG_FILENAME = os.path.join(log_path, 'server.log')
LOG_BACKUP_COUNT = 5
LOG_FILE_SIZE_BYTES = 50 * 1024 * 1024

VOICE_DECODE_ERROR = 10
PREDICTION_ERROR = 12
UNKNOWN_ERROR = 21
INVALID_FORMAT = 30
MISSING_ARGUMENTS = 40

errors = {
    VOICE_DECODE_ERROR: "VOICE_DECODE_ERROR",
    PREDICTION_ERROR: "PREDICTION_ERROR",
    UNKNOWN_ERROR: "UNKNOWN_ERROR",
    INVALID_FORMAT: "INVALID_FORMAT_REQ",
    MISSING_ARGUMENTS: "MISSING_ARGUMENTS_REQ"
}

def init_logger(app):
    handler = RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_SIZE_BYTES, backupCount=LOG_BACKUP_COUNT)
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    loggers = [app.logger]
    for logger in loggers:
        logger.addHandler(handler)

spu_core = SpeechProcessingUnit(fs=16000)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

init_logger(app)

@app.before_request
def log_request():
    app.logger.debug("Request: %s %s", request.method, request.url)

class WebAppException(Exception):
    def __init__(self, error_code, status_code=None):
        Exception.__init__(self)
        self.status_code = 400
        self.exception = Exception
        self.error_code = error_code
        try:
            self.message = errors[self.error_code]
        except:
            self.error_code = UNKNOWN_ERROR
            self.message = errors[self.error_code]
        if status_code is not None:
            self.status_code = status_code

    def to_dict(self):
        rv = dict()
        rv['status'] = 'failed'
        rv['code'] = self.error_code
        rv['message'] = self.message
        return rv

class ThrowsWebAppException(object):
    def __init__(self, error_code, status_code=None):
        self.error_code = error_code
        self.status_code = status_code

    def __call__(self, function):
        def return_function(*args, **kwargs):
            try:
                return function(*args, **kwargs)
            except Exception as e:
                raise WebAppException(self.error_code)

        return return_function

@app.errorhandler(WebAppException)
def handle_exception(error):
    app.logger.exception(error.message)
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@ThrowsWebAppException(error_code=PREDICTION_ERROR)
def vad_prediction(audio_file, threshold):
    vad_annotation = spu_core.apply_vad(file_path=audio_file, threshold=threshold, gpu_number=0)
    vad_out = {"sad_annotation": vad_annotation}
    return vad_out

@app.route('/sad', methods=['POST'])
def vad():
    if request.headers['Content-Type'].startswith('multipart/form-data'):
        try:
            # Remember the paramName was set to 'file', we can use that here to grab it
            file = request.files['file']
            # secure_filename makes sure the filename isn't unsafe to save
            temp_path = os.path.join(current_dir, "temp_data")
            if not os.path.exists(temp_path):
                os.mkdir(temp_path)
            save_path = os.path.join(temp_path, str(random.randint(0, 1000000)) + secure_filename(file.filename))
            # We need to append to the file, and write as bytes
            with open(save_path, 'ab') as temp_file:
                temp_file.seek(0, 2)
                file_byes = file.read()
                temp_file.write(file_byes)

            audio_file = save_path
            threshold = float(request.form["threshold"])
        except:
            raise WebAppException(error_code=MISSING_ARGUMENTS)
        response = jsonify(vad_prediction(audio_file, threshold))
        return response
    else:
        raise WebAppException(error_code=INVALID_FORMAT)

if __name__ == '__main__':
    host = '0.0.0.0'
    port = 5005
    app.run(host=host, port=port, debug=True, use_reloader=False, threaded=False)


import pyarrow  # type: ignore
from pyarrow.cffi import ffi
import rpy2.rinterface as rinterface
import rpy2.robjects as robjects
import rpy2.robjects.conversion as conversion
import rpy2.robjects.packages as packages
import typing
import warnings

rarrow = packages.importr('arrow')

if rinterface.BoolSexpVector(
        rinterface.evalr("""
        utils::packageVersion("arrow") < base::package_version("12.0")
        """)
)[0]:
    warnings.warn('Segfaults may occur with the R package arrow < 12.0')

# make sure a version is installed with the C API
_rarrow_has_c_api = rinterface.BoolSexpVector(
    rinterface.evalr("""
    utils::packageVersion("arrow") >= base::package_version("5.0.0")
    """)
)[0]

if not _rarrow_has_c_api:
    raise ValueError("rpy2_arrow requires R 'arrow' package version >= 5.0.0")

# In arrow >= 7.0.0, pointers can be passed as externalptr,
# bit64::integer64(), or string, all of which prevent possible
# problems with the previous versions which required a double().
_use_r_ptr_string = rinterface.BoolSexpVector(
    rinterface.evalr("""
    utils::packageVersion("arrow") >= base::package_version("6.0.1.9000")
    """)
)[0]

def _rarrow_ptr(ptr) -> typing.Union[str, float]:
    ptr_value = int(ffi.cast('uintptr_t', ptr))
    return str(ptr_value) if _use_r_ptr_string else float(ptr_value)

def _c_ptr_to_int(ptr) -> int:
    return int(ffi.cast('uintptr_t', ptr))

def pyarrow_to_r_array(
        obj: 'pyarrow.lib.Array'
):
    """Create an R `arrow::Arrow` object from a pyarrow Array.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """
    array_ptr = ffi.new('struct ArrowArray*')
    schema_ptr = ffi.new('struct ArrowSchema*')

    obj._export_to_c(_c_ptr_to_int(array_ptr), _c_ptr_to_int(schema_ptr))
    return rarrow.Array['import_from_c'](_rarrow_ptr(array_ptr), _rarrow_ptr(schema_ptr))

def rarrow_to_py_array(
        obj: robjects.Environment
) -> pyarrow.Array:
    """Create a pyarrow array from an R `arrow::Array` object.

    This is sharing the C/C++ object between the two languages.
    """
    array_ptr = ffi.new('struct ArrowArray*')
    schema_ptr = ffi.new('struct ArrowSchema*')

    obj['export_to_c'](_rarrow_ptr(array_ptr), _rarrow_ptr(schema_ptr))
    return pyarrow.lib.Array._import_from_c(_c_ptr_to_int(array_ptr), _c_ptr_to_int(schema_ptr))

def pyarrow_to_r_recordbatch(
        obj: 'pyarrow.lib.RecordBatch'
):
    """Create an R `arrow::RecordBatch` object from a pyarrow RecordBatch.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """
    array_ptr = ffi.new('struct ArrowArray*')
    schema_ptr = ffi.new('struct ArrowSchema*')

    obj._export_to_c(_c_ptr_to_int(array_ptr), _c_ptr_to_int(schema_ptr))
    return rarrow.RecordBatch['import_from_c'](_rarrow_ptr(array_ptr), _rarrow_ptr(schema_ptr))

def rarrow_to_py_recordbatch(
        obj: robjects.Environment
) -> pyarrow.lib.RecordBatch:
    """Create a pyarrow record batch from an R `arrow::Array` object.

    This is sharing the C/C++ object between the two languages.
    """
    array_ptr = ffi.new('struct ArrowArray*')
    schema_ptr = ffi.new('struct ArrowSchema*')

    obj['export_to_c'](_rarrow_ptr(array_ptr), _rarrow_ptr(schema_ptr))
    return pyarrow.lib.RecordBatch._import_from_c(_c_ptr_to_int(array_ptr), _c_ptr_to_int(schema_ptr))

def pyarrow_to_r_recordbatchreader(
        obj: 'pyarrow.lib.RecordBatchReader'
):
    """Create an R `arrow::RecordBatchReader` from a pyarrow RecordBatchReader.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """

    stream_ptr = ffi.new('struct ArrowArrayStream*')
    obj._export_to_c(_c_ptr_to_int(stream_ptr))
    return rarrow.RecordBatchReader['import_from_c'](_rarrow_ptr(stream_ptr))

def rarrow_to_py_recordbatchreader(
        obj: robjects.Environment
) -> pyarrow.lib.RecordBatchReader:
    """Create a pyarrow RecordBatchReader from an R `arrow::RecordBatchReader` object.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """

    stream_ptr = ffi.new('struct ArrowArrayStream*')
    obj['export_to_c'](_rarrow_ptr(stream_ptr))
    return pyarrow.lib.RecordBatchReader._import_from_c(_c_ptr_to_int(stream_ptr))

def pyarrow_to_r_chunkedarray(
        obj: 'pyarrow.lib.ChunkedArray'
):
    """Create an R `arrow::ChunkedArray` object from a pyarrow ChunkedArray.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """
    chunks = tuple(pyarrow_to_r_array(x) for x in obj.chunks)
    res = rarrow.ChunkedArray['create'](*chunks)
    return res

def rarrow_to_py_chunkedarray(
        obj: robjects.Environment
) -> pyarrow.lib.ChunkedArray:
    """Create a pyarrow chunked array from an R `arrow::ChunkedArray` object.

    This is sharing the C/C++ object between the two languages.
    """
    chunks = tuple(rarrow_to_py_array(x) for x in obj['chunks'])
    return pyarrow.chunked_array(chunks)

def pyarrow_to_r_datatype(
        obj: 'pyarrow.lib.DataType'
):
    schema_ptr = ffi.new('struct ArrowSchema*')
    obj._export_to_c(_c_ptr_to_int(schema_ptr))
    return rarrow.DataType['import_from_c'](_rarrow_ptr(schema_ptr))

def rarrow_to_py_datatype(
        obj: robjects.Environment
) -> pyarrow.lib.DataType:
    """Create a pyarrow.lib.DataType from an R `arrow::DataType` object.

    This is sharing the C/C++ object between the two languages.
    """
    schema_ptr = ffi.new('struct ArrowSchema*')
    obj['export_to_c'](_rarrow_ptr(schema_ptr))
    return pyarrow.lib.DataType._import_from_c(_c_ptr_to_int(schema_ptr))

def pyarrow_to_r_field(
        obj: 'pyarrow.lib.Field'
):
    schema_ptr = ffi.new('struct ArrowSchema*')
    obj._export_to_c(_c_ptr_to_int(schema_ptr))
    return rarrow.Field['import_from_c'](_rarrow_ptr(schema_ptr))

def rarrow_to_py_field(
        obj: robjects.Environment
) -> pyarrow.lib.Field:
    """Create a pyarrow.lib.Field from an R `arrow::DataType` object.

    This is sharing the C/C++ object between the two languages.
    """

    schema_ptr = ffi.new('struct ArrowSchema*')
    obj['export_to_c'](_rarrow_ptr(schema_ptr))
    return pyarrow.lib.Field._import_from_c(_c_ptr_to_int(schema_ptr))

_as_arrow_table_from_stream_ptr = rinterface.SexpClosure(
    rinterface.evalr(
        """
        function(recordbatchreader) {
        arrow::as_arrow_table(recordbatchreader)
        }
        """
    )
)

def _pyarrow_table_to_r_table_ri(tbl: pyarrow.lib.Table) -> rinterface.SexpEnvironment:
    """Create an R `arrow` Table to mirror an Arrow Table in `pyarrow`."""
    recordbatchreader = pyarrow_to_r_recordbatchreader(tbl.to_reader())
    return _as_arrow_table_from_stream_ptr(recordbatchreader)

def pyarrow_table_to_r_table(obj: pyarrow.lib.Table):
    """Create an R `arrow::Table` object from a pyarrow Table.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.

    :param:obj: A :class:`pyarrow.lib.Table`.
    :return: The result of conversion rules for R `arrow` `Table` objects.
    By default a :class:`rpy2.robjects.Environment`.
    """
    # `res` is a low-level (rinterface-level) rpy2 object. This is an
    # rpy2 robject-level function. Use the conversion.
    res = _pyarrow_table_to_r_table_ri(obj)
    converter = (
        conversion.get_conversion()  # rpy2 >=3.5.2
        if hasattr(conversion, 'get_conversion') else
        conversion.converter  # rpy2 <3.5.2
    )
    return converter.py2rpy(res)

def rarrow_to_py_table(
        obj: robjects.Environment,
        rpy2py: typing.Optional[
            conversion.Converter] = None
) -> pyarrow.Table:
    """Create a pyarrow Table from an R `arrow::Table` object.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2.
    """

    if rpy2py is None:
        rpy2py = converter
    # TODO: rpy2 conversion forces something a little kludgy here.
    columns = [
        (rpy2py._rpy2py_nc_map[rinterface.SexpEnvironment][x.rclass[0]](x))
        for x in obj['columns']
    ]
    schema = rarrow_to_py_schema(obj['schema'])
    py_table = pyarrow.Table.from_arrays(columns,
                                         schema=schema)
    return py_table

def pyarrow_to_r_schema(
        obj: 'pyarrow.lib.Schema'
):
    """Create an R `arrow::Schema` object from a pyarrow Schema.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """

    schema_ptr = ffi.new('struct ArrowSchema*')
    obj._export_to_c(_c_ptr_to_int(schema_ptr))
    return rarrow.Schema['import_from_c'](_rarrow_ptr(schema_ptr))

def rarrow_to_py_schema(
        obj: robjects.Environment
) -> pyarrow.Schema:
    """Create a pyarrow Schema from an R `arrow::Schema` object.

    This is sharing the C/C++ object between the two languages.
    The returned object depends on the active conversion rule in
    rpy2. By default it will be an `rpy2.robjects.Environment`.
    """

    schema_ptr = ffi.new('struct ArrowSchema*')
    obj['export_to_c'](_rarrow_ptr(schema_ptr))
    return pyarrow.lib.Schema._import_from_c(_c_ptr_to_int(schema_ptr))

converter: conversion.Converter = conversion.Converter(
    'default arrow conversion',
    template=robjects.default_converter
)

# Pyarrow to R arrow.
converter.py2rpy.register(pyarrow.lib.Array, pyarrow_to_r_array)
converter.py2rpy.register(pyarrow.lib.Field, pyarrow_to_r_field)
converter.py2rpy.register(pyarrow.lib.ChunkedArray,
                          pyarrow_to_r_chunkedarray)
converter.py2rpy.register(pyarrow.lib.RecordBatch,
                          pyarrow_to_r_recordbatch)
converter.py2rpy.register(pyarrow.lib.RecordBatchReader,
                          pyarrow_to_r_recordbatchreader)
converter.py2rpy.register(pyarrow.lib.Schema, pyarrow_to_r_schema)
converter.py2rpy.register(pyarrow.lib.Table, pyarrow_table_to_r_table)
converter.py2rpy.register(pyarrow.lib.DataType, pyarrow_to_r_datatype)

# R arrow to pyarrow.
converter._rpy2py_nc_map.update(
    {
        rinterface.SexpEnvironment:
        conversion.NameClassMap(robjects.Environment)
    }
)

# TODO: use complete class name hierarchy to be safer?
converter._rpy2py_nc_map[rinterface.SexpEnvironment].update(
    {
        'Array': rarrow_to_py_array,
        'ChunkedArray': rarrow_to_py_chunkedarray,
        'Field': rarrow_to_py_field,
        'RecordBatch': rarrow_to_py_recordbatch,
        'RecordBatchReader': rarrow_to_py_recordbatchreader,
        'Schema': rarrow_to_py_schema,
        'Table': rarrow_to_py_table,
        'Type': rarrow_to_py_datatype
    }
)


from RacesClass import Human, Elf, Dwarf
from journey import go_on_journey
from hero_actions import check_inventory

def introduce_hero(hero):
    print(f"You're {hero.race} named {hero.name} and your skills are:")
    print(f"Health: {hero.health}\nAttack: {hero.offence}\nDefence: {hero.defence}")

def main_Function():
    counter = 1

    hero_name = input("What's your name? ")

    while True:
        hero_race = input("You're... [Pick your race: Human/Elf/Dwarf ").capitalize()
        if hero_race == "Human":
            hero = Human(hero_name)
            break
        elif hero_race == "Elf":
            hero = Elf(hero_name)
            break
        elif hero_race == "Dwarf":
            hero = Dwarf(hero_name)
            break

    introduce_hero(hero)

    while counter != 6:
        journey_choice = int(input("What are you want to do?\n1-Check your inventory\n2-Go for next journey\n3-Quit\n"))
        print(journey_choice)
        if journey_choice == 1:
            check_inventory(hero)
        if journey_choice == 2:
            go_on_journey(hero)
        if journey_choice == 3:
            quit()
        counter += 1
    print("Story is over. To play launch the game again.")

if __name__ == '__main__':
    main_Function()


# Two ways to load ron.txt in python

# First method
raw_moods = []
raw_genres = []

with  open('./data/ron.txt', 'r') as f:  # read in Ron's data
	for line in f.readlines():
		mood, genre = line.strip().split('\t')
		raw_moods.append(mood)
		raw_genres.append(genre)

# Second method
import numpy as np
data = np.genfromtxt('./data/ron.txt', dtype=str, delimiter='\t')
moods = [x[0] for x in data]
genres = [x[1] for x in data]


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 20 16:59:47 2017

@author: changlue.she
"""
import jieba.posseg as pseg
import jieba
import pandas as pd
import numpy as np
from collections import Counter
jieba.load_userdict('C:/Users/Administrator.NBJXUEJUN-LI/Desktop/project/pythonProj/intel_cust_stastis/userDict.txt')
#---------------------------------------------------------------------------------------------------
#rawdata = pd.read_csv('C:/Users/Administrator.NBJXUEJUN-LI/Desktop/project/MSXF/ZhiChi/Statistic/output/conversation.csv',
#                      header=0,encoding='gbk',usecols=[u'消息目标',u'会话ID',u'消息内容'])
#rawdata = rawdata.loc[rawdata[u'消息目标'] == u'机器人',:]
#rawdata = rawdata.sort([u'会话ID'])

rawdata = pd.read_csv('C:/Users/Administrator.NBJXUEJUN-LI/Desktop/project/MSXF/message feature etl/smsResult.csv',
                      header=0,encoding='gbk' )
rawdata = rawdata.drop_duplicates()
#---------------------------------------------------------------------------------------------------
TF_term = []
IDF_term = []
ALL_term = []
#userIDs = list(rawdata[u'会话ID'])
userIDs = range(len(rawdata['x']))
conversations = list(rawdata[u'x'])
oldidx=None
add = ['used to drop']

for idx,userID in enumerate(userIDs):
    conversation = conversations[idx]
    if  len(conversation)>6:
        conversation = [pair.word for pair in pseg.lcut(conversation) if pair.flag in ['n','ns','vs','nv']]
        if len(conversation)>0:
            if userID!=oldidx:
                 oldidx = userID
                 ALL_term += add
                 tf = dict(Counter(add))
                 IDF_term+=tf.keys()
                 TF_term.append(tf)
                 add = conversation
            else:
                 add+= conversation

TF_term.pop(0)
wordFreq  = dict(Counter(ALL_term))
allDocNum = len(TF_term)
IDF       = dict(Counter(IDF_term))
keyWord   = []
tfidf     = []
for tf in TF_term:
    tmp = 0
    for word in tf.keys():
        tf_idf = tf[word]*np.log(allDocNum/IDF[word])
        if tf_idf>tmp:
            tmp  = tf_idf
            keyW = word
            tfs  = tf_idf
        keyWord.append(keyW)
        tfidf.append(tfs)
        tmp = 0
keyWord = dict(Counter(keyWord))

idxs = np.argsort(-np.array(list(keyWord.values())))[:20]
keywords = [list(keyWord.keys())[idx] for idx in idxs]
wordFreq = [wordFreq[word] for word in keywords]
#save those key words
outfile = pd.DataFrame([keywords,wordFreq])
outfile = outfile.T
dirs = 'C:/Users/Administrator.NBJXUEJUN-LI/Desktop/project/MSXF/message feature etl/关键词句.xlsx'
outfile.to_excel(dirs,encoding='gb18030',index=False )


def notas(*n , sit=False):
    """
    -> Função para analisar notas e a situacao de vários alunos
    :param n: uma ou mais notas dos alunos
    :param sit: valor opcional, indicando a situacao do aluno
    : return: dicionarios com varias informacoes
    """
    dic = {}
    dic['Total'] = len(n)
    dic['Maior'] = max(n)
    dic['Menor'] = min(n)
    dic['Média'] = sum(n)/ len(n)
    if sit:
        if dic['Média'] >= 9:
            dic['Situação'] = 'MUITO BOA'
        elif dic['Média'] >= 7:
            dic['Situação'] = 'BOA'
        elif dic['Média' ] >= 5:
            dic['Situação'] = 'RUIM'
        else:
            dic['Situação'] = 'MUITO RUIM'
    return dic

#Programa principal
resp= notas(10, sit=True)
print(resp)
# help(notas)