def __make_update(self):
     with open(self.__data_path + "/" + SHEETS_FILE) as f:
         sheet_keys = f.read().splitlines()
     for sheet_key in sheet_keys:
         sheet = Sheet(sheet_key)
         sheet.update()
     return
Exemplo n.º 2
0
def null(message):
    admins = get_admins()

    if message.from_user.username in admins:
        sheet = Sheet("photos_vote_bot")
        sheet.null()
        bot.send_message(message.chat.id, "Таблицю обнулено.")
Exemplo n.º 3
0
 def do_sheet(self, elem):
     bk = self.bk
     sheetx = bk.nsheets
     # print elem.attrib
     rid = elem.get(U_ODREL + 'id')
     sheetId = int(elem.get('sheetId'))
     name = unescape(unicode(elem.get('name')))
     reltype = self.relid2reltype[rid]
     target = self.relid2path[rid]
     if self.verbosity >= 2:
         self.dumpout(
             'sheetx=%d sheetId=%r rid=%r type=%r name=%r',
             sheetx, sheetId, rid, reltype, name)
     if reltype != 'worksheet':
         if self.verbosity >= 2:
             self.dumpout('Ignoring sheet of type %r (name=%r)', reltype, name)
         return
     bk._sheet_visibility.append(True)
     sheet = Sheet(bk, position=None, name=name, number=sheetx)
     sheet.utter_max_rows = X12_MAX_ROWS
     sheet.utter_max_cols = X12_MAX_COLS
     bk._sheet_list.append(sheet)
     bk._sheet_names.append(name)
     bk.nsheets += 1
     self.sheet_targets.append(target)
     self.sheetIds.append(sheetId)
Exemplo n.º 4
0
def main(file_path, X, Y, V, saveAs, convertor):
    file_path = Path(file_path)
    sheets = pd.read_excel(file_path, sheet_name=None, engine='openpyxl')

    sheet_names = []
    for sheet in sheets.keys():
        sheet_names.append(sheet)

    # Using sheet 1 as the default sheet.
    sheet_name = sheet_names[0]

    df = sheets[sheet_name]
    sheet = Sheet(sheet_name=sheet_name, df=df)
    sheet.save_cols(X=X, Y=Y, V=V)

    if convertor == "convertor_1":
        new_sheet = sheet.convertor1()
        sheet.save_excel(new_sheet, f"{saveAs}")

    elif convertor == "convertor_2":
        new_sheet = sheet.convertor2()
        sheet.save_excel(new_sheet, f"{saveAs}")

    elif convertor == "convertor_3":
        new_sheet = sheet.convertor3()
        sheet.save_excel(new_sheet, f"{saveAs}")

    elif convertor == "convertor_4":
        new_sheet = sheet.convertor4()
        sheet.save_excel(new_sheet, f"{saveAs}")

    else:
        raise Exception(f"Invalid convertor name: '{convertor}'.")
Exemplo n.º 5
0
    def __init__(self,
                 server="smtp.gmail.com",
                 port=587,
                 username="",
                 password="",
                 auth_file=""):
        """
        init
        """

        try:
            self.sheet = Sheet(auth_file_name=auth_file, sheet_name="contacts")
            self.sheet.open_sheet()
            self.config_distrib_list()

            self.smtpserver = smtplib.SMTP(server, port)
            self.smtpserver.ehlo()
            self.smtpserver.starttls()
            self.smtpserver.ehlo()

            self.smtpserver.login(self.smtp_username, self.smtp_password)

            self.initiated = True

        except Exception as e:

            logging.debug(" unable to initiate email notifications ")
            logging.debug(e)
Exemplo n.º 6
0
 def __init__(self):
     self.idm = "01010312841a360d"
     self.isScaned = True  #for demonstration
     self.isStepped = False
     self.IDs = ["01010a10e41a9f23", "01010A10E41A9F25"]
     self.sheet = Sheet()
     self.num = 0
     self.sheet.write(self.IDs)
Exemplo n.º 7
0
    def __init__(self, filename=None):
        self.__sheet = Sheet()
        self.__cursor = Cursor()
        self.__io = FileIO(filename)
        self.__programIsRunning = True
        self.__lastCommand = ""

        self.load()
Exemplo n.º 8
0
def test_sheetGeneration():
    config = json.load(
        open("resources/powerup_config.json", "r", encoding="utf-8"))
    gen = Sheet(config)
    fields = json.load(
        open("resources/powerup_test_3.json", "r", encoding="utf-8"))
    gen.create_from_json(fields)
    pass
Exemplo n.º 9
0
def begin(message):
    admins = get_admins()

    if message.from_user.username in admins:
        database_interface.free()
        global participants
        sheet = Sheet("photos_vote_bot")
        participants = sheet.get_participants()
        bot.send_message(message.chat.id, "Голосування запущено.")
Exemplo n.º 10
0
    def __init__(self, fname, sheet_name, feature_extractors,
                 out_dir="out", out_format="png"):

        self.fname = fname
        self.sheet_name = sheet_name
        self.out_format = out_format
        self.out_dir = out_dir

        orig_img = cv2.imread(fname)
        self.sheet = Sheet(orig_img, dpi=self._dpi_from_exif(),
                           save_image=self.save_image)
        self.feature_extractors = [
            feat(self.sheet) for feat in feature_extractors]
Exemplo n.º 11
0
    def run(self):
        """
        initialize sheets and notifier
        """

        try:
            logging.info("\nOpening notification sheet ... ")
            self.ntfr = Notifier(auth_file=self.ui.get_google_auth_file_name())

            logging.info("\nOpening the tracking sheet ... ")
            if (self.ui.get_google_auth_file_name() != ""):
                self.sheet = Sheet(
                    auth_file_name=self.ui.get_google_auth_file_name())
            else:
                self.sheet = Sheet()

            self.sheet.open_sheet()

            # get back to caller from this thread
            self.nt_ready_signal.emit()

            #self.ui.activateButton.setEnabled(True)
            #self.ui.deactivateButton.setEnabled(False)

        except Exception as e:

            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            logging.debug(exc_type, fname, exc_tb.tb_lineno)
            logging.debug(e)

            logging.error(
                " An issue occurred while initializing network components ")
            logging.error(e)

            #self.ui.activateButton.setEnabled(False)
            #self.ui.refreshButton.setEnabled(True)

            self.nt_ready_signal.emit()
Exemplo n.º 12
0
    def open_file(self):
        # get the file
        existing_file = askopenfilename(title="Select file.")

        self.sheet = Sheet("Jeb")

        # call Sheet read function
        self.sheet.read_file(month, year, existing_file)

        self.display_day_accounts['text'] = "Accounts of the day\n{}".format(
            self.get_day_projects())

        self.day_total_base = self.sheet.total_day(today)
Exemplo n.º 13
0
    def __init__(self):
        # SpreadSheet
        logger.info('--- Initialize Spreadsheet')
        self.mysheet = Sheet()

        # Google Drive
        logger.info('--- Initialize Google Drive')
        self.mydrive = GDrive()

        # Slack
        # logger.info('--- Initialize Slack')
        # self.slack = Slack()

        # Zoom
        logger.info('--- Initialize Zoom')
        self.zoom = Zoom()
Exemplo n.º 14
0
 def openFile(
     self, file_name
 ):  # used to read an excel sheet and parses all its sheets contents to separate sheet objects in fl
     #sheet = Sheet(file_name)         # for separate excel sheet
     xls = pd.ExcelFile(
         file_name
     )  # initialize an excel sheet with path specified in file_name as xls
     self.file_path = file_name
     self.building_name, ext = path_leaf(file_name).split('.')
     for sheet_name in xls.sheet_names:  # loop for every sheets in xls parses its dataframe by calling sheet objects methods
         sheet = Sheet(self.building_name + ' - ' +
                       sheet_name)  # add filename + " - " later
         sheet.zeroRemove(xls)
         if 'Max' not in sheet.df.index:
             sheet.addStatsRow()
         self.fl.append(sheet)
Exemplo n.º 15
0
def easy_way():
    metadata = MetaData()
    engine = Sqlite3Engine(":memory:")
    datatype = DataType()
    employee = Table(
        "employee",
        metadata,
        Column("employee_id", datatype.text, primary_key=True),
        Column("age", datatype.integer),
        Column("height", datatype.real),
        Column("enroll_date", datatype.date),
        Column("create_datetime", datatype.datetime),
    )
    metadata.create_all(engine)
    ins = employee.insert()

    timer.start()
    # === real work ===
    sheet = Sheet({
        "employee_id": "TEXT",
        "age": "INTEGER",
        "height": "REAL",
        "enroll_date": "DATE",
        "create_datetime": "DATETIME"
    })

    csvfile = CSVFile(r"testdata\bigcsvfile.txt",
                      sep=",",
                      header=True,
                      dtype={
                          "CREATE_DATE": "DATE",
                          "CREATE_DATETIME": "DATETIME"
                      })
    sheet.match(csvfile.sample)

    for row in csvfile.generate_rows():
        try:
            engine.insert_row(ins, Row.from_dict(sheet.convert(row)))
        except:
            pass
    timer.timeup()
    engine.prt_all(employee)
Exemplo n.º 16
0
    def _init_existing_sheets(self):
        """Init Sheet() object for every sheet in this spreadsheet.

        Returns:
            dict: {<sheet_name>: <sheet.Sheet>} - sheets index.
        """
        sheets = {}
        resp = self._ss_resource.get(spreadsheetId=self._id).execute()

        for sheet in resp["sheets"]:
            props = sheet["properties"]
            name = props["title"]

            if name == self._config.ARCHIVE_SHEET.get("name"):
                self._archive = ArchiveSheet(name, self._id, props["sheetId"])
                continue

            sheets[name] = Sheet(name, self._id, props["sheetId"])

        return sheets
Exemplo n.º 17
0
def result(message):
    admins = get_admins()

    if message.from_user.username in admins:
        sheet = Sheet("photos_vote_bot")
        global participants

        if participants is None:
            participants = sheet.get_participants()

        if database_interface.count_votes(sheet, participants) is True:
            bot.send_message(message.chat.id, "Таблиця результатів оновлена.")
        else:
            bot.send_message(
                message.chat.id,
                "Щось пішло не так, спробуй ще раз або напиши розробнику.")
    else:
        bot.send_message(
            message.chat.id,
            "Упс... Схоже тебе немає в списку адміністраторів, звернись до розробника."
        )
Exemplo n.º 18
0
    def _build_new_sheets_requests(self, sheets_in_conf):
        """Build add-new-sheet requests for the new sheets.

        Args:
            sheets_in_conf (tuple): Sheets list from the configurations.

        Returns:
            list: List of add-new-sheet requests.
        """
        add_sheet_reqs = []

        for name in sheets_in_conf:
            if name not in self.sheets.keys():
                self.sheets[name] = Sheet(name, self._id)
                add_sheet_reqs.append(self.sheets[name].create_request)

        if self._config.ARCHIVE_SHEET and self._archive.is_new:
            add_sheet_reqs.append(self._archive.create_request)
            self._archive.is_new = False

        return add_sheet_reqs
Exemplo n.º 19
0
def runUpdate(monthStart, yearStart, monthEnd, yearEnd):

    curMonth = monthStart
    curYear = yearStart

    updateList = []

    while (curYear < yearEnd or (curYear == yearEnd and curMonth <= monthEnd)):
        for card in cards:
            for test in tests:
                search = genSearchString(card, test, curYear, curMonth)
                results = driveService.files().list(
                    includeTeamDriveItems=True,
                    supportsTeamDrives=True,
                    pageSize=100,
                    q=search,
                    corpora="domain").execute()
                files = results["files"]
                for file in files:
                    datetime = getEpochTime(file["name"])
                    curSheet = Sheet(test, card, datetime, file["id"])
                    updateList = updateList + curSheet.genUpdate(sheetService)
                    time.sleep(1.3)

        curYear = curYear + 1 if curMonth == 12 else curYear
        curMonth = (curMonth % 12) + 1

    query = []
    for update in updateList:
        query.append(
            UpdateOne(
                {
                    "sheetId": update["sheetId"],
                    "subtest": update["subtest"],
                    "test": update["test"],
                    "type": update["type"]
                }, {"$set": update},
                upsert=True))

    collection.bulk_write(query)
Exemplo n.º 20
0
import sys
from sheet import Sheet

if __name__ == "__main__":
    config = json.load(
        open("resources/powerup_config.json", "r", encoding="utf-8"))
    if len(sys.argv) >= 2:
        # Format: <event-name> [event-id] [frc-api-token]
        config['event'] = sys.argv[1]
        if len(sys.argv) >= 3:
            config['event_code'] = sys.argv[2]
            if len(sys.argv) >= 4:
                config['frc_api'] = sys.argv[3]

    print("Generating scouting sheets for " + config['event_code'] + " - " +
          config['event'])
    gen = Sheet(config)
    fields = json.load(
        open("resources/powerup_test_3.json", "r", encoding="utf-8"))
    gen.create_from_json(fields)


def test_sheetGeneration():
    config = json.load(
        open("resources/powerup_config.json", "r", encoding="utf-8"))
    gen = Sheet(config)
    fields = json.load(
        open("resources/powerup_test_3.json", "r", encoding="utf-8"))
    gen.create_from_json(fields)
    pass
Exemplo n.º 21
0
    # Create an new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook('model.xlsx')
    business_transactions_sheet = workbook.add_worksheet(
        'Input Business Transactions')
    it_transactions_sheet = workbook.add_worksheet('Input IT Transactions')

    # Create styles
    bold = workbook.add_format({'bold': True})

    header_row = 7

    btHeaders = [
        'Business Transaction Name', 'Transaction Description',
        'Business Volumes', 'Frequency', 'Notes'
    ]
    btSheet = Sheet(business_transactions_sheet)
    btSheet.add_header(btHeaders)
    btSheet.write_headers(header_row, bold)

    itHeaders = [
        'Business Transaction', 'IT Transaction Name',
        'IT Transaction Description', 'Qty per transaction',
        'Transaction Rating', 'TPS', 'Notes'
    ]
    itSheet = Sheet(it_transactions_sheet)
    itSheet.add_header(itHeaders)
    itSheet.write_headers(header_row, bold)

    # Parse the xml data.
    tree = ET.parse('data.xml')
    root = tree.getroot()
 def __init__(self):
     self.base_url = "https://rightmove.co.uk"
     # Default to 24 hour period for now, don't show let agreed
     self.base_search_url = self.base_url + \
         "/property-to-rent/find.html?maxDaysSinceAdded=1&_includeLetAgreed=false&"
     self.sheet = Sheet(service_account_configuration_path, sheet_name)
#import audio
from sheet import Sheet
import pyglet

WIDTH = 600
HEIGHT = 400

sheet = Sheet(width=WIDTH,
              height=HEIGHT,
              caption="Term Project -- Refactored",
              resizable=False)

pyglet.gl.glClearColor(255, 255, 255, 1)

pyglet.app.run()
Exemplo n.º 24
0
 def __init__(self):
     self.sheet = Sheet(PUS_SHEET_ID)
Exemplo n.º 25
0
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import time
from sheet import Sheet
import settings

url = "https://messages.google.com/web/conversations/new"
table = Sheet(settings.FILE_NAME,settings.SHEET_NAME)
table.row_count = len(table.worksheet.get_all_records())

def start_web_driver():
	options = Options()
	# options.add_argument(f"user-agent={user_agent}")
	options.add_argument('--disable-infobars')
	options.add_argument('--disable-extensions')
	options.add_argument('--incognito')
	options.add_argument('--profile-directory=Default')
	options.add_argument('--disable-plugins-dicovery')
	options.add_argument('--start-maximized')
	options.add_experimental_option('excludeSwitches', ['enable-automation'])
	driver = webdriver.Chrome(settings.CHROME_DRIVER, options=options)
	return driver

driver = start_web_driver()

driver.get(url)
Exemplo n.º 26
0
from sheet import Sheet
import bitly_api
from dotenv import load_dotenv
import os
import sys
load_dotenv()

access_token = os.getenv("access_token")
c = bitly_api.Connection(access_token=access_token)

table = Sheet("arac-tel", "Sheet1")
row_count = len(table.worksheet.get_all_records())

for row_number in range(2, row_count):
    row = table.get_row(row_number)
    if row[3].isdigit() and int(row[3]) > 0:
        table.update_one_cell(row_number, "clicked",
                              c.clicks(shortUrl=row[1])[0]["global_clicks"])
    else:
        sys.exit("Dolu satırlar bitti.")
Exemplo n.º 27
0
from sheet import Sheet
from voyabot import RocketBot

inputs = Sheet('results.xlsx')
outputs = Sheet('emails.xlsx')

bot = RocketBot(inputs)
df = bot.scrape_data()

outputs.write(df)
bot.close_driver()
Exemplo n.º 28
0
    def create_testdata():
        df = [["eid001", 100, 1.23, date.today(), datetime.now()]]
        df = pd.DataFrame(
            df, columns=["TEXT", "INTEGER", "REAL", "DATE", "DATETIME"])
        df.to_csv(r"testdata\with_header.txt", index=False)
        df.to_csv(r"testdata\without_header.txt", header=False, index=False)

#     create_testdata()

# 定义你目标数据格式

    sheet = Sheet({
        "_id": "TEXT",
        "age": "INTEGER",
        "height": "REAL",
        "create_date": "DATE",
        "datetime": "DATETIME"
    })

    csvfile_with_header = CSVFile(r"testdata\with_header.txt",
                                  sep=",",
                                  header=True,
                                  usecols=[0, 1, 2, 3, 4],
                                  dtype={
                                      "DATE": "DATE",
                                      "DATETIME": "DATETIME"
                                  })
    sheet.match(csvfile_with_header.sample)
    for row in csvfile_with_header.generate_rows():
        print(sheet.convert(row))
Exemplo n.º 29
0
    def import_data_dictionary(path, header=1, config=None):
        if config:
            Importer.config = config.parse()
            
        dict_config = Importer.config['dictionary']
        label_number = dict_config["header_line"] - 1

        excel = Importer.import_workbook(path)
        sheet_names = Importer.get_sheet_names_from_workbook(excel)

        sheets = {}

        ignored_reasons = {}

        for sheet_name in sheet_names:
            print(sheet_name)
            sheet_parsed = Importer.import_sheet_from_workbook(excel, sheet_name, header=label_number)

            if not sheet_name in dict_config["sheets"]:
                print("Planilha não configurada encontrada: " + str(sheet_name))
                continue

            try:
                clean_columns = Importer.clean_columns(sheet_parsed.columns, dict_config["columns"])

            except Exception as exception:
                print("The sheet ("+ sheet_name + ") could not be processed because of: " + exception.args[0] + "\n")

                for ignored_column in exception.args[1]:
                    print("Coluna ("+ignored_column+") não configurada encontrada e ignorada para a planilha ("+sheet_name+")")

                continue

            sheet = Sheet(sheet_name, [])
            
            rows = sheet_parsed.get([i["sheet_column"] for i in clean_columns])

            for j, columns in enumerate(rows.values):
                row = list(columns)

                row_dict = {}
                include_row = True

                for i, column in enumerate(row):
                    row_dict[clean_columns[i]["column_key"]] = column

                    if type(column) == float and math.isnan(column) :
                        if clean_columns[i]["mandatory"]:
                            include_row = False
                            if clean_columns[1]["sheet_column"] not in ignored_reasons:
                                ignored_reasons[clean_columns[1]["sheet_column"]] = []

                            ignored_reasons[clean_columns[1]["sheet_column"]].append((j,sheet_name))
                            break                
                
                if include_row:
                    sheet.data.append(row_dict)
            
            # print(sheet.name,len(sheet.data))
            sheets[dict_config["sheets"][sheet_name]] = sheet
        print("Linhas ignoradas para as seguintes chaves configuradas como obrigatórias: ", ignored_reasons, "\n")
        
        return sheets
Exemplo n.º 30
0
from sheet import Sheet

import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

if __name__ == '__main__':
    N = 15

    a = 2.46
    a_1 = [a, 0, 0]
    a_2 = [a / 2.0, a * math.sqrt(3) / 2, 0]
    sites = [[0.0, 0.0, 0.0], [a / 2.0, a / (2.0 * math.sqrt(3)), 0.0]]

    s1 = Sheet([a_1, a_2, [0, 0, 1]], ['C', 'C'], sites, [0], [-N, -N], [N, N],
               'graphene')
    s2 = Sheet([a_1, a_2, [0, 0, 1]], ['C', 'C'], sites, [0], [-N, -N], [N, N],
               'graphene')
    s3 = Sheet([a_1, a_2, [0, 0, 1]], ['C', 'C'], sites, [0], [-N, -N], [N, N],
               'graphene')
    h = Heterostructure((s1, s2, s3), [0, math.pi / 90, math.pi / 45],
                        [0, 6, 12])
    H = h.localitySweep(2)
    '''
    val_arr = set()
    vec_arr = set()
    for i in np.linspace(0,1,4,endpoint=False):
        for j in np.linspace(0,1,4,endpoint=False):
            h.setShift([[0,0,0],[i,j,0]])
            H12 = h.interHamiltonian(0,1)
            H21 = h.interHamiltonian(1,0)