# -*- coding: utf-8 -*-
"""
Created on Tue Aug 23 10:27:58 2016
Función para calcular el caudal que debe circular por el lazo dadas unas condiciones meteo

@author: miguel
"""
import time
import numpy as np
from EQSolares import IAM_calc
from iapws import IAPWS97
from solatom_param import solatom_param
from iteration_process import IT_flow
from iteration_process import IT_temp
from iteration_process import flow_calc

#INPUTS ----------------------------------------------------

#Inputs de meteo obtenidos por scrapping
DNI=800 #W/m2
temp_amb=24 #C

#Inputs de TABLAS!!!

    #LLAMADA A TABLA de parametros de simulacion !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
DNI_min=100 #W/m2 valor mínimo para empezar a operar, ya sea en recirculación o producción
coef_flow_rec=2 #Coef por el que se multiplica el caudal de min para obtener el caudal de recirculación
    #LLAMADA A TABLA de usuario !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # Process Design parameters
T_in_C=120 #In C
T_out_C=160 #In C
P_op_bar=20 #In bar

    ## Fecha y hora actual obtenidos del reloj del orenador
year=int(time.strftime("%Y"))
month=int(time.strftime("%m"))
day=int(time.strftime("%d"))
current_hour=int(time.strftime("%H"))

id_year=int(time.strftime("%j")) #dia del año, identificador de la fila para consultas en la tabla

    #LLAMADA A TABLA de valores anuales de posicion solar !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #Con el id_year obtengo de la tabla
theta_i_rad=0.0943588651234
theta_transv_rad=0.718427638896

    #LLAMADA A TABLA de parametros del colector !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
type_coll=20
IAM_file="Fabian.csv"
REC_type=1 #Tubo receptor Schott PTR70

    #LLAMADA A TABLA de simulación DESIGN
m_dot_min_kgs=.2 #kg/s valor obtenido de la simulación DESIGN
num_loops=1 #Numero de loops en el sistema
n_coll_loop=5 # numero de colectores por loop
# -----------------------------------------------------

#Preparación de variables
temp_amb_K=temp_amb+273 #Temp ambiente en Kelvin

#Cálculo del IAM long y transv
theta_i_deg=theta_i_rad*180/np.pi
theta_transv_deg=theta_transv_rad*180/np.pi

[IAM_long]=IAM_calc(theta_i_deg,0,IAM_file) #Longitudinal
[IAM_t]=IAM_calc(theta_transv_deg,1,IAM_file) #Transversal
IAM=IAM_long*IAM_t

if DNI<=DNI_min:
    pass #No tenemos suficiente radiación
else: #Tenemos suficiente radiación

    #Primero calculo del caudal que circula para satisfacer la temp de salida de diseño
    T_in_K=T_in_C+273 # In K
    T_out_K=T_out_C+273 # In K
    P_op_Mpa=P_op_bar/10 #In Mpa

    inlet=IAPWS97(P=P_op_Mpa, T=T_in_K)
    h_in_kJkg=inlet.h

    T_av_K=(T_in_K+T_out_K)/2
    average=IAPWS97(P=P_op_Mpa, T=T_av_K)
    h_av_kJkg=average.h
    Cp_av_KJkgK=average.cp #kJ/kgK

    [D,Area_coll,rho_optic_0,huella_coll,Long]=solatom_param(type_coll)
    Area=Area_coll*n_coll_loop

    [flow_rate_kgs]=flow_calc (T_out_K,T_in_K,P_op_Mpa,temp_amb_K,REC_type,theta_i_rad,DNI,Long,IAM,Area,n_coll_loop)

    #[flow_rate_kgs,T_outlet_K]=IT_flow(T_out_K,T_in_K,P_op_Mpa,temp_amb_K,REC_type,theta_i_rad,DNI,Long,IAM,Area,n_coll_loop)

    if flow_rate_kgs<=m_dot_min_kgs and T_out_K>T_in_K: #El caudal necesario para obtener la temp de salida es inferior al mínimo
        #RECIRCULACION
        flow_rate_rec=coef_flow_rec*m_dot_min_kgs
        [T_outlet_K]=IT_temp(T_in_K,P_op_Mpa,temp_amb_K,REC_type,theta_i_rad,DNI,Long,IAM,Area,n_coll_loop,flow_rate_rec)
        Q_prod=0 #No hay produccion

    else: #El caudal es suficientemente elevado para tener producción
        outlet=IAPWS97(P=P_op_Mpa, T=T_out_K)
        h_out_kJkg=outlet.h
        Q_prod=flow_rate_kgs*(h_out_kJkg-h_in_kJkg) #In kW
        bypass=0 #Significa que he producido


# CMSC 21800
# Assignment 4 - Data Integration
# Firat Ciftci (firatciftci)

from core import *
import datetime

JACCARD_THRESHOLD = 0.50

def tokenize(st):
    '''
    Takes in a string, converts all characters to lowercase, and tokenizes
    by splitting each individual word

    Returns a new set of tokenized string
    '''
    return set(st.lower().split())

def jaccard(a, b):
    '''
    Given two strings, computes the Jaccard similarity score between them

    Returns the Jaccard similarity score
    '''
    Ta = tokenize(a)
    Tb = tokenize(b)

    return len(Ta.intersection(Tb)) / len(Ta.union(Tb))

def match():
    '''
    Match must return a list of tuples of amazon ids and google ids.
    For example:
    [('b000jz4hqo', http://www.google.com/base/feeds/snippets/11125907881740407428'),....]

    '''
    matches = []
    amazon = amazon_catalog()
    google = google_catalog()

    for i in amazon:
        for j in google:
            if jaccard(i['title'], j['title']) >= JACCARD_THRESHOLD:
                matches.append((i['id'], j['id']))

    return matches

# prints out the accuracy
now = datetime.datetime.now()
out = eval_matching(match())
timing = (datetime.datetime.now() - now).total_seconds()
print("----Accuracy----")
print(out)
print("---- Timing ----")
print(timing, "seconds")


# encoding:utf-8

import xmlrpclib
from database import DB
from time import sleep

'''
绑定表价签与商品表内的商品一一绑定
'''
server = xmlrpclib.ServerProxy("http://127.0.0.1:9000")
db = DB()
cmd = 'select eslid from esl_list'
db.cursor.execute(cmd)
all_esl = db.cursor.fetchall()

cmd1 = 'select salesno from sales_list'
db.cursor.execute(cmd1)
all_sales = db.cursor.fetchall()

esl_list = []
for eslid in all_esl:
	eslid = eslid[0]
	esl_list.append(eslid)

salesno_list = []
for salesno in all_sales:
	salesno = salesno[0]
	salesno_list.append(salesno)

bind_all_list = []
for i in range(0, len(salesno_list)-1):
	bind_all_list.append({'apid': '1', 'salesno': '%s' % salesno_list[i], 'eslid': '%s' % esl_list[i]})

server.send_cmd("BIND", bind_all_list)


import pandas as pd
from flask import request
from flask_restplus import Namespace, fields, Resource, reqparse
from datetime import datetime
import jwt

import os
import sys

from markupsafe import escape

sys.path.append("..")

from lib.db_help import dbHelper

# 아이템 파라미터 정보
Work = Namespace('work', description='구직 신규 등록 / 구직 검색(단일)')

# 아이템 단일 검색 API
@Work.route('/<work_seq>')
@Work.response(200, 'OK')
@Work.response(500, 'Internal Error')
class Single_Work(Resource):
    # @Work.expect(work_model)
    def get(self, work_seq):
        try:
            db = dbHelper()

            sql = "SELECT * FROM work a, work_type b, company c WHERE c.company_seq = a.company_seq AND a.work_type_seq = b.work_type_seq AND a.work_seq = %s";

            db.cursor.execute(sql, work_seq)
            result = db.cursor.fetchone()

            data = {
                "work_seq": result['work_seq'], "work_type_nm": result['work_type_nm'], "company_seq": result['company_seq'], "company_nm": result['company_nm'],
                "work_title": result['work_title'], "work_intro": result['work_intro'], "work_img": result['work_img'], "work_startAt": str(result['work_startAt']),
                "work_endAt": str(result['work_endAt']), "work_recruit": result['work_recruit'], "work_pay": result['work_pay'], "work_deposit_yn": result['work_deposit_yn'],
                "isDeleted": result['isDeleted']
            }
        except Exception as e:
            return {"code": "err", "message": str(e)}

        return {"code": "success", "data": data}

# 등록 파라미터 정보
Apply = Namespace('apply', description='구직 신규 신청')
apply_work_model = Apply.model('apply work data', {
    'user_seq': fields.Integer,
    'work_seq': fields.Integer,
    'volunteer_content': fields.String,
})

# 아이템 신청 API
@Apply.route('/apply')
@Apply.response(200, 'OK')
@Apply.response(500, 'Internal Error')
@Apply.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
class Apply_Work(Resource):
    @Apply.expect(apply_work_model)
    def post(self):
        try:
            db = dbHelper()

            # Authorization 헤더로 담음
            header = request.headers.get('Authorization')

            if header is None:
                return {"code": "err", "message": "Not Allow Authorization"}

            try:
                data = jwt.decode(header, "secret", algorithms=["HS256"])
            except Exception as e:
                return {"code": "err", "message": "Token Expired"}

            parser = reqparse.RequestParser()
            parser.add_argument('user_seq', type=int)
            parser.add_argument('work_seq', type=int)
            parser.add_argument('volunteer_content', type=str)
            args = parser.parse_args()

            # sql = "SELECT * FROM volunteer where user_seq = %s AND work_seq = %s AND volunteer_yn = %s"
            # db.cursor.execute(sql, (args['user_seq'], args['work_seq'], 'Y'))
            # result = db.cursor.fetchall()
            #
            # if result is not None:
            #     return {"code": "err", "message": "Already have an apply"}

            sql = "INSERT into volunteer(user_seq, work_seq, volunteer_content, volunteer_yn) VALUES (%s, %s, %s, %s)"
            db.cursor.execute(sql, (args['user_seq'], args['work_seq'], args['volunteer_content'], 'Y'))

            # sql = "UPDATE work SET work_recruit = work_recruit - 1 WHERE work_seq = %s"
            # db.cursor.execute(sql, args['work_seq'])
            db.conn.commit()

        except Exception as e:
            return {"code": "err", "message": str(e)}

        return {"code": "success"}

# 취소 파라미터 정보
Cancel = Namespace('cancel', description='구직 신청 취소')

cancle_work_model = Apply.model('cancle work data', {
    'user_seq': fields.Integer,
})

# 아이템 취소 API
@Cancel.route('/cancel/<work_seq>')
@Cancel.response(200, 'OK')
@Cancel.response(500, 'Internal Error')
@Cancel.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
class Cancel_Work(Resource):
    @Apply.expect(cancle_work_model)
    def put(self, work_seq):
        try:
            db = dbHelper()

            # Authorization 헤더로 담음
            header = request.headers.get('Authorization')

            if header is None:
                return {"code": "err", "message": "Not Allow Authorization"}

            try:
                data = jwt.decode(header, "secret", algorithms=["HS256"])
            except Exception as e:
                return {"code": "err", "message": "Token Expired"}

            parser = reqparse.RequestParser()
            parser.add_argument('user_seq', type=int)
            args = parser.parse_args()

            sql = "UPDATE volunteer SET volunteer_yn = %s isDeleted = %s WHERE work_seq = %s AND user_seq = %s AND volunteer_yn = 'Y'"
            db.cursor.execute(sql, ('N', work_seq, args['user_seq'], 'Y'))

            # sql = "UPDATE work SET work_recruit = work_recruit + 1 WHERE work_seq = %s"
            # db.cursor.execute(sql, work_seq)
            db.conn.commit()

        except Exception as e:
            return {"code": "err", "message": str(e)}

        return {"code": "success"}

# 일자리 신규 등록 파라미터
# Work = Namespace('work', description='일자리 신규 등록')

post_work_model = Apply.model('post work data', {
    'work_type_seq': fields.Integer,
    'company_seq': fields.Integer,
    'work_title': fields.String,
    'work_startAt': fields.String,
    'work_endAt': fields.String,
    'work_recruit': fields.Integer,
    'work_pay': fields.Integer,
    'work_intro': fields.String,
})

# 일자리 신규 등록 API
@Work.route('/')
@Work.response(200, 'OK')
@Work.response(500, 'Internal Error')
@Work.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
class Apply_Work(Resource):
    @Apply.expect(post_work_model)
    def post(self):
        try:
            db = dbHelper()

            # Authorization 헤더로 담음
            header = request.headers.get('Authorization')

            if header is None:
                return {"code": "err", "message": "Not Allow Authorization"}

            try:
                data = jwt.decode(header, "secret", algorithms=["HS256"])
            except Exception as e:
                return {"code": "err", "message": "Token Expired"}

            parser = reqparse.RequestParser()
            parser.add_argument('work_type_seq', type=int)
            parser.add_argument('company_seq', type=int)
            parser.add_argument('work_title', type=str)
            parser.add_argument('work_startAt', type=str)
            parser.add_argument('work_endAt', type=str)
            parser.add_argument('work_recruit', type=int)
            parser.add_argument('work_pay', type=int)
            parser.add_argument('work_intro', type=str)

            args = parser.parse_args()

            sql = "INSERT into work(work_type_seq, company_seq, work_title, work_recruit, work_pay, work_intro, work_startAt, work_endAt) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"

            db.cursor.execute(sql, (args['work_type_seq'], args['company_seq'], args['work_title'], args['work_recruit'], args['work_pay'], args['work_intro'], args['work_startAt'], args['work_endAt']))
            db.conn.commit()
        except Exception as e:
            return {"code": "err", "message": str(e)}

        return {"code": "success"}


# from _typeshed import Self
# from decimal import Decimal
class BankAccount:

    bank_name = "First National Bank "
    all_accounts = []

    def __init__(self, int_rate=0.01, balance=0):
        self.int_rate = int_rate
        self.balance = balance
        BankAccount.all_accounts.append(self)

    def deposit(self, amount):
        self.balance += amount
        return self

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            self.balance = self.balance - 5
            print("Insufficinet funds")
        return self

    def display_account_info(self):
        print("Balance: {self.balance}")
        return self

    def yield_interest(self):
        if self.balance > 0:
           self.balance += (self.balance * self.int_rate)
        return self
# ---------------------->
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.account = BankAccount(int_rate=0.02, balance=0)

    def make_deposit(self, amount):
        self.account.balance += amount
        return self

    def make_withdrawl(self, amount):
        if amount <= self.account.balance:
            self.account.balance -= amount
        else:
            return "Insuffiecient funds"
        return self

    def display_user_balance(self):
        print("User: {self.name}, Balance: ${self.account.balance}")
        return self

    def transfer_money(self, User, amount):
        if amount <= self.account.balance:
            User.account.balance += amount
            self.account.balance -= amount
        else:
            return "insufficinet funds"
        return self

    def example_method(self):
        paul.account.deposit(100)
        print(self.account.balance)

paul = User("friya", "friya@gmail.com")
dan  = User("daniel", "daniel@gmail.com")
phil = User("diya", "diya3@gmail.com")

print(paul.name, paul.email)
print(dan.name, dan.email)
print(phil.name, phil.email)

paul.make_deposit(100)
paul.make_withdrawl(45)
print(paul.account.balance)
paul.display_user_balance()

paul.make_deposit(100).make_deposit(347).make_deposit(289).make_withdrawl(450).display_user_balance()
dan.make_deposit(1000).make_deposit(543).make_withdrawl(3).display_user_balance()
phil.make_deposit(10000).make_withdrawl(2800).make_withdrawl(4000).make_withdrawl(347).display_user_balance()

paul.transfer_money(dan, 25)
paul.display_user_balance()
phil.display_user_balance()


# -*- coding: utf-8 -*-
###############################################################################
#
# filetypes.py
#
# class FileTypes
#
###############################################################################
from enum import Enum
import json
import xml.dom.minidom as minidom

from .common import get_text
from .config import FILETYPESPATH
from .fileutil import FileUtil
from .searchexception import SearchException

class FileType(Enum):
    """FileType enum"""
    UNKNOWN = 0
    ARCHIVE = 1
    BINARY = 2
    CODE = 3
    TEXT = 4
    XML = 5

    @classmethod
    def from_name(cls, name):
        uname = name.upper()
        try:
            return FileType[uname]
        except KeyError:
            raise SearchException('Invalid file type: {0!s}\n'.format(name))

class FileTypes(object):
    """a class to provide file type information"""

    __slots__ = ['_filetypes']

    def __init__(self):
        self._filetypes = {}
        self._populate_filetypes_from_json()

    def get_filetype(self, filename: str) -> FileType:
        if self.is_text_file(filename):
            return FileType.TEXT
        if self.is_binary_file(filename):
            return FileType.BINARY
        if self.is_archive_file(filename):
            return FileType.ARCHIVE
        if self.is_code_file(filename):
            return FileType.CODE
        if self.is_xml_file(filename):
            return FileType.XML
        return FileType.UNKNOWN

    def is_archive_file(self, f: str) -> bool:
        """Return true if file is of a (known) archive file type"""
        return FileUtil.get_extension(f) in self._filetypes['archive']

    def is_binary_file(self, f: str) -> bool:
        """Return true if file is of a (known) searchable binary file type"""
        return FileUtil.get_extension(f) in self._filetypes['binary']

    def is_code_file(self, f: str) -> bool:
        """Return true if file is of a (known) code file type"""
        return FileUtil.get_extension(f) in self._filetypes['code']

    def is_searchable_file(self, f: str) -> bool:
        """Return true if file is of a (known) searchable type"""
        return FileUtil.get_extension(f) in self._filetypes['searchable']

    def is_text_file(self, f: str) -> bool:
        """Return true if file is of a (known) text file type"""
        return FileUtil.get_extension(f) in self._filetypes['text']

    def is_xml_file(self, f: str) -> bool:
        """Return true if file is of a (known) xml file type"""
        return FileUtil.get_extension(f) in self._filetypes['xml']

    def _populate_filetypes_from_json(self):
        with open(FILETYPESPATH, mode='r') as f:
            filetypes_dict = json.load(f)
        for filetype_obj in filetypes_dict['filetypes']:
            typename = filetype_obj['type']
            exts = set(filetype_obj['extensions'])
            self._filetypes[typename] = exts
        self._filetypes['text'].update(self._filetypes['code'],
                                       self._filetypes['xml'])
        self._filetypes['searchable'] = \
            self._filetypes['binary'].union(self._filetypes['archive'],
                                           self._filetypes['text'])

    def _populate_filetypes_from_xml(self):
        filetypedom = minidom.parse(FILETYPESPATH)
        filetypenodes = filetypedom.getElementsByTagName('filetype')
        for filetypenode in filetypenodes:
            name = filetypenode.getAttribute('name')
            extnode = filetypenode.getElementsByTagName('extensions')[0]
            exts = set(get_text(extnode.childNodes).split())
            self._filetypes[name] = exts
        self._filetypes['text'].update(self._filetypes['code'],
                                       self._filetypes['xml'])
        self._filetypes['searchable'] = \
            self._filetypes['binary'].union(self._filetypes['archive'],
                                           self._filetypes['text'])


import numpy as np

from astropy.modeling import models
from specreduce.utils.synth_data import make_2dspec_image
from specreduce.tracing import Trace, FlatTrace, ArrayTrace, KosmosTrace

IM = make_2dspec_image()

# test basic trace class
def test_basic_trace():
    t_pos = IM.shape[0] / 2
    t = Trace(IM)

    assert(t[0] == t_pos)
    assert(t[0] == t[-1])
    assert(t.shape[0] == IM.shape[1])

    t.shift(100)
    assert(t[0] == 600.)

    t.shift(-1000)
    assert(np.ma.is_masked(t[0]))

# test flat traces
def test_flat_trace():
    t = FlatTrace(IM, 550.)

    assert(t.trace_pos == 550)
    assert(t[0] == 550.)
    assert(t[0] == t[-1])

    t.set_position(400.)
    assert(t[0] == 400.)

    t.set_position(-100)
    assert(np.ma.is_masked(t[0]))

# test array traces
def test_array_trace():
    arr = np.ones_like(IM[0]) * 550.
    t = ArrayTrace(IM, arr)

    assert(t[0] == 550.)
    assert(t[0] == t[-1])

    t.shift(100)
    assert(t[0] == 650.)

    t.shift(-1000)
    assert(np.ma.is_masked(t[0]))

    arr_long = np.ones(5000) * 550.
    t_long = ArrayTrace(IM, arr_long)

    assert(t_long.shape[0] == IM.shape[1])

    arr_short = np.ones(50) * 550.
    t_short = ArrayTrace(IM, arr_short)

    assert(t_short[0] == 550.)
    assert(np.ma.is_masked(t_short[-1]))
    assert(t_short.shape[0] == IM.shape[1])

# test KOSMOS trace algorithm
def test_kosmos_trace():
    # create image (process adapted from compare_extractions.ipynb)
    np.random.seed(7)
    nrows = 200
    ncols = 160
    sigma_pix = 4
    sigma_noise = 1

    col_model = models.Gaussian1D(amplitude=1, mean=nrows/2, stddev=sigma_pix)
    noise = np.random.normal(scale=sigma_noise, size=(nrows, ncols))

    index_arr = np.tile(np.arange(nrows), (ncols, 1))
    img = col_model(index_arr.T) + noise

    # calculate trace on normal image
    t = KosmosTrace(img)

    # test shifting
    shift_up = int(-img.shape[0]/4)
    t_shift_up = t.trace + shift_up

    shift_out = img.shape[0]

    t.shift(shift_up)
    assert np.sum(t.trace == t_shift_up) == t.trace.size, 'valid shift failed'

    t.shift(shift_out)
    assert t.trace.mask.all(), 'invalid values not masked'

    # create same-shaped variations of image with invalid values
    img_all_nans = np.tile(np.nan, (nrows, ncols))

    window = 10
    guess = int(nrows/2)
    img_win_nans = img.copy()
    img_win_nans[guess - window:guess + window] = np.nan

    # error on trace of otherwise valid image with all-nan window around guess
    try:
        KosmosTrace(img_win_nans, guess=guess, window=window)
    except ValueError as e:
        print(f"All-NaN window error message: {e}")
    else:
        raise RuntimeError('Trace was erroneously calculated on all-NaN window')

    # error on trace of all-nan image
    try:
        KosmosTrace(img_all_nans)
    except ValueError as e:
        print(f"All-NaN image error message: {e}")
    else:
        raise RuntimeError('Trace was erroneously calculated on all-NaN image')

    # could try to catch warning thrown for all-nan bins


#!/usr/bin/python3
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory
from pathlib import Path
from tqdm import tqdm
import os
import sys
import math

def index(hashs, lists):
    for i in lists:
        if i in hashs:
            hashs[i] += 1
        else:
            hashs[i] = 1

# stopword dalam bahasa indonesian
get_stopword = StopWordRemoverFactory()
stopwords = get_stopword.create_stop_word_remover()

# stemming dalam bahasa indonesian
get_stemmer = StemmerFactory()
stemmer = get_stemmer.create_stemmer()

# hash
tf, df, idf, kalimatUtama, judul = dict(), dict(), dict(), dict(), dict()

if os.path.exists('../data/clean'):
    print(f'Directory : ../data/clean')
    for f in tqdm(Path('../data/clean').glob("*.txt")):
        name = str(f).split('/')
        df[name[3]], kalimatUtama[name[3]], judul[name[3]] = dict(), dict(), dict()

        File = open(f, 'r').read()
        File = stopwords.remove(File)

        sentence = File.split('\n')
        title = stemmer.stem(sentence[0].lower()).split()
        main = stemmer.stem(sentence[1].lower()).split()
        hasil = stemmer.stem(File.lower()).split()

        index(judul[name[3]], title)
        index(kalimatUtama[name[3]], main)
        index(tf, hasil)
        index(df[name[3]], hasil)
else:
    print("Wrong directory path")
    sys.exit(1)

print(f'unique words : {len(tf)}\n')

with open('../data/index/index.txt', 'w') as file:
    for term, freq in tqdm(tf.items()):
        idf[term] = 1 + math.log10(len(df)/tf[term])
        file.write(f"{term}")
        for doc, tfdoc in df.items():
            if term in tfdoc:
                if term in judul[doc]:
                    weigth = (tfdoc[term] * idf[term])*1
                elif term in kalimatUtama[doc]:
                    weigth = (tfdoc[term] * idf[term])*2/3
                else:
                    weigth = (tfdoc[term] * idf[term])*1/3
            else:
                file.write(f' {doc}:0')
                continue
            file.write(f' {doc}:{weigth}')
        file.write('\n')
print('done')


import click
from groundcontrol.scheduler import Scheduler
from groundcontrol.server import app
from groundcontrol.deployment import Deployment
from groundcontrol.models import set_aws_host
from groundcontrol.models import set_aws_region
import logging
import logging.config
import yaml

@click.group()
def cli():
    pass

@cli.command()
@click.option('--debug', help='Run the server in debug mode', default=False, is_flag=True)
@click.option('--aws-region', help='aws region', envvar='AWS_DEFAULT_REGION', default='eu-west-1')
@click.option('--dynamodb-host', help='dynamodb host', envvar='DYNAMODB_HOST', default=None)
@click.option('-v', '--verbosity', help='verbosity', default='CRITICAL')
@click.option('--log-config', envvar='GC_LOG_CONFIG', help='python yaml config file', default=None)
@click.option('--flyby-endpoint', envvar='GC_FLYBY_ENDPOINT', help='Fully qualified FlyBy endpoint', default=None)
def server(debug, aws_region, dynamodb_host, verbosity, log_config, flyby_endpoint):
    logging.getLogger().setLevel(level=getattr(logging, verbosity))
    if log_config:
        with open(log_config, 'r') as conf:
            logging.config.dictConfig(yaml.load(conf))
    set_aws_host(dynamodb_host)
    set_aws_region(aws_region)
    Deployment.create_tables()
    scheduler = Scheduler(region_name=aws_region, flyby_endpoint=flyby_endpoint)
    try:
        scheduler.start()
        app.run(host='0.0.0.0', debug=debug)
    except (KeyboardInterrupt, SystemExit):
        scheduler.stop()
        raise


import argparse
import os
import settings

parser = argparse.ArgumentParser(description='Classification')

##################################################
# Env
##################################################
parser.add_argument('--gpu_id', type=str, default='0')
parser.add_argument('--num_workers', type=int, default=4)

##################################################
# Data
##################################################
parser.add_argument('--train_dset_path', type=str, default='C:\\Users\\9live\\hm_code\\open_code')
parser.add_argument('--val_dset_path', type=str, default='C:\\Users\\9live\\hm_code\\open_code')
#parser.add_argument('--test_dset_path', type=str, default='C:\\Users\\9live\\hm_code\\open_code')

parser.add_argument('--train_batchsize', type=int, default=32)
parser.add_argument('--val_batchsize', type=int, default=32)
#parser.add_argument('--test_batchsize', type=int, default=4)

parser.add_argument('--imshow', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--cv_imshow', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes'])) #parser.add_argument('--cv_imshow', type=bool, default=False) --> false 인식 못함
parser.add_argument('--matplot_imshow', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))

##################################################
# Data Info
##################################################
#parser.add_argument('--class_num', type=int, default=10)

##################################################
# Data Pre-process from torch (torch에 있는 표현)
##################################################

#### Normalize
#parser.add_argument('--Normalize', type=bool, default=True)
parser.add_argument('--Normalize', default=True, type=lambda x: (str(x).lower() in ['true','1', 'yes']))

parser.add_argument('--Normalize_mean', type=float, default=[0.485, 0.456, 0.406] , help='ImageNet mean')
parser.add_argument('--Normalize_std', type=float, default=[0.229, 0.224, 0.225] , help='ImageNet std')

#### RandomResizedCrop
parser.add_argument('--RandomResizedCrop_train', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--RandomResizedCrop_size_train',type=int, default=256)

parser.add_argument('--RandomResizedCrop_val', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--RandomResizedCrop_size_val',type=int, default=256)

#### Centercrop

parser.add_argument('--CenterCrop_train', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--CenterCrop_size_train',type=int, default=224)

parser.add_argument('--CenterCrop_val', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--CenterCrop_size_val',type=int, default=224)

#### Resize
parser.add_argument('--Resize_train', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--Resize_size_train',type=int, default=224)

parser.add_argument('--Resize_val', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']))
parser.add_argument('--Resize_size_val',type=int, default=256)

'''
##################################################
# Network
##################################################
parser.add_argument('--net', type=str, default='resnet50', choices=['resnet50'])

##################################################
# Output
##################################################
parser.add_argument('--test_interval', type=int, default=500)
parser.add_argument('--output_dir', type=str, default='output')

##################################################
# Train
##################################################
parser.add_argument('--lr', type=float, default=0.001)

parser.add_argument('--num_iterations', type=int, default=10000)

parser.add_argument('--optimizer', type=str, default='SGD', choices=['SGD'])

"""LR 스케쥴러, optimizer에 대해서 더 업데이트 하기"""
'''
########################################################################################
'''
args = parser.parse_args()

os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_id

config={}
config['gpu_id'] = args.gpu_id
config['num_workers'] = args.num_workers

#config['data']={}
config['train_dset_path']=args.train_dset_path
config['val_dset_path']=args.val_dset_path
# config['test_dset_path']=args.test_dset_path
#
config['train_batchsize']=args.train_batchsize
config['val_batchsize']=args.val_batchsize
# config['test_batchsize']=args.test_batchsize
#
# config['class_num']=args.class_num

config['imshow']=args.imshow
config['cv_imshow']=args.cv_imshow
config['matplot_imshow']=args.matplot_imshow
####################################
# Pre-process
####################################

config['Normalize'] = args.Normalize
config['Normalize_mean'] = args.Normalize_mean
config['Normalize_std'] = args.Normalize_std

config['RandomResizedCrop_train']=args.RandomResizedCrop_train
config['RandomResizedCrop_size_train']=args.RandomResizedCrop_size_train

config['RandomResizedCrop_val']=args.RandomResizedCrop_train
config['RandomResizedCrop_size_val']=args.RandomResizedCrop_size_train

config['CenterCrop_train'] = args.CenterCrop_train
config['CenterCrop_size_train'] = args.CenterCrop_size_train

config['CenterCrop_val'] = args.CenterCrop_val
config['CenterCrop_size_val'] = args.CenterCrop_size_val

config['Resize_train']=args.Resize_train
config['Resize_size_train']=args.Resize_size_train

config['Resize_val']=args.Resize_val
config['Resize_size_val']=args.Resize_size_val

# config['Colorjitter'] = args.Colorjitter
# config['Colorjitter_brightness'] = args.brightness
# config['Colorjitter_contrast'] = args.contrast
# config['Colorjitter_saturation'] = args.saturation
# config['Colorjitter_hue'] = args.hue

# config['num_iterations'] = args.num_iterations
# config['test_interval'] = args.test_interval
# config['output_path'] = args.output_dir
# if not os.path.exists(config["output_path"]):
#     os.mkdir(config["output_path"])
#
# config['out_file'] = open(os.path.join(config['output_path'], 'log.txt'), 'w')
# if not os.path.exists(config["output_path"]):
#     os.mkdir(config["output_path"])
#
# config['optimizer'] = {}
# config['optimizer']['type']=args.optimizer
# #config['optimizer']['optim_params']=
#
#
# config['lr']=args.lr
#
# config['network']=args.net

#config['out_file'].write(str(config))
#config['out_file'].flush()
'''
#########################################################################################################

os.environ["CUDA_VISIBLE_DEVICES"] = settings.gpu_id

config={}
config['gpu_id'] = settings.gpu_id
config['num_workers'] = settings.num_workers

#config['data']={}
config['train_dset_path']=settings.train_dset_path
config['val_dset_path']=settings.val_dset_path
# config['test_dset_path']=asettings.test_dset_path
#
config['train_batchsize']=settings.train_batchsize
config['val_batchsize']=settings.val_batchsize
# config['test_batchsize']=settings.test_batchsize
#
# config['class_num']=settings.class_num

config['imshow']=settings.imshow
config['cv_imshow']=settings.cv_imshow
config['matplot_imshow']=settings.matplot_imshow
####################################
# Pre-process
####################################

config['Normalize'] = settings.Normalize
config['Normalize_mean'] = settings.Normalize_mean
config['Normalize_std'] = settings.Normalize_std

config['RandomResizedCrop_train']=settings.RandomResizedCrop_train
config['RandomResizedCrop_size_train']=settings.RandomResizedCrop_size_train

config['RandomResizedCrop_val']=settings.RandomResizedCrop_train
config['RandomResizedCrop_size_val']=settings.RandomResizedCrop_size_train

config['CenterCrop_train'] = settings.CenterCrop_train
config['CenterCrop_size_train'] = settings.CenterCrop_size_train

config['CenterCrop_val'] = settings.CenterCrop_val
config['CenterCrop_size_val'] = settings.CenterCrop_size_val

config['Resize_train']=settings.Resize_train
config['Resize_size_train']=settings.Resize_size_train

config['Resize_val']=settings.Resize_val
config['Resize_size_val']=settings.Resize_size_val

# config['Colorjitter'] = settings.Colorjitter
# config['Colorjitter_brightness'] = settings.brightness
# config['Colorjitter_contrast'] = settings.contrast
# config['Colorjitter_saturation'] = settings.saturation
# config['Colorjitter_hue'] = settings.hue

'''
config['num_iterations'] = settings.num_iterations
config['test_interval'] = settings.test_interval
config['output_path'] = settings.output_dir
if not os.path.exists(config["output_path"]):
    os.mkdir(config["output_path"])

config['out_file'] = open(os.path.join(config['output_path'], 'log.txt'), 'w')
if not os.path.exists(config["output_path"]):
    os.mkdir(config["output_path"])

config['optimizer'] = {}
config['optimizer']['type']=settings.optimizer
#config['optimizer']['optim_params']=

config['lr']=settings.lr

config['network']=settings.net
'''
#config['out_file'].write(str(config))
#config['out_file'].flush()


import graphviz as gv

def create_image(graph, filename):
    """
    Создаёт граф в формате graphviz и отрисовывает его
    сполученное изображение хранится в img/graph.svg
    :type graph: object
    :param graph:
    :return:
    """
    g = gv.Digraph(format='svg')
    for vertex in graph.dictionary:
        for connection in graph.dictionary[vertex]:
            g.node(connection)
            g.node(vertex)
    for vertex in graph.dictionary:
        for connection in graph.dictionary[vertex]:
            g.edge(vertex, connection)
    g.render("./img/"+filename)

def render_path(graph, path, filename):
    """
    Отрисовывает граф, отмечая посещённые вершины и рёбра
    :type graph: object
    """
    g = gv.Digraph(format='svg')
    edges = []
    for vertex_num, vertex in enumerate(path):
        if vertex_num < len(path)-1:
            edges.append([vertex, path[vertex_num+1]])
        else:
            break
    for vertex in graph.dictionary:
        for connection in graph.dictionary[vertex]:
            if connection in path:
                g.node(connection, color='red')
            if vertex in path:
                g.node(vertex, color='red')
            g.node(connection)
            g.node(vertex)
    for vertex in graph.dictionary:
        for connection in graph.dictionary[vertex]:
            if len(path) == 1 and vertex == connection:
                g.edge(vertex, connection, color='red', label='step 1')
                continue
            if [vertex, connection] in edges:
                g.edge(vertex, connection, color='red', label="step " + str(path.index(connection)) + "\n weight " + str(graph.dictionary[vertex][connection]))
            else:
                g.edge(vertex, connection)
    g.render("./img/"+filename)


# coding:utf-8
import time
import grpc
from concurrent import futures
from person_pb2 import ResponseResult
import person_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = '127.0.0.1'
_PORT = '9002'

class Person(person_pb2_grpc.PersonInterfaceServicer):
	def AddPerson(self, request, context):
		print(type(request))  # <class 'person_pb2.PersonInfo'>
		print(request)
		# age: 32
		# name: "kevin"
		# phone: "84039284"
		# email: "kevin@nuctech.com"

		print(context)

		return ResponseResult(result=request.age)

def serve():
	g_server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
	person_pb2_grpc.add_PersonInterfaceServicer_to_server(Person(), g_server)
	g_server.add_insecure_port(_HOST + ':' + _PORT)
	g_server.start()
	return g_server

if __name__ == "__main__":
	gc_server = serve()

	try:
		while True:
			time.sleep(_ONE_DAY_IN_SECONDS)
	except KeyboardInterrupt:
		gc_server.stop()


import os
import xlrd
import re
import pyperclip
import requests
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill
from pathlib import Path
from rich import print

def init():
    print('初始化中，请稍等...')
    version = 1.4
    print('此程序版本：' + str(version))
    try:
        urlgithub = 'https://raw.githubusercontent.com/evilbutcher/Python/master/evanescent/release.json'
        update = requests.get(urlgithub)
        ver = update.json()
        if ver['releases'][0]['version'] > version:
            print('[bold yellow]更新[/bold yellow]啦！从GitHub获取更新详情成功！\n最新版本是：' +
                  str(ver['releases'][0]['version']))
            print('更新内容是：' + ver['releases'][0]['details'])
            print('可前往：https://github.com/evilbutcher/Python 查看Releases\n')
        else:
            print('检测更新完成，暂无更新\n')
    except (Exception):
        urlgitee = 'https://gitee.com/evilbutcher/Python/raw/master/evanescent/release.json'
        try:
            update = requests.get(urlgitee)
            ver = update.json()
            if ver['releases'][0]['version'] > version:
                print('[bold red]更新[/bold red]啦！从Gitee获取更新详情成功！\n最新版本是：' +
                      str(ver['releases'][0]['version']))
                print('更新内容是：' + ver['releases'][0]['details'])
                print('可前往：https://github.com/evilbutcher/Python 查看Releases\n')
            else:
                print('检测更新完成，暂无更新\n')
        except Exception as e:
            print('检测更新失败，原因：')
            print(str(e) + '\n')
    try:
        path = Path('origindata/')
        if path.is_dir() is False:
            os.mkdir(path)
        a = pyperclip.paste()
        if a == 'debugturnon':
            return True
    except Exception as e:
        print('初始化[bold red]失败[/bold red]，原因：' + str(e))

def dealxlsx(path: str, name: str, canprint: bool):
    try:
        workbook = xlrd.open_workbook(path + '/' + name)
        sheet_name = workbook.sheet_names()[0]
        print('\n读取的Excel表名为：' + sheet_name)
        sheet = workbook.sheet_by_index(0)
        allrows = sheet.nrows
        allcols = sheet.ncols - 1
        print('一共有：' + str(allcols) + '列  ' + str(allrows) + '行（第一列时间未计入统计）')
        secend = input('请输入基准点（第几秒）：')
        valueforall = input('请输入一个基准值（自定即可）：')
        startpoint = int(secend)
        startvalue = sheet.cell(startpoint, 0).value
        print('所选取的修改起始点为：' + str(int(startvalue)) + '秒的数据')
        wb = Workbook()  # 引入result.xlsx工作表
        result = wb["Sheet"]
        if result.cell(1, 1).value is None:  # 因为两个库起始index不同，先设置一下第一行
            result.cell(1, 1).value = 0
            if canprint is True:
                print('\n1列1行 写入时间：0秒\n')
        for col in range(1, allcols + 1):  # 获取数据excel每列与基准值的差值
            minus = sheet.cell(startpoint, col).value - float(valueforall)
            print('第' + str(col) + '列截取的起始数据点为：' +
                  str(sheet.cell(startpoint, col).value))
            print('第' + str(col) + '列与基准值的差为：' + str(minus) + '\n')
            vcols = sheet.col_values(col)
            result.cell(1, col + 1).value = float(
                valueforall)  # 因为两个库起始index不同，先设置一下第一行
            if canprint is True:
                print(
                    str(col + 1) + '列1行' + '写入数据：' + str(float(valueforall)) +
                    '\n')
            for num in range(1, len(vcols)):  # 获取数据excel每行的数据，写入index+1的位置
                if result.cell(num + 1, 1).value is None:
                    result.cell(num + 1, 1).value = int(num)
                    if canprint is True:
                        print('1列' + str(num + 1) + '行 写入时间：' + str(int(num)) +
                              '秒' + '\n')
                if num > startpoint:
                    if canprint is True:
                        print(
                            str(col + 1) + '列' + str(num + 1) + '行' + '读取数据：' +
                            str(sheet.cell(num, col).value))
                    if isinstance(sheet.cell(num, col).value, float) is True:
                        result.cell(
                            num + 1,
                            col + 1).value = sheet.cell(num, col).value - minus
                    else:
                        print(
                            str(col) + '列' + str(num + 1) +
                            '行 读取数据[bold red]错误[/bold red]，请检查相应位置，此处选用上一个数值')
                        if isinstance(sheet.cell(num - 1, col).value,
                                      float) is True:
                            result.cell(num + 1, col + 1).value = sheet.cell(
                                num - 1, col).value - minus
                        else:
                            print(
                                str(col) + '列' + str(num + 1) +
                                '行 读取数据出现[bold red]连续错误[/bold red]，请检查数据完整性')
                            return
                    if canprint is True:
                        print(
                            str(col + 1) + '列' + str(num + 1) + '行' + '写入数据：' +
                            str(float(sheet.cell(num, col).value - minus)) +
                            '\n')
                else:
                    if canprint is True:
                        print(
                            str(col + 1) + '列' + str(num + 1) + '行' + '读取数据：' +
                            str(sheet.cell(num, col).value))
                    result.cell(num + 1, col + 1).value = float(valueforall)
                    if canprint is True:
                        print(
                            str(col + 1) + '列' + str(num + 1) + '行' + '写入数据：' +
                            str(float(valueforall)) + '\n')
        wb.save("result.xlsx")
        print('[bold green]数据处理完成[/bold green]')
    except Exception as e:
        print('处理excel[bold red]失败[/bold red]，原因：' + str(e))

def setcolor():
    wb = load_workbook(r'result.xlsx')
    sheetnames = wb.sheetnames
    ws = wb[sheetnames[0]]
    rows = ws.max_row
    columns = ws.max_column
    color = 'FF6666'
    fille = PatternFill('solid', fgColor=color)
    num = int(input('请输入本次实验的平行实验次数：'))
    waittocolor = []
    startnum = 1
    for m in range(0, num):
        startnum = startnum + 1
        waittocolor.append(startnum)
    for i in waittocolor:
        for k in range(i, columns + 1, num * 2):
            for j in range(1, rows + 1):
                ws.cell(j, k).fill = fille
    wb.save(r'result.xlsx')
    print('着色区分完成')

def main():
    try:
        canprint = False
        if init() is True:
            canprint = True
        name = input('请输入要处理的文件名')
        if re.search(r'xlsx|xls', name) is None:
            namewithsuffix4 = name + '.xlsx'
            path = Path('origindata/' + namewithsuffix4)
            if path.is_file() is True:
                dealxlsx('origindata/', namewithsuffix4, canprint)
            else:
                namewithsuffix3 = name + '.xls'
                path = Path('origindata/' + namewithsuffix3)
                if path.is_file() is True:
                    dealxlsx('origindata/', namewithsuffix3, canprint)
        else:
            dealxlsx('origindata/', name, canprint)
        exist = Path('result.xlsx')
        if exist.is_file() is True:
            setcolor()
        input('如有问题请前往 https://github.com/evilbutcher/Python 提出issue，请按任意键退出')
    except Exception as e:
        print('主函数运行[bold red]出现错误[/bold red]，原因：' + str(e))
        input('如有问题请前往 https://github.com/evilbutcher/Python 提出issue，请按任意键退出')

if __name__ == "__main__":
    main()


import numpy as np
import mabd_llcd_class_v1 as AmabdLLCD
import rss_editor_class as anRSSeditor
import matplotlib.pyplot as plt

####################
# Network parameters
numNodes = 8
numCh = 4

####################
# RSS data files
rss_data_f_name = 'data/rss_data/meb/rss_data_2015_10_19_all_2.txt'

####################
# RSS editors
fb_choice = 'fb'
ch_list = [0,1,2,3] # \in 0,1,2,...,C-1

node_list = np.arange(numNodes)+1 # \in 1,2,...,N
my_rss_editor_1 = anRSSeditor.RssEditor(numNodes, numCh, ch_list, node_list, fb_choice)

#################
# MABD parameters
stb_len = 5  # short term buffer length
ltb_len = 20 # long term buffer length
stateb_len = 12 # state buffer length
tau = 0.025   # threshold
num_consec = 2
out_type = 'a'

my_mabd = AmabdLLCD.myMABDClass(my_rss_editor_1, stb_len, ltb_len, stateb_len, tau, num_consec, out_type)

######################
# Loop through data
states_all = []
times_all = []

with open(rss_data_f_name, 'r') as f:
    for line in f:

        my_mabd.observe(line)
        states_all.append(my_mabd.get_state_est().tolist())
        times_all.append(my_mabd.get_time())

states_all = np.array(states_all)
times_all = np.array(times_all)
times_all = times_all - times_all[0]

plt.plot(times_all,states_all[:,0],'r-')
plt.plot(times_all,states_all[:,1],'k--')
plt.plot(times_all,states_all[:,2],'g-.')

# plt.plot(times_all,states_all[:,3],'r-')
# plt.plot(times_all,states_all[:,4],'k--')
# plt.plot(times_all,states_all[:,5],'g-.')
# plt.plot(times_all,states_all[:,6],'m-')
plt.ylim([0,1.5])
plt.grid()
plt.show()


# -*- coding: utf-8 -*-
# Copyright 2023 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
#
#     http://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.
#
from collections import OrderedDict
import functools
import re
from typing import (
    Dict,
    Mapping,
    MutableMapping,
    MutableSequence,
    Optional,
    Sequence,
    Tuple,
    Type,
    Union,
)

from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.api_core.client_options import ClientOptions
from google.auth import credentials as ga_credentials  # type: ignore
from google.oauth2 import service_account  # type: ignore

from google.cloud.talent_v4 import gapic_version as package_version

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.longrunning import operations_pb2
from google.protobuf import field_mask_pb2  # type: ignore

from google.cloud.talent_v4.services.company_service import pagers
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service

from .client import CompanyServiceClient
from .transports.base import DEFAULT_CLIENT_INFO, CompanyServiceTransport
from .transports.grpc_asyncio import CompanyServiceGrpcAsyncIOTransport

class CompanyServiceAsyncClient:
    """A service that handles company management, including CRUD and
    enumeration.
    """

    _client: CompanyServiceClient

    DEFAULT_ENDPOINT = CompanyServiceClient.DEFAULT_ENDPOINT
    DEFAULT_MTLS_ENDPOINT = CompanyServiceClient.DEFAULT_MTLS_ENDPOINT

    company_path = staticmethod(CompanyServiceClient.company_path)
    parse_company_path = staticmethod(CompanyServiceClient.parse_company_path)
    tenant_path = staticmethod(CompanyServiceClient.tenant_path)
    parse_tenant_path = staticmethod(CompanyServiceClient.parse_tenant_path)
    common_billing_account_path = staticmethod(
        CompanyServiceClient.common_billing_account_path
    )
    parse_common_billing_account_path = staticmethod(
        CompanyServiceClient.parse_common_billing_account_path
    )
    common_folder_path = staticmethod(CompanyServiceClient.common_folder_path)
    parse_common_folder_path = staticmethod(
        CompanyServiceClient.parse_common_folder_path
    )
    common_organization_path = staticmethod(
        CompanyServiceClient.common_organization_path
    )
    parse_common_organization_path = staticmethod(
        CompanyServiceClient.parse_common_organization_path
    )
    common_project_path = staticmethod(CompanyServiceClient.common_project_path)
    parse_common_project_path = staticmethod(
        CompanyServiceClient.parse_common_project_path
    )
    common_location_path = staticmethod(CompanyServiceClient.common_location_path)
    parse_common_location_path = staticmethod(
        CompanyServiceClient.parse_common_location_path
    )

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            CompanyServiceAsyncClient: The constructed client.
        """
        return CompanyServiceClient.from_service_account_info.__func__(CompanyServiceAsyncClient, info, *args, **kwargs)  # type: ignore

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            CompanyServiceAsyncClient: The constructed client.
        """
        return CompanyServiceClient.from_service_account_file.__func__(CompanyServiceAsyncClient, filename, *args, **kwargs)  # type: ignore

    from_service_account_json = from_service_account_file

    @classmethod
    def get_mtls_endpoint_and_cert_source(
        cls, client_options: Optional[ClientOptions] = None
    ):
        """Return the API endpoint and client cert source for mutual TLS.

        The client cert source is determined in the following order:
        (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
        client cert source is None.
        (2) if `client_options.client_cert_source` is provided, use the provided one; if the
        default client cert source exists, use the default one; otherwise the client cert
        source is None.

        The API endpoint is determined in the following order:
        (1) if `client_options.api_endpoint` if provided, use the provided one.
        (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
        default mTLS endpoint; if the environment variable is "never", use the default API
        endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
        use the default API endpoint.

        More details can be found at https://google.aip.dev/auth/4114.

        Args:
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. Only the `api_endpoint` and `client_cert_source` properties may be used
                in this method.

        Returns:
            Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
                client cert source to use.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If any errors happen.
        """
        return CompanyServiceClient.get_mtls_endpoint_and_cert_source(client_options)  # type: ignore

    @property
    def transport(self) -> CompanyServiceTransport:
        """Returns the transport used by the client instance.

        Returns:
            CompanyServiceTransport: The transport used by the client instance.
        """
        return self._client.transport

    get_transport_class = functools.partial(
        type(CompanyServiceClient).get_transport_class, type(CompanyServiceClient)
    )

    def __init__(
        self,
        *,
        credentials: Optional[ga_credentials.Credentials] = None,
        transport: Union[str, CompanyServiceTransport] = "grpc_asyncio",
        client_options: Optional[ClientOptions] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
    ) -> None:
        """Instantiates the company service client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, ~.CompanyServiceTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (ClientOptions): Custom options for the client. It
                won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        self._client = CompanyServiceClient(
            credentials=credentials,
            transport=transport,
            client_options=client_options,
            client_info=client_info,
        )

    async def create_company(
        self,
        request: Optional[Union[company_service.CreateCompanyRequest, dict]] = None,
        *,
        parent: Optional[str] = None,
        company: Optional[gct_company.Company] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> gct_company.Company:
        r"""Creates a new company entity.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import talent_v4

            async def sample_create_company():
                # Create a client
                client = talent_v4.CompanyServiceAsyncClient()

                # Initialize request argument(s)
                company = talent_v4.Company()
                company.display_name = "display_name_value"
                company.external_id = "external_id_value"

                request = talent_v4.CreateCompanyRequest(
                    parent="parent_value",
                    company=company,
                )

                # Make the request
                response = await client.create_company(request=request)

                # Handle the response
                print(response)

        Args:
            request (Optional[Union[google.cloud.talent_v4.types.CreateCompanyRequest, dict]]):
                The request object. The Request of the CreateCompany
                method.
            parent (:class:`str`):
                Required. Resource name of the tenant under which the
                company is created.

                The format is
                "projects/{project_id}/tenants/{tenant_id}", for
                example, "projects/foo/tenants/bar".

                This corresponds to the ``parent`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            company (:class:`google.cloud.talent_v4.types.Company`):
                Required. The company to be created.
                This corresponds to the ``company`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.talent_v4.types.Company:
                A Company resource represents a
                company in the service. A company is the
                entity that owns job postings, that is,
                the hiring entity responsible for
                employing applicants for the job
                position.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([parent, company])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        request = company_service.CreateCompanyRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.
        if parent is not None:
            request.parent = parent
        if company is not None:
            request.company = company

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.create_company,
            default_timeout=30.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def get_company(
        self,
        request: Optional[Union[company_service.GetCompanyRequest, dict]] = None,
        *,
        name: Optional[str] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> company.Company:
        r"""Retrieves specified company.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import talent_v4

            async def sample_get_company():
                # Create a client
                client = talent_v4.CompanyServiceAsyncClient()

                # Initialize request argument(s)
                request = talent_v4.GetCompanyRequest(
                    name="name_value",
                )

                # Make the request
                response = await client.get_company(request=request)

                # Handle the response
                print(response)

        Args:
            request (Optional[Union[google.cloud.talent_v4.types.GetCompanyRequest, dict]]):
                The request object. Request for getting a company by
                name.
            name (:class:`str`):
                Required. The resource name of the company to be
                retrieved.

                The format is
                "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
                for example,
                "projects/api-test-project/tenants/foo/companies/bar".

                This corresponds to the ``name`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.talent_v4.types.Company:
                A Company resource represents a
                company in the service. A company is the
                entity that owns job postings, that is,
                the hiring entity responsible for
                employing applicants for the job
                position.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([name])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        request = company_service.GetCompanyRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.
        if name is not None:
            request.name = name

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.get_company,
            default_retry=retries.Retry(
                initial=0.1,
                maximum=60.0,
                multiplier=1.3,
                predicate=retries.if_exception_type(
                    core_exceptions.DeadlineExceeded,
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=30.0,
            ),
            default_timeout=30.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def update_company(
        self,
        request: Optional[Union[company_service.UpdateCompanyRequest, dict]] = None,
        *,
        company: Optional[gct_company.Company] = None,
        update_mask: Optional[field_mask_pb2.FieldMask] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> gct_company.Company:
        r"""Updates specified company.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import talent_v4

            async def sample_update_company():
                # Create a client
                client = talent_v4.CompanyServiceAsyncClient()

                # Initialize request argument(s)
                company = talent_v4.Company()
                company.display_name = "display_name_value"
                company.external_id = "external_id_value"

                request = talent_v4.UpdateCompanyRequest(
                    company=company,
                )

                # Make the request
                response = await client.update_company(request=request)

                # Handle the response
                print(response)

        Args:
            request (Optional[Union[google.cloud.talent_v4.types.UpdateCompanyRequest, dict]]):
                The request object. Request for updating a specified
                company.
            company (:class:`google.cloud.talent_v4.types.Company`):
                Required. The company resource to
                replace the current resource in the
                system.

                This corresponds to the ``company`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
                Strongly recommended for the best service experience.

                If
                [update_mask][google.cloud.talent.v4.UpdateCompanyRequest.update_mask]
                is provided, only the specified fields in
                [company][google.cloud.talent.v4.UpdateCompanyRequest.company]
                are updated. Otherwise all the fields are updated.

                A field mask to specify the company fields to be
                updated. Only top level fields of
                [Company][google.cloud.talent.v4.Company] are supported.

                This corresponds to the ``update_mask`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.talent_v4.types.Company:
                A Company resource represents a
                company in the service. A company is the
                entity that owns job postings, that is,
                the hiring entity responsible for
                employing applicants for the job
                position.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([company, update_mask])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        request = company_service.UpdateCompanyRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.
        if company is not None:
            request.company = company
        if update_mask is not None:
            request.update_mask = update_mask

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.update_company,
            default_timeout=30.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata(
                (("company.name", request.company.name),)
            ),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def delete_company(
        self,
        request: Optional[Union[company_service.DeleteCompanyRequest, dict]] = None,
        *,
        name: Optional[str] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> None:
        r"""Deletes specified company.
        Prerequisite: The company has no jobs associated with
        it.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import talent_v4

            async def sample_delete_company():
                # Create a client
                client = talent_v4.CompanyServiceAsyncClient()

                # Initialize request argument(s)
                request = talent_v4.DeleteCompanyRequest(
                    name="name_value",
                )

                # Make the request
                await client.delete_company(request=request)

        Args:
            request (Optional[Union[google.cloud.talent_v4.types.DeleteCompanyRequest, dict]]):
                The request object. Request to delete a company.
            name (:class:`str`):
                Required. The resource name of the company to be
                deleted.

                The format is
                "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
                for example, "projects/foo/tenants/bar/companies/baz".

                This corresponds to the ``name`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([name])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        request = company_service.DeleteCompanyRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.
        if name is not None:
            request.name = name

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.delete_company,
            default_retry=retries.Retry(
                initial=0.1,
                maximum=60.0,
                multiplier=1.3,
                predicate=retries.if_exception_type(
                    core_exceptions.DeadlineExceeded,
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=30.0,
            ),
            default_timeout=30.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
        )

        # Send the request.
        await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

    async def list_companies(
        self,
        request: Optional[Union[company_service.ListCompaniesRequest, dict]] = None,
        *,
        parent: Optional[str] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> pagers.ListCompaniesAsyncPager:
        r"""Lists all companies associated with the project.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import talent_v4

            async def sample_list_companies():
                # Create a client
                client = talent_v4.CompanyServiceAsyncClient()

                # Initialize request argument(s)
                request = talent_v4.ListCompaniesRequest(
                    parent="parent_value",
                )

                # Make the request
                page_result = client.list_companies(request=request)

                # Handle the response
                async for response in page_result:
                    print(response)

        Args:
            request (Optional[Union[google.cloud.talent_v4.types.ListCompaniesRequest, dict]]):
                The request object. List companies for which the client
                has ACL visibility.
            parent (:class:`str`):
                Required. Resource name of the tenant under which the
                company is created.

                The format is
                "projects/{project_id}/tenants/{tenant_id}", for
                example, "projects/foo/tenants/bar".

                This corresponds to the ``parent`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.talent_v4.services.company_service.pagers.ListCompaniesAsyncPager:
                The List companies response object.
                Iterating over this object will yield
                results and resolve additional pages
                automatically.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([parent])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        request = company_service.ListCompaniesRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.
        if parent is not None:
            request.parent = parent

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.list_companies,
            default_retry=retries.Retry(
                initial=0.1,
                maximum=60.0,
                multiplier=1.3,
                predicate=retries.if_exception_type(
                    core_exceptions.DeadlineExceeded,
                    core_exceptions.ServiceUnavailable,
                ),
                deadline=30.0,
            ),
            default_timeout=30.0,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # This method is paged; wrap the response in a pager, which provides
        # an `__aiter__` convenience method.
        response = pagers.ListCompaniesAsyncPager(
            method=rpc,
            request=request,
            response=response,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def get_operation(
        self,
        request: Optional[operations_pb2.GetOperationRequest] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: Union[float, object] = gapic_v1.method.DEFAULT,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> operations_pb2.Operation:
        r"""Gets the latest state of a long-running operation.

        Args:
            request (:class:`~.operations_pb2.GetOperationRequest`):
                The request object. Request message for
                `GetOperation` method.
            retry (google.api_core.retry.Retry): Designation of what errors,
                    if any, should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        Returns:
            ~.operations_pb2.Operation:
                An ``Operation`` object.
        """
        # Create or coerce a protobuf request object.
        # The request isn't a proto-plus wrapped type,
        # so it must be constructed via keyword expansion.
        if isinstance(request, dict):
            request = operations_pb2.GetOperationRequest(**request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method.wrap_method(
            self._client._transport.get_operation,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def __aenter__(self) -> "CompanyServiceAsyncClient":
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await self.transport.close()

DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
    gapic_version=package_version.__version__
)

__all__ = ("CompanyServiceAsyncClient",)


import discord
from discord.ext import commands
from discord.ext.commands import bot
from discord.utils import get
from core import gestion as ge
from DB import SQLite as sql

rolelist = ["Baron du Bastion", "Inquisiteur du Bastion", "BastioBot", "PEGI master", "Groovy", "Joueurs", "Archive", "Nouveau"]

async def addrole(member, role):
    setrole = get(member.guild.roles, name=role)
    if setrole != None:
        await member.add_roles(setrole)
    else:
        await print("Role introuvable")

async def removerole(member, role):
    setrole = get(member.guild.roles, name=role)
    if setrole != None:
        await member.remove_roles(setrole)
    else:
        await print("Role introuvable")

class Roles(commands.Cog):

    def __init__(self, ctx):
        return(None)

    @commands.command(pass_context=True, aliases=['gamecreate'])
    async def rolecreate(self, ctx, game, categorie = None):
        """**[role]** | Permet de créer un nouveau role pour un jeu"""
        # Paramètres:
        # - game: Nom du jeu/role
        # - categorie: Nom du grand salon (combat/societe/tirs/voiture/rpg/sandbox/strategie/divers)
        guild = ctx.guild
        member = ctx.author
        rolesearch = discord.utils.get(member.guild.roles, name=game)
        if ge.permission(ctx, ge.Inquisiteur):
            if rolesearch == None:
                await guild.create_role(name=game)
                desc = "Le jeu '{0}' a été créé".format(game)

                if categorie != None:
                    rolesearch = discord.utils.get(member.guild.roles, name=game)
                    categorie = categorie.lower()

                    if categorie == "combat":
                        channeladd = guild.get_channel(589944955800256515)
                    elif categorie == "societe":
                        channeladd = guild.get_channel(589945591203889152)
                    elif categorie == "tirs":
                        channeladd = guild.get_channel(589946246437797888)
                    elif categorie == "voiture":
                        channeladd = guild.get_channel(589946276540448821)
                    elif categorie == "rpg":
                        channeladd = guild.get_channel(589946305917222916)
                    elif categorie == "sandbox":
                        channeladd = guild.get_channel(589946380416581632)
                    elif categorie == "strategie":
                        channeladd = guild.get_channel(589953946639007764)
                    elif categorie == "divers":
                        channeladd = guild.get_channel(590664052318142474)
                    else:
                        channeladd = guild.get_channel(589942497678196764)# 590664052318142474
                    await channeladd.set_permissions(rolesearch, overwrite=discord.PermissionOverwrite(read_messages=True))
                    desc += "Ajout d'un nouveau jeu dans la catégorie {}: {}".format(channeladd.mention, rolesearch.mention)
                    # channel = guild.get_channel(417449076775321600)
                msg = discord.Embed(title = "Création de jeu", color= 13752280, description = desc)
                await ctx.channel.send(embed = msg)
            else:
                await ctx.channel.send("Le jeu {0} existe déjà".format(game))
        else :
            await ctx.channel.send("Tu ne peux pas exécuter cette commande.")

    @commands.command(pass_context=True, aliases=['gameadd'])
    async def roleadd(self, ctx, role, nom = None):
        """**[role]** | Permet de s'ajouter des roles (Pour les Inquisiteurs, mentionner l'utilisateur cible apres le role pour lui affecter)"""
        if ge.permission(ctx, ge.Joueurs):
            if nom != None:
                if ge.permission(ctx, ge.Inquisiteur):
                    ID = sql.nom_ID(nom)
                    nom = ctx.guild.get_member(ID)
                    nom = nom.name
                else:
                    await ctx.channel.send("Tu peux exécuter cette commande uniquement pour toi.")
                    return
            else:
                ID = ctx.author.id
                nom = ctx.author.name
            user = get(ctx.guild.members, id=ID)
            if user:
                setrole = get(user.guild.roles, name=role)
                if ge.permission(ctx, ge.Inquisiteur) is False:
                    for i in range(0, len(rolelist)):
                        if role == rolelist[i]:
                            await ctx.channel.send("Tu ne peux pas exécuter cette commande avec ce role.")
                            return
                await user.add_roles(setrole)
                desc = "Le role `{0}` a été ajouté à {1}".format(role, nom)
                msg = discord.Embed(title = "Ajout de jeu", color= 13752280, description = desc)
                await ctx.channel.send(embed = msg)
                return
            else:
                await ctx.channel.send("L'utilisateur n'as pas été trouvé.")
        else:
            await ctx.channel.send("Tu ne peux pas exécuter cette commande.")

    @commands.command(pass_context=True, aliases=['gameremove'])
    async def roleremove(self, ctx, role, nom = None):
        """**[role]** | Permet de s'enlever des roles (Pour les Inquisiteurs, mentionner l'utilisateur cible apres le role pour lui enlever)"""
        if ge.permission(ctx, ge.Joueurs):
            if nom != None:
                if ge.permission(ctx, ge.Inquisiteur):
                    ID = sql.nom_ID(nom)
                    nom = ctx.guild.get_member(ID)
                    nom = nom.name
                else:
                    await ctx.channel.send("Tu peux exécuter cette commande uniquement pour toi.")
                    return
            else:
                ID = ctx.author.id
                nom = ctx.author.name
            user = get(ctx.guild.members, id=ID)
            if user:
                setrole = get(user.guild.roles, name=role)
                await user.remove_roles(setrole)
                desc = "Le role `{0}` a été enlevé à {1}".format(role, nom)
                msg = discord.Embed(title = "Retrait de jeu", color=9109504, description = desc)
                await ctx.channel.send(embed = msg)
                return
            else:
                await ctx.channel.send("L'utilisateur n'as pas été trouvé.")
        else:
            await ctx.channel.send("Tu ne peux pas exécuter cette commande.")

    @commands.command(pass_context=True, aliases=['gamelist'])
    async def rolelist(self, ctx):
        """Affiche la liste des rôles disponible"""
        desc = ""
        jsonlist = ctx.guild.roles
        rolelist = []
        gamelist = []
        check = False
        for i in range(0, len(jsonlist)):
            temp = "{}".format(jsonlist[i])
            rolelist.append(temp)
        for i in range(0, len(rolelist)):
            if rolelist[i] == "Joueurs":
                check = False
            if check:
                gamelist.append(rolelist[i])
            if rolelist[i] == "Nouveau":
                check = True
        gamelist.sort()
        for i in range(0, len(gamelist)):
            desc += "{}\n".format(gamelist[i])
        msg = discord.Embed(title = "Liste des rôles disponible", color=35723, description = desc)
        await ctx.channel.send(embed = msg)

def setup(bot):
    bot.add_cog(Roles(bot))
    open("help/cogs.txt", "a").write("Roles\n")


# -*- coding: utf-8 -*-
from django.contrib import admin

from .models import Author, Topic, Comment

class AuthorAdmin(admin.ModelAdmin):
    list_display = (u'id', 'created', 'modified', 'login', 'username')
    list_filter = ('created', 'modified')
admin.site.register(Author, AuthorAdmin)

class TopicAdmin(admin.ModelAdmin):
    list_display = (
        u'id',
        'created',
        'modified',
        'url',
        'title',
        'text',
        'date',
        'author_url',
        'author',
    )
    list_filter = ('created', 'modified', 'date', 'author')
admin.site.register(Topic, TopicAdmin)

class CommentAdmin(admin.ModelAdmin):
    list_display = (
        u'id',
        'created',
        'modified',
        'date',
        'date_string',
        'url',
        'author_url',
        'author',
    )
    list_filter = ('created', 'modified', 'date', 'author', 'topic')
admin.site.register(Comment, CommentAdmin)


#!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_one_parameter

# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/delete-database.html
if __name__ == '__main__':
    """
	create-database : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/create-database.html
	get-database : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-database.html
	get-databases : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-databases.html
	update-database : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/update-database.html
    """

    parameter_display_string = """
    # name : The name of the database to delete. For Hive compatibility, this must be all lowercase.
    """
    add_option_dict = {}

    #######################################################################
    # parameter display string
    add_option_dict["parameter_display_string"] = parameter_display_string
    # ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
    write_one_parameter("glue", "delete-database", "name", add_option_dict)


"""Main WSGI application. Just URL routes to the other modules."""
import importlib

from oauth_dropins.webutil import appengine_info, appengine_config, handlers
import webapp2

routes = []
for module in (
  'activitypub',
  'add_webmention',
  'logs',
  'redirect',
  'render',
  'salmon',
  'superfeedr',
  'webfinger',
  'webmention',
):
  routes += importlib.import_module(module).ROUTES

application = handlers.ndb_context_middleware(
    webapp2.WSGIApplication(routes, debug=appengine_info.DEBUG),
    client=appengine_config.ndb_client)