# -*- coding: utf-8 -*-
from odoo import api, models, fields, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError
from odoo.osv import osv
import xmlrpclib

class FeedbackStage(models.Model):
    _name = 'ct_feedback_server.feedback.stage'
    _order = 'sequence'

    name = fields.Char(string='Name', translated=True)
    sequence = fields.Integer(string='Sequence', translated=True)
    fold = fields.Boolean(string='Folded', translated=True)

class Issue(models.Model):
    _inherit = 'project.issue'

    @api.multi
    def handle(self):
        for rec in self:
            if rec.feedback_stage_id == self.env.ref('ct_feedback_server.feedback_stage_unsolved'):
                rec.write({
                    'discarded': False,
                    'user_id': self.env.uid,
                    'feedback_stage_id': self.env.ref('ct_feedback_server.feedback_stage_inprocess').id,
                    'notify_feedback_state_change': 'handled'
                })
        return

    @api.multi
    def discard(self):
        for rec in self:
            if (rec.user_id != self.env.user) and (self.env.uid != SUPERUSER_ID):
                raise UserError(_("Only concerned user can do this operation. "
                                  "Please contact your administrator if you think there is an error."))

            if rec.feedback_stage_id == self.env.ref('ct_feedback_server.feedback_stage_inprocess'):
                rec.write({
                    'discarded': True,
                    'fixed': False,
                    'user_id': False,
                    'feedback_stage_id': self.env.ref('ct_feedback_server.feedback_stage_unsolved').id,
                    'notify_feedback_state_change': 'submitted'
                })
        return

    @api.multi
    def engage_discussion(self):
        # TODO: ALLOW ONLY THE HANDLER TO START THE DISCUSSION
        # print self[0].im_chat_url
        # return {
        #     "type": "ir.actions.act_url",
        #     "url": self[0].im_chat_url,
        #     "target": "new",
        # }
        self.ensure_one()
        ir_model_data = self.env['ir.model.data']
        compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]
        template_id = ir_model_data.get_object_reference('ct_feedback_server', 'feedback_reply_template')[1]
        ctx = dict(self.env.context or {})
        ctx.update({
            'default_model': 'project.issue',
            'default_res_id': self.ids[0],
            'default_use_template': bool(template_id),
            'default_template_id': template_id,
            'default_composition_mode': 'comment',
        })
        return {
            'name': _('Compose Email'),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'mail.compose.message',
            'views': [(compose_form_id, 'form')],
            'view_id': compose_form_id,
            'target': 'new',
            'context': ctx,
        }

    @api.multi
    def assign(self):
        if self[0].feedback_stage_id == self.env.ref('ct_feedback_server.feedback_stage_solved'):
            raise UserError(_("You cannot assign an already solved feedback!"))
        return {
            'name': 'Assign feedback to user',
            'type': 'ir.actions.act_window',
            'res_model': 'ct_feedback_server.wizard.issue',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_operation_type': 'assign',
                'default_feedback_id': self[0].id,
            }
        }

    @api.multi
    def solve(self):
        # if (self[0].user_id != self.env.user) and (self.env.uid != SUPERUSER_ID):
        if self[0].user_id != self.env.user:
            raise UserError(_("Only concerned user can do this operation. "
                              "Please contact your administrator if you think there is an error."))
        return {
            'name': 'Solve feedback',
            'type': 'ir.actions.act_window',
            'res_model': 'ct_feedback_server.wizard.issue',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_operation_type': 'fix',
                'default_feedback_id': self[0].id,
                'default_user_id': self.env.uid,
            }
        }

    def _prepare_discard_data(self, vals):
        vals['discarded'] = True
        vals['user_id'] = False
        # vals['fix_date'] = False
        vals['fixed'] = False
        # vals['fixed_by'] = False
        vals['notify_feedback_state_change'] = 'submitted'

    @api.multi
    def _compute_current_user(self):
        for rec in self:
            rec.current_uid = self.env.uid

    @api.multi
    def _compute_kanban_user_id(self):
        for rec in self:
            rec.kanban_user_id = rec.user_id and rec.user_id.id or 0

    @api.multi
    def _compute_solvable(self):
        for rec in self:
            rec.solvable = rec.feedback_stage_id and (
            rec.feedback_stage_id == self.env.ref('ct_feedback_server.feedback_stage_inprocess')) or False

    @api.multi
    def _check_user_right(self, object, action=None):
        ACTION_LIST = ['discard', 'handled', 'submitted', 'handle', 'fix', 'solved']
        if action in ACTION_LIST:
            if (object.user_id != self.env.user) and (self.env.uid != SUPERUSER_ID):
                raise UserError(_("Only concerned user can do this operation. "
                                  "Please contact your administrator if you think there is an error."))
        elif action == None:
            if self.env.uid != SUPERUSER_ID:
                raise UserError(_("Action forbidden to simple user; You may get in touch with your administrator"))

    def _default_feedback_stage(self):
        stage = self.env.ref('ct_feedback_server.feedback_stage_unsolved', raise_if_not_found=False)
        return stage and stage.id or False

    def _compute_form_link(self):
        for record in self:
            # id=3&view_type=form&model=ct_feedback_client.question&action=166
            record.form_link = "%s/web/#id=%s&view_type=form&model=ct_feedback_client.question" % (record.submitter_host, record.info_id)

    @api.model
    def _read_group_feedback_stage_ids(self, stages, domain, order):
        return stages.sudo().search([])

    write_uid = fields.Many2one('res.users', string='Discarded by', translated=True)
    fixed_by = fields.Many2one('res.users', string='Fixed by', translated=True)
    submitter_email = fields.Char(string='Submitter email', translated=True)
    submitter_name = fields.Char(string='Submitter', translated=True)
    submitter_db = fields.Char(string='Submitter database', translated=True)
    submitter_host = fields.Char(string='Submitter\'s host', translated=True)
    info_num = fields.Char(string='Feedback number', translated=True)
    info_id = fields.Integer(string='Feedback id', translated=True)

    submitter_ip = fields.Char(string='Submitter ip address', translated=True)
    submitter_county = fields.Char(string='Submitter country', translated=True)
    submitter_os = fields.Char(string='Submitter OS', translated=True)
    submitter_language = fields.Char(string='Submitter language', translated=True)
    submitter_resolution = fields.Char(string='Submitter resolution', translated=True)
    submitter_browser = fields.Char(string='Submitter resolution', translated=True)

    form_link = fields.Char(compute='_compute_form_link')
    description = fields.Html()
    is_feedback = fields.Boolean(string='Feedback', help='If this issue is a feedback from the remote client',
                                 translated=True)
    discarded = fields.Boolean(string='Discarded', help='If this issue has been discarded', tranlated=True)
    fixed = fields.Boolean(string='Fixed', help='If this issue has been fixed', tranlated=True)
    fix_date = fields.Datetime(string='Fixed on', help='Date of fixing', readonly=True, tranlated=True)
    fix_description = fields.Html(string='Fixing explanation', translated=True)
    feedback_stage_id = fields.Many2one('ct_feedback_server.feedback.stage',
                                        'Feedback stage',
                                        readonly=False,
                                        track_visibility='onchange',
                                        group_expand='_read_group_feedback_stage_ids',
                                        default=lambda self: self._default_feedback_stage(),
                                        translated=True)
    sequence = fields.Integer(string='Sequence', translated=True)
    current_uid = fields.Integer(compute='_compute_current_user', store=False)
    kanban_user_id = fields.Integer(compute='_compute_kanban_user_id', store=False)
    solvable = fields.Boolean(compute='_compute_solvable', store=False)
    # priority = fields.Selection(attrs={'readonly':['|',('discarded','=',True),('feedback_stage_id','=', lambda self: self.env.ref('ct_feedback.feedback_stage_solved').id)]})
    im_chat_url = fields.Char(string='Feedback instant message url')

    # ------------------------------
    # CRUD OVERRIDING
    # ------------------------------
    @api.multi
    def write(self, vals):

        if self.is_feedback:

            # Impossible to change the description of the feedback submitted by customer
            # TODO: Maybe Excepted the feedback_agent
            if 'description' in vals: del vals['description']

            if 'priority' in vals and (self.discarded or self.fixed):
                if self.fixed:
                    del vals['priority']
                elif not self.env.user.has_group('project.group_project_manager'):
                    del vals['priority']

            unsolved_stage = self.env.ref('ct_feedback_server.feedback_stage_unsolved')
            inprocess_stage = self.env.ref('ct_feedback_server.feedback_stage_inprocess')
            solved_stage = self.env.ref('ct_feedback_server.feedback_stage_solved')

            stages = {
                unsolved_stage.id: unsolved_stage,
                inprocess_stage.id: inprocess_stage,
                solved_stage.id: solved_stage,
            }

            '''
            CONTROLS IN CASE THE STAGE IS CHANGED USING THE KANBAN
            '''
            if self.env.context.get('from_kanban') and 'feedback_stage_id' in vals:
                new_feedback_stage = stages[vals['feedback_stage_id']]

                if self.feedback_stage_id == unsolved_stage:
                    '''IF NEW STAGE IS INPROCESSING: NOTIFY HANDLING'''
                    if new_feedback_stage == inprocess_stage:
                        vals['discarded'] = False
                        vals['user_id'] = self.env.uid
                        vals['notify_feedback_state_change'] = 'handled'
                    else:
                        '''ELSE RAISE EXCEPTION: IMPOSSIBLE TO MOVE DIRECTLY TO ANY OTHER STAGE'''
                        raise UserError(_("You cannot move directly a feedback from '%s' to '%s'" % (
                        unsolved_stage.name, new_feedback_stage.name)))

                elif self.feedback_stage_id == inprocess_stage:
                    '''IF NEW STAGE IS UNSOLVED: NOTIFY DISCARD'''
                    '''BUT BEFORE CHECK IF THE USER IS THE RESPONSIBLE'''

                    self._check_user_right(object=self, action="discard")

                    if new_feedback_stage == unsolved_stage:
                        self._prepare_discard_data(vals)

                    elif new_feedback_stage == solved_stage:
                        '''ELSE RAISE EXCEPTION: IMPOSSIBLE TO MOVE TO SOLVED BY DRAGGING'''
                        raise UserError(_("It is not allowed to move a feedback to '%s' by dragging; "
                                          "You may click on the button 'Solve' (Displayed in Form mode if the current user is responsible of the related feedback)" % solved_stage.name))
                elif self.feedback_stage_id == solved_stage:
                    # if not self.env['res.users'].has_group('project.group_project_manager'):
                    self._check_user_right(object=self, action=None)

                    '''IF NEW STAGE IS UNSOLVED: NOTIFY DISCARD IF USER IS ROOT'''
                    if new_feedback_stage == unsolved_stage:
                        self._prepare_discard_data(vals)
                    else:
                        '''ELSE RAISE EXCEPTION: IMPOSSIBLE TO MOVE DIRECTLY TO ANY OTHER STAGE'''
                        raise UserError(_("You cannot move directly a feedback from '%s' to '%s'" % (
                            solved_stage.name, new_feedback_stage.name)))
            else:
                """
                CONTROLS IN CASE THE USER JUST USED THE WIZARDS TO CHANGE THE STAGE
                """
                if 'notify_feedback_state_change' in vals:
                    self._check_user_right(object=self, action=vals['notify_feedback_state_change'])

        result = super(Issue, self).write(vals)

        if self.is_feedback:
            database = self.submitter_db
            url = self.submitter_host
            question_num = self.info_num

            if 'notify_feedback_state_change' in vals:
                r = self.env['ct_feedback_server.feedback.wizard'].notify_feedback_state_change(
                    database=database, url=url, question_num=question_num,
                    new_state=vals['notify_feedback_state_change'], update_data=vals.get('notify_feedback_data', {}))
                if not r:
                    raise UserError(_("An error occurred while reporting the feedback status change to '%s'." % url))
        return result


#!/usr/bin/python3

#Daemon manager for dnsserverp.py. Use this to run dns server as daemon, or use
#initscripts or systemd
#Run this manager with arguments [-start] or [-stop]
#
#Written for python3.4
#
#
#
#Forking daemon based off
#  http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
#

import sys, os, signal
import argparse
import time
import pwd

import dumbdns

##### Settings (change these): #####

#PID file location. The dumb-dns-server's process id will be stored here so we can
#find the process again when we want to kill the server
PID_FILE = "/var/run/dumbdns-server.pid"

def main():
   #Check if root user, if not, then exit. We need root privilege to write pid
   #files to /var/run
   if(os.getuid() != 0):
      print("You need to be root to run this")
      sys.exit(0)

   #Read command line arguments
   parser = argparse.ArgumentParser(description='dnsserver: a simple DNS server in Python3.')
   group = parser.add_mutually_exclusive_group()
   group.add_argument('-start', action='store_true', help="Start dumb-dns")
   group.add_argument('-stop', action='store_true', help="Stop dumb-dns")

   args = parser.parse_args()
   if not (args.start or args.stop):
      parser.error("Please select -start or -stop")

   #Try to lookup any previous saved process IDs
   try:
      with open(PID_FILE) as f:
         pid = int(f.readline().strip())
         if(isinstance(pid, int)):
            if(args.start):
               print("Existing pid file at {} with process ID {}".format(PID_FILE, pid))
               print("You should run -stop before trying to start a new daemon")
               sys.exit(1)
            elif(args.stop):
               stopDaemon(pid)

   #PID_FILE was not found
   except FileNotFoundError:
      if(args.start):
         startDaemon()
      elif(args.stop):
         print("Could not find pid file at {}".format(PID_FILE))
         print("Lost track of daemon, if it's running you should manually terminate it")
         sys.exit(1)

def startDaemon():

   #Begin forking daemon process, double fork used to completely decouple the daemon
   #Double forking is normally overkill and uneccesary
   #  read the following for more info:
   #  http://stackoverflow.com/questions/881388/
   try:
      pid = os.fork()
      if(pid > 0):
         #exit first parent
         sys.exit(0)
   except OSError as e:
      sys.stderr.write(e.strerror)
      sys.exit(2)

   #decouple from parent environment
   os.chdir("/")
   os.setsid()
   os.umask(0)

   #Second fork
   try:
      pid = os.fork()
      if(pid > 0):
         #exit second parent
         sys.exit(0)
   except OSError as e:
      sys.stderr.write(e.strerror)
      sys.exit(2)

   #write pid to pidfile
   pid = str(os.getpid())
   try:
      with open(PID_FILE, "w") as f:
         f.write("{}\n".format(pid))
   except:
      sys.exit(2)

   #redirect standard file descriptors to null, everything after this should go to
   #a log file
   sys.stdout.flush()
   sys.stderr.flush()
   sin = open(os.devnull, "r")
   sout = open(os.devnull, "a+")
   serr = open(os.devnull, "a+")
   os.dup2(sin.fileno(), sys.stdin.fileno())
   os.dup2(sout.fileno(), sys.stdout.fileno())
   os.dup2(serr.fileno(), sys.stderr.fileno())

   #Run daemon (dumbdns)
   dumbdns.startServer()

def stopDaemon(pid):
   print("Stopping daemon (pid = {})".format(pid))
   os.remove(PID_FILE)
   try:
      os.kill(pid, signal.SIGTERM)
   except:
      pass

if __name__ == '__main__':
   main()


import argparse
import logging
import coloredlogs

import mwclient
import mwparserfromhell

import auth_store

parser = argparse.ArgumentParser(description='Automate the wiki.')
parser.add_argument('-v', '--verbose', action='count')
parser.add_argument('-s', '--study', help='Update study pages', action='store_true')
parser.add_argument('--selfreport', help='Create initial self report pages (DO NOT RUN, for one-time use)', action='store_true')
parser.add_argument('--selfreportlibrary', help='Update self report library', action='store_true')
parser.add_argument('--medialinks-category', help='Update File: to Media: links in given category', action='append')
parser.add_argument('--medialinks-page', help='Update File: to Media: links on given page', action='append')
parser.add_argument('--redirectlinks-page', help='Update redirected links in given pages', action='append')
parser.add_argument('--redirectlinks-category', help='Update redirected links in category')
parser.add_argument('--studylibrary', help='Update study library', action='store_true')
parser.add_argument('--studyimporter', metavar="CSV", help='Create study pages from given tsv')
parser.add_argument('--timeline', help='Create or update timeline page based on Category:Study, Category:Project, and Category:Grant', action='store_true')
parser.add_argument('--studyreport', help='Generate CSV report about studies', action='store_true')
parser.add_argument('--add-category', nargs=2, metavar=('category', 'match'), help='Add category `category` to pages with `match` in the title')
parser.add_argument('--rename-category', nargs=2, metavar=('old', 'new'), help='Rename category `old` to `new`')
parser.add_argument('--rename-regex', nargs=3, metavar=('match', 'regex', 'result'), help='Rename all pages with `match` in the title replacing `regex` with `result`')
parser.add_argument('--export-gdoc', nargs=5, metavar=('wiki_prefix', 'file_prefix', 'http_prefix', 'drive_id', 'unsorted_folder_id'), help='Export wiki with `wiki_prefix` to google drive at `drive_id` creating unsorted folders in `unsorted_folder_id` for eventual gdocwiki use where `file_prefix` allows public-internet-visible viewing of files at `http_prefix` [EXPERIMENTAL]')
parser.add_argument('--export-gdoc-single', nargs=6, metavar=('wiki_prefix', 'file_prefix', 'http_prefix', 'drive_id', 'unsorted_folder_id', 'page_title'), help='Export single wiki page with `wiki_prefix` to google drive at `drive_id` creating unsorted folders in `unsorted_folder_id` for eventual gdocwiki use where `file_prefix` allows public-internet-visible viewing of files at `http_prefix` [EXPERIMENTAL]')
parser.add_argument('--link-gdoc', nargs=4, metavar=('file_prefix', 'drive_id', 'files_folder_id', 'folder_id'), help='Walk folder with `folder_id` and repair links based on stored mappings [EXPERIMENTAL]')
parser.add_argument('--link-gdoc-single', nargs=4, metavar=('file_prefix', 'drive_id', 'files_folder_id', 'doc_id'), help='Repair links in doc based on stored mappings [EXPERIMENTAL]')
parser.add_argument('-f', '--force', help='Force whatever changes instead of trying to be precise about updates', action='store_true')
parser.add_argument('-n', '--older', metavar="ISO_DATE", help='Update pages not updated since a given date')
parser.add_argument('-a', '--all', help='Run all known automated updates', action='store_true')
args = parser.parse_args()

if args.verbose:
    if args.verbose > 1:
        coloredlogs.install(level='DEBUG')
    elif args.verbose > 0:
        coloredlogs.install(level='INFO')
else:
    coloredlogs.install(level='WARN')

auth = auth_store.get_auth()
user = auth[0]

ua = 'factuator/0.1 run by User:' + user
mother = mwclient.Site('wiki.keck.waisman.wisc.edu', path='/wikis/mother/', httpauth=auth)

if args.study:
    import study
    study.run(mother)
elif args.selfreport:
    import selfreport
    selfreport.run(mother)
elif args.selfreportlibrary:
    import selfreportlibrary
    selfreportlibrary.run(mother)
elif args.medialinks_category:
    import medialinks
    medialinks.run_categories(mother, args.medialinks_category)
elif args.medialinks_page:
    import medialinks
    medialinks.run_pages(mother, args.medialinks_page)
elif args.redirectlinks_page:
    import redirectlinks
    redirectlinks.run_pages(mother, args.redirectlinks_page)
elif args.redirectlinks_category:
    import redirectlinks
    redirectlinks.run_category(mother, args.redirectlinks_category)
elif args.studyimporter:
    import studyimporter
    studyimporter.run(mother, args.studyimporter)
elif args.studylibrary:
    import studylibrary
    studylibrary.run(mother)
elif args.timeline:
    import timeline
    timeline.run(mother)
elif args.studyreport:
    import studyreport
    studyreport.run(mother)
elif args.add_category:
    import addcategory
    addcategory.run(mother, args.add_category[0], args.add_category[1])
elif args.rename_category:
    import renamecategory
    renamecategory.run(mother, args.rename_category[0], args.rename_category[1])
elif args.rename_regex:
    import renameregex
    renameregex.run(mother, args.rename_regex[0], args.rename_regex[1], args.rename_regex[2])
elif args.all:
    import study
    study.run(mother)
    import studylibrary
    studylibrary.run(mother)
    import selfreportlibrary
    selfreportlibrary.run(mother)
    import timeline
    timeline.run(mother)
elif args.export_gdoc:
    import gdocdriver
    gdocdriver.export_mediawiki(mother, args.export_gdoc[0],
            args.force, args.older,
            args.export_gdoc[1], args.export_gdoc[2],
            args.export_gdoc[3], args.export_gdoc[4])
elif args.export_gdoc_single:
    import gdocdriver
    gdocdriver.export_mediawiki(mother, args.export_gdoc_single[0],
            args.force, args.older,
            args.export_gdoc_single[1], args.export_gdoc_single[2],
            args.export_gdoc_single[3], args.export_gdoc_single[4],
            args.export_gdoc_single[5])
elif args.link_gdoc:
    import gdocdriver
    gdocdriver.link_folder(mother, args.link_gdoc[0], args.link_gdoc[1],
            args.link_gdoc[2], args.link_gdoc[3])
elif args.link_gdoc_single:
    import gdocdriver
    gdocdriver.link_doc(mother, args.link_gdoc_single[0], args.link_gdoc_single[1],
            args.link_gdoc_single[2], args.link_gdoc_single[3])
else:
    parser.print_help()


import argparse
import glob
import json
import os
import shutil
from subprocess import check_call

install_schemes = {
    'system': {
        'application': '/opt',
        'commands': '/usr/local/bin',
        'desktop': '/usr/local/share/applications',
        'icons': '/usr/local/share/icons',
        'mimetypes': '/usr/local/share/mime/packages',
    },
    'user': {
        'application': '{XDG_DATA_HOME}/installed-applications',
        'commands': '~/.local/bin',
        'desktop': '{XDG_DATA_HOME}/applications',
        'icons': '{XDG_DATA_HOME}/icons',
        'mimetypes': '{XDG_DATA_HOME}/mime/packages',
    }
}

class ApplicationInstaller(object):
    def __init__(self, directory, scheme):
        self.directory = directory
        self.scheme = install_schemes[scheme]
        with open(self._relative('batis_info', 'metadata.json')) as f:
            self.metadata = json.load(f)

    def _relative(self, *path):
        return os.path.join(self.directory, *path)

    def destination(self, component):
        XDG_DATA_HOME = os.environ.get('XDG_DATA_HOME') or "~/.local/share"
        path = os.path.expanduser(self.scheme[component].format(XDG_DATA_HOME=XDG_DATA_HOME))
        os.makedirs(path, mode=0o755)
        return path

    def copy_application(self):
        shutil.copytree(self.directory, os.path.join(self.destination('application'),
                                                     os.name))

    def install_commands(self):
        pass

    def install_icons(self):
        pass
        # check_call(['xdg-icon-resource', 'install', '--noupdate', '--theme', theme,
        #       '--size', size, '--context', context, file])
        # check_call(['xdg-icon-resource', 'forceupdate', '--theme', theme])

    def install_mimetypes(self):
        for file in glob.glob(self._relative('batis_info', 'mime', '*.xml')):
            check_call(['xdg-mime', 'install', file])

    def install_desktop_files(self):
        files = glob.glob(self._relative('batis_info', 'desktop', '*.desktop'))
        check_call(['desktop-file-install', '--rebuild-mime-info-cache'] + files)

    def install(self):
        self.copy_application()
        self.install_commands()
        self.install_icons()
        self.install_mimetypes()
        self.install_desktop_files()

def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--system', action='store_true',
            help='Install systemwide, instead of for the user')
    ap.add_argument('directory', help='The unpacked application tarball')
    args = ap.parse_args(argv)
    ai = ApplicationInstaller(args.directory, 'system' if args.system else 'user')
    ai.install()

if __name__ == '__main__':
    main()


import json
import pickle
import argparse
import numpy as np
from collections import namedtuple

Turn = namedtuple('Turn', ['in_edge', 'outflows', 'probabilities'])
Outflow = namedtuple('Outflow', ['out_edge', 'phase'])

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--turns-file', required=True, help='Turns file (.pkl)')
    parser.add_argument('--flow-file', required=True, help='Flow file (.json)')
    parser.add_argument('--output-file', required=True, help='Output file')
    parser.add_argument('--sample-count', type=int, required=True, help='Sample count')
    args = parser.parse_args()
    return args

def sample_outflows_for_edge(edge, turns, sample_count):
    outflow_count = len(turns.outflows)
    indices = np.random.choice(outflow_count,
                               size=sample_count,
                               p=turns.probabilities)
    return [turns.outflows[index] for index in indices]

# Warning: Works only for a single intersection!
def main():
    args = get_args()

    with open(args.turns_file) as fp:
        turns = pickle.load(fp)

    with open(args.flow_file) as fp:
        flows = json.load(fp)

    samples = {}

    for flow in flows:

        route = flow['route'].split()
        count = flow['count']
        prefix = flow['id']

        for vehIndex in range(count):
            vehID = '{}.{}'.format(prefix, vehIndex)
            samples[vehID] = {}

            processed_edges = set()
            unprocessed_edges = set()

            for edge in route:
                if edge in unprocessed_edges:
                    raise ValueError('{} occurs twice in {}\'s route'.format(edge, vehID))
                unprocessed_edges.add(edge)

            while unprocessed_edges:

                edge = unprocessed_edges.pop()

                # Don't sample on boundary edges
                if edge not in turns:
                    continue

                if edge in processed_edges:
                    continue

                sampled_outflows = sample_outflows_for_edge(edge, turns[edge], args.sample_count)
                samples[vehID][edge] = sampled_outflows
                processed_edges.add(edge)

                for (out_edge, phase) in sampled_outflows:
                    if out_edge not in processed_edges:
                        unprocessed_edges.add(out_edge)

    with open(args.output_file, 'w') as fp:
        pickle.dump(samples, fp)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# encoding: utf-8
"""
variant_annotator.py

Consumes batches of variants and annotates them. Each batch is a dictionary
with variant_id:s as keys and dictionaries with variant information.
The variants will get different annotations depending on input

Created by Måns Magnusson on 2013-03-01.
Copyright (c) 2013 __MyCompanyName__. All rights reserved.
"""

from __future__ import (division, print_function, absolute_import)

import sys
import os
import operator
import tabix
import logging

from multiprocessing import Process
from math import log10

from genmod.vcf_tools import get_variant_dict, add_vcf_info
from genmod.annotate_regions import (get_genes, check_exonic)
from genmod.annotate_variants import (get_frequencies, get_cadd_scores,
get_spidex_score, get_cosmic)

# from . import (annotate_cadd_score, annotate_frequency, check_genetic_models)

class VariantAnnotator(Process):
    """
    Annotates variant in batches from the task queue and puts the result in
    the results queue.
    """

    def __init__(self, task_queue, results_queue, **kwargs):

        Process.__init__(self)
        self.logger = logging.getLogger(__name__)

        self.proc_name = self.name

        self.logger.info("Setting up variant_annotator: {0}".format(
            self.proc_name))
        self.logger.debug("Setting up task queue")

        self.task_queue = task_queue

        self.logger.debug("Setting up results queue")
        self.results_queue = results_queue

        self.header_line = kwargs.get('header_line')
        if not self.header_line:
            raise IOError("VariantAnnotator needs a vcf header line")

        self.cadd_raw = kwargs.get('cadd_raw', None)
        self.logger.debug("Setting cadd raw to {0}".format(self.cadd_raw))

        self.max_af = kwargs.get('max_af', None)
        self.logger.debug("Setting max_af to {0}".format(self.max_af))

        self.spidex = kwargs.get('spidex', None)
        self.logger.debug("Setting spidex to {0}".format(self.spidex))

        self.cosmic = kwargs.get('cosmic', None)
        self.logger.debug("Setting cosmic to {0}".format(self.spidex))

        self.exon_trees = kwargs.get('exon_trees', {})
        self.gene_trees = kwargs.get('gene_trees', {})

        ######### Annotation files #########
        # Cadd files #
        self.cadd_handles = []
        for cadd_path in kwargs.get('cadd_files', []):
            self.logger.debug("Opening cadd file {0} with tabix open".format(
                cadd_path
            ))
            self.cadd_handles.append(tabix.open(cadd_path))
            self.logger.debug("Cadd file opened")

        # Frequency files #
        self.thousand_g = kwargs.get('thousand_g', None)
        self.logger.debug("1000G frequency file {0}".format(self.thousand_g))
        self.exac = kwargs.get('exac', None)
        self.logger.debug("Exac frequency file {0}".format(self.thousand_g))
        # self.dbNSFP = kwargs.get('dbNSFP', None)

        if self.thousand_g:
            self.logger.debug("Opening 1000G frequency file with tabix open")
            self.thousand_g = tabix.open(self.thousand_g)
            self.logger.debug("1000G frequency file opened")
        if self.exac:
            self.logger.debug("Opening ExAC frequency file with tabix open")
            self.exac = tabix.open(self.exac)
            self.logger.debug("ExAC frequency file opened")
        if self.spidex:
            self.logger.debug("Opening Spidex database with tabix open")
            self.spidex = tabix.open(self.spidex)
            self.logger.debug("Spidex file opened")
        if self.cosmic:
            self.logger.debug("Opening COSMIC database with tabix open")
            self.cosmic = tabix.open(self.cosmic)
            self.logger.debug("COSMIC file opened")

    def run(self):
        """Run the consuming"""
        self.logger.info('%s: Starting!' % self.proc_name)
        # Check if there are any batches in the queue
        while True:
            # A batch is a dictionary on the form {variant_id:variant_dict}
            variant_line = self.task_queue.get()

            if variant_line is None:
                self.logger.info('No more variants')
                self.task_queue.task_done()
                self.logger.info('{0}: Exiting'.format(self.proc_name))
                break

            variant_dict = get_variant_dict(
                variant_line = variant_line,
                header_line = self.header_line
            )

            chrom = variant_dict['CHROM'].lstrip('chr')
            position = int(variant_dict['POS'])
            ref = variant_dict['REF']
            alternative = variant_dict['ALT']

            longest_alt = max([
                len(alt) for alt in alternative.split(',')])

            if self.exon_trees:
                exonic = check_exonic(
                    chrom = chrom,
                    start = position,
                    stop = (position+longest_alt)-1,
                    exon_trees = self.exon_trees
                )
                if exonic:
                    variant_dict = add_vcf_info(
                            keyword = 'Exonic',
                            variant_dict=variant_dict,
                            annotation=None
                            )

            if self.gene_trees:
                genes = get_genes(
                    chrom = chrom,
                    start = position,
                    stop = (position+longest_alt)-1,
                    gene_trees = self.gene_trees
                )
                if genes:
                    variant_dict = add_vcf_info(
                        keyword = "Annotation",
                        variant_dict = variant_dict,
                        annotation = ','.join(genes)
                    )
            if self.thousand_g:

                frequencies = get_frequencies(
                    tabix_reader = self.thousand_g,
                    chrom=chrom,
                    start=position,
                    alt=alternative
                )
                if frequencies.get('AF'):
                    variant_dict = add_vcf_info(
                        keyword = "1000GAF",
                        variant_dict = variant_dict,
                        annotation = frequencies['AF']
                    )
                if self.max_af:
                    if frequencies.get('MAX_AF'):
                        variant_dict = add_vcf_info(
                            keyword = "1000G_MAX_AF",
                            variant_dict = variant_dict,
                            annotation = frequencies['MAX_AF']
                            )

            if self.exac:

                frequencies = get_frequencies(
                    tabix_reader = self.exac,
                    chrom=chrom,
                    start=position,
                    alt=alternative
                )
                if frequencies.get('AF'):
                    variant_dict = add_vcf_info(
                        keyword = "ExACAF",
                        variant_dict = variant_dict,
                        annotation = frequencies['AF']
                    )
                if self.max_af:
                    if frequencies.get('MAX_AF'):
                        variant_dict = add_vcf_info(
                            keyword = "ExAC_MAX_AF",
                            variant_dict = variant_dict,
                            annotation = frequencies['MAX_AF']
                        )

            if self.spidex:
                spidex_score = get_spidex_score(
                        tabix_reader=self.spidex,
                        chrom=chrom,
                        start=position,
                        alt=alternative
                    )
                if spidex_score:
                    variant_dict = add_vcf_info(
                        keyword = "SPIDEX",
                        variant_dict = variant_dict,
                        annotation = spidex_score
                    )

            if self.cosmic:
                in_cosmic = get_cosmic(
                        tabix_reader=self.cosmic,
                        chrom=chrom,
                        start=position,
                        alt=alternative
                    )
                if in_cosmic:
                    variant_dict = add_vcf_info(
                        keyword = "COSMIC",
                        variant_dict = variant_dict,
                    )

            if self.cadd_handles:

                cadd_phred = None
                cadd_raw = None
                for cadd_handle in self.cadd_handles:

                    cadd_scores = get_cadd_scores(
                        tabix_reader=cadd_handle,
                        chrom=chrom,
                        start=position,
                        alt=alternative
                    )
                    if cadd_scores['cadd_phred']:
                        cadd_phred = cadd_scores['cadd_phred']
                        cadd_raw = cadd_scores['cadd_raw']

                        variant_dict = add_vcf_info(
                            keyword = "CADD",
                            variant_dict = variant_dict,
                            annotation = cadd_phred
                        )

                        if self.cadd_raw and cadd_raw:
                            variant_dict = add_vcf_info(
                                keyword = "CADD_raw",
                                variant_dict = variant_dict,
                                annotation = cadd_raw
                            )
                        break

            self.results_queue.put(variant_dict)
            self.task_queue.task_done()

        return

def main():
    pass

if __name__ == '__main__':
    main()


import numpy as np
import cv2 as cv
import os

def detect_faces(image, f_scale=1.3, f_near=2):
    faces = []
    face_cascade = cv.CascadeClassifier('model/haarcascade_frontalface_default.xml')
    if os.path.isdir('temp'):
        pass
    else:
        os.makedirs('temp')
    img = cv.imread(image)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    face_detector = face_cascade.detectMultiScale(gray, f_scale, f_near)
    n = 0
    for (x,y,w,h) in face_detector:
        n = n + 1
        cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        #roi_gray = gray[y:y+h, x:x+w]
        #roi_color = img[y:y+h, x:x+w]
        crop_face = img[y:y+h, x:x+w]
        faces.append(crop_face)
        cv.imwrite('temp/{}.jpg'.format(n),crop_face)
    print('{} faces detected'.format(len(faces)))


from unittest import TestCase
import numpy as np
from pyqr.linalg import qr, inner_prod, mat_vec_prod

import numpy.testing as nt

class TestLinAlg(TestCase):
    def test_innerprod(self):
        a = np.array([1.0, 2.0, 3.0])
        b = np.array([1.0, -1.0, 3.0])
        self.assertAlmostEqual(inner_prod(a, b), 8.0, places=5)

    def test_qr(self):
        a = np.array([[1.0, 2.0], [1.0, -1.0], [1.0, 2.0]])
        result = qr(a)
        # test q*r == a
        nt.assert_almost_equal(a, mat_vec_prod(result.q, result.r), decimal=5)
        # test q'*q = eye(2)
        nt.assert_almost_equal(inner_prod(result.q, result.q), np.eye(2,2), decimal=5)


from flask import Blueprint, abort, jsonify, redirect, request

from api.downloaders import SpotifyDownloader
from core import config, const, spotdl
from core.const import log

app = Blueprint('/', 'main')

@app.errorhandler(400)
def custom400(error):
    res = jsonify({'error': error.description})
    res.status_code = 400
    return res

@app.errorhandler(500)
def custom500(error):
    res = jsonify({'error': error.description})
    res.status_code = 500
    return res

@app.route('/', methods=['GET'])
def index():
    return redirect("/index.html", code=302)

current_downloads = {}

@app.route('/download', methods=['POST'])
def post_download():
    if not request.json or 'url' not in request.json:
        abort(400, 'Error downloading playlist info: url obligatory')

    try:
        url = request.json['url']

        log.info("Downloading url[%s]", url)

        if url not in current_downloads:
            downloader = SpotifyDownloader(url)

            downloader.start()

            current_downloads[url] = downloader

            return jsonify({'status': 'OK'})
        else:
            return jsonify({'status': 'ALREADY_ADDED'})
    except Exception:
        log.error("Error downloading playlist info", exc_info=True)

        abort(400, 'Error downloading playlist info')

@app.route('/info', methods=['POST'])
def info():
    if not request.json or 'url' not in request.json:
        abort(400, 'Error getting playlist info: url obligatory')

    try:
        url = request.json['url']

        log.info("Get playlist info[%s]", url)

        info = spotdl.fetch_info(url)

        return jsonify(info)
    except Exception:
        log.error("Error getting playlist info", exc_info=True)

        abort(500, 'Error getting playlist info')

@app.route('/youtube', methods=['GET'])
def youtube():
    if 'url' not in request.args:
        abort(400,
              'Error getting playlist redirecting to youtube: url obligatory')

    try:
        url = request.args['url']

        log.info("Redirecting to youtube[%s]", url)

        yt_url = spotdl.fetch_yt_url(url)

        return redirect(yt_url, code=302)
    except Exception:
        log.error("Error redirecting to youtube", exc_info=True)

        abort(500, 'Error redirecting to youtube')

@app.route('/search', methods=['POST'])
def search():
    if not request.json or 'query' not in request.json:
        abort(400, 'Error searching: query obligatory')

    try:
        query = request.json['query']

        log.info("Searching[%s]", query)

        items = spotdl.search(query, max_results_per_type=int(
            const.config.search_max_results))

        return jsonify(items)
    except Exception:
        log.error("Error searching", exc_info=True)

        abort(500, 'Error searching')

@app.route('/download_history', methods=['GET'])
def download_history():
    log.info("Retrieving download_history")

    try:
        items = list(map(lambda d: {
            'url': d[0],
            'name': d[1].get_name(),
            'status': d[1].get_status().__dict__,
            'init_date': d[1].get_init_date(format="%H:%M:%S"),
            'end_date': d[1].get_end_date(format="%H:%M:%S"),
        },
            current_downloads.items()))

        response = {
            'items': items
        }

        return jsonify(response)
    except Exception:
        log.error("Error retrieving download_history", exc_info=True)

        abort(500, 'Error retrieving download_history')

@app.route('/settings', methods=['GET'])
def get_settings():
    log.info("Retrieving settings")

    try:
        settings = {
            'settings': config.get_config_dict()
        }

        return jsonify(settings)
    except Exception:
        log.error("Error Retrieving settings", exc_info=True)

        abort(500, 'Error Retrieving settings')

@app.route('/settings', methods=['PUT'])
def put_settings():
    if not request.json or 'settings' not in request.json:
        abort(400, 'Error Saving settings: settings obligatory')

    log.info("Saving settings")

    try:
        config.save_config(request.json['settings'])

        config.init_config()

        return jsonify({'status': 'OK'})
    except Exception:
        log.error("Error Saving settings", exc_info=True)

        abort(500, 'Error Saving settings')


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

# In[14]:

j = 1
for i in range(1,11) : # i 라는 변수를 1부터 10까지 나열되게 루프가 생성된다.
    j = j + i          #  range(1, 11) 값인 1부터 10까지가 게속 j 값에 더해지며 코드가 실행된다.
    print(j)           #예시 j -> 1일때, i -> 2, j = j + i 에 의해 j = 2 가되고, 다시 i -> 3 , j -> 6  이상태로 ㅑ = 10 까지 반복


import sublime_plugin
import sublime

class OneSelectionBottomCommand(sublime_plugin.TextCommand):

    '''
    When Triggered, get count of current selection
    '''

    def run(self, edit):
        selections = self.view.sel()
        # path = sublime.packages_path()
        # sublime.message_dialog(path)

        for i, selection in enumerate(selections):
            if i == 0:

                region_list = list(selections)
                last_region = region_list[-1]

                # line_col_tup = self.view.rowcol(selection.begin())
                # sublime.message_dialog(str(line_col_tup))

                point = last_region.end() - 1
                # sublime.message_dialog(str(point))

                self.view.sel().clear()
                self.view.sel().add(point)

                # region = sublime.Region(point, point + 1)
                # sublime.message_dialog(str(region))

                # self.view.insert(edit, point, ' ')
                # self.view.erase(edit, region)


from bs4 import BeautifulSoup
import requests

# 告诉网站我们是一个合法的浏览器
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.8",
    "Connection": "close",
    "Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1",
    "Referer": "http://www.infoq.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER"
}

url = 'http://www.infoq.com/cn/news'

# 获取新闻标题
def craw2(url):

    print(current_thread().getName(), 'start')
    response = requests.get(url,headers = headers)
    soup = BeautifulSoup(response.text,'lxml')

    for title_href in soup.find_all('div',class_='news_type_block'):
        print([title.get('title')
               for title in title_href.find_all('a') if title.get('title')])
    print("-------------------------------------")

import threading
from threading import current_thread

# 翻页
for i in range(15,80,15):

    threadCraw = threading.Thread(target=craw2, args=(url,))
    threadCraw.start()
    url = 'http://www.infoq.com/cn/news' + str(i)


#--------------------------------- layers.py file --------------------------------------#
"""
This file contains functions that help build the tensorflow graph in TBNN-s.
"""

# ------------ Import statements
import tensorflow as tf
import joblib
import numpy as np
from tbnns import constants

class FullyConnected(object):
    """
    Simple fully connected layer. To use:

    fc = FullyConnected(output_size, drop_prob, relu, name)
    x2 = fc.build(x1) # x1 is the input tensor, x2 is the output tensor
    """

    def __init__(self, out_size, drop_prob, relu=True, name=""):
        """
        Constructor method, instantiates the class with key properties

        Arguments:
        out_size -- integer, number of neurons in the output layer
        drop_prob -- float, drop probability to use for dropout (0 deactivates it)
        relu -- optional argument, whether to use a relu activation function. If False,
                use a linear activation
        name -- string, add to the scope of the variables defined here
        """

        self.out_size = out_size
        self.drop_prob = drop_prob
        self.relu = relu
        self.name = name # this is used to create different variable contexts

    def build(self, layer_inputs):
        """
        Takes in the layer inputs and produces the output tensor

        Arguments:
        layer_inputs -- tensor of inputs, shape [None, previous_layer_size]

        Returns:
        out -- tensor of outputs, after fully connected + relu + dropout is applied,
               shape [None, out_size]
        """
        with tf.compat.v1.variable_scope("FC_"+self.name):

            out = tf.contrib.layers.fully_connected(layer_inputs, self.out_size,
                                                    activation_fn=None)
            if self.relu:
                out = tf.nn.relu(out)
                out = tf.nn.dropout(out, rate=self.drop_prob) # Apply dropout

            return out

def lossLog(uc, uc_predicted, tf_flag=False):
    """
    One possible loss to determine how bad is uc_predicted compared to uc, the log
    loss: mean(log(||uc-uc_predicted||/||uc||))

    Arguments:
    uc -- np.array or tensor containing the true uc vector, shape [None, 3]
    uc_predicted -- np.array or tensor containing the predicted uc vector,
                    shape [None, 3]
    tf_flag -- optional argument, bool which says whether we are dealing with tensorflow
               tensors or with numpy arrays.

    Returns:
    loss_pred -- the prediction loss for the given uc_predicted (either a number or a
                 tensor shape [] depending on tf_flag)
    """

    if tf_flag:
        loss_ratio = ( tf.norm(uc - uc_predicted, ord=2, axis=1) /
                       tf.norm(uc, ord=2, axis=1) )
        loss_pred = tf.reduce_mean(tf.math.log(loss_ratio))
        return loss_pred
    else:
        loss_ratio = ( np.linalg.norm(uc-uc_predicted, ord=2, axis=1) /
                       np.linalg.norm(uc, ord=2, axis=1) )
        loss_pred = np.mean(np.log(loss_ratio))
        return loss_pred

def lossL2k(uc, uc_predicted, one_over_k, tf_flag=False):
    """
    One possible loss to determine how bad is uc_predicted compared to uc, the l2
    loss normalized by k: mean(||uc-uc_predicted||^2/k)

    Arguments:
    uc -- np.array or tensor containing the true uc vector, shape [None, 3]
    uc_predicted -- np.array or tensor containing the predicted uc vector,
                    shape [None, 3]
    one_over_k -- np.array or tensor containing the elements in k (turbulent kinetic
                  energy), shape [None, 1] (must be broadcastable with uc)
    tf_flag -- optional argument, bool which says whether we are dealing with tensorflow
               tensors or with numpy arrays.

    Returns:
    loss_pred -- the prediction loss for the given uc_predicted (either a number or a
                 tensor shape [] depending on tf_flag)
    """

    FACTOR = 2e3 # factor to multiply the loss so it's O(1)
    if tf_flag:
        loss = tf.math.squared_difference(uc, uc_predicted)*one_over_k
        loss_pred = FACTOR*tf.reduce_mean(tf.reduce_sum(loss, axis=1))
        return loss_pred
    else:
        if len(one_over_k.shape) == 1: one_over_k=np.expand_dims(one_over_k,-1)
        loss_pred = FACTOR*np.mean( np.sum((uc_predicted - uc)**2 * one_over_k, axis=1) )
        return loss_pred

def lossL2(uc, uc_predicted, one_over_u2c2, tf_flag=False):
    """
    One possible loss to determine how bad is uc_predicted compared to uc, the l2
    loss un-normalized (non-dimensionalized by bulk quantities):
    mean(||uc-uc_predicted||^2/Uj^2C^2)

    Arguments:
    uc -- np.array or tensor containing the true uc vector, shape [None, 3]
    uc_predicted -- np.array or tensor containing the predicted uc vector,
                    shape [None, 3]
    one_over_u2c2 -- np.array or tensor containing the elements in 1/Uj^2*C^2 (bulk
                     quantities for U and C), shape [None, 1] (must be broadcastable
                     with uc)
    tf_flag -- optional argument, bool which says whether we are dealing with tensorflow
               tensors or with numpy arrays.

    Returns:
    loss_pred -- the prediction loss for the given uc_predicted (either a number or a
                 tensor shape [] depending on tf_flag)
    """

    FACTOR = 4e4 # factor to multiply the loss so it's O(1)
    if tf_flag:
        loss = tf.math.squared_difference(uc, uc_predicted)*one_over_u2c2
        loss_pred = FACTOR*tf.reduce_mean(tf.reduce_sum(loss, axis=1))
        return loss_pred
    else:
        if len(one_over_u2c2.shape) == 1: one_over_u2c2=np.expand_dims(one_over_u2c2,-1)
        loss_pred = FACTOR*np.mean(np.sum((uc_predicted - uc)**2 *one_over_u2c2, axis=1))
        return loss_pred

def lossL1(uc, uc_predicted, one_over_uc, tf_flag=False):
    """
    One possible loss to determine how bad is uc_predicted compared to uc, the l1
    loss un-normalized (non-dimensionalized by bulk quantities):
    mean(|uc-uc_predicted|/Uj*C)

    Arguments:
    uc -- np.array or tensor containing the true uc vector, shape [None, 3]
    uc_predicted -- np.array or tensor containing the predicted uc vector,
                    shape [None, 3]
    one_over_uc -- np.array or tensor containing the elements in 1/Uj^2*C^2 (bulk
                   quantities for U and C), shape [None, 1] (must be broadcastable
                   with uc)
    tf_flag -- optional argument, bool which says whether we are dealing with tensorflow
               tensors or with numpy arrays.

    Returns:
    loss_pred -- the prediction loss for the given uc_predicted (either a number or a
                 tensor shape [] depending on tf_flag)
    """

    FACTOR = 2e2 # factor to multiply the loss so it's O(1)
    if tf_flag:
        loss = tf.abs(uc - uc_predicted)*one_over_uc
        loss_pred = FACTOR*tf.reduce_mean(tf.reduce_sum(loss, axis=1))
        return loss_pred
    else:
        if len(one_over_uc.shape) == 1: one_over_uc=np.expand_dims(one_over_uc,-1)
        loss_pred = FACTOR*np.mean(np.sum(np.abs(uc_predicted - uc)*one_over_uc, axis=1))
        return loss_pred

def lossCos(uc, uc_predicted, tf_flag=False):
    """
    One possible loss to determine how bad is uc_predicted compared to uc, the angle
    loss. This is quadratic in the cosine of the angle between uc and uc_predicted
    (0 is best, 1 is worst)

    Arguments:
    uc -- np.array or tensor containing the true uc vector, shape [None, 3]
    uc_predicted -- np.array or tensor containing the predicted uc vector,
                    shape [None, 3]
    tf_flag -- optional argument, bool which says whether we are dealing with tensorflow
               tensors or with numpy arrays.

    Returns:
    loss_pred -- the prediction loss for the given uc_predicted (either a number or a
                 tensor shape [] depending on tf_flag)
    """

    if tf_flag:
        cos = ( tf.reduce_sum(uc*uc_predicted, axis=1) /
                (tf.norm(uc, ord=2, axis=1)*tf.norm(uc_predicted, ord=2, axis=1)) )
        loss_pred = 0.5*(-1.0*tf.reduce_mean(cos)+1.0)
        return loss_pred
    else:
        cos = ( np.sum(uc*uc_predicted, axis=1) /
             (np.linalg.norm(uc, ord=2, axis=1)*np.linalg.norm(uc_predicted, ord=2, axis=1)) )
        loss_pred = 0.5*(-1.0*np.mean(cos)+1.0)
        return loss_pred


import time
import numpy as np
import networkx as nx
from networkx.algorithms.flow import maximum_flow
from evacuation import FlowGraph, max_flow

def transform_matrix_to_adj(matrix, num_of_vertices, m, limit):
    if m > limit:
        edges = set(np.random.permutation(range(m))[:limit])
    adjacency = [[] for i in range(num_of_vertices)]
    costs = [[] for i in range(num_of_vertices)]
    for i in range(0, matrix.shape[0]):
        for j in range(0, matrix.shape[1]):
            if matrix[i, j] and ((m > limit and i*matrix.shape[0]+j in edges) or m <= limit):
                adjacency[i].append(j)
                costs[i].append(matrix[i, j])
    return adjacency, costs

def build_graph(num_of_vertices, adjacency, costs):
    graph = FlowGraph(num_of_vertices)
    edges = [(i, m, w) for i, n in enumerate(zip(adjacency, costs)) for m, w in zip(*n)]
    for (i, m, w) in edges:
        graph.add_edge(i, m, w)
    return graph

def nx_flow(num_of_vertices, adjacency, costs):
    G = nx.DiGraph()
    G.add_nodes_from(list(range(0, num_of_vertices)))
    edges = [(i, m, w) for i, n in enumerate(zip(adjacency, costs)) for m, w in zip(*n)]
    G.add_weighted_edges_from(edges)
    flow, _ = maximum_flow(G, 0, num_of_vertices-1, capacity='weight')
    return flow

if __name__ == '__main__':
    for ri in range(10**6):
        np.random.seed(ri)
        while True:
            s0 = time.time()
            n = np.random.randint(2, 10 ** 2, 1)[0]
            matrix = np.random.randint(0, 2, (n, n))
            m = np.sum(matrix)
            matrix_costs = np.random.randint(0, 1000, (n, n))
            matrix = np.multiply(matrix, matrix_costs)
            adjacency, costs = transform_matrix_to_adj(matrix, n, m, 10 ** 4)

            graph = build_graph(n, adjacency, costs)
            s0 = time.time()
            my_result, iters = max_flow(graph, 0, graph.size() - 1)
            s1 = time.time()
            result = nx_flow(n, adjacency, costs)
            s2 = time.time()

            print(ri, s1-s0, s2-s1, n, m, result, my_result, iters)

            assert my_result == result


# -*- coding: utf-8 -*-
"""
Dubalu Framework
~~~~~~~~~~~~~~~~

URLconf for registration and activation, using django-registration's
default backend.

If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::

    (r'^accounts/', include('dfw.registration.backends.default.urls')),

This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.

If you'd like to customize the behavior (e.g., by passing extra
arguments to the various views) or split up the URLs, feel free to set
up your own URL patterns for these views instead.

:author: Dubalu Framework Team. See AUTHORS.
:copyright: Copyright (c) 2013-2014, deipi.com LLC. All Rights Reserved.
:copyright: Copyright (c) 2007-2012, James Bennett.
:license: See LICENSE for license details.

"""
from __future__ import absolute_import, unicode_literals

from django.conf.urls import patterns, include, url

from ...views import activate, register, direct_to_template

def get_urlpatterns(backend='dfw.registration.backends.default.DefaultBackend'):
    return patterns('',
        url(
            r'^activate/complete/$',
            direct_to_template,
            {
                'template_name': 'registration/activate.html',
                'backend': backend,
                'extra_context': {'account': True},
            },
            name='registration_activation_complete',
        ),
        # Activation keys get matched by \w+ instead of the more specific
        # [a-fA-F0-9]{40} because a bad activation key should still get to the view;
        # that way it can return a sensible "invalid key" message instead of a
        # confusing 404.
        url(
            r'^activate/(?P<activation_key>\w+)/$',
            activate,
            {
                'backend': backend,
            },
            name='registration_activate',
        ),
        url(
            r'^register/$',
            register,
            {
                'backend': backend,
            },
            name='registration_register',
        ),
        url(
            r'^register/complete/$',
            direct_to_template,
            {
                'template_name': 'registration/registration_complete.html',
                'backend': backend,
            },
            name='registration_complete'),
        url(
            r'^register/closed/$',
            direct_to_template,
            {
                'template_name': 'registration/registration_closed.html',
                'backend': backend,
            },
            name='registration_disallowed',
        ),
        (r'', include('dfw.registration.auth_urls')),
    )

urlpatterns = get_urlpatterns()


# coding=utf-8
import requests
import codecs
from lxml import html
from lxml import etree
import  os,re
import time
import pymongo
import datetime
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

# http://blog.csdn.net/selectdb/article/details/14523205

def get_unix_time(s=u""):
    if u"天" in s:
        day = s.split(u'天')[0]
        return int(time.mktime(datetime.date(datetime.date.today().year, datetime.date.today().month, datetime.date.today().day-int(day)).timetuple()))
    elif u"月" in s:
        month = s.split(u"个")[0]
        return int(time.mktime(datetime.date(datetime.date.today().year, datetime.date.today().month-int(month), datetime.date.today().day).timetuple()))
    elif u"年" in s:
        year = s.split(u'年')[0]
        return int(time.mktime(datetime.date(datetime.date.today().year-int(year), datetime.date.today().month,  datetime.date.today().day).timetuple()))

def get_unix_time1(s=u""):
    # print(s)
    current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    day = s.split(' ')[0]
    t1 = day.split('/')
    f1 = 0
    for i in t1:
        f1 +=1
    hour = s.split(' ')[1]
    if u"今天" == day:
        s = current_time.replace('-', '/')+' '+hour+':'+'00'
    elif u"昨天" == day:
        t = current_time.split('-')
        current_time = str(t[0])+'/'+str(t[1])+'/'+str(int(t[2])-1)
        s = current_time+' '+hour + ':00'
    elif u"前天" == day:
        t = current_time.split('-')
        current_time = str(t[0])+'/'+str(t[1])+'/'+str(int(t[2])-2)
        s = current_time + ' ' + hour + ':00'
    elif f1 == 2:
        t = current_time.split('-')
        s = str(t[0]) + '/' + day+' '+hour+':00'
    else:
        s = s + ':'+'00'
    # print(s)
    return int(time.mktime(time.strptime(s, '%Y/%m/%d %H:%M:%S')))

def get1(url=''):
    try:
        conn = pymongo.MongoClient('localhost', 27017)
        db = conn.test
    except Exception as e:
        print("连接数据库失败！")
        return
    headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding':'gzip, deflate, sdch, br',
    'Accept-Language':'zh-CN,zh;q=0.8',
    'Cache-Control':'max-age=0',
    'Connection':'keep-alive',
    'Cookie':'_user_behavior_=0421f753-481e-4765-ba5d-1724ab418db1; oscid=oFK7%2Bn8AFTbDIwoUMx0%2FjqaizEcjLGGK0sSawThXO5G%2BDoLLtdmsTIO8jDG5XBd3lEvcR7HRr5qypzmd30PKg8Y523vRM2i5EzJnLPnDasZEFz%2BEM%2F07Iz87%2BKOafyqgx7zSa%2FEjwNUNtb8QeK6VkA%3D%3D; Hm_lvt_a411c4d1664dd70048ee98afe7b28f0b=1478488050,1478512945,1478513960,1478566809; Hm_lpvt_a411c4d1664dd70048ee98afe7b28f0b=1478566809',
    'Host':'my.oschina.net',
    'Referer':'https://my.oschina.net/u/136849/home',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36'
        }
    headers2 = {
    'Accept':'text/html,*/*;q = 0.01',
    'Accept-Encoding':'gzip, deflate, sdch, br',
    'Accept-Language':'zh - CN, zh;q = 0.8',
    'Connection':'keep-alive',
    'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
    'Cookie':'_user_behavior_ = 0421f753-481e-4765-ba5d-1724ab418db1;oscid=oFK7%2Bn8AFTbDIwoUMx0%2FjqaizEcjLGGK0sSawThXO5G%2BDoLLtdmsTIO8jDG5XBd3lEvcR7HRr5qypzmd30PKg8Y523vRM2i5EzJnLPnDasZEFz%2BEM%2F07Iz87%2BKOafyqgx7zSa%2FEjwNUNtb8QeK6VkA%3D%3D;Hm_lvt_a411c4d1664dd70048ee98afe7b28f0b=1478488050,1478512945,1478513960,1478566809',
    'Host':'my.oschina.net',
    'Referer':'https://my.oschina.net/u/136848/home?type=bbs&scope=best',
    'User-Agent':'Mozilla/5.0(X11;Linuxi686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36',
    'X-PJAX':'true',
    'X-PJAX-Container':'# main-article',
    'X-Requested-With':'XMLHttpRequest'
    }
    # 解析出错
    b = 0
    # 访问出错
    c = 0
    gender = ""
    avatar = ""
    username = ""
    company = ""
    location = ""
    position = ""
    point = 0
    follower = 0
    following = 0
    join_date = []
    rec_login_time ={}
    week_visits = 0
    month_visits = 0
    all_visits = 0
    # 个性签名
    signature = ""
    # 熟悉的开发平台
    fam_devplatform = []
    # 专长领域
    expertise = []
    # 软件作品
    software = []
    # 博文阅读数
    blog_readcount = []
    # 最佳答案
    best_answer = []
    for i in range(1, 2):
        # 访问网页异常处理
        try:
            s = requests.Session()
            # r = s.get('https://my.oschina.net/u/{0}/home?type=bbs&scope=best'.format(str(i)), headers=headers)
            r = s.get(url+'?type=bbs&scope=best', headers=headers)
            tree = html.fromstring(r.content.decode('utf-8'))
            # 解析网页异常处理
            try:
                # 元素是否存在异常处理
                try:
                    avatar = tree.xpath('//*[@class="user-icon"]/a/img/@src')[0]
                except Exception as e:
                    avatar = ""
                try:
                    username = tree.xpath('//*[@class="user-info-detail"]/div/a/span/text()')[0]
                except Exception as e:
                    username = ""
                try:
                    temp = tree.xpath('//*[@class="user-info-detail"]/div[1]/span[1]/text()')[0]
                    s1 = str(temp)
                    if('-' in s1):
                        company = s1.split('-')[0]
                        position = s1[s1.find('-', 0) + 2:len(s1)]
                    else:
                        company = ""
                        position = s1
                        # print(position)
                except Exception as e:
                    company = ""
                    position = ""
                try:
                    location = tree.xpath('//*[@class="user-info-detail"]/div[1]/span[2]/text()')[0]
                except Exception as e:
                    location = ""
                # 性别
                try:
                    gender = tree.xpath('/html/body/section/section[1]/div/div[1]/span/@class')[0]
                    gender = str(gender).split(' ')[1]
                except Exception as e:
                    gender = ""
                    print(e)
                # 加入时间
                join_datet = tree.xpath('//*[@id="user-score-pjax"]/div/div[4]/text()')[0]
                t4 = str(join_datet).strip().split(' ')
                join_datet = t4[1]
                tj = int(time.mktime(time.strptime(join_datet, '%Y/%m/%d')))
                tmpj = {"join_date":join_datet, "unix_timestamp": tj}
                join_date.append(tmpj)
                # 最近登录时间
                rec_login_time_t = tree.xpath('//*[@id="user-score-pjax"]/div/div[4]/text()')[0]
                rec_login_time_t = str(rec_login_time_t).strip()
                rec_login_time_t = rec_login_time_t[rec_login_time_t.find(u'录')+2:len(rec_login_time_t)]
                if rec_login_time_t != "":
                    unix_timestamp = get_unix_time1(rec_login_time_t)
                    rec_login_time = {"recent_login_time": rec_login_time_t, "unix_timestamp": unix_timestamp}
                else:
                    rec_login_time = {}

                # 积分
                point = int(tree.xpath('//*[@id="user-score-pjax"]/div/div[1]/a/text()')[0])
                # 粉丝
                follower = int(tree.xpath('//*[@id="user-score-pjax"]/div/div[2]/a/text()')[0])
                # 关注
                following = int(tree.xpath('//*[@id="user-score-pjax"]/div/div[3]/a/text()')[0])
                # 个性签名
                signature = tree.xpath('//*[@class="user-signature"]/span/text()')[0]
                if u'没写' in str(signature):
                    signature = ""
                # 本周访问
                week_visitst = tree.xpath('//*[@class="count-list"]/li[3]/text()')[0]
                week_visits = int(str(week_visitst)[str(week_visitst).find(':')+2:len(str(week_visitst))])
                # 本月访问
                month_visitst = tree.xpath('//*[@class="count-list"]/li[4]/text()')[0]
                month_visits = int(str(month_visitst)[str(month_visitst).find(':') + 2:len(str(month_visitst))])
                # 所有访问
                all_visitst = tree.xpath('//*[@class="count-list"]/li[5]/text()')[0]
                all_visits = int(str(all_visitst)[str(all_visitst).find(':') + 2:len(str(all_visitst))])
                # 熟悉平台
                try:
                    temp = tree.xpath('//div[@class="skills-item"]/p')[0]
                    t2 = 1
                    for k1 in temp.xpath('./span/text()'):
                        if(t2<5):
                            fam_devplatform.append(str(k1))
                            #print (fam_devplatform)
                            t2=t2+1
                        else:
                            break
                    #fam_devplatform=temp
                except Exception as e:
                    fam_devplatform = []

                # 专长领域
                try:
                    temp = tree.xpath('//div[@class="skills-item"]/p')[1]
                    t2=1
                    for k1 in temp.xpath('./span/text()'):
                        if(t2<=3):
                            expertise.append(str(k1))
                            t2=t2+1
                        else:
                            break
                except Exception as e:
                    expertise = []
                # 软件作品
                for ts in range(1, 10):
                    try:
                        s_title = tree.xpath('//*[@class="software-list"]/div[{0}]/div/a/div[1]/text()'.format(str(ts)))[0]
                        s_describe = tree.xpath('//*[@class="software-list"]/div[{0}]/div/a/div[2]/text()'.format(str(ts)))[0]
                        s_url = tree.xpath('//*[@class="software-list"]/div[{0}]/div/a/@href'.format(str(ts)))[0]
                        tmps = {"soft_title": s_title, "soft_describe": s_describe, "soft_url": s_url}
                        software.append(tmps)
                    except Exception as e:
                        break
                # 最佳回答
                for ta in range(1, 4):
                    try:
                        question = tree.xpath('//*[@id="main-anchor"]/div[2]/div[2]/div[{0}]/div[2]/div[2]/div[1]/a/@alt'.format(str(ta)))[0]
                        reply = int(tree.xpath('//*[@id="main-anchor"]/div[2]/div[2]/div[{0}]/div[2]/div[3]/span/span/text()'.format(str(ta)))[0])
                        rep_time = tree.xpath('//*[@id="main-anchor"]/div[2]/div/div[{0}]/div[2]/div[1]/span[2]/text()'.format(str(ta)))[0]
                        unix_timestamp = get_unix_time(rep_time)
                        tempa = {"question": question, "reply": reply, "reply_time": rep_time, "unix_timestamp": unix_timestamp}
                        best_answer.append(tempa)
                    except Exception as e:
                        break
            except Exception as e:
                print(e)
                print("index1")
                b= b+1

            # 博客阅读数
            try:
                s = requests.Session()
                url1 = url.split('home')[0]
                s.get(url1+'/blog/?sort=hot', headers=headers2)
                # r = s.get('https://my.oschina.net/u/136848?sort=hot', headers=headers3)
                tree = html.fromstring(r.content.decode('utf-8'))
                # print(r.content.decode('utf-8'))
                for tm in range(1, 6):
                    try:
                        title = tree.xpath('//*[@id="list"]/div[{0}]/div/div/div[1]/a/text()'.format(str(tm)))[0]
                        read_num = int(tree.xpath('//*[@id="list"]/div[{0}]/div/div/div[2]/ul//li[1]/span/text()'.format(str(tm)))[0])
                        comment_num = int(tree.xpath('//*[@id="list"]/div[{0}]/div/div/div[2]/ul//li[2]/span/text()'.format(str(tm)))[0])
                        com_time = tree.xpath('//*[@id="list"]/div[{0}]/div/div/div[3]/text()'.format(str(tm)))[0]
                        com_time = str(com_time).strip().split(' ')[0]
                        unix_timestamp = int(time.mktime(time.strptime(com_time, '%Y/%m/%d')))
                        tempm = {"title": str(title).strip(), "read_count": read_num, "comment_count": comment_num,
                                 "comment_time": com_time, "unix_timestamp": unix_timestamp}
                        blog_readcount.append(tempm)
                    except Exception as e:
                        break
            except Exception as e:
                print(e)
                print("index4")
                b=b+1
            db.osChinaTest1.insert({"avatar": avatar,
                                   "gender": gender,
                                   "username": username,
                                   "company": company,
                                   "location": location,
                                   "position": position,
                                   "point": point,
                                   "follower": follower,
                                   "following": following,
                                   "join_date": join_date,
                                   "recent_login_time": rec_login_time,
                                   "week_visits": week_visits,
                                   "month_visits": month_visits,
                                   "all_visits": all_visits,
                                   "signature": signature,
                                   "familiar_develop_platform": fam_devplatform,
                                   "expertise": expertise,
                                   "software": software,
                                   "best_answer": best_answer,
                                   "blog_read_count": blog_readcount
                                   })
            fam_devplatform.clear()
            expertise.clear()
            software.clear()
            best_answer.clear()
            blog_readcount.clear()
            join_date.clear()
            rec_login_time.clear()
        except Exception as e:
            c = c+1
            print(e)
    # print("解析网页失败:"+str(b))
    # print("访问网页失败:"+str(c))

con = pymongo.MongoClient('localhost', 27017)
d = con.test
cu = d.Url
r = cu.find({})
t3 = 0
for i in r:
    t3 += 1
    url = i["url"]
    get1(url)
    if t3 == 2:
        break
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


#calss header
class _ENCLOSED():
	def __init__(self,):
		self.name = "ENCLOSED"
		self.definitions = [u'surrounded by walls, objects, or structures: ', u'sent to someone in an envelope with a letter: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'adjectives'

	def run(self, obj1, obj2):
		self.jsondata[obj2] = {}
		self.jsondata[obj2]['properties'] = self.name.lower()
		return self.jsondata


#!/usr/env/python3
# -*- coding: utf-8 -*-
"""Demo csci4831final code."""
import os
import logging
import cv2
import numpy as np
import matplotlib.pyplot as plt

logging.basicConfig(
    level=logging.INFO,
    format="(%(levelname)s): %(asctime)s --- %(message)s",
)

import csci4831final as csf

def demo(image: str, background: str, result_dir: str) -> None:
    """
    Perform demo of csci4831final code.

    Does the following in order:
    1. Craft a true foreground mask of image.
    2. Use mini-batch k-means with identity, grayscale and gaussian
       transforms to get predicted foreground mask.
    3. Use matplotlib to create result graph.
    4. Save results to result_dir.

    Parameters
    ----------
    image: str
        Path to image to process.
    background: str
        Path to virtual background image.
    result_dir: str
        Path to save results to.
    """

    if os.path.exists("all_results.csv"):
        os.remove("all_results.csv")
    if os.path.exists("avg_results.csv"):
        os.remove("avg_results.csv")
    for file in os.listdir(result_dir):
        if not file.startswith("."):
            os.remove(os.path.join(result_dir, file))

    logging.info("Starting...")
    logging.info("Reading images...")
    image_data = cv2.imread(image)
    background_data = cv2.imread(background)
    logging.info("Showing test image...")
    cv2.imshow("Test Image", image_data)
    cv2.imshow("Background Image", background_data)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    logging.info("Getting true mask using grabcut...")
    true_mask = csf.get_points.get_true_mask(image_data)
    logging.info("Got true mask...")

    logging.info("Testing mini-batch KMeans with ID, GS, and 51GB...")
    tests = csf.main.make_tests(
        [
            (csf.clusters.minibatch_kmeans, "MBK")
        ],
        [
            (lambda i: i, "ID"),
            (lambda i: cv2.cvtColor(i, cv2.COLOR_BGR2GRAY), "GS"),
            (lambda i: cv2.GaussianBlur(i, (5, 5), 1), "51GB"),
        ]
    )
    pi = csf.main.PeopleImage(
        filename=os.path.basename(image),
        path=image,
        mask_path="",
        data=image_data,
        mask_data=true_mask
    )
    for test in tests:
        logging.info(
            f"Running {test.model_name} with transform {test.transform_name}"
        )
        csf.main.do_test(test, [pi], result_dir)
        logging.info(f"Time taken: {test.avg_time}")
        logging.info(f"Accuracy: {test.acc}")

    logging.info("Showing Results...")
    fig = plt.figure()
    axes = list()
    rows = 3
    cols = 2
    i = 1
    for prediction in os.listdir(result_dir):
        if prediction.startswith("."):
            continue
        logging.info(f"Loading {prediction}...")
        filename, model_name, trans_name, acc, run_time = prediction.split("_")
        pred_data = np.float32(cv2.imread(
            os.path.join(result_dir, prediction), cv2.IMREAD_COLOR
        ))
        virt_data = np.float32(
            csf.vbg.replace_background(pred_data, background_data)
        )

        pred_data = np.int32(cv2.cvtColor(pred_data, cv2.COLOR_BGR2RGB))
        virt_data = np.int32(cv2.cvtColor(virt_data, cv2.COLOR_BGR2RGB))

        axes.append(fig.add_subplot(rows, cols, i))
        axes[-1].set_title(f"Prediction ({trans_name})")
        plt.imshow(np.int32(pred_data))

        axes.append(fig.add_subplot(rows, cols, i + 1))
        plt.imshow(np.int32(virt_data))

        i += 2

    fig.tight_layout()
    plt.show()

    return None

if __name__ == "__main__":
    demo(
        os.path.abspath("./image.jpg"),
        os.path.abspath("./background.jpg"),
        os.path.abspath("./results")
    )


"""Common fixutres with default mocks as well as common test helper methods."""
from unittest.mock import patch

import pytest
import tesla_wall_connector

from homeassistant.components.tesla_wall_connector.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry

@pytest.fixture
def mock_wall_connector_version():
    """Fixture to mock get_version calls to the wall connector API."""

    with patch(
        "tesla_wall_connector.WallConnector.async_get_version",
        return_value=get_default_version_data(),
    ):
        yield

def get_default_version_data():
    """Return default version data object for a wall connector."""
    return tesla_wall_connector.wall_connector.Version(
        {
            "serial_number": "abc123",
            "part_number": "part_123",
            "firmware_version": "1.2.3",
        }
    )

async def create_wall_connector_entry(
    hass: HomeAssistant, side_effect=None
) -> MockConfigEntry:
    """Create a wall connector entry in hass."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: "1.2.3.4"},
        options={CONF_SCAN_INTERVAL: 30},
    )

    entry.add_to_hass(hass)

    # We need to return vitals with a contactor_closed attribute
    # Since that is used to determine the update scan interval
    fake_vitals = tesla_wall_connector.wall_connector.Vitals(
        {
            "contactor_closed": "false",
        }
    )

    with patch(
        "tesla_wall_connector.WallConnector.async_get_version",
        return_value=get_default_version_data(),
        side_effect=side_effect,
    ), patch(
        "tesla_wall_connector.WallConnector.async_get_vitals",
        return_value=fake_vitals,
        side_effect=side_effect,
    ), patch(
        "tesla_wall_connector.WallConnector.async_get_lifetime",
        return_value=None,
        side_effect=side_effect,
    ):
        await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

    return entry


'''
문제 : 경로 찾기
난이도 : 실버1

가중치가 없는 방향 그래프가 주어졌을 때 모든 정점에 대해서
i에서 j로 가는 경로가 *있는지 없는지* 구하는 프로그램

'''
import sys
from collections import deque

n = int(sys.stdin.readline())

# 그래프 인접 행렬 입력
graph = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
visited = [[0]*n for _ in range(n)]

def bfs(x):
    queue = deque()
    queue.append(x)
    check = [0 for _ in range(n)]

    while queue:
        q = queue.popleft()

        for i in range(n):
            if check[i] == 0 and graph[q][i] == 1:
                queue.append(i)
                check[i] = 1
                visited[x][i] = 1

for i in range(0, n):
    bfs(i)

for i in visited:
    print(*i)


import re
import json
import requests
from pprint import pprint

def main():
    url = 'http://www.acfun.cn/comment_list_json.aspx?contentId=3491484&currentPage=1'
    r = requests.get(url, verify=False)
    mjson = json.loads(r.text)
    num = 0
    print(mjson['data'])
    commentContentArr = mjson['data']['commentContentArr']
    for var in commentContentArr:
        #print('')
        num = num+1
        print(commentContentArr[var]['userName']+" "+commentContentArr[var]['content'])
    print(num)
if __name__ == '__main__':
    main()


import ctypes
import threading
import time
from contextlib import contextmanager
from queue import Queue
from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union, cast

import attr
import hypothesis
import hypothesis.errors
import requests
from requests.auth import AuthBase

from .._hypothesis import make_test_or_exception
from ..constants import USER_AGENT
from ..exceptions import InvalidSchema
from ..loaders import from_uri
from ..models import Case, Endpoint, Status, TestResult, TestResultSet
from ..schemas import BaseSchema
from ..utils import capture_hypothesis_output, get_base_url
from . import events
from .checks import DEFAULT_CHECKS

DEFAULT_DEADLINE = 500  # pragma: no mutate

Auth = Union[Tuple[str, str], AuthBase]  # pragma: no mutate

def get_hypothesis_settings(hypothesis_options: Optional[Dict[str, Any]] = None) -> hypothesis.settings:
    # Default settings, used as a parent settings object below
    settings = hypothesis.settings(deadline=DEFAULT_DEADLINE)
    if hypothesis_options is not None:
        settings = hypothesis.settings(settings, **hypothesis_options)
    return settings

@attr.s
class BaseRunner:
    schema: BaseSchema = attr.ib()
    checks: Iterable[Callable] = attr.ib()
    hypothesis_settings: hypothesis.settings = attr.ib(converter=get_hypothesis_settings)
    auth: Optional[Auth] = attr.ib(default=None)
    headers: Optional[Dict[str, Any]] = attr.ib(default=None)
    request_timeout: Optional[int] = attr.ib(default=None)
    seed: Optional[int] = attr.ib(default=None)

    def execute(self,) -> Generator[events.ExecutionEvent, None, None]:
        """Common logic for all runners."""
        results = TestResultSet()

        initialized = events.Initialized(
            results=results, schema=self.schema, checks=self.checks, hypothesis_settings=self.hypothesis_settings
        )
        yield initialized

        yield from self._execute(results)

        yield events.Finished(results=results, schema=self.schema, running_time=time.time() - initialized.start_time)

    def _execute(self, results: TestResultSet) -> Generator[events.ExecutionEvent, None, None]:
        raise NotImplementedError

@attr.s(slots=True)
class SingleThreadRunner(BaseRunner):
    """Fast runner that runs tests sequentially in the main thread."""

    def _execute(self, results: TestResultSet) -> Generator[events.ExecutionEvent, None, None]:
        with get_session(self.auth, self.headers) as session:
            for endpoint, test in self.schema.get_all_tests(single_test, self.hypothesis_settings, self.seed):
                for event in run_test(self.schema, endpoint, test, self.checks, session, results, self.request_timeout):
                    yield event
                    if isinstance(event, events.Interrupted):
                        return

def thread_task(
    tasks_queue: Queue,
    events_queue: Queue,
    schema: BaseSchema,
    checks: Iterable[Callable],
    settings: hypothesis.settings,
    auth: Optional[Auth],
    headers: Optional[Dict[str, Any]],
    request_timeout: Optional[int],
    seed: Optional[int],
    results: TestResultSet,
) -> None:
    """A single task, that threads do.

    Pretty similar to the default one-thread flow, but includes communication with the main thread via the events queue.
    """
    # pylint: disable=too-many-arguments
    with get_session(auth, headers) as session:
        with capture_hypothesis_output():
            while not tasks_queue.empty():
                endpoint = tasks_queue.get()
                test = make_test_or_exception(endpoint, single_test, settings, seed)
                for event in run_test(schema, endpoint, test, checks, session, results, request_timeout):
                    events_queue.put(event)

def stop_worker(thread_id: int) -> None:
    """Raise an error in a thread so it is possible to asynchronously stop thread execution."""
    ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), ctypes.py_object(SystemExit))

class ThreadInterrupted(Exception):
    """Special exception when worker thread received SIGINT."""

@attr.s(slots=True)
class ThreadPoolRunner(BaseRunner):
    """Spread different tests among multiple worker threads."""

    workers_num: int = attr.ib(default=2)

    def _execute(self, results: TestResultSet) -> Generator[events.ExecutionEvent, None, None]:
        """All events come from a queue where different workers push their events."""
        tasks_queue = self._get_tasks_queue()
        # Events are pushed by workers via a separate queue
        events_queue: Queue = Queue()
        workers = self._init_workers(tasks_queue, events_queue, results)

        def stop_workers() -> None:
            for worker in workers:
                # workers are initialized at this point and `worker.ident` is set with an integer value
                ident = cast(int, worker.ident)
                stop_worker(ident)
                worker.join()

        is_finished = False
        try:
            while not is_finished:
                # Sleep is needed for performance reasons
                # each call to `is_alive` of an alive worker waits for a lock
                # iterations without waiting are too frequent and a lot of time will be spent on waiting for this locks
                time.sleep(0.001)
                is_finished = all(not worker.is_alive() for worker in workers)
                while not events_queue.empty():
                    event = events_queue.get()
                    yield event
                    if isinstance(event, events.Interrupted):
                        # Thread received SIGINT
                        # We could still have events in the queue, but ignore them to keep the logic simple
                        # for now, could be improved in the future to show more info in such corner cases
                        raise ThreadInterrupted
        except ThreadInterrupted:
            stop_workers()
        except KeyboardInterrupt:
            stop_workers()
            yield events.Interrupted(results=results, schema=self.schema)

    def _get_tasks_queue(self) -> Queue:
        """All endpoints are distributed among all workers via a queue."""
        tasks_queue: Queue = Queue()
        tasks_queue.queue.extend(self.schema.get_all_endpoints())
        return tasks_queue

    def _init_workers(self, tasks_queue: Queue, events_queue: Queue, results: TestResultSet) -> List[threading.Thread]:
        """Initialize & start workers that will execute tests."""
        workers = [
            threading.Thread(
                target=thread_task,
                kwargs={
                    "tasks_queue": tasks_queue,
                    "events_queue": events_queue,
                    "schema": self.schema,
                    "checks": self.checks,
                    "settings": self.hypothesis_settings,
                    "auth": self.auth,
                    "headers": self.headers,
                    "request_timeout": self.request_timeout,
                    "seed": self.seed,
                    "results": results,
                },
            )
            for _ in range(self.workers_num)
        ]
        for worker in workers:
            worker.start()
        return workers

def execute_from_schema(
    schema: BaseSchema,
    checks: Iterable[Callable],
    *,
    workers_num: int = 1,
    hypothesis_options: Optional[Dict[str, Any]] = None,
    auth: Optional[Auth] = None,
    headers: Optional[Dict[str, Any]] = None,
    request_timeout: Optional[int] = None,
    seed: Optional[int] = None,
) -> Generator[events.ExecutionEvent, None, None]:
    """Execute tests for the given schema.

    Provides the main testing loop and preparation step.
    """
    runner: BaseRunner
    if workers_num > 1:
        runner = ThreadPoolRunner(
            schema, checks, hypothesis_options, auth, headers, request_timeout, seed, workers_num=workers_num
        )
    else:
        runner = SingleThreadRunner(schema, checks, hypothesis_options, auth, headers, request_timeout, seed)

    yield from runner.execute()

def run_test(
    schema: BaseSchema,
    endpoint: Endpoint,
    test: Union[Callable, InvalidSchema],
    checks: Iterable[Callable],
    session: requests.Session,
    results: TestResultSet,
    request_timeout: Optional[int],
) -> Generator[events.ExecutionEvent, None, None]:
    """A single test run with all error handling needed."""
    # pylint: disable=too-many-arguments
    result = TestResult(endpoint=endpoint, schema=schema)
    yield events.BeforeExecution(results=results, schema=schema, endpoint=endpoint)
    hypothesis_output: List[str] = []
    try:
        if isinstance(test, InvalidSchema):
            status = Status.error
            result.add_error(test)
        else:
            with capture_hypothesis_output() as hypothesis_output:
                test(session, checks, result, request_timeout)
            status = Status.success
    except AssertionError:
        status = Status.failure
    except hypothesis.errors.Flaky:
        status = Status.error
        result.mark_errored()
        # Sometimes Hypothesis detects inconsistent test results and checks are not available
        if result.checks:
            flaky_example = result.checks[-1].example
        else:
            flaky_example = None
        result.add_error(
            hypothesis.errors.Flaky(
                "Tests on this endpoint produce unreliable results: \n"
                "Falsified on the first call but did not on a subsequent one"
            ),
            flaky_example,
        )
    except hypothesis.errors.Unsatisfiable:
        # We need more clear error message here
        status = Status.error
        result.add_error(hypothesis.errors.Unsatisfiable("Unable to satisfy schema parameters for this endpoint"))
    except KeyboardInterrupt:
        yield events.Interrupted(results=results, schema=schema)
        return
    except Exception as error:
        status = Status.error
        result.add_error(error)
    # Fetch seed value, hypothesis generates it during test execution
    result.seed = getattr(test, "_hypothesis_internal_use_seed", None) or getattr(
        test, "_hypothesis_internal_use_generated_seed", None
    )
    results.append(result)
    yield events.AfterExecution(
        results=results, schema=schema, endpoint=endpoint, status=status, hypothesis_output=hypothesis_output
    )

def execute(  # pylint: disable=too-many-arguments
    schema_uri: str,
    checks: Iterable[Callable] = DEFAULT_CHECKS,
    api_options: Optional[Dict[str, Any]] = None,
    loader_options: Optional[Dict[str, Any]] = None,
    hypothesis_options: Optional[Dict[str, Any]] = None,
    loader: Callable = from_uri,
) -> TestResultSet:
    generator = prepare(
        schema_uri=schema_uri,
        checks=checks,
        api_options=api_options,
        loader_options=loader_options,
        hypothesis_options=hypothesis_options,
        loader=loader,
    )
    all_events = list(generator)
    finished = all_events[-1]
    return finished.results

def prepare(  # pylint: disable=too-many-arguments
    schema_uri: str,
    checks: Iterable[Callable] = DEFAULT_CHECKS,
    workers_num: int = 1,
    api_options: Optional[Dict[str, Any]] = None,
    loader_options: Optional[Dict[str, Any]] = None,
    hypothesis_options: Optional[Dict[str, Any]] = None,
    loader: Callable = from_uri,
    seed: Optional[int] = None,
) -> Generator[events.ExecutionEvent, None, None]:
    """Prepare a generator that will run test cases against the given API definition."""
    api_options = api_options or {}
    loader_options = loader_options or {}

    if "base_url" not in loader_options:
        loader_options["base_url"] = get_base_url(schema_uri)
    schema = loader(schema_uri, **loader_options)
    return execute_from_schema(
        schema, checks, hypothesis_options=hypothesis_options, seed=seed, workers_num=workers_num, **api_options
    )

def single_test(
    case: Case,
    session: requests.Session,
    checks: Iterable[Callable],
    result: TestResult,
    request_timeout: Optional[int],
) -> None:
    """A single test body that will be executed against the target."""
    # pylint: disable=too-many-arguments
    timeout = prepare_timeout(request_timeout)
    response = case.call(session=session, timeout=timeout)
    errors = None

    for check in checks:
        check_name = check.__name__
        try:
            check(response, result)
            result.add_success(check_name, case)
        except AssertionError as exc:
            errors = True  # pragma: no mutate
            result.add_failure(check_name, case, str(exc))

    if errors is not None:
        # An exception needed to trigger Hypothesis shrinking & flaky tests detection logic
        # The message doesn't matter
        raise AssertionError

def prepare_timeout(timeout: Optional[int]) -> Optional[float]:
    """Request timeout is in milliseconds, but `requests` uses seconds"""
    output: Optional[Union[int, float]] = timeout
    if timeout is not None:
        output = timeout / 1000
    return output

@contextmanager
def get_session(
    auth: Optional[Auth] = None, headers: Optional[Dict[str, Any]] = None
) -> Generator[requests.Session, None, None]:
    with requests.Session() as session:
        if auth is not None:
            session.auth = auth
        session.headers["User-agent"] = USER_AGENT
        if headers is not None:
            session.headers.update(**headers)
        yield session


"""Configures rejection of anomalous events.

The module is exploited by cmsRun configuration MiniAOD_cfg.py.  It
exports function apply_event_filters, which configures the process
accordingly.
"""

import FWCore.ParameterSet.Config as cms

def apply_event_filters(process, paths, runOnData=False, isPromptReco=False):
    """Configure the process to reject anomalous events.

    Apply filters to reject anomalous or otherwise problematic events as
    recommended for analyses involving MET.  Follow instructions
    provided in [1] except for the filtering on primary vertices.  The
    latter is applied in the main configuration (and in a slightly
    tighter version).

    Arguments:
        process: The process to which the filters are to be added.
        paths: A PathManager with all active paths.
        runOnData: Flag to distinguish processing of data and
            simulation.
        isPromptReco: Flag to distinguish PromptReco of data from
            ReReco.  Not used currently.

    Return value:
        None.

    [1] https://twiki.cern.ch/twiki/bin/viewauth/CMS/MissingETOptionalFiltersRun2?rev=103
    """

    # Decisions of most filters are stored in MiniAOD as trigger
    # results, which are true for good events.  It is sufficient to
    # simply check the corresponding bits.
    process.applyEmulatedMETFilters = cms.EDFilter('HLTHighLevel',
        HLTPaths = cms.vstring(
            'Flag_HBHENoiseFilter', 'Flag_HBHENoiseIsoFilter', 'Flag_globalTightHalo2016Filter',
            'Flag_EcalDeadCellTriggerPrimitiveFilter', 'Flag_eeBadScFilter'
        ),
        andOr = cms.bool(False),  # AND mode
        throw = cms.bool(True),
        TriggerResultsTag = cms.InputTag('TriggerResults', '', 'PAT')
    )

    paths.append(process.applyEmulatedMETFilters)

    # Filter for "bad" muons
    from RecoMET.METFilters.BadPFMuonFilter_cfi import BadPFMuonFilter
    process.badPFMuonFilter = BadPFMuonFilter.clone(
        muons = cms.InputTag('slimmedMuons'),
        PFCandidates = cms.InputTag('packedPFCandidates')
    )

    paths.append(process.badPFMuonFilter)

    # Filter for "bad" charged hadrons
    from RecoMET.METFilters.BadChargedCandidateFilter_cfi import BadChargedCandidateFilter
    process.badChargedCandidateFilter = BadChargedCandidateFilter.clone(
        muons = cms.InputTag('slimmedMuons'),
        PFCandidates = cms.InputTag('packedPFCandidates')
    )

    paths.append(process.badChargedCandidateFilter)