Example #1
0
    def load_events_file(self):
        # The QWidget widget is the base class of all user interface objects in PyQt4.
        w = QtGui.QWidget()
        # Set window size.
        w.resize(320, 240)
        # Set window title
        w.setWindowTitle("Hello World!")
        filename = QtGui.QFileDialog.getOpenFileName(
            w, 'Open File', '/', "Text Files (*.txt *.csv)")
        print(filename)

        try:
            df = pd.read_csv(str(filename))
            if not is_in(REQUIRED_COLS, df.columns):
                # display error message
                show_message("Dataframe must contain columns:\n\n{0}".format(
                    ", ".join(REQUIRED_COLS)))
            else:
                folder = os_path.dirname(str(filename))
                self.events_df = df
                self.events_df[
                    "next_img_name"] = folder + self.events_df["next_img_name"]
                self.images_names = df.next_img_name.unique()
                self.count = -1
                self.update_image(foward=True)
        except Exception as e:
            print(e)
            show_message("Not a valid dataframe")
Example #2
0
 def get_table(self, ikey, table, current_dict, factor):
     if not table.isEnabled():
         return
     ncols = table.columnCount()
     nrows = table.rowCount()
     current_dict[ikey] = []
     for irow in range(0, nrows):
         dict_row = []
         for icol in range(0, ncols):
             if not table.item(irow, icol):
                 current_dict[ikey] = []
                 show_message(
                     'Please provide all the fields for the %s table' %
                     ikey)
                 # dejo que salte el error en el try de accept
             text = table.item(irow, icol).text()
             text_parsed = convert_string(text)
             text_parsed = text_parsed * factor[icol]
             if ncols == 1:
                 current_dict[ikey].append(text_parsed)
             else:
                 dict_row.append(text_parsed)
         if dict_row != []:
             current_dict[ikey].append(dict_row)
     return
Example #3
0
    def plot_table(self):
        """
        plot the current angle-lift or lift-dc table
        """
        key = ''
        if self.sender().objectName() == "plot_lift_cd_pushButton":
            key = 'Cd'
        elif self.sender().objectName() == "plot_angle_lift_pushButton":
            key = 'Lv'
        assert (key != '')

        if key not in self.current_dict.keys() or self.current_dict[key] == []:
            show_message("Not valid data")
            return
        pg.setConfigOptions(background=None)
        pg.setConfigOptions(foreground='k')
        xdata = [item[0] for item in self.current_dict[key]]
        ydata = [item[1] for item in self.current_dict[key]]
        plot = pg.PlotWidget()
        set_plot(plot, "Angle [deg]" if key=='Lv' else "Lift[mm]", "Lift [mm]" \
                 if key=='Lv' else "Discharge Coefficient", "")
        dialog = QtWidgets.QDialog()
        dialog.setLayout(QtWidgets.QHBoxLayout())
        dialog.layout().addWidget(plot)
        dialog.setWindowTitle("Angle vs. Lift Plot" if key=='Lv' else \
                              "Lift vs. Discharge Coefficient")
        plot.plot(xdata, ydata, pen={'color': 'r', 'width': 1})
        dialog.exec_()
        return
Example #4
0
 def format_curve(self):
     curve_format_dialog = CurveFormatDialog()
     return_value = curve_format_dialog.exec_()
     if return_value:
         try:
             curve_item = self.current_selected_curve
             color = CURVE_COLORS[
                 curve_format_dialog.ui_cfd.color.currentText()]
             line_format = CURVE_LINE_FORMATS[
                 curve_format_dialog.ui_cfd.line_format.currentText()]
             width = curve_format_dialog.ui_cfd.width.value()
             pen = {'color': color, 'width': width, 'style': line_format}
             curve_item.setPen(pen)
             legend_text = self.curve_attributes[curve_item][0]
             plot_type = self.curve_attributes[curve_item][1]
             figure_number = self.curve_attributes[curve_item][2]
             # When the curve style is modified, we need to have a reference to
             # the label that matches with the curve. This information is stored
             # in the dictionary curve_attributes. Pyqtgraph dont provide
             # methods to change the item, so I must erease and insert it again.
             self.legends[plot_type][figure_number].removeItem(legend_text)
             self.legends[plot_type][figure_number].addItem(
                 curve_item, legend_text)
         except:
             show_message('Error trying to set the format of the curve')
Example #5
0
 def get_table(self, ikey, table, current_dict, factor=1.0):
     if not table.isEnabled():
         return True
     ncols = table.columnCount()
     nrows = table.rowCount()
     current_dict[ikey] = [] if ikey!='state_ini' else current_dict[ikey]
     for irow in range(0, nrows):
         dict_row = []
         for icol in range(0, ncols):
             if not table.item(irow,icol):
                 current_dict[ikey] = []
                 show_message('Please provide all the fields for the %s table'%ikey)
                 return False
             if not check_if_float(table.item(irow,icol).text(), ikey):
                 show_message('Please provide valid values for the %s table'%ikey)
                 current_dict[ikey] = []
                 return False
             text = table.item(irow,icol).text()
             text_parsed = convert_string(text)
             text_parsed = text_parsed*factor
             if ncols==1:
                 current_dict[ikey].append(text_parsed)
             else:
                 dict_row.append(text_parsed)
         if dict_row!=[]:
             current_dict[ikey].append(dict_row)
     return True
Example #6
0
 def log_training(self,epoch, iteration, iter, iter_size, stats, dur_iter, epoch_iter, verbose=True):
     stats = {f'training/{key}': value for key, value in stats.items()}
     loss_value = [value for value in stats.values()]
     self._log_losses(iteration, loss_stats=stats)
     show_message("epoch {:4d} | iter {:>12d}  {:>3d}/{:3d} | {:3.2f}s/iter {:d}s/epoch | losses {:>12.6f} {:>12.6f} ".format(
             epoch, iteration, iter, iter_size, dur_iter, epoch_iter, loss_value[0], loss_value[1]  ), verbose=verbose
              )
Example #7
0
    def start_game(self):
        if (len(self.users) == 0):
            show_message("No User Registed", "", 2)
            return

        self.game_started = True
        for user_index, user in enumerate(self.users):
            self.step_index += 1
            step = Step()
            step.user = user_index
            step.index = self.step_index
            step.action = "setup user"
            step.command = [
                user.username, user.avatar, self.nodes_list[user_index]
            ]
            self.broad_cast(step)

        step = Step()
        step.action = "start game"
        self.process(step)

        self.get_initial_funding()

        step = Step()
        step.action = "next turn"
        self.process(step)
Example #8
0
 def log_test(self, epoch, stats, verbose=True):
     if self.rank != 0: return
     stats = {f'test/{key}': value for key, value in stats.items()}
     self._log_losses(epoch, loss_stats=stats)
     show_message(
         f'Epoch: {epoch} | Losses: {[value for value in stats.values()]}',
         verbose=verbose)
Example #9
0
 def log_training(self, iteration, stats, verbose=True):
     if self.rank != 0: return
     stats = {f'training/{key}': value for key, value in stats.items()}
     self._log_losses(iteration, loss_stats=stats)
     show_message(
         f'Iteration: {iteration} | Losses: {[value for value in stats.values()]}',
         verbose=verbose)
Example #10
0
    def set_linear_table(self):
        """
        set a values defined with linear function (min/max user input) 
        in all the rows of the table
        """
        if self.sender() == self.ui_td.linear_diameter_pushButton:
            table = self.ui_td.diameter_tableWidget
            dialog_label1 = 'Insert First Diameter [mm]:'
            dialog_label2 = 'Insert Second Diameter [mm]:'
        elif self.sender() == self.ui_td.linear_temperature_pushButton:
            table = self.ui_td.temperature_tableWidget
            dialog_label1 = 'Insert First Temperature [K]:'
            dialog_label2 = 'Insert Second Temperature [K]:'
        else:
            return

        vals = []
        for i in range(0, 2):
            textval = self.input_dialog(dialog_label1 if i ==
                                        0 else dialog_label2)
            if textval == -1:
                return
            try:
                vals.append(float(textval))
            except:
                show_message("Wrong input value")
                return
        nrows = self.ui_td.nodalcoord_tableWidget.rowCount()
        vals = np.linspace(vals[0], vals[1], nrows)
        table.clearContents()
        for irow in range(0, nrows):
            it = QtWidgets.QTableWidgetItem(str(vals[irow]))
            it.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
            table.setItem(irow, 0, it)
        return
Example #11
0
    def __init__(self, stdscr):
        self.__stdscr = stdscr
        loading = Loading(stdscr)
        loading.start()

        try:
            cred = Credentials()
            flag, email, password = cred.get_credentials()
            if not flag:
                raise Exception("Invalid credentials")
            imap = IMAP(email, password)
            folders = imap.get_mailboxes()
            options = []
            for item in folders:
                options.append({
                    'title': item.replace('"', ''),
                    'Function': EMAIL_LIST,
                    'args': (item, imap)
                })
            options.append({'title': "Back", 'Function': None, 'args': None})
            loading.stop()
            Menu(self.__stdscr, options, "Folders")

        except:
            loading.stop()
            utils.show_message(self.__stdscr,
                               "Something went wrong! Press 'q' to go back")
Example #12
0
    def choose_component(self, component):
        if component == 'Globals':
            self.clear_comboboxes([0, 1, 2, 3])
            self.ui.variable.addItems(GLOBALS)
            return

        self.clear_comboboxes([0, 1, 2, 3])
        selected_rpms = self.get_list_items(self.ui.rpms)
        added_elements = []
        for irpm in selected_rpms:
            rpm_folder = os.path.join(self.current_run_dir, "RPM_%s" % irpm)
            if not os.path.isdir(rpm_folder):
                show_message("There is no folder for RPM %s" % irpm)
                return
            else:
                archives = [f for f in os.listdir(rpm_folder) if (COMPONENTS_DICT[component] \
                            in f and '.txt' in f and 'extras' not in f)]
                archives.sort()  # Para que me aparezcan en orden numerico
                for index, iarchive in enumerate(archives):
                    iarchive = iarchive.replace('.txt', '')
                    new_element = self.current_objects[component][int(
                        iarchive[-1])].object['label']
                    if new_element not in added_elements:
                        self.ui.element.addItem(new_element)
                        added_elements.append(new_element)

        self.choose_element(self.ui.element.currentText())
        return
Example #13
0
def estimate_average_rtf_on_filelist(filelist_path,
                                     config,
                                     model,
                                     verbose=True):
    device = next(model.parameters()).device
    config.training_config.test_filelist_path = filelist_path
    dataset = AudioDataset(config, training=False)
    mel_fn = MelSpectrogramFixed(sample_rate=config.data_config.sample_rate,
                                 n_fft=config.data_config.n_fft,
                                 win_length=config.data_config.win_length,
                                 hop_length=config.data_config.hop_length,
                                 f_min=config.data_config.f_min,
                                 f_max=config.data_config.f_max,
                                 n_mels=config.data_config.n_mels,
                                 window_fn=torch.hann_window).to(device)
    rtfs = []
    for i in (tqdm(range(len(dataset))) if verbose else range(len(dataset))):
        datapoint = dataset[i].to(device)
        mel = mel_fn(datapoint)[None]
        start = datetime.now()
        sample = model.forward(mel, store_intermediate_states=False)
        end = datetime.now()
        generation_time = (end - start).total_seconds()
        rtf = compute_rtf(sample,
                          generation_time,
                          sample_rate=config.data_config.sample_rate)
        rtfs.append(rtf)
    average_rtf = np.mean(rtfs)
    std_rtf = np.std(rtfs)

    show_message(f'DEVICE: {device}. average_rtf={average_rtf}, std={std_rtf}',
                 verbose=verbose)

    rtf_stats = {'rtfs': rtfs, 'average': average_rtf, 'std': std_rtf}
    return rtf_stats
Example #14
0
 def save_file(self, message_shown=True):
     create_folder()
     f = open("logs/data_third.txt", "w")
     f.write(str(self.result_value))
     if message_shown:
         show_message("Інформацію збережено до файлу logs/data_third.txt",
                      QMessageBox.Information)
     f.close()
Example #15
0
 def save_file(self, message_shown=True):
     create_folder()
     f = open("logs/data_fourth.txt", "w")
     f.write(str(self.logic.get_z()))
     if message_shown:
         show_message("Інформацію збережено до файлу logs/data_fourth.txt",
                      QMessageBox.Information)
     f.close()
Example #16
0
def print_variant():
    number = 102  # Номер заліковки
    variant = number % 10 + 1
    output = "Ім'я: Бугайчук Сергій Володимирович" + \
             "\nГрупа: ІО-01" + \
             "\nНомер у групі: 2"
    output += "\nВаріант: " + str(variant)
    show_message(output, QMessageBox.Information)
Example #17
0
 def change_item(self, item):
     i, j = item.row(), item.column()
     if item.text() != str(self.logic.graph[i][j]):
         if not can_convert_str_to_int(item.text()):
             show_message("Неправильно уведені дані")
             self.update_table()
         else:
             self.logic.graph[i][j] = self.logic.nx_graph[i][j]['weight'] = int(item.text())
Example #18
0
 def log_training(self, iteration, loss_stats, verbose=True):
     show_message(
         f"""Iteration {iteration} | Backbone loss {loss_stats['backbone_model/total_loss']} | Duration model {loss_stats['duration_model/total_loss']}""",
         verbose=verbose)
     self.logger.log(iteration,
                     loss_stats={
                         f'training/{key}': value
                         for key, value in loss_stats.items()
                     })
Example #19
0
 def success_simulation(self):
     if not show_errors(SIMULATOR_PATH) and not self.process_killed:
         show_message('Simulation Finished', 1)
         msg = "Do you want to generate the default Post Process?"
         reply = show_message(msg,4,QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No)
         if reply == QtWidgets.QMessageBox.Yes:
             self.plot_defaultPostProcess_after_run_f()
     self.process_killed = False
     return
Example #20
0
 def check_json_keys(self):
     """
     check if the loaded json include all the obligatory keys
     """
     for ikey in JSON_ATMOSPHERE_KEYS:
         if ikey not in self.current_dict.keys():
             show_message("Wrong number of keys in json default atmosphere archive")
             return False
     return True
Example #21
0
	def js_changed(self, index):
		if self.ui.comboBox_2.itemText(index) == "PBS":
			if not utils.check_PBS():
				utils.show_message("No PBS detected !")
				self.ui.comboBox_2.setCurrentIndex(0)
			else:
				self.jss = str(self.ui.comboBox_2.currentText())
		else:
			pass
		self.JobCenter.setjss(self.jss)
Example #22
0
    def __set_confirm_email_bar(self):
        '''Setup confirm email bar'''

        try:
            h, w = self.__stdscr.getmaxyx()
            self.__stdscr.clear()
            self.__set_email_list(isConfirm=True)

            while 1:
                key = self.__stdscr.getch()

                if key == curses.KEY_UP and self.__curr_confirm_index != 0:
                    self.__curr_confirm_index -= 1
                elif key == curses.KEY_DOWN and self.__curr_confirm_index != len(
                        self.__confirm_menu) - 1:
                    self.__curr_confirm_index += 1

                # TODO: Do the functionality according to choice of user
                elif key == curses.KEY_ENTER or key in [10, 13]:
                    if self.__curr_confirm_index == 0:
                        utils.show_status_message(self.__stdscr,
                                                  "Deleting email....",
                                                  isLoading=True)
                        try:
                            num = self.__imap.delete_email(self.__num -
                                                           self.__arr_position)

                            # Set the new mail count
                            self.__num = num

                            main_list_length = len(self.__main_list)

                            # Update the array
                            self.__main_list.pop(self.__arr_position)

                            if main_list_length - 1 == self.__arr_position:
                                self.__curr_position -= 1
                                self.__arr_position -= 1

                            # Show mail sent successfully message
                            utils.show_status_message(
                                self.__stdscr,
                                "Mail deleted Successfully",
                                time_to_show=1)
                        except Exception as e:
                            utils.show_status_message(self.__stdscr, str(e), 2)

                    self.__set_email_list()
                    break

                self.__set_email_list(isConfirm=True)
        except:
            utils.show_message(self.__stdscr,
                               "Something went wrong! Press 'q' to go back")
	def change_orientation(self,arg1,data):
		self.get_panel_properties()
		if self.orientation != backend.load_setting("orientation"):
			if self.orientation == None:
				backend.save_setting('orientation', 'bottom')
				backend.save_setting('size', self.size)
			else:
				utils.show_message(_('Menu needs to restart , restart now?'))
				backend.save_setting('orientation', self.orientation)
				backend.save_setting('size', self.size)
				sys.exit()
Example #24
0
 def load_configuration(self):
     (success, new_configuration) = load_configuration_aux(self, 'tube')
     if not success or not self.check_json_keys(new_configuration):
         return
     try:
         self.current_dict = new_configuration
         self.set_parameters()
         show_message('Configuration successfully loaded!', 1)
     except:
         show_message('Error trying to set the loaded configuration')
     return
Example #25
0
 def func():
     if which == 0 and self.universal[0].value(
     ) > self.logic.get_universal(1):
         self.universal[0].setValue(self.logic.get_universal(0))
         show_message("Укажіть правильний діапазон значень!")
     if which == 1 and self.universal[1].value(
     ) < self.logic.get_universal(0):
         self.universal[1].setValue(self.logic.get_universal(1))
         show_message("Укажіть правильний діапазон значень!")
     self.logic.set_universal(which, self.universal[which].value())
     self.synchronize()
Example #26
0
 def accept(self):
     success = False
     try:        
         self.current_dict['state_ini'][0] = float( self.ui_ad.density_lineEdit.text() )
         self.current_dict['state_ini'][1] = float( self.ui_ad.velocity_lineEdit.text() )
         self.current_dict['state_ini'][2] = float( self.ui_ad.pressure_lineEdit.text() )
         success = True
     except:
         show_message('Please check that all the fields has correct values')
     if success:
         self.close()
     return
Example #27
0
 def verify_data(self, rpms, cycles):
     for ilist in (rpms, cycles):
         if ilist == []:
             show_message('Please, select at least one RPM and one cycle')
             return False
     cbs = ['element', 'node']
     for icb in cbs:
         cb = self.ui.__getattribute__(icb)
         if cb.count() == 0:
             show_message('There are no items for %s' % (icb.capitalize()))
             return False
     return True
Example #28
0
def print_variant():
    g = 1  # Номер групи
    n = 2  # Номер у списку групи
    m = "IO"
    output = "Ім'я: Бугайчук Сергій Володимирович\n" + \
             "Група: " + str(m) + "-" + ("0" if g < 10 else "") + str(g) + \
             "\nНомер у групі: " + str(n)
    if m == "IO":
        n += 1
    variant = (n + g % 60) % 30 + 1
    output += "\nВаріант: " + str(variant)
    show_message(output, QMessageBox.Information)
Example #29
0
 def check_json_keys(self, configuration_to_check=None):
     """
     check if the loaded json include all the obligatory keys
     """
     if not configuration_to_check:
         configuration_to_check = self.current_dict
     for ikey in JSON_VALVE_KEYS:
         if ikey not in configuration_to_check.keys():
             show_message(
                 "Wrong number of keys in json default valve archive")
             return False
     return True
Example #30
0
    def __set_email_list(self, isConfirm=False):
        '''To show the list of emails'''

        try:
            # Get the height and width of standard screen
            h, w = self.__stdscr.getmaxyx()

            self.__stdscr.clear()

            # setup title
            title = "Emails in " + self.__directory_name
            utils.set_title(self.__stdscr, title)

            # Start of emali list
            start = 2
            i = 0

            # Loop over the list until the screen or list is ended
            while start < h - 5 and i < len(self.__display_list):
                # Check if the list item is focused
                is_focused = i == self.__curr_position

                # Show the email
                start = self.__set_mail_item(start,
                                             self.__display_list[i]['Subject'],
                                             self.__display_list[i]['From'],
                                             self.__display_list[i]['Date'],
                                             h,
                                             w,
                                             is_focused=is_focused)
                i += 1

            # Setup the confirm email bottom menu if isConfirm is True
            if isConfirm:
                rectangle(self.__stdscr, h - 4, 0, h - 1, w - 2)
                title = " Do you want to delete email? ".upper()
                self.__stdscr.attron(curses.A_BOLD)
                self.__stdscr.addstr(h - 4, 1, title)
                self.__stdscr.attroff(curses.A_BOLD)
                self.__display_confirm_bottom_bar_menu()
            else:
                # Setup the bottom bar as screen was cleared
                self.__setup_bottom_bar()

            # Refresh the layout
            self.__stdscr.refresh()

            # Return the total number of shown emails
            return i
        except:
            utils.show_message(self.__stdscr,
                               "Something went wrong! Press 'q' to go back")
Example #31
0
 def save_postpro(self):
     name = QtWidgets.QFileDialog.getSaveFileName(
         self, 'Save Post Process As', "./",
         "Hierarchical Data Format Files (*.hdf)")
     filename = name[0]
     filename = filename + '.hdf' if filename.find(
         '.hdf') == -1 else filename
     try:
         with h5py.File(filename, 'w') as outfile:
             for itypeplot in range(0, NTYPE_PLOTS):
                 for iplot in range(len(self.plots[itypeplot])):
                     # cada curva del plot, en formato (x,y)
                     plot_items = self.plots[itypeplot][iplot].getPlotItem(
                     ).listDataItems()
                     plot_data = None
                     legends = []
                     for index, idataitem in enumerate(plot_items):
                         data = idataitem.getData()
                         data = [[data[0][i], data[1][i]]
                                 for i in range(len(data[0]))]
                         data = np.array(data)
                         plot_data = np.concatenate(
                             (plot_data, data),
                             axis=0) if plot_data is not None else data
                         legends.append(self.legends[itypeplot]
                                        [iplot].items[index][1].text)
                     plot_dataset = outfile.create_dataset(
                         PLOT_ARGUMENTS[itypeplot]['title'] + ' ' +
                         str(iplot),
                         data=plot_data)
                     plot_dataset.attrs['title'] = str(
                         self.plots[itypeplot]
                         [iplot].getPlotItem().titleLabel.text)
                     plot_dataset.attrs['xlabel'] = str(
                         self.plots[itypeplot][iplot].getPlotItem().getAxis(
                             'bottom').labelText)
                     plot_dataset.attrs['xunits'] = str(
                         self.plots[itypeplot][iplot].getPlotItem().getAxis(
                             'bottom').labelUnits)
                     plot_dataset.attrs['ylabel'] = str(
                         self.plots[itypeplot][iplot].getPlotItem().getAxis(
                             'left').labelText)
                     plot_dataset.attrs['yunits'] = str(
                         self.plots[itypeplot][iplot].getPlotItem().getAxis(
                             'left').labelUnits)
                     plot_dataset.attrs['legends'] = legends
                     plot_dataset.attrs['nplots'] = len(plot_items)
         show_message('Post Process successfully saved!', 1)
     except:
         show_message('Error saving the archive %s' % filename)
     return
Example #32
0
    def run(self):
        """Called at interval, must return number (negative if error)"""
        raid = self.get_raid()
        for config_array, config_devices in self.get_config():
            try:
                status, mode, devices = raid[config_array][0:3]
                for config_device in config_devices.split(","):
                    config_device = config_device.strip()
                    if config_device not in devices:
                        devices_str = ""
                        for part in devices:
                            if len(devices_str) > 0:
                                devices_str += ", "
                            devices_str += part
                        error = "[%s (%s) - %s]: device %s is not present, current devices [%s]" % (config_array, mode, status, config_device, devices_str)
                        show_message(self.logger, logging.WARNING, error)
                        continue
            except KeyError:
                error = "[%s]: array doesn't exist" % config_array
                show_message(self.logger, logging.WARNING, error)
                continue

        for dev in raid:
            status, mode, _, total, count, ready = raid[dev]
            if total is not None and count is not None and total != count:
                error = "[%s (%s) - %s]: device count %s is less than total %s [%s]" % (dev, mode, status, count, total, ready)
                show_message(self.logger, logging.WARNING, error)
                continue
            if ready is not None and "_" in ready:
                error = "[%s (%s) - %s]: device ready contains non ready character [%s]" % (dev, mode, status, ready)
                show_message(self.logger, logging.WARNING, error)
                continue

        return 0
Example #33
0
	def store_settings(self):
		"""Stores orientation in settings"""
		if self.orientation != backend.load_setting("orientation"):
			if self.orientation is None:
				backend.save_setting('orientation', 'bottom')
				backend.save_setting('size', self.size)
			else:
				utils.show_message(_('Menu needs to restart , restart now?'))
				backend.save_setting('orientation', self.orientation)
				backend.save_setting('size', self.size)
				sys.exit()
		try:
			backend.save_setting('orientation', self.orientation)
			backend.save_setting('size', self.size)
		except:pass
Example #34
0
	def change_orientation(self,arg1,data):
		orient = self.applet.get_orient()
		self.orientation = None
		if orient == 1:
			self.orientation = 'top'
		else:
			self.orientation = 'bottom'
		if self.orientation != backend.load_setting("orientation"):
			if self.orientation is None:
				backend.save_setting('orientation', 'bottom')
				backend.save_setting('size', self.size)
			else:
				utils.show_message(_('Menu needs to restart , restart now?'))
				backend.save_setting('orientation', self.orientation)
				backend.save_setting('size', self.size)
				sys.exit()
Example #35
0
 def run(self):
     """Called at interval, must return number (negative if error)"""
     data = self.get_gateway()
     if data is not None:
         destination, gateway, flags, dev = data
         for config_ip, config_gateways in self.get_config():
             if destination == config_ip:
                 match = False
                 for config_gateway in config_gateways.split(","):
                     config_gateway = config_gateway.strip()
                     if gateway == config_gateway:
                         match = True
                 if not match:
                     text = "Destination %s has gateway %s (%s) not in [%s] in dev %s" % (destination, gateway, flags, config_gateways, dev)
                     show_message(self.logger, logging.WARNING, text)
     return 0
Example #36
0
    def store_settings(self):
        """Stores orientation in settings"""
        if self.orientation != backend.load_setting("orientation"):
            if self.orientation is None:
                backend.save_setting("orientation", "bottom")
                backend.save_setting("size", self.size)
            else:
                import utils

                utils.show_message(_("Menu needs to restart , restart now?"))
                backend.save_setting("orientation", self.orientation)
                backend.save_setting("size", self.size)
                sys.exit()
        try:
            backend.save_setting("orientation", self.orientation)
            backend.save_setting("size", self.size)
        except:
            pass
Example #37
0
	def bind_with_custom(self):
		print 'Using own key method - binding'
		x = commands.getoutput('xmodmap')
		if x.find('Super_L') == '-1' and Globals.Settings['Bind_Key'] == 'Super_L':
			os.system("xmodmap -e 'keycode 115 = Super_L'")
			os.system('xmodmap -e "add mod4 = Super_L"')
		try:
			from Xlib.display import Display
			from Xlib import X
			from globalkeybinding import GlobalKeyBinding
			gtk.gdk.threads_init ()
			keybinding = GlobalKeyBinding (Globals.Settings['Bind_Key'])
			keybinding.connect ('activate', self.bindkey_callback)
			keybinding.grab ()
			keybinding.start ()
		except:
			if Globals.FirstUse:
				utils.show_message('Please install python xlib')
			else:
				print 'Please install python xlib'
Example #38
0
    def run(self):
        """Called at interval, must return number (negative if error)"""
        arp = self.get_arp()
        for config_ip, config_macs in self.get_config():
            try:
                arp_mac, arp_dev = arp[config_ip]
                arp_mac = arp_mac.upper()
            except KeyError:
                continue

            match = False
            for config_mac in config_macs.split(","):
                config_mac = config_mac.strip().upper()
                if config_mac == arp_mac:
                    match = True

            if not match and arp_mac != "00:00:00:00:00:00":
                text = "IP %s with dev %s has mac %s not in [%s]" % (config_ip, arp_dev, arp_mac, config_macs)
                show_message(self.logger, logging.WARNING, text)
        return 0
Example #39
0
    def run(self):
        """Called at interval, must return number (negative if error)"""
        for device, config_code in self.get_config():
            error = None
            status, firmware, test, code = self.get_smart(device)
            device = device.split(" ")[0]
            if status is None:
                continue
            if status != "Enabled":
                error = "Device %s doesn't have SMART enabled: %s [%s]" % (device, status, code)
            elif test != "PASSED":
                error = "Device %s has test result: %s [%s]" % (device, test, code)
            elif code != int(config_code):
                error = "Device %s returned code %s instead of %s" % (device, code, config_code)
            elif firmware and device not in self.update_notified:
                self.update_notified.append(device)
                text = "Device %s has firmware update [%s]" % (device, code)
                show_message(self.logger, logging.INFO, text)
            if error is not None:
                show_message(self.logger, logging.WARNING, error)

        return 0
Example #40
0
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license. 
# Thank you for using free software!
#
#(c) Whise 2008, 2009 <*****@*****.**>
#
# GNOME MENU DIALOG
# Part of the GnoMenu
 
import sys
try:
	from Xlib import X, display, Xatom
	import Xlib
except:
	import utils
	utils.show_message("Dependency missing: python-xlib not installed.")
	sys.exit ()

def get_atom(display, atom_name):

	atom = XInternAtom(disp, atom_name, False)
	if atom == None:
		print "This action requires python xlib installed, please install it for the menu to appear"
		sys.exit ()
	return atom

# Get display
disp =  Xlib.display.Display()
# Get atoms for panel and run dialog menu
gnome_panel_atom = disp.intern_atom("_GNOME_PANEL_ACTION")
run_atom = disp.intern_atom("_GNOME_PANEL_ACTION_MAIN_MENU") #"_GNOME_PANEL_ACTION_RUN_DIALOG"
Example #41
0
                        raise Exception(msg % (module.name, "run", code))
                    log.debug(msg % (module.name, "run", code))
                    module.last_time = time()

                # Remove if no interval
                if module.interval == 0:
                    code = safe_call(module.unload, log, None, None, False)
                    log.debug(msg % (module.name, "unload", code))

                sleep(0.5)
    finally:
        # Attempt to unload modules
        for module in frozenset(modules):
            code = safe_call(module.unload, log, None, None, False)
            log.info(msg % (module.name, "unload", code))


if __name__ == "__main__":
    try:
        # open(get_base_dir() + sep + LOG_FILENAME, "w").close() # Clear log
        error_log = get_logger("Init", [stderr])
        error_flag = Event()
        safe_call(main, error_log, error_flag, None, False)
        if error_flag.is_set() and not flag_verbose_mode():
            show_message(error_log, logging.ERROR, "Error at main")
    except Exception as e:
        if not flag_verbose_mode():
            show_message(None, logging.ERROR, "Error at main: %s" % e)
        raise e
    exit()
Example #42
0
    def handle_event(self, method, params, connection_ref):
        """Handle RPC calls and notifications from the pool"""
        log.warn("@@ %s @@" % method)
        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()

        if method == "mining.notify":
            """Proxy just received information about new mining job"""

            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = params[:9]
            # print len(str(params)), len(merkle_branch)

            if clean_jobs:
                log.warn("--Clean Jobs!--")
                rpc_tx = {"method": "clean_job", "params": [], "id": "cj"}
                for c in ws_svr:
                    print "ws_svr"
                    print c
                    c.sendMessage(json.dumps(rpc_tx))
            """
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            """

            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs
            )

            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime)
            log.info(
                "New job %s for prevhash %s, clean_jobs=%s" % (job.job_id, utils.format_hash(job.prevhash), clean_jobs)
            )

            self.job_registry.add_template(job, clean_jobs)

        elif method == "mining.set_difficulty":
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)

            stratum_listener.DifficultySubscription.on_new_difficulty(difficulty)
            self.job_registry.set_difficulty(difficulty)

        elif method == "client.reconnect":
            (hostname, port, wait) = params[:3]
            new = list(self.job_registry.f.main_host[::])
            if hostname:
                new[0] = hostname
            if port:
                new[1] = port

            log.info("Server asked us to reconnect to %s:%d" % tuple(new))
            self.job_registry.f.reconnect(new[0], new[1], wait)

        elif method == "client.add_peers":
            """New peers which can be used on connection failure"""
            return False
            """
            peerlist = params[0] # TODO
            for peer in peerlist:
                self.job_registry.f.add_peer(peer)
            return True
            """
        elif method == "client.get_version":
            return "stratum-proxy/%s" % _version.VERSION

        elif method == "client.show_message":

            # Displays message from the server to the terminal
            utils.show_message(params[0])
            return True

        elif method == "mining.get_hashrate":
            return {}  # TODO

        elif method == "mining.get_temperature":
            return {}  # TODO

        else:
            """Pool just asked us for something which we don't support..."""
            log.error("Unhandled method %s with params %s" % (method, params))
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''

        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()
        
        if method == 'mining.notify':
            '''Proxy just received information about new mining job'''
            
            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = params[:9]
            #print len(str(params)), len(merkle_branch)
            
            '''
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            '''
        
            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                            job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
            
            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime)
            log.info("New job %s for prevhash %s, clean_jobs=%s" % \
                 (job.job_id, utils.format_hash(job.prevhash), clean_jobs))

            self.job_registry.add_template(job, clean_jobs)
            
            
            
        elif method == 'mining.set_difficulty':
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)
            
            stratum_listener.DifficultySubscription.on_new_difficulty(difficulty)
            self.job_registry.set_difficulty(difficulty)
                    
        elif method == 'client.reconnect':
            (hostname, port, wait) = params[:3]
            new = list(self.job_registry.f.main_host[::])
            if hostname: new[0] = hostname
            if port: new[1] = port

            log.info("Server asked us to reconnect to %s:%d" % tuple(new))
            self.job_registry.f.reconnect(new[0], new[1], wait)
            
        elif method == 'client.add_peers':
            '''New peers which can be used on connection failure'''
            return False
            '''
            peerlist = params[0] # TODO
            for peer in peerlist:
                self.job_registry.f.add_peer(peer)
            return True
            '''
        elif method == 'client.get_version':
            return "stratum-proxy/%s" % _version.VERSION

        elif method == 'client.show_message':
            
            # Displays message from the server to the terminal
            utils.show_message(params[0])
            return True
            
        elif method == 'mining.get_hashrate':
            return {} # TODO
        
        elif method == 'mining.get_temperature':
            return {} # TODO
        
        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))