def test_get_non_existing_cell_raises_exception(self):
        ss = Spreadsheet(self.basic_data)
        with self.assertRaises(InvalidCellIdException):
            ss.get_value(0, -1)

        with self.assertRaises(InvalidCellIdException):
            ss.get_value(29, 1)
 def test_advance_row(self):
     spreadsheet = Spreadsheet()
     spreadsheet.advance_column()
     spreadsheet.advance_column()
     spreadsheet.advance_column()
     self.assertEqual(spreadsheet.current_cell(), 'D1')
     spreadsheet.advance_row()
     self.assertEqual(spreadsheet.current_cell(), 'A2')
    def test_initialize_and_access_spreadsheet_with_references(self):
        self.basic_data[0][0] = "10"
        for j in range(1, Spreadsheet.COLUMNS):
            self.basic_data[0][j] = "A1"

        ss = Spreadsheet(self.basic_data)
        for j in range(Spreadsheet.COLUMNS):
            self.assertEquals(ss.get_value(0, j), 10)
def test_group_index():
    assert Spreadsheet._group_index([]) == []
    assert Spreadsheet._group_index([1]) == [[1, 2]]
    assert Spreadsheet._group_index([1, 2]) == [[1, 3]]
    assert Spreadsheet._group_index([1, 2, 5]) == [[1, 3], [5, 6]]
    assert Spreadsheet._group_index([1, 2, 3, 12, 13, 8, 6]) == [[1,
                                                                  4], [6, 7],
                                                                 [8, 9],
                                                                 [12, 14]]
def check_requests(request_type, auth_file, worksheet_key):
    """Check for new approved requests"""
    sheet = Spreadsheet(keyfile=auth_file, sheet_id=worksheet_key)
    rows = sheet.get_all_rows('Form Responses 1')
    timestamp = datetime.now().strftime("%d %b %Y %H:%M:%S")
    processed_rows = []

    # set som type-specific things
    if request_type == 'access':
        parse_function = parse_user_row
        csr_type = 'Access Request'

    elif request_type == 'quota':
        parse_function = parse_quota_row
        csr_type = 'Quota Request'
    else:
        raise Exception('Unknown request type: `{}`'.format(request_type))

    for idx, row in enumerate(rows):

        if (idx == 0) or (row == []):
            # skip header row and blank rows
            continue

        elif (row[0].lower().strip() == 'approved') and (row[1] == ''):
            # process rows that are marked approved but not notified
            request_info = parse_function(row)
            notify_helpdesk(template=helpdesk_template,
                            sender=helpdesk_email,
                            receiver=helpdesk_email,
                            csr_type=csr_type,
                            priority='High',
                            queue='Monitoring',
                            **request_info)

            processed_rows.append(idx)
            if args.log:
                log_request(args.log, timestamp, request_info['user_email'])

        elif (row[0] == '') and (datetime.now() >= dateparser.parse(row[2]) +
                                 timedelta(hours=24)):
            # send reminder about rows that have been waiting for approval
            # for more than 24 hours
            request_info = parse_function(row)
            reminder(template=reminder_template,
                     sender=reminder_email,
                     receiver=reminder_email,
                     request_type=request_type,
                     **request_info)

        else:
            # skip over unapproved or already-notified rows
            continue

    # Google API returns an error if you send an empty request
    if processed_rows:
        timestamp_spreadsheet(sheet, timestamp, processed_rows)
    def test_get_cells_with_references(self):
        computed_fib = [0, 1, 1, 2, 3, 5, 8, 13, 21]
        self.basic_data[0][0] = '0'
        self.basic_data[0][1] = '1'
        for j in range(2, Spreadsheet.COLUMNS):
            self.basic_data[0][j] = "A{} + A{}".format(str(j+1-2), str(j+1-1))

        ss = Spreadsheet(self.basic_data)
        for j in range(Spreadsheet.COLUMNS - 1, -1, -1):
            self.assertEquals(ss.get_value(0, j), computed_fib[j])
    def test_set_value_modifying_references(self):
        self.basic_data[0][0] = 'A2'
        self.basic_data[1][0] = 'A1'
        ss = Spreadsheet(self.basic_data)
        self.assertEquals(ss.get_value(0, 0), float(self.basic_data[0][1]))
        self.assertEquals(ss.get_value(1, 0), float(self.basic_data[0][1]))

        ss.set_value(0, 0, 'A3')
        self.assertEquals(ss.get_value(0, 0), float(self.basic_data[0][2]))
        self.assertEquals(ss.get_value(1, 0), float(self.basic_data[0][2]))
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon(":/images/icon.png"))
        self.setCurrentFile("")

        # ----------- 数据 -------------
        self.spreadsheet = Spreadsheet()
        self.setCentralWidget(self.spreadsheet)

        self.findDialog = None
        self.locationLabel = None
        self.formulaLabel = None
        self.recentFiles = None  # QStringList recentFiles;
        self.curFile = None  # QString curFile;

        self.MaxRecentFiles = 5
        self.recentFileActions = [None] * self.MaxRecentFiles
        #
        self.separatorAction = None
        # #
        self.fileMenu = None
        self.editMenu = None
        self.selectSubMenu = None
        self.toolsMenu = None
        self.optionsMenu = None
        self.helpMenu = None
        self.fileToolBar = None
        self.editToolBar = None
        self.newAction = None
        self.openAction = None
        self.saveAction = None
        self.saveAsAction = None
        self.exitAction = None
        self.cutAction = None
        self.copyAction = None
        self.pasteAction = None
        self.deleteAction = None
        self.selectRowAction = None
        self.selectColumnAction = None
        self.selectAllAction = None
        self.findAction = None
        self.goToCellAction = None
        self.recalculateAction = None
        self.sortAction = None
        self.showGridAction = None
        self.autoRecalcAction = None
        self.aboutAction = None
        self.aboutQtAction = None
        # self.qApp = QApplication([]) # 这样写 有问题

        self.createActions()
        self.createMenus()
        self.createContextMenu()
        self.createToolBars()
        self.createStatusBar()
Esempio n. 9
0
async def on_ready():
    # global calls so we can modify these variables
    global isReady
    global RolesManager
    global googleSheet
    global discordG

    print(f'{client.user} has connected to Discord')

    for guild in client.guilds:
        if guild.name == GUILD:
            break

    discordG = guild
    rosterChan = None
    for channel in guild.text_channels:
        if channel.id == chanIds["roster"]:
            rosterChan = channel

    googleSheet = Spreadsheet(os.getenv('SHEET_IDENTIFIER'))
    RolesManager = AshesRolesManager(rosterChan, discordIds, googleSheet)
    await RolesManager.init(discordIds, guild)

    isReady = True
    print("Setup complete")
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon(":/images/icon.png"))
        self.setCurrentFile("")

        # ----------- 数据 -------------
        self.spreadsheet = Spreadsheet()
        self.setCentralWidget(self.spreadsheet)

        self.findDialog = None
        self.locationLabel = None
        self.formulaLabel = None
        self.recentFiles = None  # QStringList recentFiles;
        self.curFile = None      # QString curFile;

        self.MaxRecentFiles = 5
        self.recentFileActions = [None] * self.MaxRecentFiles
        #
        self.separatorAction = None
        # #
        self.fileMenu = None
        self.editMenu = None
        self.selectSubMenu = None
        self.toolsMenu = None
        self.optionsMenu = None
        self.helpMenu = None
        self.fileToolBar = None
        self.editToolBar = None
        self.newAction = None
        self.openAction = None
        self.saveAction = None
        self.saveAsAction = None
        self.exitAction = None
        self.cutAction = None
        self.copyAction = None
        self.pasteAction = None
        self.deleteAction = None
        self.selectRowAction = None
        self.selectColumnAction = None
        self.selectAllAction = None
        self.findAction = None
        self.goToCellAction = None
        self.recalculateAction = None
        self.sortAction = None
        self.showGridAction = None
        self.autoRecalcAction = None
        self.aboutAction = None
        self.aboutQtAction = None
        # self.qApp = QApplication([]) # 这样写 有问题


        self.createActions()
        self.createMenus()
        self.createContextMenu()
        self.createToolBars()
        self.createStatusBar()
Esempio n. 11
0
 def __init__(self, test_setup_info, test_data_collection):
     self.path = Test_Data_Persistence.test_data_path + str(test_setup_info)
     self.test_data_collection = test_data_collection
     self.spreadsheet_mode = True
     self.data_plot_mode = True
     self.tzero_mode = True
     self.spreadsheets = {}
     
     for key, value in self.test_data_collection.items():
         self.spreadsheets[key] = Spreadsheet(self.path, key, value)
 def test_letter(self):
     spreadsheet = Spreadsheet()
     self.assertEqual(spreadsheet.letter(0), 'A')
     self.assertEqual(spreadsheet.letter(25), 'Z')
     self.assertEqual(spreadsheet.letter(26), 'AA')
     self.assertEqual(spreadsheet.letter(27), 'AB')
     self.assertEqual(spreadsheet.letter(51), 'AZ')
     self.assertEqual(spreadsheet.letter(52), 'BA')
     self.assertEqual(spreadsheet.letter(77), 'BZ')
     self.assertEqual(spreadsheet.letter(78), 'CA')
Esempio n. 13
0
    def test_set_value_with_references(self):
        self.basic_data[4][5] = 'A9'
        ss = Spreadsheet(self.basic_data)

        new_value = ss.get_value(0, 8) + ss.get_value(1, 5) + 10

        ss.set_value(4, 5, 'A9 + B6 + 10')
        self.assertEquals(ss.get_value(4, 5), new_value)
Esempio n. 14
0
    def test_set_value_with_dependent_cells(self):
        self.basic_data[0][0] = '0'
        for j in range(1, Spreadsheet.COLUMNS):
            self.basic_data[0][j] = 'A%d + 1' % j

        ss = Spreadsheet(self.basic_data)
        for j in range(Spreadsheet.COLUMNS):
            ss.get_value(0, j)

        ss.set_value(0, 0, '1')
        for j in range(Spreadsheet.COLUMNS - 1, -1, -1):
            self.assertEquals(ss.get_value(0, j), j+1)
Esempio n. 15
0
def show_all():
    # TODO make toolbar buttons work
    ntb = backend_bases.NavigationToolbar2
    ntb.toolitems = (
        ('Home', 'Reset original view', 'home', 'home'),
        (None, None, None, None),
        ('Back', 'Back to  previous view', 'back', 'back'),
        ('Forward', 'Forward to next view', 'forward', 'forward'),
        (None, None, None, None),
        ('Save', 'Save the figure', 'filesave', 'save_figure'),
    )
    for column in Spreadsheet().columns():
        TTest(
            title=column.get_title(),
            measure_unit=column.get_unit(),
            instrument_error=column.get_instr_err(),
            nums=column.get_nums(),
            dpi=130,
        ).express_solution()
    plt.show()
Esempio n. 16
0
def parse_bestworst_data(file, bestCol="best", worstCol="worst", sep=None):
    """parses best-worst data from file, where each trial is returned as tuple:
         (best, worst, (unchosen1, unchosen2, ..., unchosen[K-2]))

       A list of parsed trials is returned.
    """
    # figure out our seperator first
    if sep == None and file.endswith(".tsv"):
        sep = "\t"
    elif sep == None:
        sep = ","

    # read in the trials
    ss = Spreadsheet.read_csv(file, delimiter=sep)
    trials = []
    for row in ss:
        # read best and worst choices
        best = row[bestCol]
        worst = row[worstCol]
        opts = []

        # read all options that were choosable
        i = 1
        while True:
            col = "option%d" % i
            if col in ss.header:
                opts.append(row[col])
                i += 1
            else:
                break

        # strip best and worst choices from the list of other options
        if best in opts:
            opts.remove(best)
        if worst in opts:
            opts.remove(worst)

        trials.append((best, worst, tuple(opts)))

    # return the parsed trials
    return trials
Esempio n. 17
0
def main():
    session = Session()
    session.start_session()
    creds = session.get_credentials()

    spreadsheet = Spreadsheet(creds)

    while True:
        operation = int(input('Operations:\n1 - Read sheet\n2 - Update sheet\n3 - Cancel\n'))
        if operation == 1:  
            values = spreadsheet.get_spreadsheet_values("A1:E12")
            spreadsheet.print_sheet(values)
        elif operation == 2:
            payment_one = int(input('Payment One: '))
            payment_two = int(input('Payment Two: '))
            month = int(input('Month: '))
            spreadsheet.insert_values_in_sheet(payment_one, payment_two, month)
        elif operation == 3:
            break
        else:
            print('Invalid operation!')
Esempio n. 18
0
         "Content-Type", "Authorization", "Access-Control-Allow-Credentials"
     ],
     supports_credentials=True)
api = Api(app)
CORS(app,
     origins="http://127.0.0.1:8080",
     allow_headers=[
         "Content-Type", "Authorization", "Access-Control-Allow-Credentials"
     ],
     supports_credentials=True)

spreadsheet_args = reqparse.RequestParser()
spreadsheet_args.add_argument("text", type=str, required=True)
spreadsheet_args.add_argument("url", type=str, required=True)

curr_spreadsheet = Spreadsheet()

model = MyClassifier(vectorizer='pretrained_glove_50',
                     spreadsheet=curr_spreadsheet,
                     debug=False)


class SpreadsheetManager(Resource):
    def post(self):
        args = spreadsheet_args.parse_args()
        url = args["url"]
        text = args["text"]

        # get sheet number
        parsed = urlparse.urlparse(url)
        gid = parse_qs(parsed.fragment)['gid'][0]
Esempio n. 19
0
       text="Pie Chart",
       width=button_width,
       command=lambda: switch_window(pie_chart)).pack()
button_frame.grid(column=0, row=0, sticky="NW")

# Creates content at the right
content_frame = Frame(root)
content_frame.grid(column=1, row=0)

main_window_list = []

home = Home(content_frame)
main_window_list.append(home)

num_of_cases = NumOfCases(content_frame)
main_window_list.append(num_of_cases)

spreadsheet = Spreadsheet(content_frame)
main_window_list.append(spreadsheet)

time_plot = TimePlot(content_frame)
main_window_list.append(time_plot)

pie_chart = PieChart(content_frame)
main_window_list.append(pie_chart)

current_window = home
current_window.pack()

root.mainloop()
Esempio n. 20
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description=
        'Command line for generating best-worst trials from a list of items.')
    parser.add_argument(
        "input",
        type=str,
        help=
        "Path to a file containing input data (i.e., a list of words or other text stimuli)."
    )
    parser.add_argument(
        "N",
        nargs="?",
        type=int,
        default=None,
        help=
        "Number of best-worst trials to generate. Suggested amount: number of items, times 8. So if you have 1000 items, 8000 trials. You may get *slightly* better results up to an N of 16, but gains are marginal. You may need fewer trials if your K is larger. Empirical testing not yet done."
    )
    parser.add_argument("K",
                        nargs="?",
                        type=int,
                        default=4,
                        help="Number of items per best-worst trial.")
    parser.add_argument(
        "--generator",
        type=str,
        default="norepeateven",
        help=
        "Method for generating trials. Don't screw with unless you know what you are doing. Options are: random, even, norepeat, norepeateven."
    )
    parser.add_argument(
        "--column",
        type=str,
        default=None,
        help=
        "If inputting a structured text file, indicate which column to pull data from."
    )
    parser.add_argument(
        "--sep",
        type=str,
        default=None,
        help=
        "Specify the column separator. If None specified, use default (tab for .tsv, comma for all else)"
    )

    args = parser.parse_args()

    # read in the items to build trials from
    items = []
    if args.input.endswith(
            ".txt") and args.sep == None and args.column == None:
        items = [item.strip() for item in open(args.input, "r").read().split()]
    elif args.column == None:
        raise Exception(
            "You must specify a column name with --column= to generate trials this way."
        )
    else:
        # comma by default or if specified, tab if .tsv
        sep = args.sep
        if sep == None and args.input.endswith(".tsv"):
            sep = "\t"
        elif sep == None:
            sep = ","
        ss = Spreadsheet.read_csv(args.input, delimiter=sep)

        # take the first column if no column specified
        items = ss[args.column]

    # filter out empty strings
    items = [item for item in items if len(item) > 0]

    # parse our N and K
    K = args.K
    N = args.N
    if N == None:
        N = len(items) * 3

    # generate trials from items
    trials = []
    if args.generator == "norepeateven":
        trials = trialgen.build_trials_even_bigram_norepeat(items, N=N, K=K)
    elif args.generator == 'even':
        trials = trialgen.build_trials_even(items, N=N, K=K)
    elif args.generator == 'random':
        trials = trialgen.build_trials_random(items, N=N, K=K)
    elif args.generator == "norepeat":
        trials = trialgen.build_trials_random_bigram_norepeat(items, N=N, K=K)
    else:
        raise Exception(
            "You must specify a proper generation method: norepeateven, even, random, norepeat."
        )

    # print the output, complete with header.
    # header = [ "option%d" % (i+1) for i in range(K) ]
    # print(",".join(header))
    # for trial in trials:
    #     print(",".join(trial))
    # return trials
    df = pd.DataFrame(trials)
    df.to_csv("all_trials_reduced.csv")
Esempio n. 21
0
 def test_get_cell_with_auto_reference_raises_exception(self):
     self.basic_data[0][0] = 'A1'
     ss = Spreadsheet(self.basic_data)
     with self.assertRaises(CircularReferenceException):
         ss.get_value(0, 0)
Esempio n. 22
0
# Create the Reddit instance
reddit = praw.Reddit('bot1')

# and login
reddit = praw.Reddit(client_id='',
                     client_secret='',
                     user_agent='',
                     username='',
                     password='')

subreddit = reddit.subreddit('3dprintmything')

# Get the newest 6 values from the subreddit
for submission in subreddit.new(limit=6):
    #print(submission.title)
    spreadsheet = Spreadsheet(submission.id)
    seen_bool = spreadsheet.run()
    counter = 0
    # If we haven't seen this post before
    if not seen_bool:
        send_sms.send_alert()









class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon(":/images/icon.png"))
        self.setCurrentFile("")

        # ----------- 数据 -------------
        self.spreadsheet = Spreadsheet()
        self.setCentralWidget(self.spreadsheet)

        self.findDialog = None
        self.locationLabel = None
        self.formulaLabel = None
        self.recentFiles = None  # QStringList recentFiles;
        self.curFile = None      # QString curFile;

        self.MaxRecentFiles = 5
        self.recentFileActions = [None] * self.MaxRecentFiles
        #
        self.separatorAction = None
        # #
        self.fileMenu = None
        self.editMenu = None
        self.selectSubMenu = None
        self.toolsMenu = None
        self.optionsMenu = None
        self.helpMenu = None
        self.fileToolBar = None
        self.editToolBar = None
        self.newAction = None
        self.openAction = None
        self.saveAction = None
        self.saveAsAction = None
        self.exitAction = None
        self.cutAction = None
        self.copyAction = None
        self.pasteAction = None
        self.deleteAction = None
        self.selectRowAction = None
        self.selectColumnAction = None
        self.selectAllAction = None
        self.findAction = None
        self.goToCellAction = None
        self.recalculateAction = None
        self.sortAction = None
        self.showGridAction = None
        self.autoRecalcAction = None
        self.aboutAction = None
        self.aboutQtAction = None
        # self.qApp = QApplication([]) # 这样写 有问题


        self.createActions()
        self.createMenus()
        self.createContextMenu()
        self.createToolBars()
        self.createStatusBar()

        # self.readSettings()

    # def closeEvent(self, event):
    #     if (self.okToContinue()):
    #         self.writeSettings()
    #         event.accept()
    #     else:
    #         event.ignore()

    @pyqtSlot()
    def newFile(self):
        if (self.okToContinue()):
            pass
            # spreadsheet.clear()
            # setCurrentFile("")

    @pyqtSlot()
    def open(self):
        pass

    @pyqtSlot()
    def save(self):
        pass

    @pyqtSlot()
    def saveAs(self):
        pass

    @pyqtSlot()
    def find(self):
        pass

    @pyqtSlot()
    def goToCell(self):
        pass

    @pyqtSlot()
    def sort(self):
        pass

    # 关于
    @pyqtSlot()
    def about(self):
        QMessageBox.about(self, str("About Spreadsheet"),
                str("<h2>Spreadsheet 1.1</h2>"
                   "<p>Copyright &copy 2008 Software Inc."
                   "<p>Spreadsheet is a small application that "
                   "demonstrates QAction, QMainWindow, QMenuBar, "
                   "QStatusBar, QTableWidget, QToolBar, and many other "
                   "Qt classes."))

    @pyqtSlot()
    def openRecentFile(self):
        pass

    @pyqtSlot()
    def updateStatusBar(self):
        pass

    def spreadsheetModified(self):
        pass

    # 创建 Actions
    def createActions(self):

        # 新建
        self.newAction = QAction(str("&New"), self)
        self.newAction.setIcon(QIcon(":/images/new.png"))
        self.newAction.setShortcut(QKeySequence.New)
        self.newAction.setStatusTip(str("Create a new spreadsheet file"))
        self.connect(self.newAction, SIGNAL("triggered()"), self, SLOT("newFile()"))

        # 打开
        self.openAction = QAction(str("&Open..."), self)
        self.openAction.setIcon(QIcon(":/images/open.png"))
        self.openAction.setShortcut(QKeySequence.Open)
        self.openAction.setStatusTip(str("Open an existing spreadsheet file"))
        self.connect(self.openAction, SIGNAL("triggered()"), self, SLOT("open()"))

        # 保存
        self.saveAction = QAction(str("&Save"), self)
        self.saveAction.setIcon(QIcon(":/images/save.png"))
        self.saveAction.setShortcut(QKeySequence.Save)
        self.saveAction.setStatusTip(str("Save the spreadsheet to disk"))
        self.connect(self.saveAction, SIGNAL("triggered()"), self, SLOT("save()"))

        # 另存为
        self.saveAsAction = QAction(str("Save &As..."), self)
        self.saveAsAction.setStatusTip(str("Save the spreadsheet under a name"))
        self.connect(self.saveAsAction, SIGNAL("triggered()"), self, SLOT("saveAs()"))

        for i in range(self.MaxRecentFiles):
            self.recentFileActions[i] = QAction(self)
            self.recentFileActions[i].setVisible(False)
            self.connect(self.recentFileActions[i], SIGNAL("triggered()"),
                         self, SLOT("openRecentFile()"))
        # 退出
        self.exitAction = QAction(str("E&xit"), self)
        self.exitAction.setShortcut(str("Ctrl+Q"))
        self.exitAction.setStatusTip(str("Exit the application"))
        self.connect(self.exitAction, SIGNAL("triggered()"), self, SLOT("close()"))

        # -------------

        # 剪切
        self.cutAction = QAction(str("Cu&t"), self)
        self.cutAction.setIcon(QIcon(":/images/cut.png"))
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.cutAction.setStatusTip(str("Cut the current selection's contents "
                                        "to the clipboard"))
        self.connect(self.cutAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("cut()"))

        # 拷贝
        self.copyAction = QAction(str("&Copy"), self)
        self.copyAction.setIcon(QIcon(":/images/copy.png"))
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.copyAction.setStatusTip(str("Copy the current selection's contents "
                                         "to the clipboard"))
        self.connect(self.copyAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("copy()"))

        # 黏贴
        self.pasteAction = QAction(str("&Paste"), self)
        self.pasteAction.setIcon(QIcon(":/images/paste.png"))
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.pasteAction.setStatusTip(str("Paste the clipboard's contents into "
                                          "the current selection"))
        self.connect(self.pasteAction, SIGNAL("triggered()"),
                self.spreadsheet, SLOT("paste()"))

        self.deleteAction = QAction(str("&Delete"), self)
        self.deleteAction.setShortcut(QKeySequence.Delete)
        self.deleteAction.setStatusTip(str("Delete the current selection's "
                                           "contents"))
        # self.connect(self.deleteAction, SIGNAL("triggered()"),
        #         self.spreadsheet, SLOT(del()))

        self.selectRowAction = QAction(str("&Row"), self)
        self.selectRowAction.setStatusTip(str("Select all the cells in the "
                                              "current row"))
        self.connect(self.selectRowAction, SIGNAL("triggered()"),
                self.spreadsheet, SLOT("selectCurrentRow()"))

        self.selectColumnAction = QAction(str("&Column"), self)
        self.selectColumnAction.setStatusTip(str("Select all the cells in the "
                                                 "current column"))
        self.connect(self.selectColumnAction, SIGNAL("triggered()"),
                self.spreadsheet, SLOT("selectCurrentColumn()"))

        self.selectAllAction = QAction(str("&All"), self)
        self.selectAllAction.setShortcut(QKeySequence.SelectAll)
        self.selectAllAction.setStatusTip(str("Select all the cells in the "
                                              "spreadsheet"))
        self.connect(self.selectAllAction, SIGNAL("triggered()"),
                self.spreadsheet, SLOT("selectAll()"))

        self.findAction = QAction(str("&Find..."), self)
        self.findAction.setIcon(QIcon(":/images/find.png"))
        self.findAction.setShortcut(QKeySequence.Find)
        self.findAction.setStatusTip(str("Find a matching cell"))
        self.connect(self.findAction, SIGNAL("triggered()"), self, SLOT("find()"))

        self.goToCellAction = QAction(str("&Go to Cell..."), self)
        self.goToCellAction.setIcon(QIcon(":/images/gotocell.png"))
        self.goToCellAction.setShortcut(str("Ctrl+G"))
        self.goToCellAction.setStatusTip(str("Go to the specified cell"))
        self.connect(self.goToCellAction, SIGNAL("triggered()"),
                self, SLOT("goToCell()"))

        self.recalculateAction = QAction(str("&Recalculate"), self)
        self.recalculateAction.setShortcut(str("F9"))
        self.recalculateAction.setStatusTip(str("Recalculate all the "
                                                "spreadsheet's formulas"))
        self.connect(self.recalculateAction, SIGNAL("triggered()"),
                self.spreadsheet, SLOT("recalculate()"))

        self.sortAction = QAction(str("&Sort..."), self)
        self.sortAction.setStatusTip(str("Sort the selected cells or all the "
                                         "cells"))
        self.connect(self.sortAction, SIGNAL("triggered()"), self, SLOT("sort()"))

        self.showGridAction = QAction(str("&Show Grid"), self)
        self.showGridAction.setCheckable(True)
        self.showGridAction.setChecked(self.spreadsheet.showGrid())
        self.showGridAction.setStatusTip(str("Show or hide the spreadsheet's "
                                             "grid"))
        self.connect(self.showGridAction, SIGNAL("toggled(bool)"),
                self.spreadsheet, SLOT("setShowGrid(bool)"))

        self.autoRecalcAction = QAction(str("&Auto-Recalculate"), self)
        self.autoRecalcAction.setCheckable(True)
        # self.autoRecalcAction.setChecked(self.spreadsheet.autoRecalculate())
        self.autoRecalcAction.setStatusTip(str("Switch auto-recalculation on or "
                                               "off"))
        # self.connect(self.autoRecalcAction, SIGNAL("toggled(bool)"),\
                   # self.spreadsheet, SLOT("setAutoRecalculate(bool)"))

        self.aboutAction = QAction(str("&About"), self)
        self.aboutAction.setStatusTip(str("Show the application's About box"))
        self.connect(self.aboutAction, SIGNAL("triggered()"), self, SLOT("about()"))

        self.aboutQtAction = QAction(str("About &Qt"), self)
        self.aboutQtAction.setStatusTip(str("Show the Qt library's About box"))
        # self.connect(self.aboutQtAction, SIGNAL("triggered()"), self.qApp, SLOT("aboutQt()"))

    # 创建 菜单栏
    def createMenus(self):

        self.fileMenu = self.menuBar().addMenu(str("&File"))
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveAsAction)
        self.separatorAction = self.fileMenu.addSeparator()

        for i in range(self.MaxRecentFiles):
            self.fileMenu.addAction(self.recentFileActions[i])

        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu = self.menuBar().addMenu(str("&Edit"))
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addAction(self.deleteAction)

        self.selectSubMenu = self.editMenu.addMenu(str("&Select"))
        self.selectSubMenu.addAction(self.selectRowAction)
        self.selectSubMenu.addAction(self.selectColumnAction)
        self.selectSubMenu.addAction(self.selectAllAction)

        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.goToCellAction)

        self.toolsMenu = self.menuBar().addMenu(str("&Tools"))
        self.toolsMenu.addAction(self.recalculateAction)
        self.toolsMenu.addAction(self.sortAction)

        self.optionsMenu = self.menuBar().addMenu(str("&Options"))
        self.optionsMenu.addAction(self.showGridAction)
        self.optionsMenu.addAction(self.autoRecalcAction)

        self.menuBar().addSeparator()

        helpMenu = self.menuBar().addMenu(str("&Help"))
        helpMenu.addAction(self.aboutAction)
        helpMenu.addAction(self.aboutQtAction)

    # 添加 上下文菜单,右键快捷菜单
    def createContextMenu(self):
        pass
        self.spreadsheet.addAction(self.cutAction)
        self.spreadsheet.addAction(self.copyAction)
        self.spreadsheet.addAction(self.pasteAction)
        self.spreadsheet.setContextMenuPolicy(Qt.ActionsContextMenu)

    def createToolBars(self):
        pass

    def createStatusBar(self):
        pass

    def readSettings(self):
        pass

    def writeSettings(self):
        pass

    def okToContinue(self):
        pass

    # def loadFile(const QString &fileName)
    def loadFile(self, fileName):
        pass

    # def saveFile(const QString &fileName)
    def saveFile(self, fileName):
        pass

    # def setCurrentFile(const QString &fileName)
    def setCurrentFile(self, fileName):
        pass

    def updateRecentFileActions(self):
        pass

    # def strippedName(const QString &fullFileName)
    def strippedName(self, fullFileName):
        pass
Esempio n. 24
0
def handle_websocket():
    # assign a uuid to the client
    client_id = str(uuid.uuid4())
    print client_id, 'websocket connected'
    # request the websocket
    ws = request.environ.get('wsgi.websocket')
    if not ws:
        abort(400, 'Expected WebSocket request.')
    clients[client_id] = ws
    state = None
    while True:
        try:
            raw_msg = ws.receive()
        except:
            break
        msg = safely(lambda: json.loads(raw_msg))
        if not msg:
            time.sleep(0.1)
            continue
        print 'msg:', msg
        command = msg.get('command')
        # {command: "search", keywords: "hello world"}
        if command == 'search':
            keywords = msg['keywords'].split()
            items = pages.search(keywords)
            ws.send(json.dumps({'command': 'search-results', 'items': items}))
        # {command: "open", id: "r18r4g18734tr1087t"}
        elif command == 'open':
            id = msg['id']
            locker(
                lambda: id in sheets or sheets.update({id: Spreadsheet(id)}))
            page = pages.retrieve(id) or {
                'id': id,
                'title': 'new page',
                'markup': '',
                'code': ''
            }
            ws.send(json.dumps({'command': 'page', 'page': page}))
        # {command: "compute", id: "..." code: "...", formulas: {..}}
        elif command == 'compute':
            id = msg['id']
            if not id in sheets: continue
            sheet = sheets[id]
            if 'code' in msg:
                context = {}
                try:
                    exec(msg['code'], {}, context)  # NOT SAFE CHECK THIS HERE
                    sheets[id].context = context
                except:
                    pass
            changes = msg['formulas']
            if changes == None: return
            for key in changes.keys():
                if not changes[key] == '=':
                    safely(lambda: changes.update(
                        {key: ast.literal_eval(changes[key])}))
            changes = locker(lambda: sheets[id].process(changes))
            values = {
                key: render(value)
                for key, value in changes['values'].iteritems()
            }
            ws.send(json.dumps({'command': 'values', 'values': values}))
        # {command: "save", page: {id:..., title:..., markup:..., code:...} }
        elif command == 'save':
            pages.store(**msg['page'])
Esempio n. 25
0
encoder = RotaryEncoder.Worker(ENCODER_PIN_A, ENCODER_PIN_B)
encoder.start()

SWITCH_PIN = 9
switch = Switch(SWITCH_PIN)
switch_state = switch.get_state()

oled = Oled()
contrast = 0
oled.ssd1306.set_contrast(contrast)

rgbled.set_sequence(startup_sequence)

SPREADSHEET_NAME     = 'TimeClock'
SPREADSHEET_TEMPLATE = 'TimeClock.ods'
ss = Spreadsheet()

if not ss.oauth.has_token():
    user_code = ss.oauth.get_user_code()
    print "Go to %s and enter the code %s" % (ss.oauth.verification_url, user_code)
    # need a font that will show us the full code without scrolling
    from gaugette.fonts import arial_24
    oled.ssd1306.clear_display()
    oled.ssd1306.draw_text3(0,0,user_code,arial_24)
    oled.ssd1306.display()
    ss.oauth.get_new_token()  # this call will block until the code is entered

if not ss.get_spreadsheet_by_name(SPREADSHEET_NAME):
    print "Creating new spreadsheet '%s'." % (SPREADSHEET_NAME)
    ss.create(SPREADSHEET_TEMPLATE, SPREADSHEET_NAME)
Esempio n. 26
0
 def test_initialize_and_access_spreadsheet_without_references(self):
     ss = Spreadsheet(self.basic_data)
     for i in range(Spreadsheet.ROWS):
         for j in range(Spreadsheet.COLUMNS):
             continue
             self.assertEquals(ss.get_value(i, j), float(self.basic_data[i][j]))
Esempio n. 27
0
# -*- coding: utf-8 -*-

from telebot import types
from telebot import TeleBot
from spreadsheet import Spreadsheet

import operator
import datetime
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'resources'))
from config import token

bot = TeleBot(token)
spreadsheet = Spreadsheet()
owner_id = ''
lean_coffee = {}
themes = set()
voting = False


@bot.message_handler(commands=['lean'])
def lean(message):
    global lean_coffee
    global themes
    global owner_id

    if not owner_id:
        lean_coffee = {}
        themes = set()
Esempio n. 28
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.timeButton = QtGui.QPushButton(self.centralwidget)
        self.timeButton.setObjectName("timeButton")
        self.horizontalLayout.addWidget(self.timeButton)
        self.downloadButton = QtGui.QPushButton(self.centralwidget)
        self.downloadButton.setObjectName("downloadButton")
        self.horizontalLayout.addWidget(self.downloadButton)
        self.uploadButton = QtGui.QPushButton(self.centralwidget)
        self.uploadButton.setObjectName("uploadButton")
        self.horizontalLayout.addWidget(self.uploadButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.tableView = Spreadsheet(self.centralwidget)
        self.tableView.setObjectName("tableView")
        self.verticalLayout.addWidget(self.tableView)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.txTextBrowser = QtGui.QTextBrowser(self.centralwidget)
        self.txTextBrowser.setMaximumSize(QtCore.QSize(16777215, 100))
        self.txTextBrowser.setObjectName("txTextBrowser")
        self.horizontalLayout_2.addWidget(self.txTextBrowser)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_3.addWidget(self.label_2)
        self.rxTextBrowser = QtGui.QTextBrowser(self.centralwidget)
        self.rxTextBrowser.setMaximumSize(QtCore.QSize(16777215, 100))
        self.rxTextBrowser.setObjectName("rxTextBrowser")
        self.horizontalLayout_3.addWidget(self.rxTextBrowser)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 19))
        self.menubar.setObjectName("menubar")
        self.menuSoubor = QtGui.QMenu(self.menubar)
        self.menuSoubor.setObjectName("menuSoubor")
        self.menuBIOTX = QtGui.QMenu(self.menubar)
        self.menuBIOTX.setObjectName("menuBIOTX")
        self.menuNastaveni = QtGui.QMenu(self.menubar)
        self.menuNastaveni.setObjectName("menuNastaveni")
        self.menuN_pov_da = QtGui.QMenu(self.menubar)
        self.menuN_pov_da.setObjectName("menuN_pov_da")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNov = QtGui.QAction(MainWindow)
        self.actionNov.setObjectName("actionNov")
        self.actionOtev_t = QtGui.QAction(MainWindow)
        self.actionOtev_t.setObjectName("actionOtev_t")
        self.actionUlo_it = QtGui.QAction(MainWindow)
        self.actionUlo_it.setObjectName("actionUlo_it")
        self.actionUlo_it_jako = QtGui.QAction(MainWindow)
        self.actionUlo_it_jako.setObjectName("actionUlo_it_jako")
        self.actionDownload_data = QtGui.QAction(MainWindow)
        self.actionDownload_data.setObjectName("actionDownload_data")
        self.actionUpload_data = QtGui.QAction(MainWindow)
        self.actionUpload_data.setObjectName("actionUpload_data")
        self.actionNastavit_hodiny = QtGui.QAction(MainWindow)
        self.actionNastavit_hodiny.setObjectName("actionNastavit_hodiny")
        self.actionZm_na_S_N = QtGui.QAction(MainWindow)
        self.actionZm_na_S_N.setObjectName("actionZm_na_S_N")
        self.actionNastaven_korekce = QtGui.QAction(MainWindow)
        self.actionNastaven_korekce.setObjectName("actionNastaven_korekce")
        self.actionCOM_Port = QtGui.QAction(MainWindow)
        self.actionCOM_Port.setObjectName("actionCOM_Port")
        self.actionHelo = QtGui.QAction(MainWindow)
        self.actionHelo.setObjectName("actionHelo")
        self.actionAbout = QtGui.QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.menuSoubor.addAction(self.actionNov)
        self.menuSoubor.addAction(self.actionOtev_t)
        self.menuSoubor.addAction(self.actionUlo_it)
        self.menuSoubor.addAction(self.actionUlo_it_jako)
        self.menuBIOTX.addAction(self.actionDownload_data)
        self.menuBIOTX.addAction(self.actionUpload_data)
        self.menuBIOTX.addAction(self.actionNastavit_hodiny)
        self.menuBIOTX.addAction(self.actionZm_na_S_N)
        self.menuBIOTX.addAction(self.actionNastaven_korekce)
        self.menuNastaveni.addAction(self.actionCOM_Port)
        self.menuN_pov_da.addAction(self.actionHelo)
        self.menuN_pov_da.addAction(self.actionAbout)
        self.menubar.addAction(self.menuSoubor.menuAction())
        self.menubar.addAction(self.menuBIOTX.menuAction())
        self.menubar.addAction(self.menuNastaveni.menuAction())
        self.menubar.addAction(self.menuN_pov_da.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Interface for best-worst simulation')
    parser.add_argument(
        "input",
        type=str,
        help=
        "A .csv or .tsv input file containing two columns, named by default Item and LatentValue. Item is an identifying label and LatentValue is the item's True value along the dimension to be evaluated."
    )
    parser.add_argument(
        "N", type=int, help="Number of trials to generate for the simulation.")
    parser.add_argument("K",
                        type=int,
                        default=4,
                        help="Number of items per trial, defaults to 4.")
    parser.add_argument(
        "--noise",
        type=float,
        default=0.0,
        help=
        "the sd to use for generating noise on each decision (noise is normally distributed)."
    )
    parser.add_argument(
        "--generator",
        type=str,
        default="even",
        help=
        "The type of trial generation method for running the simulation. Options are: random, even, norepeat, norepeateven. See Hollis (2017) for details."
    )
    parser.add_argument("--sep",
                        type=str,
                        default=None,
                        help="Column seperator for the input file")
    parser.add_argument("--item",
                        type=str,
                        default="Item",
                        help="Column corresponding to item name.")
    parser.add_argument("--latentvalue",
                        type=str,
                        default="LatentValue",
                        help="Column corresponding to latent value name.")
    parser.add_argument(
        "--dummy",
        type=bool,
        default=True,
        help="use a dummy player to bound tournament-based scores.")
    parser.add_argument(
        "--iters",
        type=int,
        default=100,
        help=
        "Number of iterations to run tournament-based methods for. 100 is likely sufficient to ensure convergence, if not a little overkill."
    )

    args = parser.parse_args()

    # determine the column seperator for our input data
    sep = args.sep
    if sep == None and args.input.endswith(".tsv"):
        sep = "\t"
    elif sep == None:
        sep = ","

    # read in latent values from the input data
    latent_values = {}
    ss = Spreadsheet.read_csv(args.input, delimiter=sep)
    for row in ss:
        latent_values[str(row[args.item])] = row[args.latentvalue]

    # get the names of our unique items
    items = latent_values.keys()

    # parse our N and K
    K = args.K
    N = args.N

    # generate trials from items
    trials = []
    if args.generator == "norepeateven":
        trials = trialgen.build_trials_even_bigram_norepeat(items, N=N, K=K)
    elif args.generator == 'even':
        trials = trialgen.build_trials_even(items, N=N, K=K)
    elif args.generator == 'random':
        trials = trialgen.build_trials_random(items, N=N, K=K)
    elif args.generator == "norepeat":
        trials = trialgen.build_trials_random_bigram_norepeat(items, N=N, K=K)
    else:
        raise Exception(
            "You must specify a proper generation method: norepeateven, even, random, norepeat."
        )

    # sort words in each trial by their latent value, plus noise
    trials = [sort_words(trial, latent_values, args.noise) for trial in trials]

    # convert the trials into format: (best, worst, (others,))
    trials = [(trial[0], trial[-1], tuple(trial[1:-1])) for trial in trials]

    # perform scoring. This takes awhile.
    methods = [
        "Value", "Elo", "RW", "Best", "Worst", "Unchosen", "BestWorst", "ABW",
        "David", "ValueLogit", "RWLogit", "BestWorstLogit"
    ]
    results = scoring.score_trials(trials,
                                   methods,
                                   iters=args.iters,
                                   dummy=args.dummy)

    # print the header and results
    header = [args.item, args.latentvalue] + methods
    print ",".join(header)
    for name, data in results.iteritems():
        # skip dummy items
        if type(name) != str:
            continue

        scores = [scoring.scoring_methods[method](data) for method in methods]
        out = [name, latent_values[name]] + [str(score) for score in scores]
        print ",".join([str(v) for v in out])
Esempio n. 30
0
    exit(1)

sleep_Period = cfg['DHT']['Period']
site_For_Check = cfg['Main']['Site_for_check'].lower()
mail_Status = cfg['email']['Mail_status']
spreadsheet_Status = cfg['Spreadsheet']['Status']
clear_spreadsheet_on_start = cfg['Spreadsheet']['Clear spreadsheet on start']
send_by_str = cfg['Spreadsheet']['Send_by_str']
period_before_send = cfg['Main']['Period_before_send'].split(',')
period_before_archive = cfg['Main']['Period_before_arch'].split(',')

# Создаем экземляры классов
temp_logfile = File(Path, path_To_Temperature_Log, logger)
sensor = Sensor(logger, cfg.get('DHT'))
mail = Mail(temp_logfile, logger, cfg.get('email'))
spr_sheet = Spreadsheet(logger, Path, path_To_Temperature_Log,
                        cfg.get('Spreadsheet'))

# Если есть инет, пробуем законнектится
if is_Connected(site_For_Check) == True:
    # Инициализруем почту, если включена отправка почты
    if mail_Status is True:
        mail.login()
        is_Connected_To_Mail = True

    # Инициализруем гугл докс, если они включены в конфиге
    if spreadsheet_Status is True:
        # Логинимся и открываем таблицу
        spr_sheet.login()
        spr_sheet.open()

        # Если нужно, отчищаем гугл таблицу при старте
 def test_get_sheet(self):
     spreadsheet = Spreadsheet()
     self.assertFalse('Stats' in spreadsheet.workbook.sheetnames)
     sheet = spreadsheet.get_sheet('Stats')
     self.assertEqual(sheet.title, 'Stats')
Esempio n. 32
0
def cli_read(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.read(args.reset)
 def test_select_sheet(self):
     spreadsheet = Spreadsheet()
     self.assertNotEqual(spreadsheet.current_sheet().title, 'Stats')
     spreadsheet.select_sheet('Stats')
     self.assertEqual(spreadsheet.current_sheet().title, 'Stats')
Esempio n. 34
0
def cli_write(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.write(args.spreadsheet_dir, args.editable, args.reset)
 def test_cells(self):
     spreadsheet = Spreadsheet()
     self.assertEqual(spreadsheet.current_cell(), 'A1')
     spreadsheet.set_value('1')
     self.assertEqual(spreadsheet.current_cell(), 'B1')
     spreadsheet.set_value('1', advance_row=True)
     self.assertEqual(spreadsheet.current_cell(), 'A2')
     spreadsheet.set_value('1', advance_by_rows=3)
     self.assertEqual(spreadsheet.current_cell(), 'A5')
     spreadsheet.set_values(['1'])
     self.assertEqual(spreadsheet.current_cell(), 'A6')
Esempio n. 36
0
def check_requests(request_type, auth_file, worksheet_key):
    """Check for new approved requests"""
    # Some definitions that should eventually be set in config
    TIMESTAMP_FORMAT = "%d %b %Y %H:%M:%S"
    # hours until first reminder sent
    reminder_start = timedelta(hours=int(config.get('reminder', 'start')))
    # interval to send subsequent reminders
    reminder_interval = timedelta(
        hours=int(config.get('reminder', 'interval')))
    sheet = Spreadsheet(keyfile=auth_file, sheet_id=worksheet_key)
    rows = sheet.get_all_rows('Form Responses 1')
    timestamp = datetime.now().strftime(TIMESTAMP_FORMAT)
    processed_rows = []
    reminder_list = []
    reminder_rows = []
    now = datetime.now()

    # set some type-specific things
    if request_type == 'Access':
        parse_function = parse_user_row
        csr_type = 'Access Request'

    elif request_type == 'Quota':
        parse_function = parse_quota_row
        csr_type = 'Change Quota'
    else:
        raise Exception('Unknown request type: `{}`'.format(request_type))

    for idx, row in enumerate(rows):

        if (idx == 0) or (row == []):
            # skip header row and blank rows
            continue

        elif (row[0].lower().strip() == 'approved') and (row[1] == ''):
            # process rows that are marked approved but not notified
            request_info = parse_function(row)
            notify_helpdesk(csr_type=csr_type,
                            priority='High',
                            queue='Monitoring',
                            **request_info)

            processed_rows.append(idx)
            if args.log:
                log_request(args.log, timestamp, request_info['user_email'])

        # if request is not approved and is more than `reminder_start`
        # hours old, send a reminder
        elif row[0] == '' and (now >=
                               dateparser.parse(row[3]) + reminder_start):
            # but only send if this is the first one, or if enough time
            # has passed since the last one
            if row[2]:
                last_sent = datetime.strptime(row[2], TIMESTAMP_FORMAT)
            else:
                last_sent = None

            if not last_sent or (now >= last_sent + reminder_interval):
                request_info = parse_function(row)
                reminder_list.append(request_info)
                reminder_rows.append(idx)
        else:
            # skip over unapproved rows <24 hours old, or already-notified rows
            continue

    # Skip sending empty requests to Google API because it is slow and returns
    # an error.  Try/catch would handle the error but not avoid the time cost.
    if processed_rows:
        timestamp_spreadsheet(sheet, timestamp, processed_rows, column=1)

    if reminder_list:
        send_reminder(request_type=request_type,
                      reminders=reminder_list,
                      worksheet_key=worksheet_key)
        timestamp_spreadsheet(sheet, timestamp, reminder_rows, column=2)
Esempio n. 37
0
import yaml
from spreadsheet import Spreadsheet
from garo_gm3d import Garo

with open("config.yml", "r") as ymlfile:
    cfg = yaml.load(ymlfile)

print "Listening to energy meter on gpio pin {0}".format(cfg["gpio_pin"])
print 'Loading oauth info from the file "{0}"'.format(cfg["gdocs_oauth_json"])
print 'Logging energy meter to spreadsheet  "{0}" every {1} seconds.'.format(
    cfg["gdocs_spreadsheet_name"], cfg["frequency_seconds"]
)
print "Press Ctrl-C to quit."

# Initialize the spreadsheet
spreadsheet = Spreadsheet(cfg["gdocs_oauth_json"], cfg["gdocs_spreadsheet_name"], cfg["gdocs_spreadsheet_worksheet"])

# Get the current energy meter standing from the spreadsheet on cell B1
current_watt_hours = spreadsheet.get_cell_value("B1")
current_watt_hours = int(current_watt_hours)
print "Current energy meter standing (as read from the spreadsheet in column B1) is {}Wh".format(current_watt_hours)

# Initialize the Garo GM3D
garo = Garo(cfg["gpio_pin"], current_watt_hours)
garo.listen()

while True:
    current_watt_hours = garo.get_watt_hours()
    spreadsheet.append_row((datetime.datetime.now(), current_watt_hours))
    spreadsheet.update_cell_value("B1", current_watt_hours)
    time.sleep(cfg["frequency_seconds"])
Esempio n. 38
0
def cli_summary_read(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_read(args.spreadsheet_dir, args.reset)
Esempio n. 39
0
 def test_set_value_without_references(self):
     ss = Spreadsheet(self.basic_data)
     new_value = ss.get_value(4, 5) + 10
     ss.set_value(4, 5, str(new_value))
     self.assertEquals(ss.get_value(4, 5), new_value)
Esempio n. 40
0
def cli_summary_transform(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_transform(args.fracking)
Esempio n. 41
0
def import_to_googlesheets(records, search_term, credentials):
    ss = Spreadsheet(credentials, debug_mode=False)
    try:
        f = open('temp.txt', 'x')
        email = input('Email: ')
        ss.create('Amazon', search_term)
        ss.share_with_email_for_writing(email)
        f.write(ss.spreadsheet_id)
        f.close()
    except FileExistsError:
        f = open('temp.txt', 'r')
        ss.set_spreadsheet_by_id(f.read())
        try:
            ss.add_sheet(search_term)
        except googleapiclient.errors.HttpError:
            ss.set_sheet_by_title(search_term)
            ss.clear_sheet()
        f.close()
    finally:
        ss.prepare_set_values('A1:E1', [['Name', 'Price', 'Rating', 'Reviews', 'Url']])
        ss.prepare_set_values('A2:E%d' % (len(records) + 1), records)
        ss.run_prepared()
Esempio n. 42
0
def cli_summary_write(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_write(args.spreadsheet_dir)
Esempio n. 43
0
def cli_matches(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.matches(args.spreadsheet_dir)
def main(argv = sys.argv[1:]):
    parser = argparse.ArgumentParser(description='Command line for filtering noncompliant participants from best-worst data.')
    parser.add_argument("scores", type=str, help="Path to a file containing scores computed over all users (including noncompliant ones).")
    parser.add_argument("input", nargs="*", type=str, help="Path to a file(s) containing trial-level data.")
    parser.add_argument("--id_column", type=str, default=None, help="A column in your input data that specifies user ID. If no value is supplied, uses the name of the file.")
    parser.add_argument("--best", type=str, default="best", help="Name of column that holds string of 'best' choice.")
    parser.add_argument("--worst", type=str, default="worst", help="Name of column that holds string of 'worst' choice.")
    parser.add_argument("--score_method", type=str, default="Value", help="The scoring method to calculate compliance by.")
    parser.add_argument("--filter", type=float, default=None, help="If you want to filter users by compliance, specify the threshold here. The output will be the trials for just users who met your threshold of compliance, as a single file. This can be submitted to score_trials.py for rescoring.")

    args = parser.parse_args()

    # read the scores
    ss = Spreadsheet.read_csv(args.scores)
    scores = { }
    for row in ss:
        scores[row[0]] = row[args.score_method]

    # go through each file and calculate participant compliance and log their
    # trials
    compliance  = { }
    paircount   = { }
    user_trials = { }
    
    for file in args.input:
        # if a participant ID column is not specified, use the name of the file.
        # Otherwise, use values in the specified column to determine ID.
        id_col = None
        if args.id_column != None:
            ss = Spreadsheet.read_csv(file)
            id_col = ss[args.id_column]
                        
        # read in the user's data, calculate compliance for each trial
        trials = scoring.parse_bestworst_data(file, bestCol=args.best, worstCol=args.worst)
        # generate a user ID based on the file name
        if id_col == None:
            id_col = [ file ] * len(trials)

        # check for agreement on each trial
        for i in xrange(len(trials)):
            id    = id_col[i]
            trial = trials[i]
            best, worst, others = trial
            
            # something funny going on in your data; check it out
            duplic = best == worst
            # skip trial if best == worst
            if duplic == True:
                continue

            # set default values for participant if needed
            if id not in compliance:
                compliance[id] = 0
                paircount[id]  = 0
                user_trials[id]= [ ]

            # calculate compliance
            pairs = [ (best, other) for other in ((worst,) + others) ] + [ (other, worst) for other in others ]
            consistent = [ scores[pair[0]] > scores[pair[1]] for pair in pairs ]
            compliance[id] += sum(consistent)
            paircount[id]  += len(pairs)
            user_trials[id].append(trial)
                
    # calculate overall accuracy for each participant
    accuracy = { }
    for user in compliance.iterkeys():
        accuracy[user] = float(compliance[user]) / paircount[user]

    # print compliance for each person
    if args.filter == None:
        # sort users by their accuracy
        users = accuracy.keys()
        users.sort(lambda a,b: cmp(accuracy[a], accuracy[b]), reverse=True)

        print "ID,Compliance"
        for user in users:
            print "%s,%0.3f" % (str(user), accuracy[user])
            
    # print trials for users that meet the filter threshold
    else:
        user_count = 0
        for user in accuracy.iterkeys():
            # skip by everyone who doesn't make the cut
            if accuracy[user] < args.filter:
                continue

            # print out data for everyone else
            best,worst,others = user_trials[user][0]
            options = list(others)

            # do we need to print the header?
            if user_count == 0:
                optCols = [ "option%d" % (i+1) for i in xrange(len(options)) ]
                header  = [ "User", "best", "worst" ] + optCols
                print ",".join(header)

            # print out each trial for the user
            for trial in user_trials[user]:
                best,worst, others = trial
                options = list(others)

                out = [ user, best, worst ] + options
                out = [ str(v) for v in out ]
                print ",".join(out)

            # increment our users
            user_count += 1