import os
import re
import csv
import spacy
import convert2txt

nlp = spacy.load('skill-cv-bn')

def create_dic(filename):
    result = {
                'Filename': filename,
                'Name':[],
                'Number':[],
                'Email':[],
                'Experience':[],
                'Companies':[],
                'Designation':[],
                'Responsibilities':[],
                'Skills':[],
                'Certification':[],
                'Degree':[],
                'Institution':[],
                'Edu_subject':[],
                'Graduation_year':[]
                }
    return result

def get_info(text, dic_name):
    nlp_text = nlp(text)
    for e in nlp_text.ents:
        if e.label_ == 'Name':
            dic_name['Name'].append(e.text)
        elif e.label_ == 'Number':
            dic_name['Number'].append(e.text)
        elif e.label_ == 'Email':
            dic_name['Email'].append(e.text)
        elif e.label_ == 'Experience':
            dic_name['Experience'].append(e.text)
        elif e.label_ == 'Companies':
            dic_name['Companies'].append(e.text)
        elif e.label_ == 'Designation':
            dic_name['Designation'].append(e.text)
        elif e.label_ == 'Responsibilities':
            dic_name['Responsibilities'].append(e.text)
        elif e.label_ == 'Skills':
            dic_name['Skills'].append(e.text)
        elif e.label_ == 'Certification':
            dic_name['Certification'].append(e.text)
        elif e.label_ == 'Degree':
            dic_name['Degree'].append(e.text)
        elif e.label_ == 'Institution':
            dic_name['Institution'].append(e.text)
        elif e.label_ == 'Edu_subject':
            dic_name['Edu_subject'].append(e.text)
        elif e.label_ == 'Graduation_year':
            dic_name['Graduation_year'].append(e.text)

def extract_info(cv_dir):
    extracted_info = []
    files = os.listdir(cv_dir)
    for file in files:
        if file.endswith('.pdf'):
            text = convert2txt.extract_text(cv_dir+file, '.pdf')
            result = create_dic(file)
            get_info(text, result)
            extracted_info.append(result)
        elif file.endswith('.doc'):
            text = convert2txt.extract_text(cv_dir+file, '.doc')
            result = create_dic(file)
            get_info(text, result)
            extracted_info.append(result)
        elif file.endswith('.docx'):
            text = convert2txt.extract_text(cv_dir+file, '.docx')
            result = create_dic(file)
            get_info(text, result)
            extracted_info.append(result)
        elif file.endswith('.txt'):
            with open(cv_dir+file, encoding='utf-8-sig') as f:
                text = f.read()
            result = create_dic(file)
            get_info(text, result)
            extracted_info.append(result)
    return extracted_info

def process(txt):
    data = txt
    data = re.sub(r'â+', ' ', data)
    data = re.sub(r'ï+', ' ', data)
    data = re.sub(r'\\u+', ' ', data)
    data = re.sub(r'â€+', ' ', data)
    data = re.sub(r'™+', ' ', data)
    data = re.sub(r'â€+', ' ', data)
    data = re.sub(r'â+', ' ', data)
    data = re.sub(r'\s+', ' ', data)
    return data

def create_csv_row_dic(headers, dic):
    result = {}
    for i in range(len(headers)):
        if i == 0:
            result[headers[i]] = dic[headers[i]]
        else:
            result[headers[i]] = ', '.join([process(i) for i in dic[headers[i]]])
    return result

def export_to_csv(csv_name, extracted_info):
    with open(csv_name, 'w', newline='', encoding="utf-8") as csv_file:
        headers = [
                'Filename',
                'Name',
                'Number',
                'Email',
                'Experience',
                'Companies',
                'Designation',
                'Responsibilities',
                'Skills',
                'Certification',
                'Degree',
                'Institution',
                'Edu_subject',
                'Graduation_year'
                ]
        writer = csv.DictWriter(csv_file, fieldnames=headers)
        writer.writeheader()
        for dic in extracted_info:
            write_dic = create_csv_row_dic(headers, dic)
            writer.writerow(write_dic)

export_to_csv('skills_report.csv', extract_info('../cv/txt/'))


from django.db import models, transaction
from django.dispatch import receiver
from django.db.models.signals import post_delete
from api.espo_api_client import EspoClientMixin
from django.conf import settings
from petuni_main.celery import app

CRM_DO_NOTHING = 0
CRM_SOFT_DELETE = 1
CRM_TRUE_DELETE = 2

class CRMSignalMixin(EspoClientMixin, models.Model):
    crm_id = models.CharField(max_length=18, null=True, blank=True, unique=True)
    crm_api_path = None
    serializer_class = None
    request_type = None
    queryset = None
    sync_delete = CRM_DO_NOTHING # 0 не делаем ничего, 1 - шлем PATCH, 2 - шлем DELETE

    def get_crm_api_action(self):
        """
        Возвращает action для запроса EspoApi
        """
        assert self.crm_api_path is not None, f'crm_api_path for {self.__class__.__name__} is undefined'
        if self.crm_id:
            return f'{self.crm_api_path}/{self.crm_id}'
        return self.crm_api_path

    @classmethod
    def get_queryset(cls):
        if cls.queryset is None:
            return cls.objects.all()
        return cls.queryset

    @classmethod
    def get_crm_serializer_class(cls):
        """
        Возвращает сериализатор для запроса EspoApi
        """
        assert cls.serializer_class is not None, f'serializer for {cls.__name__} is undefined'
        return cls.serializer_class

    def get_request_type(self):
        """
        Возвращает method для запроса EspoApi
        """
        if self.crm_id:
            return 'PATCH'
        return 'POST'

    def get_sync_delete(self):
        """
        Если sync_delete == True, будет отправлена таска на удаление в crm,
        иначе обновление (для неудаляемых записей с safe-delete)
        """
        assert self.sync_delete is not None, f'sync_delete for {self.__class__.__name__} is undefined'
        return self.sync_delete

    def crm_sync_delete(self):
        """
        Синхронизация удаления
        """
        method = 'DELETE'
        data = {}
        action = self.get_crm_api_action()
        response = self.client.request(method, action, data)

    def send_espo_request(self, *args, **kwargs):
        """
        Синхронизация сохранения модели с crm
        """
        queryset = self.get_queryset()
        queryset = queryset.select_for_update()
        with transaction.atomic():
            instance = queryset.get(pk=self.pk) # TODO теперь мы берем инстанс в самой таске.
                                                # можно переделать через селф
            serializer_ = instance.get_crm_serializer_class()
            data = serializer_(instance).data
            data['skipDuplicateCheck'] = True
            method = instance.get_request_type()
            action = instance.get_crm_api_action()
            response = self.client.request(method, action, data)
            if not instance.crm_id:
                instance.crm_id = response.get('id')
                instance.save(*args, dont_sync=True, **kwargs)

    def crm_request_related_link(self, category_id, link):
        """
        Для создания связи между сущностями в срм. link - имя сущности,
        category_id - айди записи этой сущности.
        """
        self.refresh_from_db()
        assert self.crm_id is not None, "impossible to relate without crm_id"
        params = {'id': category_id}
        action = self.get_crm_api_action()
        link_action = f'{action}/{link}'
        self.client.request('POST', link_action, params=params)

    def crm_push(self, *args, **kwargs):
        """
        Вызов синхронизации с crm
        """
        self.send_espo_request(*args, **kwargs)

    def save(self, *args, **kwargs):
        dont_sync = kwargs.pop('dont_sync', False)
        with transaction.atomic():
            super().save(*args, **kwargs)
            if (dont_sync != True and settings.CRM_ENABLED and
                             self.get_queryset().filter(pk=self.pk).exists()):
                s = app.signature(
                    'crm.crm_sync',
                    kwargs={
                        'instance_id': self.pk,
                        'class_name': self.__class__.__name__
                    }
                )
                transaction.on_commit(lambda: s.apply_async())

    class Meta:
        abstract = True

@receiver(post_delete)
def crm_sync_delete(sender, instance, **kwargs):
    if isinstance(instance, CRMSignalMixin) and instance.sync_delete == CRM_TRUE_DELETE:
        with transaction.atomic():
            s = app.signature(
                    'crm.crm_sync_delete',
                    kwargs={
                        'instance': instance
                    }
            )
            transaction.on_commit(lambda:s.apply_async())


from django.contrib import admin
from django.urls import path
from .views import *

urlpatterns = [
    path('',MaincourseListView.as_view(),name='main-course-list'),
    path('explore/',courseListView.as_view(),name='course-list'),
    path('create/',courseCreateView.as_view(),name='course-create'),
    # path('',courseListView.as_view(),name='course-list'),
    path('dashboard/',teacher_dashboard,name='course-dashboard'),
    path('dashboard/list',dashboardCourseListView.as_view(),name='course-dashboard-list'),

    path('dashboard/course/create',courseCreateView.as_view(),name='course-dashboard-create'),
    path('dashboard/course/module/create',moduleCreateView.as_view(),name='course-dashboard-module-create'),
    path('dashboard/course/module/content/create',contentCreateView.as_view(),name='course-dashboard-content-create'),

    path('dashboard/course/<int:pk>',dashboardCourseDetailView.as_view(),name='course-dashboard-detail'),
    path('dashboard/course/module/<int:pk>',dashboardModuleDetailView.as_view(),name='course-dashboard-module-detail'),
    path('detail/<int:pk>/',courseDetailView.as_view(),name='course-detail'),

    path('dashboard/course/update/<int:pk>',courseUpdate.as_view(),name='course-dashboard-update'),
    path('dashboard/course/module/update/<int:pk>',modeleUpdate.as_view(),name='module-dashboard-update'),
    path('dashboard/course/module/content/update/<int:pk>',contentUpdate.as_view(),name='content-dashboard-update'),

    path('course/<int:pk>/',enrollCourse.as_view(),name='enroll-course'),
    path('course/module/<int:pk>/',enrollModule.as_view(),name='enroll-module'),
    path('course/module/content/<int:pk>/',content.as_view(),name='enroll-content'),
    path('course/enroll/<int:pk>/',Enroll,name='enroll'),

    path('course/module/content/completed/<int:pk>/',completeContent,name='completed-content'),
    path('course/module/completed/<int:pk>/',completedModule,name='completed-module'),
    path('course/completed/<int:pk>/',completedCourse,name='completed-course'),
    path('course/review/',review.as_view(),name='review'),

    path('course/discussoin/',discussionListView.as_view(),name='discuss'),
    path('course/discussoin/create',discussionCreateView.as_view(),name='discuss-create'),
    path('course/discussoin/<int:pk>',discussionDetailView.as_view(),name='discuss-det'),
    path('course/likes/<int:pk>',like_main_post, name='di-like_main_post'),
    path('course/comment/',comment, name='di-comments'),

    path('search/',search,name="search"),

]


from dataclasses import dataclass
import cv2
import math
import numpy as np
import base64
import struct
from numpy import int16, int8, uint16, uint8, uint32, int32

def drawHor(frame, theta, phi):
    widAngle = 65
    heiAngle = widAngle*3.0/4.0
    height, width, channels = frame.shape
    pm = (width/2, height/2)
    pm = (pm[0], pm[1]+theta/widAngle*height)
    r = width * .25
    p1 = (int(pm[0]-r*math.cos(phi/57.0)), int(pm[1]+r*math.sin(phi/57.0)))
    p2 = (int(pm[0]+r*math.cos(phi/57.0)), int(pm[1]-r*math.sin(phi/57.0)))
    cv2.line(frame,p1,p2,(0,255,0),3)
    return frame

def drawRange(frame, range):
    height, width, channels = frame.shape
    L = 12
    R = 28
    B = 50
    Um = height - B
    min = 50
    max = 1000
    if (range > 1000):
        range=1000
    if (range < 50):
        range=50

    U = int((Um-B)*range/(max-min))
    color = (0, int(range/(max-min)*255), 255-int(range/(max-min)*255))
    frame = cv2.rectangle(frame, (L,B), (R, U), color, -1)
    return frame

def drawState(frame,state):
    height, width, channels = frame.shape
    text = ''
    if (state == 0x01):
        text = 'MAN'
    font = cv2.FONT_HERSHEY_SIMPLEX
    org = (width-150, height-50)
    fontScale = 1
    color = (255, 0, 0)
    thickness = 2
    frame = cv2.putText(frame, text, org, font, fontScale, color, thickness, cv2.LINE_AA)
    return frame

@dataclass
class tlmAHRS:
    time: uint32 = 0
    phi: int16 = 0
    theta: int16 = 0
    psi: int16 = 0
    P: int16 = 0
    Q: int16 = 0
    R: int16 = 0
    accX: int16 = 0
    accY: int16 = 0
    accZ: int16 = 0
    smiec: int16 = 0 #?????

@dataclass
class dataAHRS:
    time: float = 0.0
    phi: float = 0.0
    theta: float = 0.0
    psi: float = 0.0
    P: float = 0.0
    Q: float = 0.0
    R: float = 0.0
    accX: float = 0.0
    accY: float = 0.0
    accZ: float = 0.0

def encodeTlm(line):
    bytes = base64.b64decode(line)
    tlm = struct.unpack('@Lhhhhhhhhhh',bytes)
    tlm = tlmAHRS(tlm[0], tlm[1], tlm[2], tlm[3], tlm[4], tlm[5], tlm[6], tlm[7], tlm[8], tlm[9], tlm[10])
    return tlm


from pyxavi.config import Config
from pyxavi.logger import Logger
from janitor.lib.system_info import SystemInfo
from janitor.lib.system_info_templater import SystemInfoTemplater
from janitor.lib.publisher import Publisher
from janitor.lib.mastodon_helper import MastodonHelper
from janitor.objects.queue_item import QueueItem
from janitor.objects.message import Message, MessageType
from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

DEFAULT_MESSAGE_TYPE = str(MessageType.NONE)

class ListenSysInfo(Resource):
    '''
    Listener from remote SysInfo Report requests to log
    '''

    def __init__(self):
        self._config = Config()
        self._logger = Logger(self._config).getLogger()
        self._sys_info = SystemInfo(self._config)
        self._parser = reqparse.RequestParser()
        self._parser.add_argument(
            'sys_data', type=dict, required=True, help='No sys_data provided', location='json'
        )
        self._logger.info("Init SysInfo Listener")

        super(ListenSysInfo, self).__init__()

    def post(self):
        """
        This is going to receive the POST request
        """

        self._logger.info("Run SysInfo Listener app")

        # Get the data
        args = self._parser.parse_args()
        if "sys_data" in args:
            sys_data = args["sys_data"]
        else:
            return {
                "error": "Expected dict under a \"sys_data\" variable was not present."
            }, 400

        # If there is no issue, just stop here.
        if not self._sys_info.crossed_thresholds(sys_data, ["hostname"]):
            self._logger.info("No issues found. Ending here.")
            return 200

        # Make it a message
        message = SystemInfoTemplater(self._config).process_report(sys_data)

        # Publish the queue
        mastodon = MastodonHelper.get_instance(self._config)
        publisher = Publisher(self._config, mastodon)
        self._logger.info("Publishing one message")
        publisher.publish_one(QueueItem(message))

        self._logger.info("End.")
        return 200

class ListenMessage(Resource):
    '''
    Listener from remote Message requests to log
    '''

    def __init__(self):
        self._config = Config()
        self._logger = Logger(self._config).getLogger()
        self._parser = reqparse.RequestParser()
        self._parser.add_argument(
            'summary',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._parser.add_argument(
            'message',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._parser.add_argument(
            'hostname',
            # type = str,
            # required = True,
            # help = 'No hostname provided',
            location='form'
        )
        self._parser.add_argument(
            'message_type',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._logger.info("Init Message Listener Listener")

        super(ListenMessage, self).__init__()

    def post(self):
        """
        This is going to receive the POST request
        """

        self._logger.info("Run Message Listener app")

        # Get the data
        args = self._parser.parse_args()
        if "summary" in args and args["summary"] is not None:
            summary = args["summary"]
        else:
            summary = None
        if "message_type" in args and args["message_type"] is not None:
            message_type = args["message_type"]
        else:
            message_type = DEFAULT_MESSAGE_TYPE
        if "message" in args and args["message"] is not None:
            text = args["message"]
        else:
            return {
                "error": "Expected string under a \"message\" variable was not present."
            }, 400
        if "hostname" in args and args["hostname"] is not None:
            hostname = args["hostname"]
        else:
            return {
                "error": "Expected string under a \"hostname\" variable was not present."
            }, 400

        # Build the message
        icon = MessageType.icon_per_type(message_type)
        if not summary:
            message = Message(text=f"{icon} {hostname}:\n\n{text}")
        else:
            message = Message(summary=f"{icon} {hostname}:\n\n{summary}", text=f"{text}")

        # Publish the queue
        mastodon = MastodonHelper.get_instance(self._config)
        publisher = Publisher(self._config, mastodon)
        self._logger.info("Publishing one message")
        publisher.publish_one(QueueItem(message))

        self._logger.info("End.")
        return 200

api.add_resource(ListenSysInfo, '/sysinfo')
api.add_resource(ListenMessage, '/message')

if __name__ == '__main__':
    app.run(
        host=Config().get("app.service.listen.host"),
        port=Config().get("app.service.listen.port")
    )


from flask import Flask, jsonify, request

weather_data = {
    'San Francisco': {'temperature': 14, 'weather': 'Cloudy'},
    'New York': {'temperature': 20, 'weather': 'Sunny'},
    'Los Angeles': {'temperature': 24, 'weather': 'Sunny'},
    'Seattle': {'temperature': 10, 'weather': 'Rainy'},
    'Austin': {'temperature': 32, 'weather': 'Hot'},
}

# crud app
def create_app():
    app = Flask(__name__)

    @app.route('/weather/<string:city>', methods=['GET'])
    def get_weather(city):
        if city in weather_data:
            return jsonify({'city': city, **weather_data[city]})
        else:
            return jsonify({'error': 'City not found'}), 404

    @app.route('/weather', methods=['POST'])
    def add_weather():
        data = request.get_json()
        city = data.get('city')
        temperature = data.get('temperature')
        weather = data.get('weather')

        if not city or not temperature or not weather:
            return jsonify({'error': 'Invalid data'}), 400

        weather_data[city] = {'temperature': temperature, 'weather': weather}
        return jsonify({'city': city, 'temperature': temperature, 'weather': weather}), 201

    @app.route('/weather/<string:city>', methods=['PUT'])
    def update_weather(city):
        if city in weather_data:
            data = request.get_json()
            temperature = data.get('temperature')
            weather = data.get('weather')

            if temperature:
                weather_data[city]['temperature'] = temperature
            if weather:
                weather_data[city]['weather'] = weather

            return jsonify({'city': city, **weather_data[city]})
        else:
            return jsonify({'error': 'City not found'}), 404

    @app.route('/weather/<string:city>', methods=['DELETE'])
    def delete_weather(city):
        if city in weather_data:
            del weather_data[city]
            return '', 204
        else:
            return jsonify({'error': 'City not found'}), 404

    return app

if __name__ == '__main__':
    app = create_app()
    app.run()


import json
from math import e
import stat
from typing import Dict
from data.google.google_email_repository import GooleCalendarEventRepository
from services.google_auth_service import GoogleAuthService
from framework.logger import get_logger
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from framework.serialization import Serializable
from framework.crypto.hashing import sha256
from datetime import datetime, timedelta
from dateutil import parser

logger = get_logger(__name__)

GOOGLE_CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

class CalendarEvent(Serializable):
    def __init__(
        self,
        id: str,
        status: str,
        link: str,
        created_date,
        updated_date,
        summary: str,
        description: str,
        event_type: str,
        location: str,
        creator: str,
        organizer: str,
        start_date: Dict,
        end_date: Dict,
        visibility: str,
        attendees: list,
        reminders: list,
        extended_properties,
        recurring_event_id: str
    ):
        self.id = id
        self.status = status
        self.link = link
        self.created_date = created_date
        self.updated_date = updated_date
        self.summary = summary
        self.description = description
        self.event_type = event_type
        self.location = location
        self.creator = creator
        self.organizer = organizer
        self.start_date = start_date
        self.end_date = end_date
        self.visibility = visibility
        self.attendees = attendees
        self.reminders = reminders
        self.extended_properties = extended_properties
        self.recurring_event_id = recurring_event_id

    def generate_hash_key(
        self
    ):
        data = json.dumps(self.to_dict(), default=str)
        return sha256(data)

    @staticmethod
    def from_entity(data: Dict):
        return CalendarEvent(
            id=data.get('id'),
            status=data.get('status'),
            link=data.get('link'),
            created_date=data.get('created_date'),
            updated_date=data.get('updated_date'),
            summary=data.get('summary'),
            description=data.get('description'),
            event_type=data.get('event_type'),
            location=data.get('location'),
            creator=data.get('creator'),
            organizer=data.get('organizer'),
            start_date=data.get('start_date'),
            end_date=data.get('end_date'),
            visibility=data.get('visibility'),
            attendees=data.get('attendees'),
            reminders=data.get('reminders'),
            extended_properties=data.get('extended_properties'),
            recurring_event_id=data.get('recurring_event_id'))

    @staticmethod
    def from_event(data: Dict):
        start_date = {
            'datetime': data.get('start', dict()).get('dateTime'),
            'timezone': data.get('start', dict()).get('timeZone')
        }

        end_date = {
            'datetime': data.get('end', dict()).get('dateTime'),
            'timezone': data.get('end', dict()).get('timeZone')
        }

        return CalendarEvent(
            id=data.get('id'),
            status=data.get('status'),
            link=data.get('htmlLink'),
            created_date=data.get('created'),
            updated_date=data.get('updated'),
            summary=data.get('summary'),
            description=data.get('description'),
            event_type=data.get('eventType'),
            location=data.get('location'),
            creator=data.get('creator', dict()).get('email'),
            organizer=data.get('organizer', dict()).get('email'),
            start_date=start_date,
            end_date=end_date,
            visibility=data.get('visibility'),
            attendees=data.get('attendees'),
            reminders=data.get('reminders'),
            extended_properties=data.get('extendedProperties'),
            recurring_event_id=data.get('recurringEventId'))

def ensure_datetime(
    value: datetime | str
) -> datetime:
    if isinstance(value, datetime):
        return value

    return parser.parse(value)

class CalendarService:
    def __init__(
        self,
        auth_service: GoogleAuthService,
        repository: GooleCalendarEventRepository
    ):
        self.__auth_service = auth_service
        self.__repository = repository

    async def get_calendar_client(
        self
    ) -> Credentials:
        logger.info(f'Fetching calendar client')
        auth = await self.__auth_service.get_auth_client(
            scopes=GOOGLE_CALENDAR_SCOPES)

        return build("calendar", "v3", credentials=auth)

    async def get_calendar_events(
        self,
        start_date: str | datetime,
        end_date: str | datetime
    ):
        logger.info(
            f'Fetching calendar events from {start_date} to {end_date}')

        start_date = ensure_datetime(start_date)
        end_date = ensure_datetime(end_date)

        service = await self.get_calendar_client()

        events_result = service.events().list(
            calendarId='primary',
            timeMin=f'{start_date.isoformat()}Z',
            timeMax=f'{end_date.isoformat()}Z',
            singleEvents=True,
            orderBy='startTime'
        ).execute()

        events = events_result.get('items', [])

        events = [CalendarEvent.from_event(event) for event in events]

        return events

    async def sync_calendar_events(
        self
    ):
        logger.info(f'Syncing calendar events')

        end_date = datetime.now().strftime('%Y-%m-%d')
        start_date = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%d')


def bellmanford(graph, numV, numE):
    INF = 1000000
    dist = []
    for i in range(numV):
        dist.append(INF)
    dist[0] = 0
    for i in range(1,numV):
        for j in range(numE):
            u = graph[j][0]
            v = graph[j][1]
            w = graph[j][2]
            if(dist[u] != INF and dist[u] + w < dist[v]):
                dist[v] = dist[u] + w
    for j in range(numE):
        u = graph[j][0]
        v = graph[j][1]
        w = graph[j][2]
        if(dist[u] != INF and dist[u] + w < dist[v]):
            return False
    return True

def main():
    testCases = int(input())
    for t in range(testCases):
        line = [int(x) for x in input().split(" ")]
        graph = [[0]*line[0] for i in range(3)]
        for i in range(line[1]):
            l = [int(x) for x in input().split(" ")]
            graph[i][0] = l[0]
            graph[i][1] = l[1]
            graph[i][2] = l[2]
        if(bellmanford(graph,line[0], line[1])):
            print("not possible")
        else:
            print("possible")

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 15:10:04 2021

@author: davidfordjour
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def Read_Two_Column_File(file_name):
    """Reading in the data for time and date."""
    with open(file_name, 'r') as data:
        x = []      # Creating empty lists for date and running times.
        times = []
        count = 0   # A line counter that starts at the top of the page

        for line in data:
            count+=1    # Moving to the next line
            d = line.split(" ")  #Indicating how columns are separated
            times.append((d[0]))    #Data in first column goes into times list
            x.append(d[1])  #Data in second column goes into x-axis
    return x, times

x, times = Read_Two_Column_File('times.txt')  #Reading times.txt file

def String_To_Minutes(time):
    """Converting strings in times-list to minutes."""
    if type(time) == bytes:
        time = time.decode()

    t = time.split(":") #Times are split with ":"
    minutes = (float(t[0])) + (float(t[1])*0.05/3)
    return minutes

y_axis = []

for y in times:
    print(String_To_Minutes(y))
    y_axis.append(String_To_Minutes(y))

print(x)
#print(y)
plt.plot(x,y_axis)
plt.xlabel("Date")
plt.ylabel("Mins")
plt.title("jogging times")


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 15:42:52 2018

@author: liuyang
"""

from datetime import datetime
import numpy as np
import pandas as pd
import MYSQLPD as sql
import math

def DatetoDigit(date):
    digitdate=date.year*10000+date.month*100+date.day
    return digitdate

#读取交易日期列表
def GetTradeDates(BegT,EndT,Freq='D'):
    TDs=pd.read_csv(r"D:\Sam\PYTHON\Tradedates.csv",encoding='utf_8_sig',parse_dates=[0])
    BTTD=TDs[(TDs['TRADEDATE']>=BegT)&(TDs['TRADEDATE']<=EndT)]
    if Freq=='W':
        TDDF=BTTD[['TRADEDATE','IsWeekEnd']]
        TDList=TDDF[TDDF['IsWeekEnd']==1].TRADEDATE.tolist()
        return TDList
    elif Freq=='D':
        TDList=BTTD[['TRADEDATE']].TRADEDATE.tolist()

        return TDList

"""得到每日收益率数据的函数"""
def GetDayReturn(date):
        digitdate=DatetoDigit(date)
        dbname1='tyb_stock'
        #SQLstrHead1='select * from stockdaily_basic where TRADEDATE='
        SQLstrHead1='select TRADEDATE,STOCKID,BFQCLOSE,HFQCLOSE,DAYRETURN,TRADABLE from stockdaily_basic where TRADEDATE='
        SQLstr1=SQLstrHead1+str(digitdate)
        #SQLstr2=SQLstrHead2+str(digitPD)
        DF=sql.toDF(SQLstr1,dbname1)
        DF=DF.rename(columns={'DAYRETURN':'RETURN'})
        #DF=DF[['TRADEDATE','STOCKID','BFQCLOSE','DAYRETURN','TRADABLE']]
        #DF=DF.loc[(DF['SWLV1']!=0)&(DF['TRADABLE']==1)]
        print(date)
        return DF

"""得到指定间隔区间收益率的函数"""
def GetIntervalReturn(d1,d2):

    DF1=GetDayReturn(d1)
    DF2=GetDayReturn(d2)
    DFL=DF1[['STOCKID','HFQCLOSE']]
    DFL=DFL.rename(columns={'HFQCLOSE':'LASTCLOSE'})
    DFM=pd.merge(DF2, DFL, how='left',on='STOCKID')
    DFM['RETURN']=(DFM['HFQCLOSE']-DFM['LASTCLOSE'])*100/DFM['HFQCLOSE']
    DFR=DFM[['TRADEDATE','STOCKID','HFQCLOSE','LASTCLOSE','TRADABLE','RETURN']]
    print(d2)

    return DFR

"""得到某一日的因子数据"""
def GetFactor(date):
        digitdate=DatetoDigit(date)
        dbname1='tyb_stock'
        #SQLstrHead1='select * from stockdaily_basic where TRADEDATE='
        SQLstrHead1='select TRADEDATE,STOCKID,MARKETVALUE,SWLV1,SWLV2,TRADABLE,BP from stockdaily_factor1 where TRADEDATE='
        SQLstr1=SQLstrHead1+str(digitdate)
        #SQLstr2=SQLstrHead2+str(digitPD)
        DF=sql.toDF(SQLstr1,dbname1)
        print(date)
        #DF=DF.rename(columns={'DAYRETURN':'RETURN'})
        #DF=DF[['TRADEDATE','STOCKID','BFQCLOSE','DAYRETURN','TRADABLE']]
        #DF=DF.loc[(DF['SWLV1']!=0)&(DF['TRADABLE']==1)]
        return DF

starttime = datetime.now()
#设定回测起止日期
BegT=datetime(2007,1,1)
EndT=datetime(2017,12,31)

TDList=GetTradeDates(BegT,EndT,Freq='D')
TDNum=len(TDList)

AllData=pd.DataFrame()

#Data=[GetDayReturn(TDList[i]) for i in range(0,TDNum)]  #每日收益率数据
#Data=[GetIntervalReturn(TDList[i-1],TDList[i]) for i in range(1,TDNum)]  #每日收益率数据
Data=[GetFactor(TDList[i]) for i in range(0,TDNum)]

AllData=pd.concat(Data,ignore_index=True)

"""
for i in range(0,TDNum):
    d0=TDList[i]
    ASDF=GetDayReturn(d0)
    AllData=pd.concat([AllData,ASDF])
    print (d0)
"""
"""
for i in range(1,TDNum):
    d0=TDList[i-1]
    d1=TDList[i]
    ASDF=GetIntervalReturn(d0,d1)
    AllData=pd.concat([AllData,ASDF])
    print (d1)
"""
stoptime = datetime.now()
print(stoptime-starttime)


from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("prices/", views.get_price, name="get_price"),
    path("home/", views.trending_tickers_view, name="trending_tickers"),
    path("new_stock/", views.new_user_stock, name="new_stock"),

]


RESPONSE_OK = object()
RESPONSE_ERROR = object()
RESPONSE_WARN = object()

class Response(object):

    def __init__(self):
        self.content = ""
        self.return_code = RESPONSE_OK

    @staticmethod
    def success(response_content=""):
        r = Response()
        r.content = response_content
        r.return_code = RESPONSE_OK
        return r

    @staticmethod
    def error(response_content=""):
        response = Response()
        response.content = response_content
        response.return_code = RESPONSE_ERROR
        return response

    def is_error(self):
        return self.return_code == RESPONSE_ERROR

class SupportedOutputFormats:
    image = "image"
    text = "text"
    json = "json"

    @staticmethod
    def is_in(value):
        return value in (SupportedOutputFormats.image,SupportedOutputFormats.text,SupportedOutputFormats.json)


# -*- coding: utf-8 -*-
"""
Created on Tue May 22 09:27:44 2018

@author: Administrator
"""
import math

# start+(end-start)/2  <--> (start+end)/2
def maxmin(L, start, end):
    """
    求出L的最大最小值的元组
    """
    if end-start <= 1:
        return (max(L[start],L[end]),min(L[start],L[end]))
    else:
        max1,min1 = maxmin(L, start, math.floor((start+end)/2))
        max2,min2 = maxmin(L, math.floor((start+end)/2)+1, end)
        return (max(max1,max2), min(min1,min2))

L=[1,2,6,7,-1,-5,9,8,13,21]
maxV,minV = maxmin(L, 0, len(L)-1)
print(maxV,minV)


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

__authors__ = 'Bruno Adelé <bruno@adele.im>'
__copyright__ = 'Copyright (C) 2013 Bruno Adelé'
__description__ = """A metar domolib"""
__license__ = 'GPL'
__version__ = '0.0.1'

# Require metar
# pip install git+https://github.com/tomp/python-metar.git

import re

try:
    from urllib.request import urlopen
except ImportError:
    from urllib import urlopen

from metar import Metar

from domolib.commons.decorator import command
from domolib.commons import cache

class dlmetar():
    def getresults(self, station):
        results = {}

        # Get Metar information
        url = 'http://weather.noaa.gov/pub/data/observations/metar/stations'

        r = None
        r = urlopen('%s/%s.TXT' % (url, station))

        if r.getcode() is None or r.getcode() != 200:
            return None

        # Extract only Metar informations
        m = re.search(
            '%s .*' % station,
            r.read().decode('utf-8')
        )

        if not m:
            return

        # Decode metar informations
        code = m.group(0)
        decode = Metar.Metar(code)

        # Get temperature
        if decode.temp:
            results['temp'] = decode.temp.value()

        # Get dewpt temperature
        if decode.dewpt:
            results['dewpt'] = decode.dewpt.value()

        # Get pressure
        if decode.press:
            results['pressure'] = decode.press.value()

        # Visibility
        if decode.vis:
            results['visibility'] = int(decode.vis.value())

        # Get wind speed
        if decode.wind_speed:
            results['wind_speed'] = decode.wind_speed.value() * 1.852

        # Calculate the relative humidity
        if decode.temp and decode.dewpt:
            temp = decode.temp.value()
            dewpt = decode.dewpt.value()
            results['humidity'] = round(
                100 * ((112 - 0.1 * temp + dewpt) / (112 + 0.9 * temp)) ** 8,
                2
            )

        # Calculate the wind chill or heat index
        if decode.temp and decode.wind_speed:
            speed = decode.wind_speed.value() * 1.852
            temp = decode.temp.value()
            results['wind_chill'] = round(
                13.12 + 0.6215 * temp +
                (0.3965 * temp - 11.37) * speed ** 0.16,
                2
            )

        return results

@command
def get_metarinfo(oaci_station):
    """
    Get a weather from metar report
    :param oaci_station:
    :return:
    """

    # Get result from cache
    mycache = cache.cache(cachefile='dlmetar.get_metarinfo')
    result = mycache.getcachedresults()
    if result:
        return result

    # Compute the result and store in the cache file
    obj = dlmetar()
    result = obj.getresults(station=oaci_station)
    mycache.setcacheresults(result)

    return result


import hmac

# The block size = 2 * hash digest length
BLK_SIZE = 32

def xor(a, b):
    """Implement xor for 2 bytearrays.

    Arguments:
        a (bytearray): First byte array.
        b (bytearray): Second byte array.

    Returns:
        bytearray: The result of a XOR b.

    """
    return bytearray([ai ^ bi for (ai, bi) in zip(a, b)])

def round(data, F):
    """Defines one round of Fiestel cipher on the bytearray ``data``
    using the function ``F``.

    Arguments:
        data (bytearray): data in the form of bytearray.
        F (callable): A function that will be used in the fiestel cipher.

    Returns:
        bytearray: returns the data after the current round of the cipher.

    """
    L = len(data)
    if L & 1:
        raise Exception("Invalid data size: {}".format(L))

    left, right = data[:L//2], data[L//2:]

    return right + xor(left, F(right))

def hash_func(data):
    """A sample hash function with a static key.

    Arguments:
        data (bytearray): The data to hash.

    Returns:
        bytearray: The hash of the data.

    """
    h = hmac.new(b'secret key')
    h.update(data)
    return bytearray(h.digest())

def flip(data):
    """Flip the data according to fiestel flip. This means that
    the first and second halves were exchanged.

    Arguments:
        data (bytearray): The data to flip.

    Returns:
        bytearray: The flipped data bytearray.
    """
    l = len(data)
    return data[l//2:] + data[:l//2]

def pad(data):
    """Pad the data bytearray with the block size of BLK_SIZE using
    the PKCS#7 format.

    Arguments:
        data (bytearray): The data to be padded.

    Returns:
        bytearray: Return the padded bytearray.
    """
    m = BLK_SIZE - len(data) % BLK_SIZE
    return data + bytearray([m] * m)

def unpad(data):
    """Unpad the PKCS#7 data with BLK_SIZE block size.

    Arguments:
        data (bytearray): Padded bytearray.

    Returns:
        bytearray: Return unpadded bytearray.
    """
    if len(data) == 0:
        return data

    return data[:-data[-1]]

def crypt(data, F, decrypt=False, r = 32):
    """Encrypt or decrypt a piece of data using the fiestel cipher and
    the hash function F.

    Arguments:
        data (bytearray): The data to encrypt.
        F (callable): A hash function that outputs 16 bytes of digest.
        decrypt (boolean): If the operation is decryption or not.
        r (int): The number of fiestel cycles.

    Returs:
        bytearray: Encrypted or decrypted data based on flags.
    """
    data = data if decrypt else pad(data)
    blks = [
        data[i: i + BLK_SIZE] for i in range(0, len(data), BLK_SIZE)
    ]

    res = bytearray()
    for blk in blks:
        for _ in range (r):
            blk = round(blk, F)
        res = res + flip(blk)

    return unpad(res) if decrypt else res

if __name__ == '__main__':
    d = bytearray("hello world with fiestel cipher but it would like to do something that no one has done before", "utf-8")
    e = crypt(d, hash_func)
    print (e)

    e = crypt(e, hash_func, True)
    print (e)


import numpy as np
import pandas as pd
import tensorflow as tf
import json
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Dense
from keras.optimizers import SGD
from keras.utils.np_utils import to_categorical
from flask import Flask, render_template, jsonify

app = Flask(__name__, template_folder ='templates',static_url_path='/static')

# Pandas read CSV
sf_train = pd.read_csv('p5_training_data.csv')

# korelasi matriks ke target
corr_matrix = sf_train.corr()
print(corr_matrix['type'])

# buang kolom
sf_train.drop(sf_train.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)
print(sf_train.head())

# baca CSV
sf_train = pd.read_csv('p5_training_data.csv')

# Korelasi matriks target
corr_matrix = sf_train.corr()
print(corr_matrix['type'])

# buang kolom
sf_train.drop(sf_train.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)
print(sf_train.head())

# panda baca data Val
sf_val = pd.read_csv('p5_val_data.csv')

# Buang kolom
sf_val.drop(sf_val.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)

# Get Pandas array value (Convert ke array NumPy)
train_data = sf_train.values
val_data = sf_val.values

# Use columns 2-akhir sbg Input
train_x = train_data[:,2:]
val_x = val_data[:,2:]

# Use columns 1 sebagai Output/Target (pake One-Hot Encoding)
train_y = to_categorical( train_data[:,1] )
val_y = to_categorical( val_data[:,1] )

# bikin jaringan
inputs = Input(shape=(16,))
h_layer = Dense(10, activation='sigmoid')(inputs)

# aktivasi softmax baut klasifikasi multiklas
outputs = Dense(3, activation='softmax')(h_layer)

model = Model(inputs=inputs, outputs=outputs)

# Optimizer / Update Rule
sgd = SGD(lr=0.001)

# Compile model dengan Cross Entropy Loss
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])

# Training model dan pake validation data
model.fit(train_x, train_y, batch_size=10, epochs=5000, verbose=1, validation_data=(val_x, val_y))
model.save_weights('weights.h5')

# Predict semual Validation data
predict = model.predict(val_x)

# Visualisasi Prediksi
#df = pd.DataFrame(predict)
#df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
#df.index = val_data[:,0]

#web server pake flask buat render template
@app.route('/index')
@app.route('/')
def index():
	return render_template("index.html")

@app.route('/dota2', methods=['GET'])
def dota():
	'''
	df = pd.DataFrame(predict)
	df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
	df.index = val_data[:,0]
	data = df.to_dict(orient='index')
	return jsonify({'data':data})
	'''
	df = pd.DataFrame(predict)
	df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
	df.index = val_data[:,0]
	temp = df.to_dict('records')
	columnNames = df.columns.values
	rowwNames = df.index
	return render_template('record.html', records=temp, colnames=columnNames,len=len(rowwNames), rownames=rowwNames)

if __name__ == '__main__':
	app.run(host='0.0.0.0', port=5000)


#imports csv functions
import csv
import datetime
from os import read

#Dictionary for storing products
prod_dict = {

}
#Dictionary for storing requests
req_dict = {

}

#Dictionary for the receipt
receipt_dict = {

}

number_of_items = 0

subtotal = 0

current_date_and_time = datetime.datetime.now()

# Format the current date and time to include only
# the day of the week, the hour, and the minute.
formatted_dt = current_date_and_time.strftime("%A %I:%M %p")

#Open products.csv
with open("/Users/elijah/BYUI/Programming with functinos/Week3/products.csv") as products:
    reader = csv.reader(products)

    #Skip first row
    next(reader)

    #Populate Dictionary
    for row in reader:
        #Elements
        #0 - Product Number
        prod_num = row[0]
        #1 - Product Name
        prod_name = row[1]
        #2 - Retail Price
        prod_cost = row[2]

        #add element to dict
        prod_dict[prod_num] = [prod_name,prod_cost]

#Open requests.csv
with open("/Users/elijah/BYUI/Programming with functinos/Week3/request.csv") as request:
    reader = csv.reader(request)

    next(reader)

    for item in reader:
        # 0 - Product Number
        prod_num = item[0]
        # 1 - Quantity
        prod_quant = item[1]

        #add item to dictionary
        req_dict[prod_num] = prod_quant

# Display Products
#print(f"THIS IS THE PRODUCTS DICT : \n{prod_dict}")
# Display Requests
#print(f"THIS IS THE REQUEST DICT : \n{req_dict}")

print("\nRequested Items : \n")
for req_item in req_dict:
    #receipt_dict[req_item] = [prod_dict[req_item]]
    name = prod_dict[req_item][0]
    cost = prod_dict[req_item][1]
    count = req_dict[req_item][0]

    subtotal += (float(cost) * int(count))

    print(f"{name:.15} : {count:.2} @ ${cost:.5} \n")

tax = subtotal * 0.06
total = subtotal + tax

print("------------------------------\n")
print(f"Subtotal : {subtotal:.2f}")
print(f"Tax : {tax:.2f}")
print(f"Total : {total:.2f}")
print("\n------------------------------\n")
print(f"Date and time of checkout : {formatted_dt}\n\n")


import os
import pandas as pd
from joblib import Parallel, delayed
from util import get_interfaces_path, iter_cdd

NUM_WORKERS = 20

def get_counts(sfam_id):
    path = os.path.join(get_interfaces_path(dataset_name), "by_superfamily",
        str(int(sfam_id)), "{}_bsa.h5".format(int(sfam_id)))
    store = pd.HDFStore(path)

    obs = store.get("/observed")
    obs_sizes = obs.groupby("ppi_type").size().reset_index(name='observed').T
    del obs

    inf = store.get("/inferred")
    inf_sizes = inf.groupby("ppi_type").size().reset_index(name='inferred').T

    sizes = pd.concat([obs_size, inf_sizes], axis=1)

    changed = inf.groupby(["ppi_type", "ppi_type_obs"]).size().reset_index(name='count')
    #changed = changed[changed["ppi_type"]!=changed["ppi_type_obs"]]
    changed = changed.apply(lambda r: pd.Series({
        "{}->{}".format(r.ppi_type_obs, r.ppi_type):r.count}, index="inferred"), axis=1)
    del inf
    store.close()
    del store

    import pdb; pdb.set_trace()
    sizes = pd.concat([sizes, changed], axis=1)

def plot_ppi_types(superfams=None):
    if superfams is not None:
        return

    sizes = Parallel(n_jobs=NUM_WORKERS)(delayed(get_counts)(sfam_id) \
        for _, sfam_id in iter_cdd(use_id=True, group_superfam=True))


# coding=utf-8
from glob import glob
import re
from time import time
import requests
import os
# from xml.dom import minidom
from lxml import etree
import base64
import traceback

import html2text as ht #

from selenium.webdriver.chrome.options import Options
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import configparser

## 配置文件名称
configFileName = "config.ini"

res = "res" # 资源目录名称
head={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52"}
base64ImgHead = "data:image/png;base64,"

request_url = ""
bypass_tables = False
chromeDriverName = ""
# 初始化配置信息
def init_config():
    global request_url
    global bypass_tables
    global chromeDriverName
    config = configparser.ConfigParser()
    config.read(configFileName)
    request_url = config['base_config']['url']
    bypass_tables = config['base_config'].getboolean('bypass_tables')
    chromeDriverName = config['base_config']['config_fileName']

## 判断当前协议
def http_protocol(url):
    if url.startswith('https://'):
        return "https:"
    elif url.startswith('http://'):
        return "http:"

def get_image_type(Url,Number):
        if Url.find(base64ImgHead) != -1:
            return ("png_base64", str(Number)+".png")
        else:
            if Url.find(".jpg") != -1:
                return("url", str(Number)+".jpg")
            elif Url.find(".png") != -1:
                return ("url", str(Number)+".png")
            else:
                return ("url", str(Number)+".png")

def init_browser(url):
    chrome_options = webdriver.ChromeOptions()
    # # 禁用浏览器弹窗
    prefs = {"profile.default_content_setting_values.notifications": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    # 设置浏览器不显示
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(os.path.join(os.getcwd(),chromeDriverName) ,chrome_options=chrome_options)
    driver.maximize_window()
    driver.get(url)
    return driver

# 创建无头浏览器，来处理浏览器执行 跑 n 秒后的页面状态返回回来
def browser_request(url, loadmore = False, waittime = 2):
    browser = init_browser(url)
    time.sleep(waittime)
    if loadmore:
        while True:
            try:
                next_button = browser.find_element_by_class_name("ant-btn")
                next_button.click()
                time.sleep(waittime)
            except Exception as e:
                # traceback.print_exc()
                # info = traceback.format_exc()
                # print(info)
                break
    else:
        time.sleep(waittime)

    html = browser.page_source
    browser.quit()
    return html

def request(url):
    Result=requests.get(url,headers=head)
    Result.encoding = 'utf-8'
    return Result.text

def save_file(fileName, text):
    fileRef = open(fileName, "w+", encoding='utf-8') # win 环境必须指定编码类型，否则默认会使用系统的 gbk编码
    fileRef.write(text)
    fileRef.close()

def get_csdn_title(root):
    r = root.xpath('//h1[@id="articleContentId"][@class="title-article"]/text()')[0].replace("/","%")
    return r

def get_jianshu_title(root): # //*[@id="__next"]/div[1]/div/div[1]/section[1]/article
    r = root.xpath('//section/h1[@class="_1RuRku"]/text()')[0].replace("/","%")

    return r

# 下载资源到本地
def download_res(img_url,srcType,name):
    # print(img_url)
    if srcType == "png_base64" :
        imageBase64Str = img_url.replace(base64ImgHead,"")
        binary_img_data = base64.b64decode(imageBase64Str)
        with open(name,'wb') as fp:
            fp.write(binary_img_data)
        # print(name,'资源下载成功！！！')
    elif srcType == "url":
        img_data = requests.get(url=img_url,headers=head).content
        with open(name,'wb') as fp:
            fp.write(img_data)
            # print(name,'资源下载成功！！！')

# 初始化目录
def init_file(dirName):
    import shutil
    if not os.path.isdir(dirName):
        # shutil.rmtree(titleName)
        os.mkdir(dirName)
    resPath = os.path.join(dirName,res)
    if not os.path.isdir(resPath):
        os.mkdir(resPath)
    return resPath

# 转换为 makedown 并存盘 titleName/titleName.md 文件
def generate_makedown(root, titleName):
    allItem = root.xpath('*')
    need_str = ""
    for p_item in allItem:
        get_str = etree.tostring(p_item,encoding="utf-8")
        need_str += get_str.decode("utf-8")
    text = makedown(need_str)
    save_file(os.path.join(titleName,titleName+".md"), text)

def makedown(need_str):
    text_maker = ht.HTML2Text()
    text_maker.bypass_tables = bypass_tables # 是否使用表格翻译
    text = text_maker.handle(need_str)
    return text

# 处理好 图片的下载逻辑
def downLoadImgMgr(root, resPath):
    imgL = root.xpath('descendant::img')
    record_list = {}
    Number = 0
    for img in imgL:
        DownloadUrl = ""
        if 'data-original-src' in img.attrib and img.attrib['data-original-src'] != "" :
            DownloadUrl = img.attrib['data-original-src']
        elif 'src' in img.attrib and img.attrib['src'] != "" :
            DownloadUrl = img.attrib['src']
        else:
            continue
        if DownloadUrl.startswith('//'):
            DownloadUrl = http_protocol(request_url) + DownloadUrl
        if DownloadUrl in record_list: # 已经下载过了不处理
            img.attrib['src']=record_list[DownloadUrl]
        else:
            srcType,ImageName = get_image_type(DownloadUrl, Number)
            DownloadImgLocalPath = os.path.join(resPath, ImageName)
            ImageNewSrc = os.path.join(res, ImageName)
            download_res(DownloadUrl,srcType, DownloadImgLocalPath)
            img.attrib['src'] = ImageNewSrc
            record_list[DownloadUrl] = ImageNewSrc
            # if srcType == "png_base64":
            Number+=1

# 请求回一个根目录的节点实例
def request_html(url):
    htmlContent = request(url)
    return etree_html(htmlContent)

# 请求回一个根目录的节点实例，通过虚拟一个无头浏览器处理，拿到让js跑完后的结构
def request_html_by_browser(url):
    htmlContent = browser_request(url, True)
    return etree_html(htmlContent)

def etree_html(htmlContent):
    return etree.HTML(htmlContent, parser=etree.HTMLParser(encoding='utf-8'))

def scoll_down(html_page):# 滚轮下拉到最底部
    html_page.send_keys(Keys.END)
    time.sleep(1)

def generate_article(user, content1, content2, AccHtmlContent):
    userHtml = user.get_attribute('outerHTML')
    content1Html = content1.get_attribute('outerHTML')
    content2Html = ""
    if len(content2) != 0 :
        content2Html = content2[0].get_attribute('outerHTML')
    saveHtml = "<div>"+ userHtml + "\n" + content1Html + "\n" + content2Html + "\n" + "</div> \n"
    AccHtmlContent += saveHtml
    return AccHtmlContent

#  csnd 的相关处理
def start_make_csdn():
    tree = request_html(request_url)
    titleName = get_csdn_title(tree)
    resPath = init_file(titleName)
    makeRoot = tree.xpath('//div[@id="content_views"]')[0]
    downLoadImgMgr(makeRoot, resPath)
    generate_makedown(makeRoot, titleName)

# 处理简书
def make_jianshu():
    tree = request_html_by_browser(request_url) # 拿到html结构
    titleName = get_jianshu_title(tree)     # 获取标题
    makeRoot = tree.xpath('//section/article')[0]
    resPath = init_file(titleName)          # 初始化所需目录
    downLoadImgMgr(makeRoot, resPath)       # 处理资源下载
    generate_makedown(makeRoot, titleName)  # 处理makedown转换

def start():
    init_config()
    print(request_url)
    if request_url == "" :
        print("url配置为空")
        return
    if request_url.find("jianshu") != -1:
        make_jianshu()
    elif request_url.find("csdn") != -1:
        start_make_csdn()
    else:
        print("url 错误 不属于csdn也不属于简书")

    print("处理 完成")

start()


from classifiers.decision_tree import DecisionTree
from collections import Counter
from utils.utility import pick_result
from random import randrange

import numpy

__author__ = 'Simon & Oskar'

class RandomForest:
    def __init__(self, max_depth = None, min_samples_leaf = 1, n_estimators = 10, sample_size = 200, max_features = None):
        self.criterion = "gini"
        self.max_features = max_features
        self.max_depth = max_depth
        self.min_samples_leaf = min_samples_leaf
        self.laplace = 0
        self.n_estimators = n_estimators
        self.bagging = 0
        self.sample_size = sample_size

        self.n_classes = None
        self.decision_trees = list()

    def fit(self, X, y):
        if self.n_classes is None:
            self.n_classes = numpy.unique(y)

        if self.sample_size is None:
            self.sample_size = X.shape[0] / self.n_estimators

        rand_features = numpy.zeros(shape = (self.n_estimators, self.sample_size, X.shape[1]),
                                    dtype = numpy.float)

        rand_classes = numpy.zeros((self.n_estimators, self.sample_size))

        for i in range(self.n_estimators):
            temp = numpy.zeros(shape = (self.sample_size, X.shape[1]),
                               dtype = numpy.float)

            temp_class = numpy.zeros(shape = self.sample_size,
                                     dtype = numpy.float)

            for j in range(self.sample_size):
                r = randrange(0, X.shape[0])
                temp[j] = X[r]
                temp_class[j] = y[r]

            rand_features[i] = temp
            rand_classes[i] = temp_class

        for i in range(self.n_estimators):
            decision_tree = DecisionTree(max_features = self.max_features,
                                         max_depth = self.max_depth,
                                         min_samples_leaf = self.min_samples_leaf,
                                         laplace = self.laplace)

            decision_tree.fit(X = rand_features[i],
                              y = rand_classes[i])

            self.decision_trees.append(decision_tree)

    def predict(self, X):
        final_result = numpy.zeros((X.shape[0]))

        for row in range(X.shape[0]):
            result = numpy.zeros((self.n_estimators, 1))

            for i in range(self.n_estimators):
                result[i] = self.decision_trees[i].predict(numpy.array([X[row]]))

            result_flattened = result.ravel()
            c = Counter(result_flattened).most_common(numpy.unique(result_flattened).size)

            final_result[row] = pick_result(c)

        return final_result

    def predict_proba(self, X):
        final_result = numpy.zeros((X.shape[0], len(self.n_classes)), numpy.float)

        for row in range(X.shape[0]):
            result = numpy.zeros((self.n_estimators, len(self.n_classes)), numpy.float)
            for i in range(self.n_estimators):
                result[i] = self.decision_trees[i].predict_proba(numpy.array([X[row]]))
            result.astype(numpy.float)
            for r in result:
                for i in range(final_result.shape[1]):
                    final_result[row, i] += r[i].astype(numpy.float) / float(self.n_estimators)

        return final_result


from django.conf.urls.defaults import *
from django.contrib.auth.models import User
from django.views.generic.simple import direct_to_template

from board.feeds import LatestPosts
from board.rpc import rpc_post, rpc_lookup, rpc_preview, rpc_ban
from board.views import *

feeds = {'latest': LatestPosts}

js_info_dict = {
    'packages': ('board',),
}

urlpatterns = patterns('',
    (r'^$', thread_index, {}, 'board_index'),
    (r'search-results/$', search),
    (r'feedback/sent/$', direct_to_template, {'template':
        'board/feedback_sent.html'}),

    (r'^private/$', private_index, {}, 'board_private_index'),
    (r'^categories/$', category_index, {}, 'board_category_index'),
    (r'^favorites/$', favorite_index, {}, 'board_favorite_index'),
    (r'^edit_post/(?P<original>\d+)/$', edit_post, {}, 'board_edit_post'),
    (r'^threads/$', thread_index, {}, 'board_thread_index'),
    (r'^threads/id/(?P<thread_id>\d+)/$', thread, {}, 'board_thread'),
    (r'^threads/category/(?P<cat_id>\d+)/$', category_thread_index, {}, 'board_category_thread_index'),
    (r'^threads/category/(?P<cat_id>\d+)/newtopic/$', new_thread, {}, 'board_new_thread'),
    (r'^threads/post/(?P<post_id>\d+)/$', locate_post, {}, 'board_locate_post'),
    (r'^settings/$', edit_settings, {}, 'board_edit_settings'),

    # Groups
    (r'^groups/(?P<group_id>\d+)/manage/$', manage_group, {}, 'board_manage_group'),
    (r'^groups/(?P<group_id>\d+)/invite/$', invite_user_to_group, {}, 'board_invite_user_to_group'),
    (r'^groups/(?P<group_id>\d+)/remuser/$', remove_user_from_group, {}, 'board_remove_user_from_group'),
    (r'^groups/(?P<group_id>\d+)/grant_admin/$', grant_group_admin_rights, {}, 'board_grant_group_admin_rights'),

    (r'^del_thread/(?P<the_id>\d+)/$', 'board.views.del_thread'),

    # Invitations
    (r'invitations/(?P<invitation_id>\d+)/discard/$', discard_invitation, {}, 'board_discard_invitation'),
    (r'invitations/(?P<invitation_id>\d+)/answer/$', answer_invitation, {}, 'board_answer_invitation'),

    # RPC
    (r'^rpc/action/$', rpc, {}, 'board_rpc_action'),
    (r'^rpc/postrev/$', rpc_post, {}, 'board_rpc_postrev'),
    (r'^rpc/preview/$', rpc_preview, {}, 'board_rpc_preview'),
    (r'^rpc/user_lookup/$', rpc_lookup,
            {
                'queryset':User.objects.all(),
                'field':'username',
            }, 'board_rpc_user_lookup'
        ),
    (r'^rpc/ban/$', rpc_ban),

    # feeds
    (r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, 'board_feeds'),

    # javascript translations
    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict, 'board_js_i18n'),
)


import logging
# import gevent
import asyncio
from typing import Optional

from xbox.sg.crypto import PKCS7Padding
from xbox.sg.utils.events import Event
from xbox.auxiliary import packer
from xbox.auxiliary.packet import aux_header_struct, AUX_PACKET_MAGIC
from xbox.auxiliary.crypto import AuxiliaryStreamCrypto
from xbox.sg.utils.struct import XStructObj

log = logging.getLogger(__name__)

class AuxiliaryPackerException(Exception):
    pass

class ConsoleConnection(object):
    BUFFER_SIZE = 2048

    def __init__(self, address, port, crypto):
        self.address = address
        self.port = port
        self.crypto = crypto

        self._reader: Optional[asyncio.StreamReader] = None
        self._writer: Optional[asyncio.StreamWriter] = None

        self._recv_task: Optional[asyncio.Task] = None
        self.on_message = Event()

    def start(self):
        self._reader, self._writer = asyncio.open_connection(
            self.address, self.port
        )
        self._recv_task = asyncio.create_task(self._recv())

    def stop(self):
        self._recv_task.cancel()

    def handle(self, data):
        try:
            msg = packer.unpack(data, self.crypto)
            # Fire event
            self.on_message(msg)
        except Exception as e:
            log.exception("Exception while handling Console Aux data, error: {}".format(e))

    async def _recv(self):
        while True:
            data = await self._reader.read(4)
            header = aux_header_struct.parse(data)

            if header.magic != AUX_PACKET_MAGIC:
                raise Exception('Invalid packet magic received from console')

            payload_sz = header.payload_size + PKCS7Padding.size(
                header.payload_size, 16
            )
            remaining_payload_bytes = payload_sz

            while remaining_payload_bytes > 0:
                tmp = await self._reader.read(remaining_payload_bytes)
                remaining_payload_bytes -= len(tmp)
                data += tmp

            data += await self._reader.read(32)

            self.handle(data)

    async def send(self, msg):
        packets = packer.pack(msg, self.crypto)

        if not packets:
            raise Exception('No data')

        for packet in packets:
            self._writer.write(packet)

class LocalConnection(asyncio.Protocol):
    data_received_event = Event()
    connection_made_event = Event()

    def connection_made(self, transport: asyncio.BaseTransport) -> None:
        self.transport = transport
        self.connection_made(transport)

    def data_received(self, data: bytes) -> None:
        self.data_received(data)

    def close_connection(self) -> None:
        print('Close the client socket')
        self.transport.close()

class AuxiliaryRelayService(object):
    def __init__(
        self,
        loop: asyncio.AbstractEventLoop,
        connection_info: XStructObj,
        listen_port: int
    ):
        if len(connection_info.endpoints) > 1:
            raise Exception(
                'Auxiliary Stream advertises more than one endpoint!'
            )

        self._loop = loop
        self.crypto = AuxiliaryStreamCrypto.from_connection_info(
            connection_info
        )
        self.target_ip = connection_info.endpoints[0].ip
        self.target_port = connection_info.endpoints[0].port

        self.console_connection = ConsoleConnection(
            self.target_ip,
            self.target_port,
            self.crypto
        )

        self.server = self._loop.create_server(
            lambda: LocalConnection(),
            '0.0.0.0', listen_port
        )

        self.client_transport = None

    async def run(self):
        async with self.server as local_connection:
            local_connection.data_received_event += self._handle_client_data
            local_connection.connection_made_event += self.connection_made

            while True:
                # HACK / FIXME
                await asyncio.sleep(10000)

    def connection_made(self, transport):
        self.client_transport = transport
        peername = transport.get_extra_info('peername')
        print('Connection from {}'.format(peername))

        self.console_connection.on_message += self._handle_console_data
        self.console_connection.start()

    def _handle_console_data(self, data):
        # Data from console gets decrypted and forwarded to aux client
        if self.client_transport:
            self.client_transport.send(data)

    def _handle_client_data(self, data):
        # Data from aux client gets encrypted and sent to console
        self.console_connection.send(data)


from FileLoader import FileLoader
import pandas

def howManyMedals(data, name):
    matchAthlete = data.loc[data['Name'] == name]
    if matchAthlete.empty:
        print("No information about this athlete.")
        return None
    matchAthlete = matchAthlete.dropna(subset=['Medal'])
    if matchAthlete.empty:
        print("This athlete didn't get any medal.")
        return None
    print(matchAthlete)
    dicts = {}
    for index, row in matchAthlete.iterrows():
        if row['Year'] not in dicts:
            dicts[row['Year']] = {'G': 0, 'S': 0, 'B': 0}
        dicts[row['Year']][row['Medal'][0]
                           ] = dicts[row['Year']][row['Medal'][0]] + 1
    return dicts


import win32serviceutil
import win32service
import win32event
import servicemanager
import configparser
import os
import inspect
from multiprocessing import Process, Pipe
from db.sqlitemanager import SQLiteManager
from proc.node_client_process import NodeClientProcess
import utils.script_manager as sm
import utils.logging as logutils

def pipe_recv_handler(node_process, parent_pipe):
    node_process._logger.info("Node Pipe Recv Handler Spawned. Listening For Messages")
    while True:
        command = parent_pipe.recv()
        node_process._logger.info("Received Command: " + str(command))

        message_for = command["to"]

        if message_for == "NODE":
            answer = node_process.handle_node_requests(command)
            # send the answer back wherever it came (most likely the http)
            # send answer if it is not None
            if answer is not None:
                parent_pipe.send(answer)
        else:
            node_process._logger.warning("Could Not Determine What Message Is For. Can't Forward Appropriatly")

def bootstrapper(wrapper_object, initialization_tuple):
    instance = wrapper_object(initialization_tuple)
    instance.start()
    exit(0)

class AppServerSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "VesselNode"
    _svc_display_name_ = "Vessel Service Node"

    _config = configparser.ConfigParser()

    _log_dir = None
    _role = None

    _node_process = None
    _script_dir = None

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

        self._config.read(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
                          + '/conf/service.ini')

        self._log_dir = self._config["LOGGING"]["log_dir"]
        self._root_dir = self._config["DEFAULT"]["root_dir"]
        self._script_dir = self._config["DEFAULT"].get("scripts_dir", self._root_dir + "/scripts")

        logutils.initialize_all_logging_configuration(self._log_dir)
        self._logger = logutils.node_logger

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))

        self._logger.info("Service Is Starting")
        self.main()

    def handle_node_requests(self, command):

        if command["command"] == "SYS" and command["param"] == "SHUTDOWN":
            self._logger.info("Shutdown Request Received. Terminating Node")
            self.SvcStop()
            return None

    def main(self):

        self._logger.info("Service Is Initializing...")

        # setup database
        sqlite_manager = SQLiteManager(self._config, self._logger)

        # catalogue all the scripts in the system
        self._logger.info("Catalogueing Engines On The System")
        sm.catalogue_local_engines(sqlite_manager, self._logger)
        self._logger.info("Catalogueing Scripts On The System")
        sm.catalogue_local_scripts(sqlite_manager, self._script_dir, self._logger)

        # create process for listening for node connections
        #  READ through parent_pipe, WRITE through child_pipe
        try:
            self._logger.info("Now Creating Pipe")
            parent_pipe, child_pipe = Pipe()
            self._logger.info("Now Creating NodeClientProcess Class")
            # node_listener = NodeListenerProcess(to_parent_pipe, to_child_pipe, self._config)
            self._logger.info("Now Creating Process With BootStrapper")
            self._node_process = Process(target=bootstrapper,
                                         args=(NodeClientProcess, (child_pipe, self._config, logutils.logging_queue)))
            self._logger.info("Now Starting Process")
            self._node_process.start()
            self._logger.info("Node Process Has Started Running")
        except Exception as e:
            self._logger.exception("An Exception Was Thrown Starting The Node Listener Process")
            self._logger.error("Later - An Exception Was Thrown")

            return

        # create process for listening for http connections

        # start logging thread
        l_thread = logutils.start_logging_thread()

        rc = None
        while rc != win32event.WAIT_OBJECT_0:
            self._logger.info("Service Is Now Running")

            # hang for 1 minute or until service is stopped - whichever comes first
            rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))

        self._node_process.terminate()

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)


from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = [

    path('admin/', admin.site.urls),
    path('', include('monitoramento.urls')),
    path('users/', include('users.urls')),
    path('clientes/', include('clientes.urls')),
    path('veiculos/', include('veiculos.urls')),
    path('', include('grupoveiculos.urls')),
    path('', include('escritorio.urls')),
    path('', include('tecnico.urls')),
    path('cadastro/', include('cadastros.urls')),

]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


import re

if __name__ == "__main__":
    text_phrases = ["[[link#subheading|alttext]]", "[[link]]", "[[link#subheading]]", "[[link|alttext]]"]
    for text in text_phrases:
        result = re.search(r"\[\[([^#|\]]+)([^|\]]*)([^\]]*)\]\]", text)
        groups = result.groups()

        printText = ""

        if groups[1] != '': # i.e. there's a subheading
            printText = "[[{}{}]]".format(groups[1],groups[2])
        else:
            printText = "[[#{}{}]]".format(groups[0], groups[2])

        print(printText)


# Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
    n = int(input())
    #print(n)
    input_string = input()
    numbers = list(map(int, input_string.split()))
    #mean
    numbersum = sum(numbers)
   # print (numbersum)
    mean = numbersum/n
    print (mean)
    #meadian
    numbers.sort()
    #print (numbers)
    if (n %2 ==1):
        median = numbers[int(n/2)-1]
    else:
        middle = [int(n/2)-1,int(n/2)]
        denominator = [numbers[i] for i in middle]
        #print (denominator)
        donominatorsum = sum(denominator)
        #print (donominatorsum)
        median = donominatorsum/2
    print (median)

    from collections import Counter
    c = Counter(numbers)
    print (c.most_common(1)[0][0])


import unittest
from typing import List

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if digits is None or len(digits) == 0:
            return []
        res = [""]
        alph = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        def combine(res, str):
            temp = []
            for i in range(0, len(str)):
                for j in range(0, len(res)):
                    temp.append(res[j] + str[i])
            return temp
        for digit in digits:
            res = combine(res, alph[int(digit)])
        return res

class UnitTest(unittest.TestCase):
    def test(self):
        digits = "23"
        self.assertEqual(["ad","ae","af","bd","be","bf","cd","ce","cf"], Solution().letterCombinations(digits))

if __name__ == "__main__":
    unittest.main()


import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_LSM303

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# Raspberry Pi pin configuration:
RST = 24
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
# Note you can change the I2C address by passing an i2c_address parameter like:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3d)
# Create a LSM303 instance.
lsm303 = Adafruit_LSM303.LSM303()

disp.begin()

disp.clear()
disp.display()

width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
x = 2
top = 2
padding = 12
# Load default font.
font = ImageFont.load_default()

dot_arr = []
dot_max = 50
def map_range(a,b, s):
	(a1, a2), (b1, b2) =a,b
	return b1 + ((s -a1) * (b2 -b1) / (a2 - a1))

while True:
    draw.rectangle((0,0,width,height), outline=0, fill=0)
   # draw graph
    draw.line((padding, height-padding, padding, -height+padding), fill=255)
    draw.line((padding, height-padding, padding+width, height-padding), fill=255)

      # Read the X, Y, Z axis acceleration values and print them.
    accel, mag = lsm303.read()
    # Grab the X, Y, Z components from the reading and print them out.
    accel_x = accel[0]

    if len(dot_arr) <= 115:
    	dot_arr.append(accel_x)
    else:
    	del dot_arr[0]
    	dot_arr.append(accel_x)
    x_pos = 15

    for i in range(1,len(dot_arr)):
    	y_pos = map_range((520, -520), (0 , height - padding), dot_arr[i])
    	last_y_pos = map_range((520, -520), (0 , height - padding), dot_arr[i-1])
    	y_pos = round(y_pos)
    	draw.point((x_pos, y_pos), fill=255)
    	draw.line((x_pos,y_pos,x_pos-1,last_y_pos),fill=255)
    	x_pos += 1

    disp.image(image)

    disp.display()
    # Wait half a second and repeat.
    time.sleep(0.5)


'''
Created on 2012/03/20

@author: hogelog
'''

from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import threading
import logging

class HttpControlerHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        mapping = self.mapping()
        path = self.path
        if path in mapping:
            content = mapping[path]()
            if content:
                self.send_response(200)
                self.send_header("Content-type", "text/plain")
                self.end_headers()
                self.wfile.write(content)
            else:
                self.send_error(500, "Server Error")
                self.end_headers()
        else:
            self.send_error(404, "Not Found")
            self.end_headers()

    def mapping(self):
        return {}

class BaseHttpControlerHandler(HttpControlerHandler):
    def index(self):
        return "Hello Http Controler!"

    def mapping(self):
        return {
            "/": self.index,
        }

class HttpControler(threading.Thread, HTTPServer):
    def __init__(self, host, port, handler):
        self.address = (host, port)
        self.handler = handler
        threading.Thread.__init__(self)
        HTTPServer.__init__(self, self.address, self.handler)

    def run(self):
        logging.info("start server: %s", self.address)
        self.serve_forever()

    def __stop(self):
        threading.Thread.__stop(self)
        logging.info("stop server: %s", self.address)

if __name__ == '__main__':
    class Handler(BaseHttpControlerHandler):
        def start(self):
            return "Start!"

        def stop(self):
            return "Stop!"

        def mapping(self):
            mapping = BaseHttpControlerHandler.mapping(self)
            mapping["/start"] = self.start
            mapping["/stop"] = self.stop
            return mapping

    server = HttpControler("0.0.0.0", 12345, Handler)
    server.start()
#    server.shutdown()


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

import os
import platform
import sys
import typing

import numpy as np
import pandas as pd
import tensorflow as tf

sys.path.append(".")
import delay
import delay.agents
import delay.core

tf.disable_eager_execution()
keras = tf.keras
if typing.TYPE_CHECKING:
    from typing import *

print('Python', platform.python_version())
print('Tensorflow', tf.VERSION)
print('Keras', keras.__version__)

# Configuration

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

H = 3600
D = 24 * H

FIT_PREDICT_KWARGS = dict(
    batch_size=10000,
    verbose=0,
    callbacks=None,
)

DATA_PATH = './data/TencentCVR_base.feather'

COLUMN_CONFIG = delay.core.ColumnConfig(
    click_ts='clickTime',
    convert_ts='conversionTime',
    features={
        # name: (shape, dtype, categorical_size + 1, embedding_size)
        'creativeID': ((), np.int32, 48836, 256),
        'positionID': ((), np.int16, 21488, 256),
        'connectionType': ((), np.int8, 5, 8),
        'telecomsOperator': ((), np.int8, 4, 8),
        'adID': ((), np.int16, 29726, 256),
        'camgaignID': ((), np.int16, 6583, 128),
        'advertiserID': ((), np.int16, 639, 32),
        'appID': ((), np.int16, 465, 32),
        'appPlatform': ((), np.int8, 2, 8),
        'appCategory': ((), np.int8, 28, 8),
        'sitesetID': ((), np.int8, 3, 8),
        'positionType': ((), np.int8, 6, 8),
        'age': ((), np.int8, 81, 16),
        'gender': ((), np.int8, 3, 8),
        'education': ((), np.int8, 8, 8),
        'marriageStatus': ((), np.int8, 4, 8),
        'haveBaby': ((), np.int8, 7, 8),
        'hometown': ((), np.int16, 365, 32),
        'residence': ((), np.int16, 405, 32),
    },
    other_embedding_size=8,
)

MIN_TS, MAX_TS, STEP_TS, EVAL_TS = 0, 12 * D, 1 * H, 7 * D

def intermediate_layers_config_fn():
    return [
        (keras.layers.Dense, dict(units=128,
                                  activation=keras.layers.LeakyReLU(),
                                  kernel_regularizer=keras.regularizers.L1L2(l2=1e-7),
                                  name='hidden_1')
         ),
        (keras.layers.Dense, dict(units=128,
                                  activation=keras.layers.LeakyReLU(),
                                  kernel_regularizer=keras.regularizers.L1L2(l2=1e-7),
                                  name='hidden_2')
         ),
    ]

# Load data

data_provider = delay.core.DataProvider(df=pd.read_feather(DATA_PATH), cc=COLUMN_CONFIG,
                                        fast_index=(MIN_TS, MAX_TS, STEP_TS))
print(len(data_provider.df), data_provider.df[COLUMN_CONFIG.convert_ts].notnull().mean())

# Experiments

def run_exp(method: 'delay.core.MethodABC'):
    if isinstance(method, delay.core.Methods.FTP):
        agent_class = delay.agents.FTPAgent
    else:
        agent_class = delay.agents.SimpleDNNAgent
    agent = agent_class(method=method,
                        data_provider=data_provider,
                        intermediate_layers_config_fn=intermediate_layers_config_fn,
                        fit_predict_kwargs=FIT_PREDICT_KWARGS)
    result = delay.core.run_streaming(agent, min_ts=MIN_TS, max_ts=MAX_TS, step_ts=STEP_TS, eval_ts=EVAL_TS)
    print(method.description, result)
    return {'method': method.description, **result}

result_df = pd.DataFrame()

result_df = result_df.append(run_exp(delay.core.Methods.Prophet(
    description='Prophet*',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.Waiting(
    window_size=4 * H,
    description='Waiting(4h)',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.Waiting(
    window_size=6 * H,
    description='Waiting(6h)',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.Waiting(
    window_size=12 * H,
    description='Waiting(12h)',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.Waiting(
    window_size=24 * H,
    description='Waiting(24h)',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.Waiting(
    window_size=48 * H,
    description='Waiting(48H)',
)), ignore_index=True)

result_df = result_df.append(run_exp(delay.core.Methods.FTP(
    task_window_sizes=[1 * H, 6 * H, 24 * H, 48 * H],
    n_more_shared_layers=1,
    fp_train_min_ts=1 * D,
    ema_loss_init=0.10,
    enable_gradients=[1, 1, 1, 1, 1],
    description='FTP',
)), ignore_index=True)

print(result_df)


import unittest
from unittest import TestCase
import sys
sys.path.insert(0, '../uasyncio')
import queues

class QueueTestCase(TestCase):

    def _val(self, gen):
        """Returns val from generator."""
        while True:
            try:
                gen.send(None)
            except StopIteration as e:
                return e.value

    def test_get_put(self):
        q = queues.Queue(maxsize=1)
        self._val(q.put(42))
        self.assertEqual(self._val(q.get()), 42)

    def test_get_put_nowait(self):
        q = queues.Queue(maxsize=1)
        q.put_nowait(12)
        try:
            q.put_nowait(42)
            self.assertTrue(False)
        except Exception as e:
            self.assertEqual(type(e), queues.QueueFull)
        self.assertEqual(q.get_nowait(), 12)
        try:
            q.get_nowait()
            self.assertTrue(False)
        except Exception as e:
            self.assertEqual(type(e), queues.QueueEmpty)

    def test_qsize(self):
        q = queues.Queue()
        for n in range(10):
            q.put_nowait(10)
        self.assertEqual(q.qsize(), 10)

    def test_empty(self):
        q = queues.Queue()
        self.assertTrue(q.empty())
        q.put_nowait(10)
        self.assertFalse(q.empty())

    def test_full(self):
        q = queues.Queue(maxsize=1)
        self.assertFalse(q.full())
        q.put_nowait(10)
        self.assertTrue(q.full())

if __name__ == '__main__':
    unittest.main()


#!/usr/bin/env python3

import os, sys, logging, subprocess, json, traceback

def main():
	s = Setup()
	s.interpret_arguments(sys.argv)
	s.ensure_java_maven_exists()
	s.ensure_conda_exists()
	s.recreate_conda_environment()
	s.install_via_pip('clingo==5.5.0.post3 jpype1==1.2.1')
	s.reclone_hexlite('v1.4.0')
	s.build_hexlite_java_api()
	s.install_hexlite()
	s.build_this_plugin()

	# either use full classpath provided by maven (that is slow)
	#s.get_classpath()
	# or use only jar with dependencies (created by maven-shade-plugin, faster than asking mvn for classpath)
	# the "./" is for being able to put log4j2.xml into ./
	cwd = os.getcwd()
	s.config['classpath'] = '%s/:%s/plugin/target/owlapiplugin-1.1.0.jar' % (cwd, cwd)

	s.run_example('koala', ['querykoala1.hex'])
	s.run_example('koala', ['querykoala2.hex'])
	s.run_example('factory', ['domain.hex', 'query_allpainted.hex'])
	s.run_example('factory', ['domain.hex', 'query_deactivatable.hex'])
	s.run_example('factory', ['domain.hex', 'query_skippable.hex'])

class Setup:
	PYTHONVER='3.7'
	# for public access
	#HEXLITE_CLONE_SOURCE='https://github.com/hexhex/hexlite.git'
	# for developer access (including push possibility)
	HEXLITE_CLONE_SOURCE='git@github.com:hexhex/hexlite.git'

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

	def __run_shell_get_stdout(self, cmd, allow_fail=False, wd=None):
		logging.info("running %s", cmd)
		env = os.environ.copy()
		if 'classpath' in self.config:
			# the first path is for the built plugin
			# the second path is for the logging configuration
			env['CLASSPATH'] = self.config['classpath'] + ':plugin/target/classes/:plugin/'
		cwd = os.getcwd()
		if wd is not None:
			cwd = wd
		p = subprocess.Popen('bash -c "%s"' % cmd, env=env, cwd=cwd, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr)
		stdout = p.communicate()[0].decode('utf-8')
		if not allow_fail and p.returncode != 0:
			raise Exception("failed program: "+cmd)
		return stdout

	def interpret_arguments(self, argv):
		if len(argv) != 2:
			raise Exception("expect exactly the following arguments: <conda-environment>")
		self.config['env'] = argv[1]
		logging.info("config is %s", self.config)

	def ensure_conda_exists(self):
		ver = self.__run_shell_get_stdout('conda --version')
		logging.info("found conda version %s", ver)

	def ensure_java_maven_exists(self):
		ver = self.__run_shell_get_stdout('java --version')
		logging.info("found java version %s", ver)
		ver = self.__run_shell_get_stdout('mvn --version')
		logging.info("found maven version %s", ver)

	def recreate_conda_environment(self):
		env = self.config['env']
		assert(env != 'base')
		self.__run_shell_get_stdout('conda env remove -y --name %s >&2' % env, allow_fail=True)
		self.__run_shell_get_stdout('conda create -y --name %s python=%s pandas >&2' % (env, self.PYTHONVER))
		self.__run_shell_get_stdout('source activate %s' % env)

	def install_jpype_via_build(self, github_ref):
		env = self.config['env']

		logging.info('cloning jpype')
		self.__run_shell_get_stdout("rm -rf jpype")
		self.__run_shell_get_stdout("git clone https://github.com/jpype-project/jpype.git >&2 && cd jpype && git checkout %s >&2" % github_ref)
		self.__run_shell_get_stdout("source activate %s && cd jpype && python setup.py sdist >&2" % (env,))

		logging.info('building jpype into conda env')
		# $ is interpreted by outer shell, but we want it to be interpreted by inner shell (the 'bash' started by __run_shell_get_stdout)
		path = self.__run_shell_get_stdout('source activate %s && echo \\$CONDA_PREFIX' % env).strip()
		logging.info('got path %s', path)
		ld_orig = path+'/compiler_compat/ld'
		ld_temp = path+'/compiler_compat/ld_temp'
		logging.info("hiding %s as %s", ld_orig, ld_temp)
		os.rename(ld_orig, ld_temp) # conda bug, see readme in hexlite repo
		try:
			self.__run_shell_get_stdout('source activate %s && cd jpype && pip install dist/* >&2' % env)
		finally:
			os.rename(ld_temp, ld_orig) # restore conda env

	def install_jpype_via_conda(self, version=None):
		env = self.config['env']
		ver = ''
		if version is not None:
			ver = '='+version
		self.__run_shell_get_stdout("source activate %s && conda install -y -c conda-forge jpype1%s >&2" % (env, ver))

	def install_via_pip(self, what='"clingo>=5.5.0" "jpype1>=1.2.1"'):
		env = self.config['env']
		self.__run_shell_get_stdout("source activate %s && pip3 install %s >&2" % (env, what))

	def reclone_hexlite(self, github_ref):
		logging.info('cloning hexlite')
		self.__run_shell_get_stdout("rm -rf hexlite")
		self.__run_shell_get_stdout("git clone %s >&2 && cd hexlite && git checkout %s >&2" % (self.HEXLITE_CLONE_SOURCE,github_ref) )

	def build_hexlite_java_api(self):
		logging.info('building and installing hexlite Java API')
		env = self.config['env']
		self.__run_shell_get_stdout("source activate %s && cd hexlite/ && mvn clean compile package install >&2" % env)

	def install_hexlite(self):
		logging.info('installing hexlite')
		env = self.config['env']
		self.__run_shell_get_stdout("source activate %s && cd hexlite/ && python setup.py install >&2" % env)

	def build_this_plugin(self):
		logging.info('building OWLAPI Plugin')
		env = self.config['env']
		self.__run_shell_get_stdout("source activate %s && cd plugin && mvn clean compile package >&2" % env)

	def get_classpath(self):
		env = self.config['env']
		self.config['classpath'] = self.__run_shell_get_stdout("source activate %s && cd plugin && mvn dependency:build-classpath -Dmdep.outputFile=/dev/stdout -q" % env)
		logging.info("got classpath %s", self.config['classpath'])

	def run_example(self, directory, hexfiles):
		env = self.config['env']
		cwd = os.getcwd()
		call = "hexlite --pluginpath %s/hexlite/plugins/ --plugin javaapiplugin at.ac.tuwien.kr.hexlite.OWLAPIPlugin --number 33" % cwd
		# call += ' --verbose'
		# call += ' --debug'
		call += ' --stats'
		#call += ' --noeatomlearn'
		logging.warning("TODO fix bug in FLP checker (parser?)")
		call += ' --flpcheck=none'
		execdir = os.path.join('examples', directory)
		stdout = self.__run_shell_get_stdout("cd %s && source activate %s && %s -- %s" % (execdir, env, call, ' '.join(hexfiles)))
		sys.stdout.write(stdout)

logging.basicConfig(level=logging.INFO)
try:
	main()
except Exception:
	logging.error(traceback.format_exc())

# vim:noet:nolist:


import sys
try:
    i=int(input("enter a number or Enter to finish: "))
except:
    print(" -_- ")
    sys.exit(0)
l=[]
while True:
    s=int(i)
    l.append(s)
    try:
        i=int(input("enter a number or Enter to finish: "))
    except:
        break
print("numbers: ",l)
c=len(l)
su=0
hi=l[0]
low=l[0]
for i in l:
    su=su+i
    if i>hi:
        hi=i
    if i<low:
        low=i
avg=su/c
for i in range(1,c):
    j=i-1
    key=l[i]
    while((j>=0)and(key<l[j])):
        l[j+1]=l[j]
        j=j-1
    l[j+1]=key
print(l)
if c%2!=0:
	med=l[int(c/2)]
else:
	med=((l[int(c/2)]+l[int(c/2)-1])/2)
print("count = ",c," sum = ",su," lowest = ",low," highest = ",hi," mean = ",avg," median = ",med)


import sqlite3

name = input("Name of the pdgm project you are working on: ")

db = sqlite3.connect(name + ".sqlite")
cursor = db.cursor()

print("""Please enter source and target of your dependencies.

After each entry you have to confirm the entry. The question can be answered in four ways:
 y - yes:  Valid entry, continue with next entry
 n - no:   Invalid entry, continue with next entry
 d - done: Valid entry, submit and stop the program
 q - quit: Invalid entry, stop without submitting
The answers are case-insensitive. The default (empty) answer means [y]es.
Every other answer is a [n]o.
""")
source = ""

def newlink():
	global source, cursor
	source = input("Source[" + source + "]: ") or source
	target = input("Target: ")
	check = input("Do you want to add link (" + source + ", " + target + ")? [y]ndq: ") or "y"
	check = check.lower()
	if check == "y":
		cursor.execute("INSERT INTO links VALUES (?,?)", (source, target))
		print("Added link (" + source + ", " + target + ")")
		return 1
	elif check == "d":
		cursor.execute("INSERT INTO links VALUES (?,?)", (source, target))
		print("Added link (" + source + ", " + target + ")")
		return -1
	elif check == "q":
		return -2
	else:
		return 0

additions = 0

while True:
	v = newlink()
	if v == -1:
		additions += 1
		break
	elif v == 1:
		additions += 1
	elif v == -2:
		break

print("Added %d links to the database." % (additions,))

db.commit()
db.close()


import sys
N=int(input())

houses = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]

dir = [(-1,0),(1,0),(0,1),(0,-1)]
def posiible_path(x,y):
    if (0<=x<N) and (0<=y<N):
        return True

    return False

def dfs(x,y,selected):
    visited[x][y]=True
    selected.append((x,y))

    for dirx, diry in dir:
        nextx = x+dirx
        nexty = y+diry

        if posiible_path(nextx,nexty):
            if not visited[nextx][nexty] and houses[nextx][nexty]==1:
                dfs(nextx,nexty,selected)

num_of_houses=0
kind_of_houses=[]
visited=[[False for _ in range(N)]for _ in range(N)]
for i in range(N):
    for j in range(N):
        if not visited[i][j] and houses[i][j]==1:
            selected=[]
            dfs(i,j,selected)
            num_of_houses+=1
            kind_of_houses.append(len(selected))

print(num_of_houses)
for num in sorted(kind_of_houses):
    print(num)


from flask import Blueprint
from flask_restful import Api

from .resources import PersonResource, PersonIdResource, PostUserResource, PostAccountResource, GetAccountResource, GetAccountIdResource

bp = Blueprint("restapi", __name__, url_prefix="/api")
api = Api(bp)

def init_app(app):
    api.add_resource(PersonResource, "/person/")
    api.add_resource(PersonIdResource, "/person/<person_id>")
    api.add_resource(PostUserResource, "/person/post/")
    api.add_resource(GetAccountResource, "/account/get/")
    api.add_resource(PostAccountResource, "/account/post/")
    api.add_resource(GetAccountIdResource, "/account/get/<account_id>")

    app.register_blueprint(bp)


import socket

remoteserver=input("Pls enter remote server name or ip for port scanning:")

remoteipaddress= socket.gethostbyname(remoteserver)

for port in range(131,151):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result= sock.connect_ex((remoteipaddress, port))
    if result == 0:
        print("{} is open".format(port))
    else:
        print("{} is closed".format(port))


########################################################################################################
#
#   Determinado banco possui os dados de histórico de empréstimo, vistos na tabela abaixo. Com esse dados,
#   o banco solicitou que fosse construído um modelo que fornecendo os dados de entrada, indique se deverá
#   fornecer ou não o empréstimo
#
#########################################################################################################

# Importando as bibliotecas
import pandas as pd
from sklearn.naive_bayes import GaussianNB
from sklearn import preprocessing

# Gerando o dataset
dados = {'Tempo': ['Ensolarado', 'Ensolarado', 'Nublado', 'Chuvoso', 'Chuvoso', 'Chuvoso',
                   'Nublado', 'Ensolarado', 'Ensolarado', 'Chuvoso'],
         'Umidade': ['Alta', 'Alta', 'Alta', 'Alta', 'Normal', 'Normal', 'Normal', 'Alta',
                     'Normal', 'Normal'],
         'Vento': ['Fraco', 'Forte', 'Fraco','Fraco', 'Fraco', 'Forte', 'Forte', 'Fraco', 'Fraco', 'Fraco'],
         'Treinou': ['Não', 'Não', 'Sim', 'Sim', 'Sim', 'Não', 'Sim', 'Não', 'Sim','Sim']}

dados = pd.DataFrame(data = dados)

# Criando o LabelEncoder
tempo_lbencoder = preprocessing.LabelEncoder()
umidade_lbencoder = preprocessing.LabelEncoder()
vento_lbencoder = preprocessing.LabelEncoder()
treinou_lbencoder = preprocessing.LabelEncoder()

# Usando o LabelEncoder para atribuir números às variáveis qualitativas
tempo_lbencoder.fit(dados['Tempo'].unique())
umidade_lbencoder.fit(dados['Umidade'].unique())
vento_lbencoder.fit(dados['Vento'].unique())
treinou_lbencoder.fit(dados['Treinou'].unique())

# Transformando o dataset de variáveis qualitativas para variáveis quantitativas
dados['Tempo'] = tempo_lbencoder.transform(dados['Tempo'])
dados['Umidade'] = umidade_lbencoder.transform(dados['Umidade'])
dados['Vento'] = vento_lbencoder.transform(dados['Vento'])
dados['Treinou'] = treinou_lbencoder.transform(dados['Treinou'])

# Separando o nosso dataset nos atributos previsores e na classe objetivo
previsor = dados[['Tempo','Umidade','Vento']]
classe = dados['Treinou']

# Criando o classificador NaiveBayes
gnb = GaussianNB()
gnb.fit(previsor, classe)

# Verificando a precisão
print("\n Precisão = ", gnb.score(previsor, classe)*100,"%")

# Inserindo novos dados para serem previstos
previsao = {'Tempo': ['Ensolarado', 'Nublado', 'Nublado','Chuvoso'],
            'Umidade': ['Normal', 'Alta','Normal','Alta'],
            'Vento':['Forte', 'Forte', 'Fraco', 'Forte']}

previsao = pd.DataFrame(data = previsao)

previsao['Tempo'] = tempo_lbencoder.transform(previsao['Tempo'])
previsao['Umidade'] = umidade_lbencoder.transform(previsao['Umidade'])
previsao['Vento'] = vento_lbencoder.transform(previsao['Vento'])

# Verificando o resultado
print("\n", gnb.predict(previsao))
print("\n", treinou_lbencoder.inverse_transform(gnb.predict(previsao)))

# Verificando as probabilidades
print("\n", gnb.predict_proba(previsao))