def __init__(self, todolist, parent=None, *args): """ variabledict dictionary of variable value pairs as defined in the pulse programmer file parameterdict dictionary of parameter value pairs that can be used to calculate the value of a variable """ QtCore.QAbstractTableModel.__init__(self, parent, *args) self.todolist = todolist self.dataLookup = { (QtCore.Qt.CheckStateRole, 0): lambda row: QtCore.Qt.Checked if self.todolist[row].enabled else QtCore.Qt.Unchecked, (QtCore.Qt.DisplayRole, 1): lambda row: self.todolist[row].scan, (QtCore.Qt.DisplayRole, 2): lambda row: self.todolist[row].measurement, (QtCore.Qt.DisplayRole, 3): lambda row: self.todolist[row].evaluation, (QtCore.Qt.DisplayRole, 4): lambda row: self.todolist[row].analysis, (QtCore.Qt.EditRole, 1): lambda row: self.todolist[row].scan, (QtCore.Qt.EditRole, 2): lambda row: self.todolist[row].measurement, (QtCore.Qt.EditRole, 3): lambda row: self.todolist[row].evaluation, (QtCore.Qt.EditRole, 4): lambda row: self.todolist[row].analysis, (QtCore.Qt.BackgroundColorRole, 1): lambda row: self.colorLookup[self.running] if self.activeRow==row else QtCore.Qt.white, (QtCore.Qt.BackgroundColorRole, 0): lambda row: self.colorStopFlagLookup[self.todolist[row].stopFlag] } self.setDataLookup ={ (QtCore.Qt.CheckStateRole, 0): self.setEntryEnabled, (QtCore.Qt.EditRole, 1): partial( self.setString, 'scan' ), (QtCore.Qt.EditRole, 2): partial( self.setString, 'measurement' ), (QtCore.Qt.EditRole, 3): partial( self.setString, 'evaluation' ), (QtCore.Qt.EditRole, 4): partial( self.setString, 'analysis' ) } self.colorLookup = { True: QtGui.QColor(0xd0, 0xff, 0xd0), False: QtGui.QColor(0xff, 0xd0, 0xd0) } self.colorStopFlagLookup = {True: QtGui.QColor( 0xcb, 0x4e, 0x28), False: QtCore.Qt.white} self.activeRow = None self.tabSelection = [] self.measurementSelection = {} self.evaluationSelection = {} self.analysisSelection = {} self.choiceLookup = { 1: lambda row: list(self.measurementSelection.keys()), 2: lambda row: self.measurementSelection[self.todolist[row].scan], 3: lambda row: self.evaluationSelection[self.todolist[row].scan], 4: lambda row: self.analysisSelection[self.todolist[row].scan]}
def setupUi(self, parent): Form.setupUi(self, parent) self.actionRun.triggered.connect( self.onRun ) self.actionStop.triggered.connect( self.onStop ) self.actionSingle.triggered.connect( self.onSingle ) self._graphicsView = self.graphicsLayout._graphicsView self.signalTableModel = LogicAnalyzerSignalTableModel(self.config, self.channelNameData) self.signalTableView.setModel(self.signalTableModel) self.signalTableView.resizeColumnsToContents() if 'LogicAnalyzer.State' in self.config: self.restoreState(self.config['LogicAnalyzer.State']) self.signalTableModel.enableChanged.connect( self.refresh ) self.headerView = RotatedHeaderView(QtCore.Qt.Horizontal ) self.traceTableView.setHorizontalHeader( self.headerView ) self.traceTableModel = LogicAnalyzerTraceTableModel(self.config, self.signalTableModel) self.traceTableView.setModel( self.traceTableModel ) self.traceTableView.resizeColumnsToContents() self.traceTableView.doubleClicked.connect( self.traceTableModel.setReferenceTimeCell ) # Context Menu for Table self.signalTableView.setContextMenuPolicy( QtCore.Qt.ActionsContextMenu ) self.hideSelectedAction = QtWidgets.QAction( "hide selected", self) self.showSelectedAction = QtWidgets.QAction( "show selected", self) self.hideSelectedAction.triggered.connect( partial(self.onShow, False) ) self.showSelectedAction.triggered.connect( partial(self.onShow, True) ) self.signalTableView.addAction( self.hideSelectedAction ) self.signalTableView.addAction( self.showSelectedAction ) restoreGuiState( self, self.config.get('LogicAnalyzer.guiState') )
def obtener_metodos(self,nombre_objeto, objeto, menu, item): metodos = type(objeto).mro()[0].__dict__ for metodo in metodos.keys(): if metodo[0]<>'_' and metodo<>'iniciar': parametros = inspect.getargspec(metodos[metodo]) men_agregar_metodo = menu.addAction(self.tr(metodo)) men_agregar_metodo.triggered.connect(partial(self.llamar_metodo,nombre_metodo=str(metodo),nombre_objeto=nombre_objeto,parametros=parametros[0])) men_agregar_metodo_eliminar = menu.addAction('eliminar') men_agregar_metodo_eliminar.triggered.connect(partial(self.eliminar_objeto,nombre_objeto=nombre_objeto,item=item))
def __init__(self, parent = None): super(SubmissionWindow, self).__init__(parent) self.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.submitPushButton.clicked.connect(self.submitCmd) self.resetPushButton.clicked.connect(self.resetCmd) self.removePushButton.clicked.connect(self.removeCmd) self.lrPushButton.clicked.connect(partial(self.departmentListCmd, ['lr', 'cp'])) self.fxPushButton.clicked.connect(partial(self.departmentListCmd, ['ef'])) self.resetCmd()
def setupUi(self,parent,extraKeywords1=[], extraKeywords2=[]): Form.setupUi(self, parent, extraKeywords1=extraKeywords1, extraKeywords2=extraKeywords2) self.findLineEdit.textChanged.connect( self.onFindTextChanged ) self.findCloseButton.clicked.connect( self.onFindClose ) self.findMatchCaseCheckBox.stateChanged.connect( partial( self.onFindFlagsChanged, 'findCaseSensitive') ) self.findWholeWordsCheckBox.stateChanged.connect( partial(self.onFindFlagsChanged, 'findWordOnly') ) self.findNextButton.clicked.connect( self.onFind ) self.findPreviousButton.clicked.connect( functools.partial(self.onFind, True)) self.errorDisplay.hide() self.findWidgetFrame.hide() self.closeErrorButton.clicked.connect( self.clearHighlightError ) self.addAction(self.actionFind) self.addAction(self.actionFindNext)
def abrir_menu_interno_mundo(self, position): items = self.arbolMundo.selectedItems() level = 0 if len(items) > 0: item = items[0] level = 1 menu = QMenu() if level == 0: men_agregar_clase = menu.addAction(self.tr("Agregar Clase")) men_agregar_clase.triggered.connect(partial(self.abrir_ventana_nueva_clase,arbol=self.arbolMundo)) elif level == 1: men_agregar_clase = menu.addAction(self.tr("Crear Fondo")) men_agregar_clase.triggered.connect(partial(self.crear_objeto,nombre_clase=str(item.text(0)))) menu.exec_(self.arbolMundo.viewport().mapToGlobal(position))
def submitCmd(self): ''' submit images from sw. to production path ''' model = self.tableView.model() row = model.rowCount() column = model.columnCount() indexLst = [model.index(i,5) for i in range(row)] threads = [SubmitWorker() for i in range(row)] for i in range(row): index = indexLst[i] subThread = threads[i] subThread.progressSignal.connect(partial(model.setData, index)) subThread.start(model.getData()[i]) subThread.finishSignal.connect(partial(self.setFlagCmd, index))
def request_handler(self): try: req = Request.from_file(self.rfile) except socket_error: # Customer connection has been lost. return except ValueError: # The request received is invalid. return app_environ = dict(req.environ, **{ 'WEBX.IS_VIRTUAL_HOST': False, 'WEBX.PATH_APP': '', 'WEBX.PATH_HANDLER': req.environ.get('PATH_INFO', '/'), 'WEBX.PATH_ACTION': req.environ.get('PATH_INFO', '/'), }) try: app_req = self.APP.request_maker(app_environ) app_req.headers.update(req.headers) app_req.body = req.body res = self.APP_RUNNER.request_handler(self.APP, app_req) except: res = self.APP_RUNNER.error_handler(req, exc_info()) for chunk in res(app_environ, partial(self.start_response, req.http_version)): self.wfile.write(chunk) # Sends a blank line after the response is sent. self.wfile.write('\r\n') self.wfile.flush() return req.headers.get('Connection') == 'keep-alive'
def maximize(self): """ Maximizes the given acquisition function. Returns ------- np.ndarray(N,D) Point with highest acquisition value. """ cand = np.zeros([self.n_restarts, self.X_lower.shape[0]]) cand_vals = np.zeros([self.n_restarts]) f = partial(self._acquisition_fkt_wrapper, acq_f=self.objective_func) for i in range(self.n_restarts): start = np.array([self.rng.uniform(self.X_lower, self.X_upper, self.X_lower.shape[0])]) res = optimize.minimize( f, start, method="L-BFGS-B", bounds=zip( self.X_lower, self.X_upper), options={ "disp": self.verbosity}) cand[i] = res["x"] cand_vals[i] = res["fun"] best = np.argmax(cand_vals) return np.array([cand[best]])
def maximize(self): """ Maximizes the given acquisition function. Returns ------- np.ndarray(N,D) Point with highest acquisition value. """ cand = np.zeros([self.n_restarts, self.X_lower.shape[0]]) cand_vals = np.zeros([self.n_restarts]) f = partial(self._acquisition_fkt_wrapper, acq_f=self.objective_func) for i in range(self.n_restarts): start = np.array([self.rng.uniform(self.X_lower, self.X_upper, self.X_lower.shape[0])]) res = optimize.basinhopping( f, start, minimizer_kwargs={ "bounds": zip( self.X_lower, self.X_upper), "method": "L-BFGS-B"}, disp=self.verbosity) cand[i] = res.x cand_vals[i] = res.fun best = np.argmax(cand_vals) return np.array([cand[best]])
def config_setter(name, type=None): # @ReservedAssignment if not hasattr(config, name): raise KeyError('No configuration key name (%r).' % (name, )) setter = partial(setattr, config, name) if type is not None: return lambda value: setter(type(value)) return setter
def run(self): self.mutex.lock() if self.data[2]: self.framesLst = fun.getFrames(self.data[2]) self.counts = len(self.framesLst) while self.working: if self.counts > 1: try: fun.copyCmd(self.data[1], self.uploadPath, self.framesLst[self.count]) except: #self.working = False continue else : try: fun.copyCmd(self.data[1], self.uploadPath) except: #self.working = False continue self.percent = self.count*100/self.counts self.progressSignal.emit(self.percent) time.sleep(1) self.count += 1 if self.count >= self.counts: self.working = False self.percent = 100 self.progressSignal.emit(self.percent) self.finished.connect(partial(self.sendFinishFlag, self.percent)) self.mutex.unlock()
def abrir_menu_interno_actores(self, position): self.men_popup_actores.clear() items = self.arbolActores.selectedItems() level = 0 if len(items) > 0: item = items[0] level = 1 if level == 0: accion = self.men_popup_actores.addAction(self.tr("Agregar Clase")) accion.triggered[()].connect(partial(self.abrir_ventana_nueva_clase,arbol=self.arbolActores)) elif level == 1: accion = self.men_popup_actores.addAction(self.tr("Crear Objeto")) accion.triggered[()].connect(partial(self.crear_objeto,nombre_clase=str(item.text(0)))) accion = self.men_popup_actores.addAction(self.tr("Abrir Editor")) ruta_clase = os.path.join(self.ruta_proyecto,str(item.text(0))+".py") accion.triggered[()].connect(partial(self.abrir_editor,ruta=ruta_clase)) self.men_popup_actores.exec_(self.arbolActores.viewport().mapToGlobal(position))
def __init__(self, parameters, container=None, parent=None, *args): QtCore.QAbstractTableModel.__init__(self, parent, *args) self.container = container # parameters are given as a list self.parameters = parameters self.dataLookup = { (QtCore.Qt.DisplayRole, 0): lambda row: self.parameters[row].space.name, (QtCore.Qt.DisplayRole, 1): lambda row: self.parameters[row].name, (QtCore.Qt.DisplayRole, 2): lambda row: str(self.parameters[row].value), (QtCore.Qt.DisplayRole, 3): lambda row: self.parameters[row].definition, (QtCore.Qt.EditRole, 1): lambda row: self.parameters[row].name, (QtCore.Qt.EditRole, 2): lambda row: self.parameters[row].value, (QtCore.Qt.EditRole, 3): lambda row: self.parameters[row].definition } self.setDataLookup = { (QtCore.Qt.EditRole, 1): partial( self.setDataString, 'name' ), (QtCore.Qt.EditRole, 2): partial( self.setDataValue, 'value' ), (QtCore.Qt.EditRole, 3): partial( self.setDataString, 'definition' ) }
def _add_all_supported_output_formats(): """Add all `nx.write_XXX()` methods plus json & matplotlib funcs, above.""" prefix = 'write_' formats = {m[len(prefix):]: partial(_call_nx_write_func, getattr(nx, m)) for m in dir(nx) if m.startswith(prefix)} formats['json'] = _store_json formats['matplotlib'] = _draw_matplotlib_graph return formats
def addThrow(self, task): delay = task['duration'] skin, anim = self.getAnim('me_throw') self.add(skin) x, y = self.getMidXY() skin.position = x, y skin.do(skeleton.Animate(anim) + CallFunc(partial(self.addThrow2, skin, delay)))
def initSettingsBreakReminderScreen(self): self.settingsBreakReminderScreen = SettingsBreakReminderScreen() #Create Label Frame to enclose the settings options. self.breakReminderLabelFrame = tk.LabelFrame(self.settingsBreakReminderScreen, text="Break Reminder Settings") self.breakReminderLabelFrame.grid(row=1) #Create back button to navigate back to ETS Reminder Settings Screen self.backButton = tk.Button(self.settingsBreakReminderScreen, text="< Back", command=self.switchToSettingsETSReminderScreen) self.backButton.grid(row=0,column=0,sticky=tk.W) #Create menu for user to select number of minutes for break reminder self.breakReminderMinutesStringVar = tk.StringVar() self.breakReminderMinutesStringVar.set("Min") self.breakReminderMB = tk.Menubutton(self.breakReminderLabelFrame, text=self.breakReminderMinutesStringVar, textvariable=self.breakReminderMinutesStringVar, relief=tk.RAISED, width=6) self.breakReminderMB.grid(row=1,columnspan=2,stick=tk.W) #Link menu to menubutton self.breakReminderMB.menu = tk.Menu(self.breakReminderMB,tearoff=0) self.breakReminderMB["menu"] = self.breakReminderMB.menu #Add menu options self.breakReminderMB.menu.add_command(label="15",command=partial(self.breakReminderMinSelectedCommand,"15")) self.breakReminderMB.menu.add_command(label="30",command=partial(self.breakReminderMinSelectedCommand,"30")) self.breakReminderMB.menu.add_command(label="45",command=partial(self.breakReminderMinSelectedCommand,"45")) self.breakReminderMB.menu.add_command(label="60",command=partial(self.breakReminderMinSelectedCommand,"60")) #Add to menubar and string vars dictionaries self.menuButtonsDict[self.breakTimerInstance.getSettingsBreakReminderMinutesKey()] = self.breakReminderMB self.stringVarsDict[self.breakTimerInstance.getSettingsBreakReminderMinutesKey()] = self.breakReminderMinutesStringVar #Create a SAVE button self.saveSettingsButton = tk.Button(self.settingsBreakReminderScreen,text="Save",command=self.doSaveSettings) self.saveSettingsButton.grid(row=2,column=2) #Hide screen self.settingsBreakReminderScreen.grid_forget()
def btnCmd(self): rowCount = self.model.rowCount() indexLst = [self.model.index(i,2) for i in range(rowCount)] threads = [AThread(0, random.randint(1,10)) for i in range(rowCount)] for i in range(rowCount): th = threads[i] ind = indexLst[i] th.progressSignal.connect(partial(self.model.setData, ind)) th.start()
def transferWeights(self,targetMesh,influencesMapping,vertexTransferMode=None): ''' Transfer weights from self.mesh onto the targetMesh. Layers are always appended to the list of existing layers; if you wish to replace old layers, delete them after the transfer (doing so before might deform the mesh and mess up vertex transfer associations). :param str targetMesh: a mesh to perform transfer to :param dict influencesMapping: a dictionary of [source influence logical ID]->destination influence logical ID :param str vertexTransferMode: "closestPoint","uvSpace" or "vertexId" ''' call = partial(self.ngSkinLayerCmd,targetMesh,transferSkinData=True, influencesMapping=self.influencesMapToList(influencesMapping)) if vertexTransferMode is not None: call = partial(call,vertexTransferMode=vertexTransferMode) call()
def wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). This is a convenience function to simplify applying partial() to update_wrapper(). """ return partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
def __init__(self, parent = None): super(LeftRightChoiceWindow, self).__init__(parent) self.HBoxLayout = QtGui.QHBoxLayout() self.leftBtn = QtGui.QPushButton("Left", parent = self) self.HBoxLayout.addWidget(self.leftBtn) self.rightBtn = QtGui.QPushButton("Right", parent = self) self.HBoxLayout.addWidget(self.rightBtn) self.setLayout(self.HBoxLayout) self.setWindowTitle('Left Right Choice') self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.leftBtn.clicked.connect(partial(self.btnCmd, 'stereoCameraLeft')) self.rightBtn.clicked.connect(partial(self.btnCmd, 'stereoCameraRight')) self.projectMatch()
def __init__(self, model, cost_model, X_lower, X_upper, compute_incumbent, is_env_variable, n_representer=10, n_hals_vals=100, n_func_samples=100, **kwargs): self.cost_model = cost_model self.n_dims = X_lower.shape[0] self.is_env_variable = is_env_variable if compute_incumbent is env_optimize_posterior_mean_and_std: compute_incumbent = partial(compute_incumbent, is_env=is_env_variable) super(EnvEntropySearchMC, self).__init__(model, X_lower, X_upper, compute_incumbent, Nb=n_representer, Nf=n_func_samples, Np=n_hals_vals)
def __init__(self, parent = None): super(Seq2MovWnd, self).__init__(parent) self.setupUi(self) ### # set ui style self.progressBar.setStyleSheet(XPROGRESS_DEFAULT_STYLE) ### # self.splitter = QtGui.QSplitter(self) self.splitter.addWidget(self.rightFrame) self.splitter.addWidget(self.errorFrame) self.viewHorizontalLayout.addWidget(self.splitter) # self.seqBtn.clicked.connect(partial(self.pathCmd, 'seq')) self.movBtn.clicked.connect(partial(self.pathCmd, 'mov')) self.runBtn.clicked.connect(self.runCmd) self.seqLineEdit.editingFinished.connect(self.loadCmd)
def callback(self, obj): def save(pf): metadata = Metadata() metadata.copy(pf.metadata) mf = MFile(pf.filename) if mf is not None: mf.delete() return pf._save_and_rename(pf.filename, metadata) for f in self.tagger.get_files_from_objects(obj, save=True): f.set_pending() thread.run_task(partial(save, f), f._saving_finished, priority=2, thread_pool=f.tagger.save_thread_pool)
def algebraic_solver(equation, initial_values): """ Given a list of normalized sympy equations. Algebraically solve the system, i.e. returns a dictionary, e.g. {'a': 5, 'b': 10, 'c': 3} :param equations: :return dict: """ indexToVariable = {i: var for (i,var) in enumerate(initial_values.keys())} evalExp = partial(evalFunctions, equation, indexToVariable) result = minimize(evalExp, initial_values.values(), method='SLSQP', options={'ftol': 10**-9, 'maxiter': 10000}) return {indexToVariable[i]:val for (i,val) in enumerate(result.x)}
def export_result_table(self): export = self.ca.mapping[["Plate", "Well", "Site", "Gene Symbol", "siRNA ID", "Group", "Object count", "Outlyingness"]] filename = self.ca.output("cluster_result_table_%s.txt" % self.cluster_class.describe()) def _class_count(x, cls): res = numpy.float32((x == cls).sum()) / len(x) return res cluster = pandas.Series(self.mapping[self.mapping['Object count'] > 0]['Outlier clustering']) class_dict = dict([(j, "Cluster") for j in range(self.k+1)]) for class_i, name in class_dict.items(): export['%02d_%s' % (class_i, name)] = cluster.map(partial(_class_count, cls=class_i)) export.to_csv(filename, sep="\t")
def loadData(self): self.category_list = self.sc.textFile(os.environ['WORKDIR']+"yelp_dataset_challenge_academic_dataset/cat_subcat.csv").map(lambda line: (line.split(',')[0], line.split(','))) category_schema = StructType([ StructField("category", StringType(), True), StructField("sub_category", ArrayType(StringType()), True) ]) # self.category_list.registerTempTable("categories_list") # subcat = self.sqlContext.sql("SELECT sub_category FROM categories_list WHERE category = \"{0}\" LIMIT 1".format(self.category)) self.category_list = self.sqlContext.createDataFrame(self.category_list, category_schema) subcat = self.category_list.where(self.category_list.category == self.category).first().sub_category self.df_business = self.sqlContext.read.json(os.environ['WORKDIR']+"/yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_business.json") # self.df_business = self.sqlContext.read.json("s3n://ds-emr-spark/data/yelp_academic_dataset_business.json").cache() self.df_business = self.df_business.select("business_id", "latitude", "longitude", "categories") filter_business = partial(isBusinessLocalAndRelevant, latitude = self.loc_lat, longitude = self.loc_long, sub_categories = subcat) self.df_business = self.df_business.rdd.filter(filter_business) self.df_business = self.sqlContext.createDataFrame(self.df_business) self.df_business = self.df_business.select(self.df_business.business_id) schema_2 = StructType([ StructField("latitude", FloatType(), True), StructField("longitude", FloatType(), True) ]) schema = StructType([ StructField("cluster_centers", ArrayType(schema_2), True), StructField("user_id", StringType(), True) ]) self.user_locations = self.sqlContext.read.json(os.environ['WORKDIR']+"clustering_models/center_gmm.json/gmm", schema) filter_users = partial(isUserlocal, latitude = self.loc_lat, longitude = self.loc_long) self.user_locations = self.user_locations.rdd.filter(filter_users) self.user_locations = self.sqlContext.createDataFrame(self.user_locations) self.user_locations = self.user_locations.select(self.user_locations.user_id) self.df_review = self.sqlContext.read.json(os.environ['WORKDIR']+"yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_review.json")
def buildWidgets(self): cmds.setParent(self.columnL) for path in self.paths: # gather actual plugin files # if( `about -mac` ) '.bundle' '.so' plugins = [] for f in os.listdir(path): for x in ['.mll', '.py', '.pyc', '.nll.dll']: if f.lower().endswith(x): plugins.append(f) break # TODO: remove .pyc that are available as .py as well plugins.sort() # TODO: handle collapsing via cmds.optionVar(q="PluginManagerState") collapsed = False label = '%s - %i' % (path, len(plugins)) cmds.frameLayout(marginHeight=10, marginWidth=10, labelVisible=True, borderStyle="etchedIn", borderVisible=True, collapse=collapsed, collapsable=True, label=label, collapseCommand=partial(self.handleCollape, path), expandCommand=partial(self.handleCollape, path)) cmds.columnLayout(adjustableColumn=True) cbLabels = ['Loaded','Auto Load'] if len(plugins) > 1: allCb = cmds.checkBoxGrp(numberOfCheckBoxes=2, label='Apply To All', cal=[1,"left"], la2=cbLabels) cmds.separator(h=10, style='in') for p in plugins: cmds.checkBoxGrp(numberOfCheckBoxes=2, label=p, cal=[1,"left"], la2=cbLabels) cmds.setParent('..') cmds.setParent('..')
def __init__(self, joystick, button, debouncePeriod=None): """ :param joystick: wpilib.Joystick that contains the button to toggle :param button: Value of button that will act as toggle. Same value used in getRawButton() """ if debouncePeriod is not None: self.joystick = Toggle._SteadyDebounce(joystick, button, debouncePeriod) else: self.joystick = joystick self.joystick.get = partial(self.joystick.getRawButton, button) self.released = False self.toggle = False self.state = False
def export_result_table(self): export = self.ca.mapping[["Plate", "Well", "Site", "Gene Symbol", "siRNA ID", "Group", "Object count", "Outlyingness"]] filename = self.ca.output("result_table_%s.txt" % self.ca.classifier.describe()) def _class_count(x, cls): res = numpy.float32((x == cls).sum()) / len(x) return res class_dict = self.ca.get_object_classificaiton_dict() class_labels = pandas.Series(self.mapping[self.mapping['Object count'] > 0]['Object classification label']) for class_i, name in class_dict.items(): export['%02d_%s' % (class_i, name)] = class_labels.map(partial(_class_count, cls=class_i)) export.to_csv(filename, sep="\t")
def editar_revistas(id, titulo): QMessageBox.about( MainWindow, "info", "vas a editar el registro con id : " + str(id) + " titulo : " + titulo) ui_ventana_editar_revistas.setupUi(MainWindow) revista_a_editar = operaciones.obtener_revista_por_id(id) ui_ventana_editar_revistas.entrada_titulo_revista.setText( revista_a_editar.titulo) ui_ventana_editar_revistas.entrada_precio_revista.setText( str(revista_a_editar.precio)) ui_ventana_editar_revistas.entrada_ditribuidor_revista.setText( str(revista_a_editar.distribuidora)) ui_ventana_editar_revistas.entrada_numero_revista.setText( str(revista_a_editar.numero_revista)) ui_ventana_editar_revistas.entrada_date_entrega.setText( revista_a_editar.date_entrega) ui_ventana_editar_revistas.entrada_date_devolucion.setText( revista_a_editar.date_devolucion) ui_ventana_editar_revistas.boton_guardar_cambios_revista.clicked.connect( partial(guardar_cambios_revista, revista_a_editar.id))
def __init__(self, input_shape, fantasy_particles=1, n_cd=1, reset_pps_int=-1, **kwargs): CostCD.__init__(self, **kwargs) Persistent.__init__(self, reset_pps_int) if fantasy_particles == None: raise ValueError( "Please specify 'fantasy_particles = N' in the config file.") self.pps_shape = [fantasy_particles] + list(input_shape) """Initialize Fantasy particles """ if len(self.pps_shape) > 2 and (self.pps_shape[3] is None or self.pps_shape[2] is None): raise NotImplementedError("PCD cannot yet deal with dynamic " "dimension lengths. Hint: Use fixed " "length training and dynamic length " "sampling.") else: self.pps = theano.shared(np.cast[fx](np.random.uniform( 0, 1, self.pps_shape)), borrow=True) if self.pps.broadcastable != self.gibbs_step_(self.pps).broadcastable: rebroadcast = T.patternbroadcast(self.gibbs_step_(self.pps), self.pps.broadcastable) else: rebroadcast = self.gibbs_step_(self.pps) self.pps_gibbs_step = self.pps_gibbs_step_fun(rebroadcast) pps_input_step = partial(self.pps_gibbs_step, self.pps.get_value()) for _ in range(n_cd): self.callback_add(pps_input_step, Notifier.BATCH_FINISHED)