#for managing the wikipedia requests
import requests
import json
#for parsing html tags
from lxml import etree
from io import StringIO
import lxml.html
# for the waiting
import time
#for managing command line arguments
from sys import argv

outputformat = "{id},{name},{release_year},[{developers}],[{publisher}],{img_url},{src_url},[{genres}],\"{description}\"\n"	#the format string for the output file writes
starter = "https://en.wikipedia.org/w/api.php?action=parse&page="	#used for all queries
URLstarter = "https://en.wikipedia.org/wiki/"	#used only for the file output
checkedPages = []

#inputManagement
#args = argv
def manageArgs():
	if (len(argv)!=4):
		print("wiki_to_csv.py [URL] [section #] [FILE]\n")
		return -1;
	else:
		global mainPage
		mainPage = argv[1]
		global sectionNumb
		sectionNumb = argv[2]
		global outputName
		outputName = argv[3]
		return 0;

def investigate_further(Name):
	prompt = starter+Name+"&prop=text&format=json&redirects"
	time.sleep(0.5)
	print("looking at ", Name)
	req = requests.get(prompt)
	Listfile = json.loads(req.text)
	if "error" in Listfile:
		print(Name+" is not on wikipedia")
		return "n/a","n/a","n/a","n/a"
	Text = Listfile["parse"]["text"]["*"]
	store = lxml.html.fromstring(Text)
	URL = URLstarter+Listfile["parse"]["title"]
	TempList = store.xpath("//a[@class='image']/@href")
	if len(TempList)>=1:
		Picture =  URLstarter+TempList[0]
	else:
		Picture = "n/a"
	Genres = store.xpath("//th/a[text()='Genre(s)']/../following::td[1]//text()")
	Genres = [item for item in Genres if item != ' ']
	Paragraphs = store.xpath("//h2/span[@id='Gameplay']/../following::p[position()<=2]")
	if len(Paragraphs)==0:#if no "gameplay" section just default to front
		Paragraphs = store.xpath("//div[@class='mw-parser-output']/p[position()<=2]")
	if len(Paragraphs)==1:#if only one paragraph, just use that
		Discription = Paragraphs[0].text_content().replace("\n", "")#no newlines!
	else:#default behavior
		Discription = Paragraphs[0].text_content().replace("\n", "")+" \\n "+Paragraphs[1].text_content().replace("\n", "")

	return URL, Picture, Genres, Discription

def Scrape(file):
	prompt = starter+mainPage+"&section="+sectionNumb+"&prop=text&format=json&redirects"
	print("asking "+prompt)
	#parser = etree.XMLParser(encoding='utf-8', recover=True)
	req = requests.get(prompt)
	Listfile = json.loads(req.text)
	if "error" in Listfile:
		print(mainPage+" is not on wikipedia")
		return
	MainText = Listfile["parse"]["text"]['*']
#	MainText = "
testing testing testing
"
#	MainText = "
Hello my name is Pedro, and I like crayons
"
	#store = etree.parse(StringIO(MainText), parser)
	store = lxml.html.fromstring(MainText)
	tableData = store.xpath("//table[@id='softwarelist']//td")
	# for item in tableData:
		# print(item.text_content())
	i=0
	j=0
	while (i<len(tableData)):
	#while (i<12):
		Name = tableData[i].text_content().replace("\n", "")
		#print("name:",tableData[i].text_content())
		Devs = tableData[i+1].text_content().replace("\n", "")
		#print("devs:",tableData[i+1].text_content())
		Publisher = tableData[i+2].text_content().replace("\n", "")
		#print("NApubs:",tableData[i+2].text_content())
		#print("EUpubs:",tableData[i+3].text_content())
		year = tableData[i+4].text_content().replace("\n", "")
		#print("NAdate",tableData[i+4].text_content())
		#print("EUdate",tableData[i+5].text_content())
		#print("rowend\n")
		URL, Picture, Genres, Discription = investigate_further(Name.replace(" ","_"))	#get image, genres, and descriptions
		i+=6;
		j+=1;
		outputString = outputformat.format(id = j,name = Name,release_year = year,developers = Devs,publisher = Publisher,img_url = Picture,genres = Genres, description = Discription, src_url=URL)
		file.write(outputString)

#the main function
if (manageArgs()==0):
	OutputFile = open(outputName,'a', encoding = "utf_16")
	OutputFile.write("id,name,release_year,publisher,image,src,genres,description\n")
	Scrape(OutputFile);
	OutputFile.close()
	#Picture, Genres, Description = investigate_further("The_3-D_Battles_of_WorldRunner")
	#print(Picture)
	#print(Genres)
	#print(Description)


import torch, copy
import torch.nn as nn
from torch.autograd import Variable
import onmt
from onmt.modules.Transformer.Models import TransformerEncoder, TransformerDecoder, Transformer
from onmt.modules.Transformer.Layers import PositionalEncoding

def build_model(opt, dicts):

    model = None

    if not hasattr(opt, 'model'):
        opt.model = 'recurrent'

    if not hasattr(opt, 'layer_norm'):
        opt.layer_norm = 'slow'

    if not hasattr(opt, 'attention_out'):
        opt.attention_out = 'default'

    if not hasattr(opt, 'residual_type'):
        opt.residual_type = 'regular'

    onmt.Constants.layer_norm = opt.layer_norm
    onmt.Constants.weight_norm = opt.weight_norm
    onmt.Constants.activation_layer = opt.activation_layer
    onmt.Constants.version = 1.0
    onmt.Constants.attention_out = opt.attention_out
    onmt.Constants.residual_type = opt.residual_type

    if opt.model == 'recurrent' or opt.model == 'rnn':

        from onmt.modules.rnn.Models import RecurrentEncoder, RecurrentDecoder, RecurrentModel

        encoder = RecurrentEncoder(opt, dicts['src'])

        decoder = RecurrentDecoder(opt, dicts['tgt'])

        generator = onmt.modules.BaseModel.Generator(opt.rnn_size, dicts['tgt'].size())

        model = RecurrentModel(encoder, decoder, generator)

    elif opt.model == 'transformer':
        # raise NotImplementedError

        max_size = 262 # This should be the longest sentence from the dataset
        onmt.Constants.init_value = opt.param_init

        if opt.time == 'positional_encoding':
            positional_encoder = PositionalEncoding(opt.model_size, len_max=max_size)
        else:
            positional_encoder = None
        #~ elif opt.time == 'gru':
            #~ positional_encoder = nn.GRU(opt.model_size, opt.model_size, 1, batch_first=True)
        #~ elif opt.time == 'lstm':
            #~ positional_encoder = nn.LSTM(opt.model_size, opt.model_size, 1, batch_first=True)

        encoder = TransformerEncoder(opt, dicts['src'], positional_encoder)
        decoder = TransformerDecoder(opt, dicts['tgt'], positional_encoder)

        generator = onmt.modules.BaseModel.Generator(opt.model_size, dicts['tgt'].size())

        model = Transformer(encoder, decoder, generator)

        #~ print(encoder)

    elif opt.model == 'stochastic_transformer':

        from onmt.modules.StochasticTransformer.Models import StochasticTransformerEncoder, StochasticTransformerDecoder

        max_size = 256 # This should be the longest sentence from the dataset
        onmt.Constants.weight_norm = opt.weight_norm
        onmt.Constants.init_value = opt.param_init

        positional_encoder = PositionalEncoding(opt.model_size, len_max=max_size)
        #~ positional_encoder = None

        encoder = StochasticTransformerEncoder(opt, dicts['src'], positional_encoder)

        decoder = StochasticTransformerDecoder(opt, dicts['tgt'], positional_encoder)

        generator = onmt.modules.BaseModel.Generator(opt.model_size, dicts['tgt'].size())

        model = Transformer(encoder, decoder, generator)

    elif opt.model == 'fctransformer':

        from onmt.modules.FCTransformer.Models import FCTransformerEncoder, FCTransformerDecoder

        max_size = 256 # This should be the longest sentence from the dataset
        onmt.Constants.weight_norm = opt.weight_norm
        onmt.Constants.init_value = opt.param_init

        positional_encoder = PositionalEncoding(opt.model_size, len_max=max_size)

        encoder = FCTransformerEncoder(opt, dicts['src'], positional_encoder)
        decoder = FCTransformerDecoder(opt, dicts['tgt'], positional_encoder)

        generator = onmt.modules.BaseModel.Generator(opt.model_size, dicts['tgt'].size())

        model = Transformer(encoder, decoder, generator)
    elif opt.model == 'ptransformer':

        from onmt.modules.ParallelTransformer.Models import ParallelTransformerEncoder, ParallelTransformerDecoder

        max_size = 256 # This should be the longest sentence from the dataset
        onmt.Constants.weight_norm = opt.weight_norm
        onmt.Constants.init_value = opt.param_init

        positional_encoder = PositionalEncoding(opt.model_size, len_max=max_size)

        encoder = ParallelTransformerEncoder(opt, dicts['src'], positional_encoder)
        decoder = ParallelTransformerDecoder(opt, dicts['tgt'], positional_encoder)

        generator = onmt.modules.BaseModel.Generator(opt.model_size, dicts['tgt'].size())

        model = Transformer(encoder, decoder, generator)

        #~ print(encoder)

    else:
        raise NotImplementedError

        #~
    #~ init = torch.nn.init
        #~
    #~ init.xavier_uniform(model.encoder.word_lut.weight)
    #~ init.xavier_uniform(model.decoder.word_lut.weight)

     # Weight tying between decoder input and output embedding:
    if opt.tie_weights:
        print("Joining the weights of decoder input and output embeddings")
        model.tie_weights()

    if opt.join_embedding:
        print("Joining the weights of encoder and decoder word embeddings")
        model.share_enc_dec_embedding()

    return model

def init_model_parameters(model, opt):

    if opt.model == 'recurrent':
        for p in model.parameters():
            p.data.uniform_(-opt.param_init, opt.param_init)
    else:
        from onmt.modules.Transformer.Layers import uniform_unit_scaling

        # We initialize the model parameters with Xavier init
        init = torch.nn.init

        init.xavier_uniform_(model.generator.linear.weight)
        init.xavier_uniform_(model.encoder.word_lut.weight.data)
        init.xavier_uniform_(model.decoder.word_lut.weight.data)

        #~ init = torch.nn.init.uniform
        #~
        #~ init(model.generator.linear.weight, -onmt.Constants.init_value,
                                             #~ onmt.Constants.init_value)
        #~ init(model.encoder.word_lut.weight, -onmt.Constants.init_value,
                                             #~ onmt.Constants.init_value)
        #~ init(model.decoder.word_lut.weight, -onmt.Constants.init_value,
                                             #~ onmt.Constants.init_value)
#~ def build_reconstructor(opt, dicts, positional_encoder):
    #~ decoder = TransformerDecoder(opt, dicts['src'], positional_encoder)

    #~ reconstructor =


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('agenda', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='image',
            field=models.ImageField(upload_to=b'media/%Y/%m/%d/', blank=True),
        ),
        migrations.AddField(
            model_name='event',
            name='image_title',
            field=models.CharField(unique=True, max_length=20, blank=True),
        ),
        migrations.AlterField(
            model_name='event',
            name='date_event',
            field=models.DateTimeField(verbose_name=b'Event Date'),
        ),
    ]


# -*- coding: utf-8 -*-
from twocaptchaapi import TwoCaptchaApi
import urllib
import threading
import os
import timeit
from timeit import Timer
import uuid
api = TwoCaptchaApi('20155321b96e31b09e17119e39218b37')

i = 0

def getI():
 global i
 return i

def incrementI():
  global i
  i = i + 1

def batchProcess():
 j=uuid.uuid1()
 newfile=urllib.URLopener()
 newfile.retrieve("http://services.ecourts.gov.in/ecourtindia_v5/securimage/securimage_show.php",str(j)+".png")
 with open(str(j)+".png", 'rb') as captcha_file:
  captcha = api.solve(captcha_file)
  filename=captcha.await_result()+".png"
  os.rename(str(j)+".png",filename)
  print(filename)

def main():
 for milo  in range(1,40):
    threading.Thread(target=batchProcess).start()

main()


from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PIL import Image
from PIL.Image import open

class LTexture:
	mTextureID = 0
	mTextureWidth = 0
	mTextureHeight = 0
	def __init__(self):
		#Inicializando ID da textura
		self.mTextureID = 0
		#Inicializando dimensões da textura
		self.mTextureWidth = 0
		self.mTextureHeight = 0

	@staticmethod
	def freeTexture(self):
		#Deletando textura
		if(self.mTextureID != 0):
			glDeleteTextures(1,self.mTextureID)
			self.mTextureID = 0
		mTextureWidth = 0
		mTextureHeight = 0

	def __del__(self):
		#Limpa dados da textura se preciso
		self.freeTexture(self)

	def loadTextureFromPixels32(self,pixels,width,height):
		#Limpa textura se existir
		self.freeTexture(self)

		#Obtém as dimensões da textura
		self.mTextureWidth = width
		self.mTextureHeight = height

		#Gera textura ID
		glGenTextures(1,self.mTextureID)

		#Define a ID da textura
		self.mTextureID = 1

		#Cria textura ID
		glBindTexture(GL_TEXTURE_2D,self.mTextureID)
		glPixelStorei(GL_UNPACK_ALIGNMENT,1)

		#Gera textura
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,pixels)

		#Definindo parâmetros da textura
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

		#Liberando textura
		glBindTexture(GL_TEXTURE_2D,0)

		#Procurando erros
		erro = glGetError()
		if(erro != GL_NO_ERROR):
			print("Erro ao carregar textura de %p pixels! %s\n",pixels,gluErrorString(erro))
			return False
		return True

	def loadTextureFromFile(self,imagem):
		textureLoaded = False

		#Gerando e Definindo uma imagem atual
		im = open(imagem).convert("RGBA")
		if(im != None):
			#Criando a textura a partir dos pixels do arquivo
			imagem = im.tobytes("raw","RGBA",0,-1)
			textureLoaded = self.loadTextureFromPixels32(imagem,im.size[0],im.size[1])
		im.close()
		if(textureLoaded == False):
			print("Não foi possível carregar a imagem!")
		return textureLoaded

	def render(self,x,y):
		#Se a textura existel
		if(self.mTextureID != 0):
			#Remove quaisquer transformações anteriores
			glLoadIdentity()

			#Movendo para o ponto de renderização
			glTranslatef(x,y,0)

			#Definindo textura ID
			glBindTexture(GL_TEXTURE_2D,self.mTextureID)

			#Renderizando quadrados texturizados
			glBegin(GL_QUADS)
			glTexCoord2f(0,0)
			glVertex2f(0,self.mTextureHeight)
			glTexCoord2f(1,0)
			glVertex2f(self.mTextureWidth,self.mTextureHeight)
			glTexCoord2f(1,1)
			glVertex2f(self.mTextureWidth,0)
			glTexCoord2f(0,1)
			glVertex2f(0,0)
			glEnd()

	def getTextureID(self):
		return self.mTextureID

	def textureWidth(self):
		return self.mTextureWidth

	def textureHeight(self):
		return self.mTextureHeight


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

# Disable pylint invalid module name complaint.
# pylint : disable = C0103

""" Pre-commit script for invoking linters and auto-formatters."""

# Make sure we use the new print function
from __future__ import print_function
from random import randint

import datetime
import imp
import os
import pylint.lint
import re
import subprocess

CLANG_FORMAT_DIFF_EXECUTABLE = "clang-format-diff-3.8"
AUTOPEP8_FORMAT_EXECUTABLE = "autopep8"

def run_command_in_folder(command, folder):
  """Run a bash command in a specific folder."""
  run_command = subprocess.Popen(command,
                                 shell=True,
                                 cwd=folder,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE)
  stdout, _ = run_command.communicate()
  command_output = stdout.rstrip()
  return command_output

def get_number_of_commits(some_folder_in_root_repo='./'):
  command = "git shortlog -s -n --all --author=\"$(git config --get user.email)\" | grep -o '[0-9]\+' |  awk '{s+=$1} END {print s}'"
  return run_command_in_folder(command, some_folder_in_root_repo)

def get_staged_files(some_folder_in_root_repo='./'):
  """Get all staged files from git."""
  output = run_command_in_folder(
      "git diff --staged --name-only", some_folder_in_root_repo)
  if len(output) == 0:
    return []
  else:
    return output.split("\n")

def get_unstaged_files(some_folder_in_root_repo='./'):
  """Get all unstaged files from git."""
  output = run_command_in_folder(
      "git diff --name-only", some_folder_in_root_repo)
  return output.split("\n")

def check_cpp_lint(staged_files, cpplint_file, ascii_art, repo_root):
  """Runs Google's cpplint on all C++ files staged for commit,"""
  cpplint = imp.load_source('cpplint', cpplint_file)
  cpplint._cpplint_state.SetFilters(
      '-legal/copyright,-build/c++11')  # pylint: disable=W0212

  # Prevent cpplint from writing to stdout directly, instead
  # the errors will be stored in pplint.output as (line, message) tuples.
  cpplint.print_stdout = False

  total_error_count = 0
  for changed_file in staged_files:
    if not os.path.isfile(changed_file):
      continue
    if changed_file.lower().endswith(('.cc', '.h', '.cpp', '.cu', '.cuh')):
      # Search iteratively for the root of the catkin package.
      package_root = ''
      search_dir = os.path.dirname(changed_file)
      found_package_root = False
      MAX_DEPTH_OF_FILES = 100
      for _ in range(1, MAX_DEPTH_OF_FILES):
        if os.path.isfile(search_dir + '/package.xml'):
          package_root = search_dir
          found_package_root = True
          break
        search_dir = os.path.dirname(search_dir)
      assert found_package_root, ("Could not find the root of the "
                                  "catkin package that contains: "
                                  "{}".format(changed_file))

      cpplint._root = package_root + '/include'   # pylint: disable=W0212

      # Reset error count and messages:
      cpplint.output = []
      cpplint._cpplint_state.ResetErrorCounts()   # pylint: disable=W0212
      v_level = cpplint._cpplint_state.verbose_level  # pylint: disable=W0212

      cpplint.ProcessFile(changed_file, v_level)

      error_count = cpplint._cpplint_state.error_count  # pylint: disable=W0212
      if error_count > 0:
        total_error_count += error_count

        print("-" * 80)
        print("Found {} errors in : {}".format(
            error_count, changed_file))
        print("-" * 80)
        for line in cpplint.output:
          assert len(line) == 2
          print("line {: >4}:\t {}".format(line[0], line[1]))

  if total_error_count > 0:
    print("=" * 80)
    print("Found {} cpplint errors".format(total_error_count))
    print("=" * 80)

    if total_error_count > 50:
      print(ascii_art.AsciiArt.cthulhu)
    elif total_error_count > 20:
      print(ascii_art.AsciiArt.tiger)
    return False
  else:
    return True

def check_modified_after_staging(staged_files):
  """Checks if one of the staged files was modified after staging."""
  files_changed = get_unstaged_files()
  files_changed = filter(None, files_changed)  # pylint: disable=W0141

  staged_files_changed = 0

  staged_files_changed_list = []

  is_first = True
  for changed_file in files_changed:
    if changed_file in staged_files:

      if is_first:
        print("=" * 80)
        is_first = False

      print("\'{}\' was modified after staging".format(changed_file))
      staged_files_changed_list.append(changed_file)
      staged_files_changed += 1

  if staged_files_changed > 0:
    print("-" * 80)
    print("Found {} files that have been changed after staging".format(
        staged_files_changed))
    print("=" * 80)

  return staged_files_changed_list

def check_commit_against_master(repo_root):
  """Check if the current commit is intended to for the master branch."""
  current_branch = run_command_in_folder(
      "git branch | grep \"*\" | sed \"s/* //\"", repo_root)
  print("\nCurrent_branch: {}\n".format(current_branch))
  return current_branch == "master"

def check_if_merge_commit(repo_root):
  """Check if the current commit is a merge commit."""
  merge_msg_file_path = repo_root + "/.git/MERGE_MSG"
  return os.path.isfile(merge_msg_file_path)

def run_clang_format(repo_root, staged_files, list_of_changed_staged_files):
  """Runs clang format on all cpp files staged for commit."""

  clang_format_path = ("/tmp/" + os.path.basename(
      os.path.normpath(repo_root)) + "_" +
      datetime.datetime.now().isoformat() + ".clang.patch")

  run_command_in_folder("git diff -U0 --cached | " +
                        CLANG_FORMAT_DIFF_EXECUTABLE +
                        " -style=file -p1 > " +
                        clang_format_path, repo_root)

  if not os.stat(clang_format_path).st_size == 0:
    if list_of_changed_staged_files:
      print("=" * 80)
      print("Cannot format your code, because some files are \n"
            "only partially staged! Format your code or try \n"
            "stashing your unstaged changes...")
      print("=" * 80)
      exit(1)

    run_command_in_folder("git apply -p0 " + clang_format_path, repo_root)
    run_command_in_folder("git add " + ' '.join(staged_files), repo_root)

    print("=" * 80)
    print("Formatted staged C++ files with clang-format.\n" +
          "Patch: {}".format(clang_format_path))
    print("=" * 80)
  return True

def run_autopep8_format(repo_root, staged_files, list_of_changed_staged_files):
  """Runs autopep8 format on all python files staged for commit."""

  first_file_formatted = True
  for staged_file in staged_files:
    if not os.path.isfile(staged_file):
      continue
    if staged_file.endswith((".py")):

      # Check if the file needs formatting by applying the formatting and store
      # the results into a patch file.
      autopep8_format_path = ("/tmp/" +
                              os.path.basename(os.path.normpath(repo_root)) +
                              "_" + datetime.datetime.now().isoformat() +
                              ".autopep8.patch")
      task = (AUTOPEP8_FORMAT_EXECUTABLE +
              " -d --aggressive --aggressive --max-line-length=80 " +
              "--indent-size=2 --ignore=E24 " +
              staged_file + " > " + autopep8_format_path)
      run_command_in_folder(task, repo_root)

      if not os.stat(autopep8_format_path).st_size == 0:
        if first_file_formatted:
          print("=" * 80)
          print("Formatted staged python files with autopep8:")
          first_file_formatted = False

        print("-> " + staged_file)

        if staged_file in list_of_changed_staged_files:
          print("Cannot format your code, because this file is \n"
                "only partially staged! Format your code or try \n"
                "stashing your unstaged changes...")
          print("=" * 80)
          exit(1)
        else:
          run_command_in_folder(
              "git apply -p1 " + autopep8_format_path, repo_root)
          run_command_in_folder("git add " + staged_file, repo_root)

  if not first_file_formatted:
    print("=" * 80)
  return True

def check_python_lint(repo_root, staged_files, pylint_file):
  """Runs pylint on all python scripts staged for commit."""

  class TextReporterBuffer(object):
    """Stores the output produced by the pylint TextReporter."""

    def __init__(self):
      """init"""
      self.content = []

    def write(self, input_str):
      """write"""
      self.content.append(input_str)

    def read(self):
      """read"""
      return self.content

  # Parse each pylint output line individualy and searches
  # for errors in the code.
  pylint_errors = []
  for changed_file in staged_files:
    if not os.path.isfile(changed_file):
      continue
    if re.search(r'\.py$', changed_file):

      print("Running pylint on \'{}\'".format(repo_root + "/" + changed_file))
      pylint_output = TextReporterBuffer()
      pylint_args = ["--rcfile=" + pylint_file,
                     "-rn",
                     repo_root + "/" + changed_file]
      from pylint.reporters.text import TextReporter
      pylint.lint.Run(pylint_args,
                      reporter=TextReporter(pylint_output),
                      exit=False)

      for output_line in pylint_output.read():
        if re.search(r'^(E|C|W):', output_line):
          print(changed_file + ": " + output_line)
          pylint_errors.append(output_line)

  if len(pylint_errors) > 0:
    print("=" * 80)
    print("Found {} pylint errors".format(len(pylint_errors)))
    print("=" * 80)
    return False
  else:
    return True

def linter_check(repo_root, linter_subfolder):
  """ Main pre-commit function for calling code checking script. """

  cpplint_file = repo_root + "/" + linter_subfolder + "/cpplint.py"
  pylint_file = repo_root + "/" + linter_subfolder + "/pylint.rc"
  ascii_art_file = repo_root + "/" + linter_subfolder + "/ascii_art.py"

  print("Found linter subfolder: {}".format(linter_subfolder))
  print("Found ascii art file at: {}".format(ascii_art_file))
  print("Found cpplint file at: {}".format(cpplint_file))
  print("Found pylint file at: {}".format(pylint_file))

  # Run checks
  staged_files = get_staged_files()

  if len(staged_files) == 0:
    print("\n")
    print("=" * 80)
    print("No files staged...")
    print("=" * 80)
    exit(1)

  # Load ascii art.
  ascii_art = imp.load_source('ascii_art', ascii_art_file)

  if check_commit_against_master(repo_root):
    print(ascii_art.AsciiArt.grumpy_cat)
    exit(1)

  if not check_if_merge_commit(repo_root):
    # Do not allow commiting files that were modified after staging.This
    # avoids problems such as forgetting to stage fixes of cpplint complaints.
    list_of_changed_staged_files = check_modified_after_staging(staged_files)

    run_clang_format(repo_root, staged_files, list_of_changed_staged_files)
    run_autopep8_format(repo_root, staged_files, list_of_changed_staged_files)

    # Use Google's C++ linter to check for compliance with Google style guide.
    cpp_lint_success = check_cpp_lint(
        staged_files, cpplint_file, ascii_art, repo_root)

    # Use pylint to check for comimpliance with Tensofrflow python style guide.
    pylint_success = check_python_lint(repo_root, staged_files, pylint_file)

    if not(cpp_lint_success and pylint_success):
      print("=" * 80)
      print("Commit rejected! Please address the linter errors above.")
      print("=" * 80)
      exit(1)
    else:

      commit_number = get_number_of_commits(repo_root)
      lucky_commit = ((int(commit_number) + 1) % 42 == 0)

      if lucky_commit:
        print(ascii_art.AsciiArt.story)

        print("=" * 80)
        print("Commit accepted, well done! This is your {}th commit!".format(
            commit_number))
        print("This is a lucky commit! Please enjoy this free sheep story.")
        print("=" * 80)
      else:
        print(ascii_art.AsciiArt.commit_success)

        print("=" * 80)
        print("Commit accepted, well done! This is the {}th commit!".format(
            commit_number))
        print("=" * 80)
  else:
    print(ascii_art.AsciiArt.homer_woohoo)


# -*- coding:utf-8 -*-

import sys
import urllib

from lxml import etree
from handhelper import ehsyparse
from httphelper import ehsyHtml

reload(sys)
sys.setdefaultencoding("utf8")

class ehsy(object):

    """
    负责执行流程的控制
    """

    def ehsyGoods(self,keywords):

        keywords = str(keywords)
        keys = urllib.quote(keywords)
        url = "%s%s" % ("http://www.ehsy.com/search?k=", keys)

        xy = ehsyHtml.ehsyHtml()
        html = xy.ehstHtml(url)

        html = etree.HTML(html)

        xyparse = ehsyparse.ehsyparse()
        xyparse.getGoods_html(html)

e =ehsy()
e.ehsyGoods("扳手")


# -*- coding: utf-8 -*-
# @Author: dgfnydx
# @Date:   2019-12-09 11:14:50
# @Last Modified by:   dgfnydx
# @Last Modified time: 2019-12-10 09:46:10

import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string

# 打开Excel，获取工作簿对象
wb = openpyxl.load_workbook('data/information.xlsx')

# 创建一个工作簿
# createSheet = wb.create_sheet('mySheet')

# 从工作薄中获取一个表单(sheet)对象
# sheets = wb.sheetnames
# print(sheets)

#获取指定工作簿
# sheet2 = wb['Sheet2']
# print(sheet2)

# for sheet in wb:
# 	print(sheet.title)

# 获取活跃工作簿
awb = wb.active

print(awb['A5'].value)

awb['A7'].value = '王二麻子'

print(awb['A5'].value)

wb.save('data/information.xlsx')

print(wb.get_named_ranges())


#!/usr/bin/env python

"""
    An OSX tool to automate downloads from showRSS
"""

from datetime import datetime
from dateutil import parser
from os import path, stat, utime
from pytz import utc
from subprocess import call
from urllib import urlencode
from urllib2 import build_opener
from xml.dom import minidom
from time import mktime

CONFIGURATION = {
    # Show RSS user id
    'user_id': USER_ID,

    # 'null'  Per show settings,
    # 0       Only standard torrents,
    # 1       Only 720p HD
    # 2       Both types of torrents
    'hd': 'null',

    # 'null'  Per show settings,
    # 0       Skip proper/repack
    # 1       Include proper/repack
    'proper': 'null',

    # Uncomment this line to use torrent files instead of the magnet protocol
    # 'magnets': 'false',

    # For reference
    # 'namespaces': 'false',
    # 'raw': 'false',
}

STAMP_FILE = path.join(path.expanduser("~"), '.show-rss')
RSS_FEED_URL = 'http://showrss.info/rss.php?' + urlencode(CONFIGURATION)

def update_timestamp(date=None):
    with open(STAMP_FILE, 'a'):
        if date is None:
            utime(STAMP_FILE, None)
        else:
            date = mktime(date.timetuple())
            utime(STAMP_FILE, (date , date) )

def get_timestamp():
    if not path.exists(STAMP_FILE):
        return None
    modtime = stat(STAMP_FILE).st_mtime
    odate = datetime.fromtimestamp(modtime)
    ldate = utc.localize(odate)
    return ldate, odate

def download_feed(url):
    opener = build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    return opener.open(url, timeout=10).read()

def parse_dates_links(feed):
    xml = minidom.parseString(feed)

    links = [z.firstChild.nodeValue
             for z in xml.getElementsByTagName('link')[1:]]

    dates = [parser.parse(z.firstChild.nodeValue)
             for z in xml.getElementsByTagName('pubDate')]

    assert(len(links) == len(dates))
    return zip(dates, links)

if __name__ == '__main__':
    timestamp = get_timestamp()
    latest = None
    odate = None
    if timestamp:
        ldate, odate = timestamp
        #print "L: ", ldate, " O: ", odate
    feed = download_feed(RSS_FEED_URL)

    for date, link in parse_dates_links(feed):
        if timestamp is None or date > ldate:
           call(['open', '-g', link])
           if latest is None or date > latest:
                latest = date
    if (latest is None) and (odate is not None):
        latest = odate
    update_timestamp(latest)


import logging

from board.cfg_db import mod_debug
mod_debug()

#board
log = logging.getLogger("BOARD")
log.setLevel(logging.INFO)

from board.cfg_db import _name_board
import sys

class uCore:
    def __init__(self, mbus, umod, board):
        self.mbus = mbus
        self.umod = umod
        self.board = board

class Activate:

    def __init__(self, mbus, umod, board_id):

        self.mbus = mbus
        self.umod = umod

        log.info("BID: {}".format(board_id))

        s_mod = umod.mod_sel("board_cfg")

        if not len(s_mod):
            from mod_u.model import init_db
            init_db(umod)
            del sys.modules["mod_u.model"]

        from board.cfg_db import push_board
        push_board(umod)

        board = _name_board

        _modules = umod.call_cmd("_scan", "board_mod")

        for mod in _modules:
            if mod["active"]:
                name_mod = mod["name"]
                try:
                    init_db = __import__("{}_mod".format(name_mod)).init_db
                    init_db(umod)
                    log.info("MOD DB ACTIVATE: {}".format(name_mod))
                    del sys.modules["{}_mod".format(name_mod)]

                except Exception as e:
                    log.info("MOD: {}, init db err: {}".format(mod, e))

        from board.cfg_db import push_data
        push_data(umod)
        del sys.modules["board.cfg_db"]

        umod.call_cmd("_upd", "board_cfg", {"board": _name_board}, init=1, uid=board_id.decode())

        # s_mod = umod.rec_sel("cfg_board", name=_name_board)
        # if len(s_mod):
        #     board = s_mod[0]["board"]
        #     if s_mod[0]["init"] == 0:
        #         from board.cfg_db import push_data
        #         push_data(umod)
        #         umod.rec_upd("cfg_board", {"board": board}, init=1, uid=board_id.decode())
        # else:
        #     log.info("BOARD: NOT CONFIGURE")

        self.core = uCore(mbus, umod, board)
        for mod in _modules:
            if mod["active"]:
                name_mod = mod["name"]

                try:
                    init_act = __import__("{}_mod".format(name_mod)).init_act
                    self.core = init_act(self.core)
                    log.info("MOD ACT ACTIVATE: {}".format(name_mod))
                    del sys.modules["{}_mod".format(name_mod)]
                    # umod.call_cmd("_upd", "board_mod", {"name": name_mod}, status="loaded")
                except Exception as e:
                    log.info("MOD: {}, activate err: {}".format(mod, e))


# per-publisher configuration for pubCrawl.py
from os.path import *
import logging, urllib2, urlparse, urllib, re
import pubConf, pubGeneric, maxCommon, html, maxCommon

# crawler delay config, values in seconds
# these overwrite the default set with the command line switch to pubCrawl
# special case is highwire, handled in the code:
# (all EST): mo-fri: 9-5pm: 120 sec, mo-fri 5pm-9am: 10 sec, sat-sun: 5 sec (no joke)
crawlDelays = {
    "www.nature.com"              : 10,
    "onlinelibrary.wiley.com" : 1,
    "dx.doi.org"              : 1,
    "ucelinks.cdlib.org"      : 20,
    "eutils.ncbi.nlm.nih.gov"      : 3,
    "sciencedirect.com"      : 15
}

def parseHighwire():
    """ create two dicts
    printIssn -> url to pmidlookup-cgi of highwire
    and
    publisherName -> top-level hostnames
    >>> temps, domains = parseHighwire()
    >>> temps['0270-6474']
    u'http://www.jneurosci.org/cgi/pmidlookup?view=long&pmid=%(pmid)s'
    >>> domains["Society for Neuroscience"]
    set([u'jneurosci'])
    """
    # highwire's publisher names are not resolved ("SAGE", "SAGE Pub", etc)
    # so: first get dict printIssn -> resolved publisherName from publishers.tab
    pubFname = join(pubConf.publisherDir, "publishers.tab")
    pIssnToPub = {}
    for row in maxCommon.iterTsvRows(pubFname):
        if not row.pubName.startswith("HIGHWIRE"):
            continue
        for issn in row.journalIssns.split("|"):
            issn = issn.rstrip(" ")
            pIssnToPub[issn] = row.pubName.replace("HIGHWIRE ","").strip()

    # go over highwire table and make dict pubName -> issn -> templates
    # and dict pubName -> domains
    fname = join(pubConf.journalListDir, "highwire.tab")
    templates = {}
    domains = {}
    for row in maxCommon.iterTsvRows(fname, encoding="latin1"):
        if row.eIssn.strip()=="Unknown":
            continue
        pubName = pIssnToPub[row.pIssn.strip()].strip()
        templates.setdefault(pubName, {})
        templates[row.pIssn.strip()] = row.urls.strip()+"/cgi/pmidlookup?view=long&pmid=%(pmid)s"

        host = urlparse.urlparse(row.urls).hostname
        domain = ".".join(host.split('.')[-2:]).strip()
        domains.setdefault(pubName, set()).add(domain)

    return templates, domains

def highwireConfigs():
    " return dict publisher name -> config for all highwire publishers "
    logging.info("Creating config for Highwire publishers")
    res = {}
    issnTemplates, pubDomains = parseHighwire()

    for pubName, domains in pubDomains.iteritems():
        templates = {}
        for issn, templUrl in issnTemplates.iteritems():
            for domain in domains:
                if domain in templUrl:
                    templates[issn]=templUrl
                    break

        res[pubName] = {
            "hostnames" : domains,
            "landingUrl_templates" : templates,
            "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
            "doiUrl_replace" : {"$" : ".long"},
            "landingUrl_isFulltextKeyword" : ".long",
            "landingPage_ignoreMetaTag" : True,
            "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
            "landingPage_suppFileList_urlREs" : [".*/content.*suppl/DC[0-9]"],
            "suppListPage_suppFile_urlREs" : [".*/content.*suppl/.*"],
        }
    return res

highwireCfg = highwireConfigs()

# crawl configuration: for each website, define how to crawl the pages
confDict = {
    "oup" :
        highwireCfg["Oxford University Press"],

    "pmc" :
    # not used at UCSC
    # caveats: we always keep html, can't distinguish between PDF-only and
    # and HTML/PDF articles
    # supplementals might not always work, tested only on PLOS
    # only gets the first supplemental file
    {
        "hostnames" : ["www.ncbi.nlm.nih.gov"],
        "landingUrl_fulltextUrl_append" : "pdf",
        "landingUrl_isSuppListUrl": True,
        "landingUrl_isFulltextKeyword" : "pmc", # always true -> always keep fulltext
        "suppListPage_suppFileTextREs" : ["Click here for additional data file.*"]
    },
    "springer" :
    # we don't use this at UCSC, we get springer directly
    {
        "hostnames" : ["link.springer.com"],
        #only pdfs "landingUrl_replaceREs" : {"$" : "?np=y"}, # switch sd to screen reader mode
        "landingPage_stopPhrases": ["make a payment", "purchase this article"],
        "landingPage_mainLinkTextREs" : [".*Download PDF +\([0-9]+ KB\)"],
        "suppListPage_suppFile_urlREs" : [".*/file/MediaObjects/.*"],
        "landingUrl_isSuppListUrl": True
    },

    "elsevier" :
    # at UCSC we don't use this, we get elsevier data via consyn.elsevier.dom
    # this is mostly for off-site use or for the odd project that doesn't
    # want to pull from consyn
    # caveats:
    # * we cannot download text html (no function to add np=y to landing url)
    # * we don't know if we actually have access to an article
    # * no supplemental files
    {
        "hostnames" : ["www.sciencedirect.com"],
        #only pdfs "landingUrl_replaceREs" : {"$" : "?np=y"}, # switch sd to screen reader mode
        "landingPage_stopPhrases": ["make a payment", "purchase this article", \
            "This is a one-page preview only"],
        "landingPage_mainLinkTextREs" : ["PDF  +\([0-9]+ K\)"],
    },

    "npg" :
    # http://www.nature.com/nature/journal/v463/n7279/suppinfo/nature08696.html
    # http://www.nature.com/pr/journal/v42/n4/abs/pr19972520a.html - has no pdf
    #
    {
        "hostnames" : ["www.nature.com"],
        "landingPage_stopPhrases": ["make a payment", "purchase this article"],
        "landingPage_acceptNoPdf": True,
        "landingUrl_isFulltextKeyword" : "full",
        "landingUrl_fulltextUrl_replace" : {"full" : "pdf", "html" : "pdf", "abs" : "pdf"},
        "landingPage_mainLinkTextREs" : ["Download PDF"],
        "landingUrl_suppListUrl_replace" : {"full" : "suppinfo", "abs" : "suppinfo"},
        "landingPage_suppListTextREs" : ["Supplementary information index", "[Ss]upplementary [iI]nfo", "[sS]upplementary [iI]nformation"],
        "suppListPage_suppFileTextREs" : ["[Ss]upplementary [dD]ata.*", "[Ss]upplementary [iI]nformation.*", "Supplementary [tT]able.*", "Supplementary [fF]ile.*", "Supplementary [Ff]ig.*", "Supplementary [lL]eg.*", "Download PDF file.*", "Supplementary [tT]ext.*", "Supplementary [mM]ethods.*", "Supplementary [mM]aterials.*", "Review Process File"]
    # Review process file for EMBO, see http://www.nature.com/emboj/journal/v30/n13/suppinfo/emboj2011171as1.html
    },

    # with suppl
    # PMID 22017543
    # http://online.liebertpub.com/doi/full/10.1089/nat.2011.0311
    # with html
    # PMID 22145933
    # http://online.liebertpub.com/doi/abs/10.1089/aid.2011.0232
    # no html
    # PMID 7632460
    # http://online.liebertpub.com/doi/abs/10.1089/aid.1995.11.443
    "mal" :
    {
        "hostnames" : ["online.liebertpub.com"],
        "landingUrl_templates" : {"anyIssn" : "http://online.liebertpub.com/doi/full/%(doi)s"},
        "landingUrl_isFulltextKeyword" : "/full/",
        "landingUrl_fulltextUrl_replace" : {"/abs/" : "/full/" },
        "landingPage_mainLinkTextREs" : ["Full Text PDF.*"],
        "landingPage_suppListTextREs" : ["Supplementary materials.*"]
    },

    # https://www.jstage.jst.go.jp/article/circj/75/4/75_CJ-10-0798/_article
    # suppl file download does NOT work: strange javascript links
    "jstage" :
    {
        "hostnames" : ["www.jstage.jst.go.jp"],
        "landingUrl_fulltextUrl_replace" : {"_article" : "_pdf" },
        "landingPage_mainLinkTextREs" : ["Full Text PDF.*"],
        "landingPage_suppListTextREs" : ["Supplementary materials.*"]
    },
    # rupress tests:
    # PMID 12515824 - with integrated suppl files into main PDF
    # PMID 15824131 - with separate suppl files
    # PMID 8636223  - landing page is full (via Pubmed), abstract via DOI
    # cannot do suppl zip files like this one http://jcb.rupress.org/content/169/1/35/suppl/DC1
    #
    "rupress" :
    {
        "hostnames" : ["rupress.org", "jcb.org"],
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignorePageWords" : ["From The Jcb"],
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf"},
        "suppListPage_addSuppFileTypes" : ["html", "htm"], # pubConf does not include htm/html
        "landingPage_mainLinkTextREs" : ["Full Text (PDF)"],
        #"landingPage_suppListTextREs" : ["Supplemental [Mm]aterial [Iindex]", "Supplemental [Mm]aterial"],
        "landingUrl_suppListUrl_replace" : {".long" : "/suppl/DC1", ".abstract" : "/suppl/DC1"},
        "suppListPage_suppFileTextREs" : ["[Ss]upplementary [dD]ata.*", "[Ss]upplementary [iI]nformation.*", "Supplementary [tT]able.*", "Supplementary [fF]ile.*", "Supplementary [Ff]ig.*", "[ ]+Figure S[0-9]+.*", "Supplementary [lL]eg.*", "Download PDF file.*", "Supplementary [tT]ext.*", "Supplementary [mM]aterials and [mM]ethods.*", "Supplementary [mM]aterial \(.*"],
        "ignoreSuppFileLinkWords" : ["Video"],
        "ignoreSuppFileContentText" : ["Reprint (PDF) Version"],
        "suppListPage_suppFile_urlREs" : [".*/content/suppl/.*"]
    },
    # http://jb.asm.org/content/194/16/4161.abstract = PMID 22636775
    "asm" :
    {
        "hostnames" : ["asm.org"],
        "landingUrl_isFulltextKeyword" : ".long",
        "doiUrl_replace" : {"$" : ".long"},
        "landingPage_ignoreMetaTag" : True,
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # if found on landing page Url, wait for 15 minutes and retry
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        #"landingUrl_fulltextUrl_replace" : {"long" : "full.pdf?with-ds=yes", "abstract" : "full.pdf?with-ds=yes" },
        #"landingUrl_suppListUrl_replace" : {".long" : "/suppl/DCSupplemental", ".abstract" : "/suppl/DCSupplemental"},
        "landingPage_suppFileList_urlREs" : [".*suppl/DCSupplemental"],
        "suppListPage_suppFile_urlREs" : [".*/content/suppl/.*"],
    },
    #
    # 21159627 http://cancerres.aacrjournals.org/content/70/24/10024.abstract has suppl file
    "aacr" :
    {
        "hostnames" : ["aacrjournals.org"],
        "landingUrl_templates" : {"0008-5472" : "http://cancerres.aacrjournals.org/content/%(vol)s/%(issue)s/%(firstPage)s.long"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
        "landingPage_stopPhrases" : ["Purchase Short-Term Access"]
    },
    # 1995 PMID 7816814
    # 2012 PMID 22847410 has one supplement, has suppl integrated in paper
    "cshlp" :
    {
        "hostnames" : ["cshlp.org"],
        "landingUrl_templates" : {"1355-8382" : "http://rnajournal.cshlp.org/content/%(vol)s/%(issue)s/%(firstPage)s.full"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
        "landingPage_stopPhrases" : ["Purchase Short-Term Access"]
    },
    "pnas" :
    {
        "hostnames" : ["pnas.org"],
        "landingUrl_templates" : {"0027-8424" : "http://pnas.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*suppl/DCSupplemental"],
        "suppListPage_suppFile_urlREs" : [".*/content/suppl/.*"],
    },
    "aspet" :
    {
        "hostnames" : ["aspetjournals.org"],
        "landingUrl_templates" : {"0022-3565" : "http://jpet.aspetjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
    },
    "faseb" :
    {
        "hostnames" : ["fasebj.org"],
        "landingUrl_templates" : {"0892-6638" : "http://www.fasebj.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
    },
    # society of leukocyte biology
    # PMID 20971921
    "slb" :
    {
        "hostnames" : ["jleukbio.org"],
        "landingUrl_templates" : {"0741-5400" : "http://www.jleukbio.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
    },
    # Company of Biologists
    "cob" :
    {
        "hostnames" : ["biologists.org"],
        "landingUrl_templates" : {"0950-1991" : "http://dev.biologists.org/cgi/pmidlookup?view=long&pmid=%(pmid)s", "0022-0949" : "http://jcs.biologists.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
    },
    # Genetics Society of America
    # PMID 22714407
    "genetics" :
    {
        "hostnames" : ["genetics.org"],
        "landingUrl_templates" : {"0016-6731" : "http://genetics.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content[0-9/]*suppl/.*"],
    },
    # Society of General Microbiology
    # PMID 22956734
    # THEY USE DC1 AND DC2 !!! Currently we're missing the DC1 or DC2 files... :-(
    # todo: invert linkdict to link -> text and not text -> link
    # otherwise we miss one link if we see twice "supplemental table" (see example)
    "sgm" :
    {
        "hostnames" : ["sgmjournals.org"],
        "landingUrl_templates" : {\
            "1466-5026" : "http://ijs.sgmjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s", \
            "1350-0872" : "http://mic.sgmjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s", \
            "0022-2615" : "http://jmm.sgmjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s", \
            "0022-1317" : "http://vir.sgmjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content.*suppl/DC[0-9]"],
        "suppListPage_suppFile_urlREs" : [".*/content.*suppl/.*"],
    },
    # SMBE - Soc of Mol Biol and Evol
    # part of OUP - careful, duplicates!
    # PMID 22956734
    "smbe" :
    {
        "hostnames" : ["mbe.oxfordjournals.org"],
        "landingUrl_templates" : \
            {"0737-4038" : "http://mbe.oxfordjournals.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content.*suppl/DC[0-9]"],
        "suppListPage_suppFile_urlREs" : [".*/content.*suppl/.*"],
    },
    # http://www.jimmunol.org/content/189/11/5129/suppl/DC1
    # http://www.jimmunol.org/content/suppl/2012/10/25/jimmunol.1201570.DC1/12-01570_S1-4_ed10-24.pdf
    "aai" :
    {
        "hostnames" : ["jimmunol.org"],
        "landingUrl_templates" : {"0022-1767" : "http://www.jimmunol.org/cgi/pmidlookup?view=long&pmid=%(pmid)s"},
        "landingPage_errorKeywords" : "We are currently doing routine maintenance", # wait for 15 minutes and retry
        "doiUrl_replace" : {"$" : ".long"},
        "landingUrl_isFulltextKeyword" : ".long",
        "landingPage_ignoreMetaTag" : True,
        "landingUrl_fulltextUrl_replace" : {"long" : "full.pdf", "abstract" : "full.pdf" },
        "landingPage_suppFileList_urlREs" : [".*/content[0-9/]*suppl/DC1"],
        "suppListPage_suppFile_urlREs" : [".*/content/suppl/.*"],
    },
    # example suppinfo links 20967753 (major type of suppl, some also have "legacy" suppinfo
    # example spurious suppinfo link 8536951
    #
    "wiley" :
    {
        "hostnames" : ["onlinelibrary.wiley.com"],
        #"landingUrl_templates" : {None: "http://onlinelibrary.wiley.com/doi/%(doi)s/full"},
        "doiUrl_replace" : {"abstract" : "full"},
        "landingUrl_isFulltextKeyword" : "full",
        "landingUrl_fulltextUrl_replace" : {"full" : "pdf", "abstract" : "pdf"},
        "landingPage_suppListTextREs" : ["Supporting Information"],
        "suppListPage_suppFile_urlREs" : [".*/asset/supinfo/.*", ".*_s.pdf"],
        "suppFilesAreOffsite" : True,
        "landingPage_ignoreUrlREs"  : ["http://onlinelibrary.wiley.com/resolve/openurl.genre=journal&issn=[0-9-X]+/suppmat/"],
        "landingPage_stopPhrases" : ["You can purchase online access", "Registered Users please login"]
    },
    # http://www.futuremedicine.com/doi/abs/10.2217/epi.12.21
    "futureScience" :
    {
        "hostnames" : ["futuremedicine.com", "future-science.com", "expert-reviews.com", "future-drugs.com"],
        "landingUrl_fulltextUrl_replace" : {"abs" : "pdfplus"},
        "landingUrl_suppListUrl_replace" : {"abs" : "suppl"},
        "suppListPage_suppFile_urlREs" : [".*suppl_file.*"],
        "landingPage_stopPhrases" : ["single article purchase is required", "The page you have requested is unfortunately unavailable"]
    },

}

def compileRegexes():
    " compile regexes in confDict "
    ret = {}
    for pubId, crawlConfig in confDict.iteritems():
        ret[pubId] = {}
        for key, values in crawlConfig.iteritems():
            if key.endswith("REs"):
                newValues = []
                for regex in values:
                    newValues.append(re.compile(regex))
            else:
                newValues = values
            ret[pubId][key] = newValues
    return ret

def prepConfigIndexByHost():
    """ compile regexes in config and return dict publisherId -> config and hostname -> config
    these make it possible to get the config either by hostname (for general mode)
    or by publisher (for per-publisher mode)
    """
    compCfg = compileRegexes()
    byHost = {}
    for pubId, crawlConfig in compCfg.iteritems():
        for host in crawlConfig["hostnames"]:
            byHost[host] = crawlConfig
    return compCfg, byHost


import os
import re
import pickle
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

todos = []

# Load the saved list if it exists
if os.path.exists('todos.pkl'):
    with open('todos.pkl', 'rb') as file:
        todos = pickle.load(file)

@app.route('/')
def index():
    error = request.args.get('error', '')
    return render_template('index.html', todos=todos, error=error)

@app.route('/submit', methods=['POST'])
def submit():
    task = request.form['task']
    email = request.form['email']
    priority = request.form['priority']

    # Validate email
    email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    if not re.match(email_regex, email):
        return redirect(url_for('index', error='Invalid email'))

    # Validate priority
    if priority not in ['Low', 'Medium', 'High']:
        return redirect(url_for('index', error='Invalid priority'))

    new_todo = {
        'task': task,
        'email': email,
        'priority': priority
    }
    todos.append(new_todo)

    return redirect(url_for('index'))

@app.route('/delete/<int:todo_index>', methods=['POST'])
def delete(todo_index):
    if 0 <= todo_index < len(todos):
        del todos[todo_index]
    return redirect(url_for('index'))

@app.route('/clear', methods=['POST'])
def clear():
    todos.clear()
    return redirect(url_for('index'))

@app.route('/save', methods=['POST'])
def save():
    with open('todos.pkl', 'wb') as file:
        pickle.dump(todos, file)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)


from django.db import models
from django.utils.translation import ugettext_lazy as _
from chaolife.models import Order
from model_utils.fields import MonitorField
from datetime import timedelta,datetime
from chaolifeProject.settings import AUTH_USER_MODEL
from .refunds import OrderRefund
from moneyed import Money
from account.models import BillHistory
class OrderBill(models.Model):

    SETTLEMENT_IMMEDIATELY = 1 # 立即结算
    SETTLEMENT_DELAY = 2# 延迟结算
    SETTLEMENT_CHOICE = (
        (SETTLEMENT_IMMEDIATELY,'立即结算'),
        (SETTLEMENT_DELAY,'延迟结算'),
    )

    order = models.OneToOneField(Order)
    seller = models.ForeignKey(AUTH_USER_MODEL,null=True)
    create_at = models.DateTimeField(auto_now_add=True,verbose_name=_('订单创建时间'))
    commission = models.FloatField(verbose_name=_('佣金(积分)'),default=0)
    order_amount = models.FloatField(verbose_name=_('订单总额'))
    refund_amount = models.FloatField(verbose_name=_('退单金额'),help_text='退单金额，可能是用户取消订单，退还的金额')
    capital_settlement = models.IntegerField( choices=SETTLEMENT_CHOICE,verbose_name=_('商家结算方式'),help_text='资金结算方式，有包括立即结算，和延时结算')
    delay_settlement_time = models.DateTimeField(verbose_name=_('需要结算的日期'),null=True)
    seller_gains = models.FloatField(verbose_name=_('卖家收益积分'),help_text='在产生积分赔付的情况下，该值可能为负')
    settled  = models.BooleanField(default=False,verbose_name=_('已结算?'),help_text='是否已结算')
    settled_at = MonitorField(monitor='settled',when=[True,])

    class Meta:
        verbose_name = "订单结算"
        verbose_name_plural = "订单结算"

    def __str__(self):
        return '订单'+self.order_id

    @classmethod
    def create_for_roomOrder_cancel(cls,roomOrder,refund_amount,):
        order_amount = roomOrder.amount
        assert refund_amount < order_amount
        can_gains_points = order_amount - refund_amount
        sell_gains = can_gains_points * 0.75
        commission = can_gains_points * 0.25
        orderbill = cls(
            order=roomOrder,
            seller=roomOrder.seller,
            commission=commission,
            order_amount=order_amount,
            refund_amount=refund_amount,
            capital_settlement=cls.SETTLEMENT_IMMEDIATELY,
            delay_settlement_time = datetime.now(),
            seller_gains=sell_gains,
            settled=True
        )
        if orderbill.capital_settlement == cls.SETTLEMENT_IMMEDIATELY:
            customer = roomOrder.customer
            seller = roomOrder.seller
            seller.add_partner_points(can_gains_points)
            customer.add_customer_points(refund_amount)
        return orderbill

    @classmethod
    def create_for_perfect_room_sell(cls,hotelPackageOrder):
        orderbill = cls(
            order=hotelPackageOrder,
            seller=hotelPackageOrder.seller,
            commission=hotelPackageOrder.amount * 0.25,
            order_amount=hotelPackageOrder.amount,
            refund_amount=0,
            capital_settlement=cls.SETTLEMENT_DELAY,
            seller_gains=hotelPackageOrder.amount * 0.75,
            delay_settlement_time=hotelPackageOrder.checkout_time + timedelta(days=2),
            settled=False
        )
        return orderbill

    @classmethod
    def create_for_refund_order(cls,orderRefund):
        order = orderRefund.order
        seller_gains = -orderRefund.losses_money * 10
        orderBill = cls(
            order=order,
            seller=order.seller,
            order_amount=order.amount,
            refund_amount=orderRefund.refund_points,
            capital_settlement=cls.SETTLEMENT_IMMEDIATELY,
            commission=0,
            seller_gains =  seller_gains,
            settled = False
        )
        orderBill.save()
        BillHistory.createForRefundOrderBill(orderBill)


#!/usr/bin/env python -W ignore

import os, sys, datetime, time

import numpy as np

from sklearn.feature_extraction import DictVectorizer

TAB = "\t"

'''
user_id
card_type
signin_count
payment_amount
resume_count
payment_count
cancel_first
first_payment_amount
first_payment_at
chargeback_at
cancelled_at
zipcode_hawaiian
zipcode_multi_race
zipcode_other_race
zipcode_black
zipcode_white
zipcode_indian
zipcode_asian
zipcode_hispanic
zipcode_non_hispanic
zipcode_poverty
zipcode_avg_rent
zipcode_family_size
zipcode_hh_avg_income
chargeback_file
chargeback_or_not
'''
def load_analysis_raw(filepath, date_split=None, skip_header=True, setting={}, ab_testing=False):
    # if ab_testing is passed as True,
    # skip certain portion of users in the prediction as control group in comparison with experiment group
    is_timing = setting.get("is_timing", False)
    is_zipcode = setting.get("is_zipcode", False)
    is_lifetime = setting.get("is_lifetime", False)
    is_onet = setting.get("is_onet", False)

    date_split = datetime.datetime.strptime(date_split, "%Y%m%d") if date_split else None

    dataset, answerset, personal_dataset = [], np.array([], dtype=np.int64), []
    prediction_dataset, prediction_answerset, prediction_personal_dataset = [], np.array([], dtype=np.int64), []

    def format_number(n):
        return float(n) if n.lower() != "none" else 0

    def get_answerset(dims, true_idx):
        results = np.array(np.zeros(shape=dims), dtype=np.int32)
        results[true_idx] = 1

        return results

    with open(filepath, "rb") as INPUT:
        for line in INPUT:
            if skip_header:
                skip_header = False
                continue
            else:
                user_id, card_type, signin_count, payment_amount, resume_count, payment_count, cancel_first, first_payment_amount, first_payment_at, chargeback_at, lifetime, \
                zipcode_hawaiian, zipcode_multi_race, zipcode_other_race, zipcode_black, zipcode_white, zipcode_indian, zipcode_asian, zipcode_hispanic, zipcode_non_hispanic, zipcode_poverty, zipcode_avg_rent, zipcode_family_size, zipcode_hh_avg_income, \
                onet_transpertation, onet_production, onet_installation, onet_eduation, onet_computer, onet_architecture, onet_arts, onet_construction, onet_business, onet_community, onet_budiling, onet_healthcare, onet_life, onet_food, onet_farming, onet_support, onet_legal, onet_office, onet_sales, onet_protective, onet_personal, onet_military, onet_management, \
                chargeback_file, chargeback_or_not = line.strip().split(TAB)

                if ab_testing and control_or_experiment(user_id):  # skip control group
                    continue

                resume_count = int(resume_count) if resume_count != "[]" else 0
                payment_count = int(payment_count)
                first_payment_amount = int(first_payment_amount)

                origin_card_type = card_type
                card_type = "master" if card_type in ["mastercard"] else card_type
                card_type = "None" if card_type in ["diners_club", "maestro"] else card_type

                cancel_first = 1 if cancel_first == "True" else 0
                first_payment_at = datetime.datetime.strptime(first_payment_at, "%Y-%m-%d")

                if setting:
                    first_payment_at_start = setting.get("first_payment_at_start", None)
                    first_payment_at_end = setting.get("first_payment_at_end", None)

                    if first_payment_at_start != None and first_payment_at < first_payment_at_start:
                        continue
                    if first_payment_at_end != None and first_payment_at > first_payment_at_end:
                        continue

                zipcode_hh_avg_income = format_number(zipcode_hh_avg_income)

                chargeback_or_not = 1 if chargeback_or_not.lower() == "y" else 0

                data = {"first_payment_amount": first_payment_amount,
                        "first_payment_weekday": first_payment_at.weekday(),
                        "resume_count": int(resume_count),
                        "card_type": card_type,
                        "cancel_first": cancel_first,
                        }

                if is_timing:
                    data["signin_count"] = int(signin_count) if signin_count.lower() != "none" else 0
                    data["payment_count"] = payment_count
                    data["payment_amount"] = float(payment_amount)

                if is_onet:
                    data["onet_transpertation"] = float(onet_transpertation)
                    data["onet_production"] = float(onet_production)
                    data["onet_installation"] = float(onet_installation)
                    data["onet_eduation"] = float(onet_eduation)
                    data["onet_computer"] = float(onet_computer)
                    data["onet_architecture"] = float(onet_architecture)
                    data["onet_arts"] = float(onet_arts)
                    data["onet_construction"] = float(onet_construction)
                    data["onet_business"] = float(onet_business)
                    data["onet_community"] = float(onet_community)
                    data["onet_budiling"] = float(onet_budiling)
                    data["onet_healthcare"] = float(onet_healthcare)
                    data["onet_life"] = float(onet_life)
                    data["onet_food"] = float(onet_food)
                    data["onet_farming"] = float(onet_farming)
                    data["onet_support"] = float(onet_support)
                    data["onet_legal"] = float(onet_legal)
                    data["onet_office"] = float(onet_office)
                    data["onet_sales"] = float(onet_sales)
                    data["onet_protective"] = float(onet_protective)
                    data["onet_personal"] = float(onet_personal)
                    data["onet_military"] = float(onet_military)
                    data["onet_management"] = float(onet_management)

                    if setting.get("is_category_onet", False):
                        possible_occupation, max_value = None, -1
                        for key, value in data.items():
                            if key.find("onet_") == 0:
                                if value > max_value:
                                    possible_occupation, max_value = key, value

                        for key in data.keys():
                            if key.find("onet_") == 0:
                                del data[key]

                        data["occupation"] = possible_occupation.split("_")[1]

                        if setting.get("target_occupation", []) and data["occupation"] not in setting["target_occupation"]:
                            continue
                        else:
                            del data["occupation"]

                if is_lifetime:
                    data["lifetime"] = int(lifetime) if lifetime != "None" else -sys.maxint

                if is_zipcode:
                    data["zipcode_hawaiian"] = float(zipcode_hawaiian) if zipcode_hawaiian.lower() != "none" else 0
                    data["zipcode_multi_race"] = float(zipcode_multi_race) if zipcode_multi_race.lower() != "none" else 0
                    data["zipcode_other_race"] = float(zipcode_other_race) if zipcode_other_race.lower() != "none" else 0
                    data["zipcode_black"] = float(zipcode_black) if zipcode_black.lower() != "none" else 0
                    data["zipcode_white"] = float(zipcode_white) if zipcode_white.lower() != "none" else 0
                    data["zipcode_indian"] = float(zipcode_indian) if zipcode_indian.lower() != "none" else 0
                    data["zipcode_asian"] = float(zipcode_asian) if zipcode_asian.lower() != "none" else 0
                    data["zipcode_hispanic"] = float(zipcode_hispanic) if zipcode_hispanic.lower() != "none" else 0
                    data["zipcode_non_hispanic"] = float(zipcode_non_hispanic) if zipcode_non_hispanic.lower() != "none" else 0
                    data["zipcode_poverty"] = float(zipcode_poverty) if zipcode_poverty.lower() != "none" else 0
                    data["zipcode_avg_rent"] = float(zipcode_avg_rent) if zipcode_avg_rent.lower() != "none" else 0
                    data["zipcode_family_size"] = float(zipcode_family_size) if zipcode_family_size.lower() != "none" else 0
                    data["zipcode_hh_avg_income"] = zipcode_hh_avg_income

                if date_split == None or first_payment_at < date_split:
                    dataset.append(data)

                    if answerset.size == 0:
                        answerset = np.array([get_answerset(2, chargeback_or_not)])
                    else:
                        answerset = np.vstack((answerset, get_answerset(2, chargeback_or_not)))

                    personal_dataset.append({user_id: {"file": chargeback_file, "card_type": origin_card_type}})
                else:
                    prediction_dataset.append(data)
                    if prediction_answerset.size == 0:
                        prediction_answerset = np.array([get_answerset(2, chargeback_or_not)])
                    else:
                        prediction_answerset = np.vstack((prediction_answerset, get_answerset(2, chargeback_or_not)))

                    prediction_personal_dataset.append({user_id: {"file": chargeback_file, "card_type": origin_card_type}})

    vec = DictVectorizer()
    transformed_dataset = vec.fit_transform(dataset).toarray() if dataset else vec.fit_transform(prediction_dataset).toarray()
    transformed_title = vec.get_feature_names()

    transformed_prediction_dataset = None
    if date_split:
        transformed_prediction_dataset = None
        for idx, prediction_data in enumerate(prediction_dataset):
            t = []
            for transformed_t in transformed_title:
                if transformed_t.find("=") == -1:
                    t.append(float(prediction_data[transformed_t]))
                else:
                    key, value = transformed_t.split("=", 1)
                    if prediction_data[key] == value:
                        t.append(float(1))
                    else:
                        t.append(float(0))

            if transformed_prediction_dataset == None:
                transformed_prediction_dataset = np.array([t])
            else:
                transformed_prediction_dataset = np.vstack((transformed_prediction_dataset, t))

    return transformed_title, personal_dataset, (transformed_dataset, answerset), (transformed_prediction_dataset, prediction_answerset, prediction_personal_dataset)


# Lint as: python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# pylint: disable=unused-variable

from absl import logging
from absl.testing import absltest
import numpy as np
from pyiree import compiler2 as compiler
from pyiree import rt

def create_add_scalar_module():
  binary = compiler.compile_str("""
    func @add_scalar(%arg0: i32, %arg1: i32) -> i32 attributes { iree.module.export } {
      %0 = addi %arg0, %arg1 : i32
      return %0 : i32
    }
    """,
                                target_backends=["vmla"])
  m = rt.VmModule.from_flatbuffer(binary)
  return m

def create_simple_static_mul_module():
  binary = compiler.compile_str("""
    func @simple_mul(%arg0: tensor<4xf32>, %arg1: tensor<4xf32>) -> tensor<4xf32>
          attributes { iree.module.export } {
        %0 = "mhlo.multiply"(%arg0, %arg1) {name = "mul.1"} : (tensor<4xf32>, tensor<4xf32>) -> tensor<4xf32>
        return %0 : tensor<4xf32>
    }
    """,
                                target_backends=["vmla"])
  m = rt.VmModule.from_flatbuffer(binary)
  return m

def create_simple_dynamic_abs_module():
  # TODO(laurenzo): Compile for more backends as dynamic shapes come online.
  target_backends = ["vmla"]
  binary = compiler.compile_str("""
    func @simple_mul(%arg0: tensor<?x?xf32>) -> tensor<?x?xf32>
          attributes { iree.module.export } {
        %0 = "mhlo.abs"(%arg0) : (tensor<?x?xf32>) -> tensor<?x?xf32>
        return %0 : tensor<?x?xf32>
    }
    """,
                                target_backends=target_backends)
  m = rt.VmModule.from_flatbuffer(binary)
  return m

class VmTest(absltest.TestCase):

  @classmethod
  def setUpClass(cls):
    super().setUpClass()
    driver_names = rt.HalDriver.query()
    logging.info("driver_names: %s", driver_names)
    cls.driver = rt.HalDriver.create("vmla")
    cls.device = cls.driver.create_default_device()
    cls.hal_module = rt.create_hal_module(cls.device)
    cls.htf = rt.HostTypeFactory.get_numpy()

  def test_variant_list(self):
    l = rt.VmVariantList(5)
    logging.info("variant_list: %s", l)
    self.assertEqual(l.size, 0)

  def test_context_id(self):
    instance = rt.VmInstance()
    context1 = rt.VmContext(instance)
    context2 = rt.VmContext(instance)
    self.assertGreater(context2.context_id, context1.context_id)

  def test_module_basics(self):
    m = create_simple_static_mul_module()
    f = m.lookup_function("simple_mul")
    self.assertGreater(f.ordinal, 0)
    notfound = m.lookup_function("notfound")
    self.assertIs(notfound, None)

  def test_dynamic_module_context(self):
    instance = rt.VmInstance()
    context = rt.VmContext(instance)
    m = create_simple_static_mul_module()
    context.register_modules([self.hal_module, m])

  def test_static_module_context(self):
    m = create_simple_static_mul_module()
    logging.info("module: %s", m)
    instance = rt.VmInstance()
    logging.info("instance: %s", instance)
    context = rt.VmContext(instance, modules=[self.hal_module, m])
    logging.info("context: %s", context)

  def test_dynamic_shape_compile(self):
    m = create_simple_dynamic_abs_module()
    logging.info("module: %s", m)
    instance = rt.VmInstance()
    logging.info("instance: %s", instance)
    context = rt.VmContext(instance, modules=[self.hal_module, m])
    logging.info("context: %s", context)

  def test_add_scalar(self):
    m = create_add_scalar_module()
    instance = rt.VmInstance()
    context = rt.VmContext(instance, modules=[self.hal_module, m])
    f = m.lookup_function("add_scalar")
    abi = context.create_function_abi(self.device, self.htf, f)
    logging.info("abi: %s", abi)

    inputs = abi.pack_inputs(5, 6)
    logging.info("serialize_inputs: %s", abi.serialize_vm_list(inputs))
    logging.info("inputs: %s", inputs)

    allocated_results = abi.allocate_results(inputs, static_alloc=False)
    logging.info("allocated_results: %s", allocated_results)
    logging.info("Invoking...")
    context.invoke(f, inputs, allocated_results)
    logging.info("...done")

    result = abi.unpack_results(allocated_results)
    logging.info("result: %s", result)
    self.assertEqual(result, 11)

  def test_synchronous_dynamic_shape_invoke_function(self):
    m = create_simple_dynamic_abs_module()
    instance = rt.VmInstance()
    context = rt.VmContext(instance, modules=[self.hal_module, m])
    f = m.lookup_function("simple_mul")
    abi = context.create_function_abi(self.device, self.htf, f)
    logging.info("abi: %s", abi)

    arg0 = np.array([[-1., 2.], [3., -4.]], dtype=np.float32)
    inputs = abi.pack_inputs(arg0)
    logging.info("Serialized inputs: %s", abi.serialize_vm_list(inputs))
    logging.info("inputs: %s", inputs)

    allocated_results = abi.allocate_results(inputs, static_alloc=False)
    logging.info("allocated_results: %s", allocated_results)
    logging.info("Invoking...")
    context.invoke(f, inputs, allocated_results)
    logging.info("...done")

    result = abi.unpack_results(allocated_results)
    logging.info("result: %s", result)
    np.testing.assert_allclose(result, [[1., 2.], [3., 4.]])

  def test_synchronous_invoke_function(self):
    m = create_simple_static_mul_module()
    instance = rt.VmInstance()
    context = rt.VmContext(instance, modules=[self.hal_module, m])
    f = m.lookup_function("simple_mul")
    abi = context.create_function_abi(self.device, self.htf, f)
    logging.info("abi: %s", abi)

    arg0 = np.array([1., 2., 3., 4.], dtype=np.float32)
    arg1 = np.array([4., 5., 6., 7.], dtype=np.float32)
    inputs = abi.pack_inputs(arg0, arg1)
    logging.info("Serialized inputs: %s", abi.serialize_vm_list(inputs))
    logging.info("inputs: %s", inputs)

    allocated_results = abi.allocate_results(inputs, static_alloc=False)
    logging.info("allocated_results: %s", allocated_results)
    logging.info("Invoking...")
    context.invoke(f, inputs, allocated_results)
    logging.info("...done")

    result = abi.unpack_results(allocated_results)
    logging.info("result: %s", result)
    np.testing.assert_allclose(result, [4., 10., 18., 28.])

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


import os
import cv2
import torch
import torchvision
import torch.utils.data
import numpy as np
from tqdm import tqdm
from Net import Net

def recognize_digit(image: np.ndarray) -> int:
    transform = torchvision.transforms.Compose([
        torchvision.transforms.ToPILImage(),
        torchvision.transforms.Resize((224, 224)),
        torchvision.transforms.ToTensor(),
        torchvision.transforms.Lambda(lambda tensor: tensor.repeat(1, 3, 1, 1))
    ])

    data = transform(image).cuda()
    y_out = net(data)
    y_out = y_out.cpu()
    _, y_pred = torch.max(y_out, dim=1)

    return int(y_pred)

def move_digit_images() -> None:
    num_train = [0] * 10
    num_test = [0] * 10

    for digit_image in tqdm(os.listdir("../../data/digits/u")):
        src_path = os.path.join("../../data/digits/u", digit_image)
        image = cv2.imread(src_path)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        digit = recognize_digit(image)
        if np.random.random() < 0.8:
            if num_train[digit] >= 1000:
                break
            dst_path = os.path.join(f"../../data/digits/train/{digit}", f"{num_train[digit]}.jpg")
            num_train[digit] += 1
        else:
            if num_test[digit] >= 1000:
                break
            dst_path = os.path.join(f"../../data/digits/test/{digit}", f"{num_test[digit]}.jpg")
            num_test[digit] += 1
        os.rename(src_path, dst_path)

if __name__ == '__main__':
    net = Net().eval().cuda()
    net.load_state_dict(torch.load("mnist_5e.pth"))
    move_digit_images()


import os.path as osp
import json
import os
from tqdm import tqdm
import numpy as np
import copy

def maybe_mkdir(x):
    if not osp.exists(x):
        os.makedirs(x)

add_data_dir = os.environ.get('SM_CHANNEL_TRAIN', '../../input/data/camper')
# 여기 부분 가지고 계신 폴더구성에 맞추어 수정해주시구요

with open(osp.join(add_data_dir, 'ufo/{}.json'.format('annotation')), 'r') as f:
# 여기 부분도 가지고 계신 파일명에 맞추어서 수정해주시길 요청드립니다.
    anno = json.load(f)

anno = anno['images']

anno_temp = copy.deepcopy(anno)

count = 0
count_normal = 0
count_none_anno = 0

for img_name, img_info in tqdm(anno.items()) :
    if img_info['words'] == {} :
        del(anno_temp[img_name])
        count_none_anno += 1
        continue
    for obj, obj_info in img_info['words'].items() :
        # illegibility는 전부 단어 이므로 false
        anno_temp[img_name]['words'][obj]['illegibility'] = False
        if len(img_info['words'][obj]['points']) == 4 :
            count_normal += 1
            continue

        elif len(img_info['words'][obj]['points']) < 4 :
            del(anno_temp[img_name]['words'][obj])
        # 폴리곤 수정시에는 여기 부분을 수정해주시면 됩니다!!
        # 다음 예제는 polygon이 넘칠 경우 해당 폴리곤을 illegibility를 삭제처리
            if anno_temp[img_name]['words'] == {} :
                del(anno_temp[img_name])
                count_none_anno += 1
                continue
        else :
            # 현동님의 기여로 만들어진 부분
            over_polygon_temp = copy.deepcopy(anno_temp[img_name]['words'][obj])
            over_poly_region = copy.deepcopy(over_polygon_temp)
            over_poly_region['points'] = []
            for index in range(len(img_info['words'][obj]['points'])//2 -1):
                over_poly_region['points'].append(over_polygon_temp['points'][index])
                over_poly_region['points'].append(over_polygon_temp['points'][index+1])
                over_poly_region['points'].append(over_polygon_temp['points'][-index-1])
                over_poly_region['points'].append(over_polygon_temp['points'][-index])
                anno_temp[img_name]['words'][obj+f'{index+911}'] = copy.deepcopy(over_poly_region) #911 현동님 생일 >_<
                over_poly_region['points'] = []
            del anno_temp[img_name]['words'][obj]
            # 폴리곤을 사각단위로 잘라서 각 부분을 word의 영역으로 사용하는 코드입니다.
            if anno_temp[img_name]['words'] == {} :
                del(anno_temp[img_name])
                count_none_anno += 1
                continue
            count += 1

print(f'normal polygon count : {count_normal}')
print(f'deleted {count} over polygon')
print(count_none_anno)

# np_point = np.array(img_info['words'][obj]['points'])
# starting_point = np_point[0]

anno = {'images': anno_temp}

ufo_dir = osp.join('../input/data/camper', 'ufo')
maybe_mkdir(ufo_dir)
with open(osp.join(ufo_dir, 'trains.json'), 'w') as f:
    json.dump(anno, f, indent=4)


import itertools

import matplotlib.pyplot as plt
import numpy as np
import random
from nasbench import api

from nasbench_analysis.search_spaces.search_space import SearchSpace
from nasbench_analysis.utils import OUTPUT_NODE, NasbenchWrapper, INPUT, OUTPUT, PRIMITIVES

class SearchSpace3(SearchSpace):
    def __init__(self):
        super(SearchSpace3, self).__init__(search_space_number=3, num_intermediate_nodes=5)
        """
        SEARCH SPACE 3
        """
        self.num_parents_per_node = {
            '0': 0,
            '1': 1,
            '2': 1,
            '3': 1,
            '4': 2,
            '5': 2,
            '6': 2
        }
        if sum(self.num_parents_per_node.values()) > 9:
            raise ValueError('Each nasbench cell has at most 9 edges.')

        self.test_min_error = 0.05338543653488159
        self.valid_min_error = 0.04847759008407593

    def create_nasbench_adjacency_matrix(self, parents, **kwargs):
        # Create nasbench compatible adjacency matrix
        adjacency_matrix = self._create_adjacency_matrix(parents, adjacency_matrix=np.zeros([7, 7]), node=OUTPUT_NODE)
        return adjacency_matrix

    def create_nasbench_adjacency_matrix_with_loose_ends(self, parents):
        return self._create_adjacency_matrix_with_loose_ends(parents)

    def sample(self):
        adjacency_matrix_sample = self._sample_adjacency_matrix_without_loose_ends(adjacency_matrix=np.zeros([7, 7]), node=OUTPUT_NODE)

        if self._check_validity_of_adjacency_matrix(adjacency_matrix_sample):
            return adjacency_matrix_sample, random.choices(PRIMITIVES, k=5)
        else:
            raise ValueError('The sampled matrix is not from the search space {}'.format(adjacency_matrix_sample))

    def sample_with_loose_ends(self):
        adjacency_matrix_sample = self.sample_adjacency_matrix_with_loose_ends()
        return adjacency_matrix_sample, random.choices(PRIMITIVES, k=5)

    def generate_adjacency_matrix_without_loose_ends(self):
        for adjacency_matrix in self._generate_adjacency_matrix(adjacency_matrix=np.zeros([7, 7]), node=OUTPUT_NODE):
            yield adjacency_matrix

    def generate_with_loose_ends(self):
        for parent_node_2, parent_node_3, parent_node_4, parent_node_5, output_parents in itertools.product(
                *[itertools.combinations(list(range(int(node))), num_parents) for node, num_parents in
                  self.num_parents_per_node.items()][2:]):
            parents = {
                '0': [],
                '1': [0],
                '2': parent_node_2,
                '3': parent_node_3,
                '4': parent_node_4,
                '5': parent_node_5,
                '6': output_parents
            }
            adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(parents)
            yield adjacency_matrix

    def sample_adjacency_matrix_with_loose_ends(self):
        parent_node_2, parent_node_3, parent_node_4, parent_node_5, output_parents = \
            [random.sample(list(itertools.combinations(list(range(int(node))), num_parents)), 1) for node, num_parents
             in self.num_parents_per_node.items()][2:]
        parents = {
            '0': [],
            '1': [0],
            '2': parent_node_2,
            '3': parent_node_3,
            '4': parent_node_4,
            '5': parent_node_5,
            '6': output_parents
        }
        adjacency_matrix = self._create_adjacency_matrix_with_loose_ends(parents)
        return adjacency_matrix

def analysis():
    # Load NASBench
    nasbench = NasbenchWrapper('/home/siemsj/data/nasbench_full.tfrecord')

    test_error = []
    valid_error = []

    search_space_3 = SearchSpace3()
    '''
    for i in range(10000):
        adjacency_matrix, node_list = search_space_3.sample_with_loose_ends()
        adjacency_list = adjacency_matrix.astype(np.int).tolist()
        node_list = [INPUT, *node_list, OUTPUT]
        model_spec = api.ModelSpec(matrix=adjacency_list, ops=node_list)
        nasbench.query(model_spec)
    '''
    for adjacency_matrix, ops, model_spec in search_space_3.generate_search_space_without_loose_ends():
        # Query NASBench
        data = nasbench.query(model_spec)
        for item in data:
            test_error.append(1 - item['test_accuracy'])
            valid_error.append(1 - item['validation_accuracy'])

    print('Number of architectures', len(test_error) / len(data))

    plt.figure()
    plt.title(
        'Distribution of test error in search space (no. architectures {})'.format(int(len(test_error) / len(data))))
    plt.hist(test_error, bins=800)
    ax = plt.gca()
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.xlabel('Test error')
    plt.grid(True, which="both", ls="-", alpha=0.5)
    plt.tight_layout()
    plt.xlim(0, 0.3)
    plt.savefig('nasbench_analysis/search_spaces/export/search_space_3/test_error_distribution.pdf', dpi=600)
    plt.show()

    plt.figure()
    plt.title('Distribution of validation error in search space (no. architectures {})'.format(
        int(len(valid_error) / len(data))))
    plt.hist(valid_error, bins=800)
    ax = plt.gca()
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.xlabel('Validation error')
    plt.grid(True, which="both", ls="-", alpha=0.5)
    plt.tight_layout()
    plt.xlim(0, 0.3)
    plt.savefig('nasbench_analysis/search_spaces/export/search_space_3/valid_error_distribution.pdf', dpi=600)
    plt.show()

    print('min test_error', min(test_error), 'min valid_error', min(valid_error))

if __name__ == '__main__':
    analysis()


# Description:
# Author: Kireev Georgiy <metallerok@gmail.com>
# Copyright (C) 2019 by Kireev Georgiy
import re

from django import forms
from catalog.models import OrderCustomerInfo

class OrderCustomerForm(forms.ModelForm):
    prefix = 'customer_info_form'

    def clean(self):
        cleaned_data = super().clean()
        phone = cleaned_data.get('customer_phone')

        r = re.compile(r'((\+7|8)+([0-9]){10})')
        if not r.findall(phone):
            self.add_error('customer_phone', "Неверный формат номера")

    class Meta:
        model = OrderCustomerInfo
        fields = [
            'customer_name',
            'customer_phone',
            'customer_email',
            'customer_street',
            'customer_house_num',
            'customer_housing',
            'customer_apartment_num'
        ]
        labels = {
            "customer_name": "Ваше имя",
            "customer_phone": "Телефон для связи",
            "customer_email": "Email",
            "customer_street": "Улица",
            "customer_house_num": "Дом",
            "customer_housing": "Корпус",
            "customer_apartment_num": "Квартира"
        }


import torch
import torch.nn.functional as tnnfunc
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
import matplotlib.pyplot as plt
import hw1_318864436_204585301_eval as eval
import numpy as np

"""
short summary:
Inside the train file is the MNIST training process.
We got an input of 784 (28 pixels * 28 pixels), the training worked best for us with 1 hidden layer in size 64,
batch size of 100, learning rate = 1 and with 50 epochs.
We first set up a net with weights and biases (according to the size of the hidden layer).
We started the forward process where we used sigmoid on the hidden layer and softmax on the result.
Next, we performed the backward process, using the gradients we calculated in the theoretical part and the predicted
values from the forward phase.
In the backward process we tried to learn with learning rate = 0.001, then with 0.01 and in the end we got
the best result with learning rate = 1.

To know the percentage of accuracy on the net, we performed a loop that goes through each epoch
(at first we tried sizes 10, 30 and in the end we got the best result with a size of 50).
For each epoch we calculated whether we were right in our prediction.
In the evaluate file we performed the same process, on the test set.

At the end we printed the average accuracy on the test set and two graphs describing the accuracy
of the sets in relation to the time (the epochs)
"""

# Hyper Parameters
input_size = 784 #28*28=784
hidden_size = 64
num_classes = 10
num_epochs = 50
batch_size = 100
learning_rate = 1

# train and test sets
transform = transforms.Compose([transforms.ToTensor()])

train_dataset = dsets.MNIST(root='./data',
                            train=True,
                            transform=transform,
                            download=True)

test_dataset = dsets.MNIST(root='./data',train=False,transform=transform)

# Dataset Loader (Input Pipline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,batch_size=batch_size,shuffle=False)

# utils functions
def sigmoid(s):
    return 1 / (1 + torch.exp(-s))

def sigmoidPrime(s):
    # derivative of sigmoid
    # s: sigmoid output
    return s * (1 - s)

def softmax(X):
    exps = torch.exp(X)
    return (exps / torch.sum(exps))

class Neural_Network:
    def __init__(self, input_size, output_size, hidden_size):
        # parameters
        self.inputSize = input_size
        self.outputSize = output_size
        self.hiddenSize = hidden_size

        # weights
        self.W1 = torch.randn(self.inputSize, self.hiddenSize)
        self.b1 = torch.zeros(self.hiddenSize)

        self.W2 = torch.randn(self.hiddenSize, self.outputSize)
        self.b2 = torch.zeros(self.outputSize)

    def forward(self, X):
        self.z1 = torch.matmul(X, self.W1) + self.b1
        self.h = sigmoid(self.z1)
        self.z2 = torch.matmul(self.h, self.W2) + self.b2
        return softmax(self.z2)

    def backward(self, X, y, y_hat, lr=learning_rate):
        batch_size = y.size(0)
        y_hat1 = tnnfunc.one_hot(y_hat)
        y1 = tnnfunc.one_hot(y)

        if y1.shape[1] < 10:
            diff = 10 - y1.shape[1]
            add = torch.zeros(y1.shape[0], diff)
            y1 = torch.cat((y1, add), 1)

        if y_hat1.shape[1] < 10:
            diff = 10 - y_hat1.shape[1]
            add = torch.zeros(y_hat1.shape[0], diff)
            y_hat1 = torch.cat((y_hat1, add), 1)

        dl_dz2 = (1 / batch_size) * (y_hat1 - y1)
        dl_dh = torch.matmul(dl_dz2, torch.t(self.W2))
        dl_dz1 = dl_dh * sigmoidPrime(self.h)

        self.W1 -= lr * torch.matmul(torch.t(X), dl_dz1)
        self.b1 -= lr * torch.matmul(torch.t(dl_dz1), torch.ones(batch_size))
        self.W2 -= lr * torch.matmul(torch.t(self.h), dl_dz2)
        self.b2 -= lr * torch.matmul(torch.t(dl_dz2), torch.ones(batch_size))

    def train(self, X, y):
        # forward + backward pass for training
        o = self.forward(X)
        _, predicted = torch.max(o.data, 1)
        self.backward(X, y, predicted)
        return predicted

def to_var(x):
    return Variable(x)

# building the net
net = Neural_Network(input_size, num_classes, hidden_size)

correct_train = 0
total_train = 0
correct_test = 0
total_test = 0
epochs_plt = []
train_plt = []
test_plt = []
avg_test=[]
# training
for epoch in range(num_epochs):
    epochs_plt.append(epoch)

    for i, (images, labels) in enumerate(train_loader):
        images = to_var(images.view(-1, 28 * 28))
        labels = to_var(labels)
        predicted = net.train(images, labels)
        total_train += labels.size(0)
        correct_train += (predicted == labels).sum()
    #train_plt.append(correct_train / total_train)

    for i, (images, labels) in enumerate(test_loader):
        images = to_var(images.view(-1, 28 * 28))
        labels = to_var(labels)
        out = net.forward(images)
        _, predicted = torch.max(out.data, 1)
        total_test += labels.size(0)
        correct_test += (predicted == labels).sum()
    avg_test.append(correct_test / total_test)
    train_plt.append(correct_train / total_train)
    test_plt.append(correct_test / total_test)

torch.save(net, 'hw1_model.pkl')
"""avg = eval.evaluate_hw1()
print('avg=',avg)"""

#ploting the train and test graphs
plt.plot(epochs_plt,train_plt,color='blue', label='train set') #plt.plot(x,y)
plt.plot(epochs_plt,test_plt, color='red', label='test set')
plt.title('Accuracy As A Function Of Time (Epochs)')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.legend()
plt.show()


from matchups.models import Pick, Matchup
from matchups import model_utilities
from django import forms

class PickForm(forms.ModelForm):
    class Meta:
        model = Pick
        fields = {'selected_team'}
    def __init__(self, *args, **kwargs):
        super(PickForm, self).__init__(*args, **kwargs)
        widget_choices = [('','')]
        if self.instance:
            week_number = self.instance.week_number
            previously_selected_teams = Pick.objects.filter(pick_set=self.instance.pick_set).exclude(week_number=week_number).values_list('selected_team', flat=True)
            team_choices = model_utilities.get_list_of_choices_for_week(week_number)
            for team in team_choices:
                if team.id not in previously_selected_teams:
                    widget_choices.append((team.id, team.full_name()))
        self.fields['selected_team'].widget.choices = widget_choices
        pick_label = "Loser pick " + str(self.instance.pick_set.letter_id)
        self.fields['selected_team'].label = pick_label

class MatchupForm(forms.ModelForm):
    class Meta:
        model = Matchup
        fields = {'home_team_score', 'away_team_score'}


# -*- coding: utf-8 -*-
from v1.models.affiliate import affiliate_schema
from flask_expects_json import expects_json
from database import db
from flask import Blueprint, request, jsonify

versao = "/v1"

affiliate = Blueprint("affiliate",__name__)

@affiliate.route(versao + "/affiliates",methods=["POST"])
#@expects_json(affiliate_schema)
def create_affiliate():
    try:
        data = request.get_json()
        affiliate = db.collection("hasEntityFederationPersonKarateka").insert({"_from":"person/"+data["idKarateka"],"_to":"entity/"+data["idEntity"]})
        return jsonify(affiliate), 201
    except Exception as e:
        return jsonify({"Message":"Server Error"}), 500

@affiliate.route(versao + "/affiliates/entity/<string:id_entity>",methods=["GET"])
def list_karatekas(id_entity):
    try:
        karatekas = db.aql.execute("FOR v,e IN INBOUND @id hasEntityFederationPersonKarateka RETURN v",bind_vars={"id":"entity/"+id_entity}).batch()
        return jsonify(karatekas), 200
    except Exception as e:
        return jsonify({"Message":"Server Error"}), 500

@affiliate.route(versao + "/affiliates/karateka/<string:id_person>",methods=["GET"])
def list_entity(id_person):
    try:
        entity = db.aql.execute("FOR v,e IN OUTBOUND @id hasEntityFederationPersonKarateka RETURN v",bind_vars={"id":"person/"+id_person}).batch()
        return jsonify(entity[0]), 200
    except Exception as e:
        return jsonify({"Message":"Server Error"}), 500

@affiliate.route(versao + "/affiliates/entity/<string:id_entity>/karateka/<string:id_person>",methods=["DELETE"])
def delete_entity_karateka(id_entity,id_person):
    try:
        db.aql.execute("FOR v,e IN OUTBOUND @id hasEntityFederationPersonKarateka FILTER v._key == @idEntity REMOVE e._key IN hasEntityFederationPersonKarateka",bind_vars={"id":"person/"+id_person,"idEntity":id_entity})
        return jsonify({"Message":"Affiliation removed successfully"}), 200
    except Exception as e:
        return jsonify({"Message":"Server Error"}), 500