rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
return Modifications | return Modification | def get_parent_model(self): return Modifications |
obj={'Model':Component,'Simulation':Simulation}[item[0]].objects.get(id=item[2][1]) | try: obj={'Model':Component,'Simulation':Simulation}[item[0]].objects.get(id=item[2][1]) except: logging.info('Attempt to access deleted component or simulation %s,%s'%(item[0],item[2][1])) return tab(item[0],'',-1) | def tabify(self,item,page): if item[0] not in ['Simulation','Model']: #it's easy: return tab(item[0],reverse(item[1],args=item[2]),page==item[0]) else: if item[2][1]==0: return tab(item[0],'',-1) else: obj={'Model':Component,'Simulation':Simulation}[item[0]].objects.get(id=item[2][1]) return tab('%s:%s'%(item[0][0:3],o... |
self.abbrev=old[0:25] | self.abbrev=old[0:24] | def __init__(self,filename): ''' Reads CIM format numerical experiments, create an experiment, and then link the numerical requirements in as well''' etree=ET.parse(filename) txt=open(filename,'r').read() logging.debug('Parsing experiment filename %s'%filename) |
name=models.CharField(max_length=64) note=models.CharField(max_length=128,blank=True) | name=models.CharField(max_length=256) note=models.CharField(max_length=256,blank=True) | def resetCoupling(self,closures=False): # we had some couplings, but we need to get rid of them for some reason # (usually because we've just change model) cgs=self.couplinggroup_set.all() if len(cgs)<>0: assert(len(cgs)==1,'Expect only one coupling group for simulation %s'%self) cg=cgs[0] cg.delete() # now put back th... |
e=ef.getroot() | cimns = 'http://www.metaforclimate.eu/schema/cim/1.5' cimdoclist=['{%s}modelComponent' %cimns,'{%s}platform' %cimns,'{%s}CIMRecord/{%s}CIMRecord/{%s}simulationRun' %(cimns,cimns,cimns)] for cimdoc in cimdoclist: if ef.getroot().find(cimdoc) is not None: e=ef.getroot().find(cimdoc) | def __init__(self,d,f): ff=os.path.join(d,f) ef=ET.parse(ff) e=ef.getroot() getter=etTxt(e) #basic document stuff for feed doc={'description':'description','shortName':'abbrev','longName':'title', 'documentCreationDate':'created','updated':'updated','documentID':'uri'} for key in doc.keys(): self.__setattr__(doc[key],g... |
if self.created=='':self.created=datetime.now() if self.updated=='':self.updated=datetime.now() | self.created=datetime.now() self.updated=datetime.now() | def __init__(self,d,f): ff=os.path.join(d,f) ef=ET.parse(ff) e=ef.getroot() getter=etTxt(e) #basic document stuff for feed doc={'description':'description','shortName':'abbrev','longName':'title', 'documentCreationDate':'created','updated':'updated','documentID':'uri'} for key in doc.keys(): self.__setattr__(doc[key],g... |
return 'Coupling4:%s(in %s)'%(self.targetInput,self.parent.simulation) | return 'CouplingFor:%s(in %s)'%(self.targetInput,self.parent.simulation) | def __unicode__(self): if self.parent.simulation: return 'Coupling4:%s(in %s)'%(self.targetInput,self.parent.simulation) else: return 'Coupling4:%s'%self.targetInput |
return 'Coupling4:%s'%self.targetInput | return 'CouplingFor:%s'%self.targetInput | def __unicode__(self): if self.parent.simulation: return 'Coupling4:%s(in %s)'%(self.targetInput,self.parent.simulation) else: return 'Coupling4:%s'%self.targetInput |
self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab) | self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab).order_by('id') | def __init__(self,*args,**kwargs): BaseParamForm.__init__(self,*args,**kwargs) # These always have instances. self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab) self.model='OR' |
self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab) | self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab).order_by('id') | def __init__(self,*args,**kwargs): BaseParamForm.__init__(self,*args,**kwargs) # These always have instances self.fields['value'].queryset=Term.objects.filter(vocab=self.instance.vocab) self.model='XOR' |
ensembleElement=self.cimRecord(root) | def q2cim(self,ref,docType): | |
ET.SubElement(ensembleElement,'shortName').text="ensemble for simulation "+simClass.abbrev | ET.SubElement(ensembleElement,'shortName').text=simClass.abbrev | def add_ensemble(self,simClass,rootElement): |
ET.SubElement(ensembleElement,'longName').text="ensemble for simulation "+simClass.title | ET.SubElement(ensembleElement,'longName').text=simClass.title | def add_ensemble(self,simClass,rootElement): |
ET.SubElement(simElement,'rationale') ''' shortName [1] ''' ET.SubElement(simElement,'shortName').text=simClass.abbrev ''' longName [1] ''' ET.SubElement(simElement,'longName').text=simClass.title | if simClass.ensembleMembers>1 : ''' shortName [1] ''' ET.SubElement(simElement,'shortName').text=simClass.abbrev+"BaseSimulation" ''' longName [1] ''' ET.SubElement(simElement,'longName').text='Base Simulation of Ensemble'+simClass.title else : ''' shortName [1] ''' ET.SubElement(simElement,'shortName').text=simClass.... | def add_simulation(self,simClass,rootElement): |
webpage=forms.CharField(widget=forms.TextInput(attrs={'size':'80'})) | webpage=forms.CharField(widget=forms.TextInput(attrs={'size':'80'}),required=False) | def __init__(self,*args,**kwargs): forms.ModelForm.__init__(self,*args,**kwargs) v=Vocab.objects.get(name='InputTypes') self.fields['ctype'].queryset=Value.objects.filter(vocab=v) |
ro.fromXML(e) ro.save() self.options.add(ro) | a = ro.fromXML(e) self.options.add(a) | def gfromXML(self,experiment,elem): ''' Initialised with an appropriate experiment, and an element tree Element ''' getter=etTxt(elem) self.docid=getter.get(elem,'id') for a in ['description','name']:self.__setattr__(a,getter.getN(elem,a)) for e in elem.findall('{%s}requirementOption'%cimv): ro=RequirementOption() ro.f... |
getter=eTxt(elem) name=eTxt.get(elem,'name') description=eTxt.get(elem,'description') return RequirementOption(name=name,description=description) | getter=etTxt(elem) name=getter.get(elem,'name') description=getter.get(elem,'description') a = RequirementOption(name=name,description=description) a.save() return a | def fromXML(self,elem): getter=eTxt(elem) name=eTxt.get(elem,'name') description=eTxt.get(elem,'description') return RequirementOption(name=name,description=description) |
experimentElement=self.cimRecord(root,ref) | experimentElement=self.cimRecord(root,ref.experiment) | def q2cim(self,ref,docType): |
ET.SubElement(expElement,'shortName').text=expClass.shortName | ET.SubElement(expElement,'shortName').text=expClass.abbrev | def addExperiment(self,expClass,rootElement): if (self.CIMXML): expElement=ET.SubElement(rootElement,'numericalExperiment',{'CIMVersion': '1.4','control':'false'}) ''' responsibleParty [0..inf] ''' ''' principleInvestigator [0..inf] ''' ''' fundingSource [0..inf] ''' ''' rationale [1..inf] ''' ET.SubElement(expElement,... |
ET.SubElement(expElement,'longName').text=expClass.longName | ET.SubElement(expElement,'longName').text=expClass.title | def addExperiment(self,expClass,rootElement): if (self.CIMXML): expElement=ET.SubElement(rootElement,'numericalExperiment',{'CIMVersion': '1.4','control':'false'}) ''' responsibleParty [0..inf] ''' ''' principleInvestigator [0..inf] ''' ''' fundingSource [0..inf] ''' ''' rationale [1..inf] ''' ET.SubElement(expElement,... |
calTypeElement=ET.SubElement(calendarElement,str(expClass.calendar)) | assert(expClass.requiredCalendar) calTypeElement=ET.SubElement(calendarElement,str(expClass.requiredCalendar.value)) | def addExperiment(self,expClass,rootElement): if (self.CIMXML): expElement=ET.SubElement(rootElement,'numericalExperiment',{'CIMVersion': '1.4','control':'false'}) ''' responsibleParty [0..inf] ''' ''' principleInvestigator [0..inf] ''' ''' fundingSource [0..inf] ''' ''' rationale [1..inf] ''' ET.SubElement(expElement,... |
ET.SubElement(durationElement,'startDate').text=expClass.startDate ET.SubElement(durationElement,'endDate').text=expClass.endDate | ET.SubElement(durationElement,'startDate').text=expClass.requiredDuration.startDate ET.SubElement(durationElement,'endDate').text=expClass.requiredDuration.endDate | def addExperiment(self,expClass,rootElement): if (self.CIMXML): expElement=ET.SubElement(rootElement,'numericalExperiment',{'CIMVersion': '1.4','control':'false'}) ''' responsibleParty [0..inf] ''' ''' principleInvestigator [0..inf] ''' ''' fundingSource [0..inf] ''' ''' rationale [1..inf] ''' ET.SubElement(expElement,... |
ET.SubElement(expElement,'Q_lengthYears').text=str(expClass.length) | ET.SubElement(expElement,'Q_lengthYears').text=str(expClass.requiredDuration.length) | def addExperiment(self,expClass,rootElement): if (self.CIMXML): expElement=ET.SubElement(rootElement,'numericalExperiment',{'CIMVersion': '1.4','control':'false'}) ''' responsibleParty [0..inf] ''' ''' principleInvestigator [0..inf] ''' ''' fundingSource [0..inf] ''' ''' rationale [1..inf] ''' ET.SubElement(expElement,... |
if c.implemented: | if c.implemented or nest==1: | def addChildComponent(self,c,root,nest,recurse=True): |
logging.debug("component "+c.abbrev+" has implemented set to false") | root.append(ET.Comment('Component '+c.abbrev+' has implemented set to false')) | def addChildComponent(self,c,root,nest,recurse=True): |
for pg in c.paramGroup.all(): constraintSet=ConstraintGroup.objects.filter(parentGroup=pg) | for pg in c.paramGroup.all().order_by('id'): constraintSet=ConstraintGroup.objects.filter(parentGroup=pg).order_by('id') | def c2text(self,c): ''' provide a textual (html) view of the status of a component ''' comp=ET.Element('div') ET.SubElement(comp,'h1').text='Component details' |
def __init__(self,tasks,options,results): | def __init__(self,tasks,options,scores): | def __init__(self,tasks,options,results): multiprocessing.Process.__init__(self) self.options = options self.tasks = tasks self.scores = scores self.bleualign = None self.scoredict = None |
self.results[i] = (data,self.multialign,self.bleualign,self.scoredict) | self.scores[i] = (data,self.multialign,self.bleualign,self.scoredict) | def run(self): i,data = self.tasks.get() while i != None: |
def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6): | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): | def centers_to_edges(x): xedge=np.zeros(x.shape[0]+1) xedge[1:-1] = (x[:-1] + x[1:])/2.0 dx = np.mean(np.abs(xedge[2:-1] - xedge[1:-2])) xedge[0] = xedge[1] - dx xedge[-1] = xedge[-2] + dx return xedge |
density_plot.set_rasterized(True) | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = data[t_name] grid = data[grid_name] a... | |
filename = 'LMA-%s_%s_%5.2fkm_%5.1fs.pdf' % (grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, time_delta.seconds) | filename = '%s-%s_%s_%05.2fkm_%05.1fs.pdf' % (filename_prefix, grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, time_delta.seconds) filename = os.path.join(outpath, filename) | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = data[t_name] grid = data[grid_name] a... |
def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA', do_save=True, image_type='pdf'): | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = dat... |
x = data[y_name] y = data[x_name] | x = data[x_name] y = data[y_name] | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = dat... |
filename = '%s-%s_%s_%05.2fkm_%05.1fs.pdf' % (filename_prefix, grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, time_delta.seconds) | filename = '%s-%s_%s_%05.2fkm_%05.1fs.%s' % (filename_prefix, grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, time_delta.seconds, image_type) | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = dat... |
fig.savefig(filename, dpi=150) | if do_save: fig.savefig(filename, dpi=150) return fig, p, frame_start_times, filename | def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time', n_cols=6, outpath='', filename_prefix='LMA'): f = nc.NetCDFFile(filename) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes x = data[y_name] y = data[x_name] t = dat... |
outgrids[0], fieldnames[0], field_descriptions[0]) | outgrids[0], field_names[0], field_descriptions[0]) | def grid_h5flashfiles(h5_filenames, start_time, end_time, frame_interval=120.0, dx=4.0e3, dy=4.0e3, x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3), z_bnd = (-20e3, 20e3), ctr_lat = 35.23833, ctr_lon = -97.46028, min_points_per_flash=10, outpath = '' ): from math import ceil """ Create 2D plan-view density grids for ... |
outgrids[1], fieldnames[1], field_descriptions[1]) | outgrids[1], field_names[1], field_descriptions[1]) | def grid_h5flashfiles(h5_filenames, start_time, end_time, frame_interval=120.0, dx=4.0e3, dy=4.0e3, x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3), z_bnd = (-20e3, 20e3), ctr_lat = 35.23833, ctr_lon = -97.46028, min_points_per_flash=10, outpath = '' ): from math import ceil """ Create 2D plan-view density grids for ... |
outgrids[2], fieldnames[2], field_descriptions[2]) | outgrids[2], field_names[2], field_descriptions[2]) | def grid_h5flashfiles(h5_filenames, start_time, end_time, frame_interval=120.0, dx=4.0e3, dy=4.0e3, x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3), z_bnd = (-20e3, 20e3), ctr_lat = 35.23833, ctr_lon = -97.46028, min_points_per_flash=10, outpath = '' ): from math import ceil """ Create 2D plan-view density grids for ... |
outgrids[3], fieldnames[3], field_descriptions[3], format='f') | outgrids[3], field_names[3], field_descriptions[3], format='f') | def grid_h5flashfiles(h5_filenames, start_time, end_time, frame_interval=120.0, dx=4.0e3, dy=4.0e3, x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3), z_bnd = (-20e3, 20e3), ctr_lat = 35.23833, ctr_lon = -97.46028, min_points_per_flash=10, outpath = '' ): from math import ceil """ Create 2D plan-view density grids for ... |
self.on_tooltip_display(self, False) | self.on_tooltip_display(self, True) | def display_tooltip(self, boolean): if boolean and len(self.tooltip.get_text()) > 0: try: self.on_tooltip_display(self, False) except: pass self._show_tooltip() else: try: self.on_tooltip_display(self, True) except: pass self._hide_tooltip() |
self.on_tooltip_display(self, True) | self.on_tooltip_display(self, False) | def display_tooltip(self, boolean): if boolean and len(self.tooltip.get_text()) > 0: try: self.on_tooltip_display(self, False) except: pass self._show_tooltip() else: try: self.on_tooltip_display(self, True) except: pass self._hide_tooltip() |
self.previous_icon = touchwizard.Icon('previous') self.previous_icon.build() | self.previous_icon = touchwizard.IconRef(touchwizard.Icon('previous')) | def __init__(self, first_page): import touchwizard clutter.Actor.__init__(self) easyevent.User.__init__(self) self.session = touchwizard.Session() self.background = None if touchwizard.canvas_bg: if not os.path.exists(touchwizard.canvas_bg): logger.error('Canvas background %s not found.', touchwizard.canvas_bg) self.... |
def action(self, source=None, event=None): | def action(self, event=None, source=None): | def action(self, source=None, event=None): what_to_do = self.ACTION_ANIMATE_AND_OPERATE new_state = None actions = (self.ACTION_ANIMATE_AND_OPERATE, self.ACTION_ANIMATE_ONLY) if self.is_locked: actions = (self.ACTION_ANIMATE_ONLY, ) if what_to_do in actions: self.toggle(new_state) if self.animate_id is None: self.anima... |
self._animate_timeout_id = None | def __init__(self, name, label=None): self.name = name if label is None: label = name.replace('_', ' ').title() self.label_text = label self.event_type = self.actioned_event_type_pattern %(name) self.cooldown_ms = self.default_cooldown self.is_locked = False self.is_on = False self.picture = None self.glow_animation = ... | |
actions = [self.ACTION_ANIMATE_AND_OPERATE, self.ACTION_ANIMATE_ONLY] | actions = (self.ACTION_ANIMATE_AND_OPERATE, self.ACTION_ANIMATE_ONLY) if self.is_locked: actions = (self.ACTION_ANIMATE_ONLY, ) if what_to_do in actions: self.toggle(new_state) if self.animate_id is None: self.animate_id = gobject.timeout_add(10, self.animate) actions = (self.ACTION_ANIMATE_AND_OPERATE, self.ACTION_OPE... | def action(self, event=None): what_to_do = self.ACTION_ANIMATE_AND_OPERATE new_state = None if event is not None and event.content is not None: what_to_do = event.content if isinstance(event.content, dict): what_to_do = event.content['action'] new_state = event.content['state'] actions = [self.ACTION_ANIMATE_AND_OPERAT... |
self.toggle(new_state) self._animate_timeout_id = gobject.timeout_add(10, self.animate) | def action(self, event=None): what_to_do = self.ACTION_ANIMATE_AND_OPERATE new_state = None if event is not None and event.content is not None: what_to_do = event.content if isinstance(event.content, dict): what_to_do = event.content['action'] new_state = event.content['state'] actions = [self.ACTION_ANIMATE_AND_OPERAT... | |
self.launch_event('infobar_message', | self.launch_event('info_message', | def action(self, event=None): what_to_do = self.ACTION_ANIMATE_AND_OPERATE new_state = None if event is not None and event.content is not None: what_to_do = event.content if isinstance(event.content, dict): what_to_do = event.content['action'] new_state = event.content['state'] actions = [self.ACTION_ANIMATE_AND_OPERAT... |
if what_to_do == self.ACTION_ANIMATE_ONLY: self.toggle(new_state) self.animate() | def action(self, event=None): what_to_do = self.ACTION_ANIMATE_AND_OPERATE new_state = None if event is not None and event.content is not None: what_to_do = event.content if isinstance(event.content, dict): what_to_do = event.content['action'] new_state = event.content['state'] actions = [self.ACTION_ANIMATE_AND_OPERAT... | |
if self._animate_timeout_id is not None: gobject.source_remove(self._animate_timeout_id) | self.animate_id = None | def animate(self): if self._animate_timeout_id is not None: gobject.source_remove(self._animate_timeout_id) self.timeline.start() if self.glow_animation: if self.is_on: self.anim_timeline.start() else: self.anim_timeline.stop() |
def __init__(self, icon, label=None, is_locked=None, is_on=None): | def __init__(self, icon, label=None, is_locked=None, is_on=False): | def __init__(self, icon, label=None, is_locked=None, is_on=None): self.icon = icon self.label = label self.is_locked = is_locked self.is_on = is_on |
bar.icon_manager.add(red, green, blue) | bar.icon_manager.add_icon(red) bar.icon_manager.add_icon(green) bar.icon_manager.add_icon(blue) | def add_bar(y, height): rect = clutter.Rectangle() rect.set_color(clutter.color_from_string('LightBlue')) rect.set_y(y) rect.set_size(stage.get_width(), height) bar = touchwizard.InfoBar() #bar.props.request_mode = clutter.REQUEST_WIDTH_FOR_HEIGHT bar.set_y(y) bar.set_size(stage.get_width(), height) # icons red = Inf... |
gobject.timeout_add(300, self.do_previous_page, event) | if self.previous_page_timeout_id is not None: gobject.source_remove(self.previous_page_timeout_id) self.previous_page_timeout_id = gobject.timeout_add(300, self.do_previous_page, event) | def evt_previous_page(self, event): if not self.previous_page_locked: self.previous_page_locked = True gobject.timeout_add(300, self.do_previous_page, event) |
if previous.need_loading: self.loading.show() | def do_previous_page(self, event): try: previous, icons = self.history.pop() except IndexError: #logger.error('Previous page requested but history is empty.') self.evt_request_quit(event) return logger.info('Back to %r page.', previous.name) self.current_page.panel.hide() gobject.idle_add(self.current_page.panel.unpare... | |
self.previous_page_locked = False | def do_previous_page(self, event): try: previous, icons = self.history.pop() except IndexError: #logger.error('Previous page requested but history is empty.') self.evt_request_quit(event) return logger.info('Back to %r page.', previous.name) self.current_page.panel.hide() gobject.idle_add(self.current_page.panel.unpare... | |
if line.line_id == line_id: | if tooltip_line.line_id == line_id: | def set_tooltip_line(self, line_id, status=None, text=None, delete=False): line = None for tooltip_line in self.tooltip_lines: if line.line_id == line_id: line = tooltip_line if delete: self.tooltip.remove_element('line_%s' %line_id) self.tooltip_lines.remove(line) break if line == None and not delete: if text == None:... |
if line == None and not delete: if text == None: text = '' line = ToolTipLine(line_id, status, text, images_path=self.images_path) line.set_font_name(self.tooltip_font_name) line.set_font_color(self.tooltip_font_color) self.tooltip.add_element(line, 'line_%s' %line_id, expand=True) self.tooltip_lines.append(line) | if line == None: if not delete: if text == None: text = '' line = ToolTipLine(line_id, status, text, images_path=self.images_path) line.set_font_name(self.tooltip_font_name) line.set_font_color(self.tooltip_font_color) self.tooltip.add_element(line, 'line_%s' %line_id, expand=True) self.tooltip_lines.append(line) | def set_tooltip_line(self, line_id, status=None, text=None, delete=False): line = None for tooltip_line in self.tooltip_lines: if line.line_id == line_id: line = tooltip_line if delete: self.tooltip.remove_element('line_%s' %line_id) self.tooltip_lines.remove(line) break if line == None and not delete: if text == None:... |
self.current_page.panel.unparent() | gobject.idle_add(self.current_page.panel.unparent) | def do_previous_page(self, event): try: previous, icons = self.history.pop() except IndexError: #logger.error('Previous page requested but history is empty.') self.evt_request_quit(event) return logger.info('Back to %r page.', previous.name) self.current_page.panel.hide() self.current_page.panel.unparent() if not self.... |
gobject.idle_add(self.do_previous_page, event) | gobject.timeout_add(300, self.do_previous_page, event) | def evt_previous_page(self, event): gobject.idle_add(self.do_previous_page, event) |
data = self.context.getField('image').get(self.context).data if type(data) == str: return data else: return data.data | data = str(self.context.getField('image').get(self.context)) return data | def get_image_data(self): data = self.context.getField('image').get(self.context).data if type(data) == str: return data else: return data.data |
loadAvrgs = re.findall(r'([0-9]+\.\d+)', uptime) | loadAvrgs = [res.replace(',', '.') for res in re.findall(r'([0-9]+[\.,]\d+)', uptime)] | def getLoadAvrgs(self): self.checksLogger.debug('getLoadAvrgs: start') if sys.platform == 'linux2': self.checksLogger.debug('getLoadAvrgs: linux2') try: self.checksLogger.debug('getLoadAvrgs: attempting open') loadAvrgProc = open('/proc/loadavg', 'r') uptime = loadAvrgProc.readlines() except IOError, e: self.checks... |
payloadHash = md5.new(payload).hexdigest() | payloadHash = md5(payload).hexdigest() | def doChecks(self, sc, firstRun, systemStats=False): macV = None if sys.platform == 'darwin': macV = platform.mac_ver() if not self.topIndex: # We cache the line index from which to read from top # Output from top is slightly modified on OS X 10.6 (case #28239) if macV and macV[0].startswith('10.6.'): self.topIndex = ... |
self.checksLogger.debug('getDiskUsage: parsing volume: ' + str(volume[0])) | self.checksLogger.debug('getDiskUsage: parsing volume: ' + volume) | def getDiskUsage(self): self.checksLogger.debug('getDiskUsage: start') # Memory logging (case 27152) if self.agentConfig['debugMode'] and sys.platform == 'linux2': mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE, close_fds=True).communicate()[0] self.checksLogger.debug('getDiskUsage: memory before Popen ... |
def get_value(_legend, _data, name): "Using the legend and a metric name, get the value or None from the data line" if name in legend: return data.get(legend.index(name), None) else: return None cpu_user = get_value("us") cpu_sys = get_value("sy") cpu_wait = get_value("wa") cpu_idle = get_value("id") cpu_st = get_value... | cpu_user = get_value(legend, data, "us") cpu_sys = get_value(legend, data, "sy") cpu_wait = get_value(legend, data, "wa") cpu_idle = get_value(legend, data, "id") cpu_st = get_value(legend, data, "st") | def get_value(_legend, _data, name): "Using the legend and a metric name, get the value or None from the data line" if name in legend: return data.get(legend.index(name), None) else: return None |
figures = lines[-2].split() cpu_user = int(figures[6]) cpu_sys = int(figures[7]) | legend = lines[1].split() data = lines[-2].split() cpu_user = get_value(legend, data, "us") cpu_sys = get_value(legend, data, "sy") | def get_value(_legend, _data, name): "Using the legend and a metric name, get the value or None from the data line" if name in legend: return data.get(legend.index(name), None) else: return None |
cpu_idle = int(figures[8]) | cpu_idle = get_value(legend, data, "id") | def get_value(_legend, _data, name): "Using the legend and a metric name, get the value or None from the data line" if name in legend: return data.get(legend.index(name), None) else: return None |
conn = Connection(self.agentConfig['MongoDBServer']) | mongoInfo = self.agentConfig['MongoDBServer'].split(':') if len(mongoInfo) == 2: conn = Connection(mongoInfo[0], mongoInfo[1]) else: conn = Connection(mongoInfo[0]) | def getMongoDBStatus(self): self.checksLogger.debug('getMongoDBStatus: start') |
status = db.command('serverStatus') | status = db.command('serverStatus', dbName) | def getMongoDBStatus(self): self.checksLogger.debug('getMongoDBStatus: start') |
status['indexCounters']['btree']['accessesPS'] = 0 status['indexCounters']['btree']['hitsPS'] = 0 status['indexCounters']['btree']['missesPS'] = 0 status['indexCounters']['btree']['missRatioPS'] = 0 status['opcounters']['insertPS'] = 0 status['opcounters']['queryPS'] = 0 status['opcounters']['updatePS'] = 0 status['opc... | self.clearMongoDBStatus(status) | def getMongoDBStatus(self): self.checksLogger.debug('getMongoDBStatus: start') |
status['indexCounters']['btree']['accessesPS'] = float(status['indexCounters']['btree']['accesses'] - self.mongoDBStore['indexCounters']['btree']['accesses']) / 60 status['indexCounters']['btree']['hitsPS'] = float(status['indexCounters']['btree']['hits'] - self.mongoDBStore['indexCounters']['btree']['hits']) / 60 stat... | accessesPS = float(status['indexCounters']['btree']['accesses'] - self.mongoDBStore['indexCounters']['btree']['accesses']) / 60 if accessesPS >= 0: status['indexCounters']['btree']['accessesPS'] = accessesPS status['indexCounters']['btree']['hitsPS'] = float(status['indexCounters']['btree']['hits'] - self.mongoDBStore... | def getMongoDBStatus(self): self.checksLogger.debug('getMongoDBStatus: start') |
def clearMongoDBStatus(self, status): status['indexCounters']['btree']['accessesPS'] = 0 status['indexCounters']['btree']['hitsPS'] = 0 status['indexCounters']['btree']['missesPS'] = 0 status['indexCounters']['btree']['missRatioPS'] = 0 status['opcounters']['insertPS'] = 0 status['opcounters']['queryPS'] = 0 status['op... | def getMongoDBStatus(self): self.checksLogger.debug('getMongoDBStatus: start') | |
itemRegexp = re.compile(r'^([a-zA-Z0-9]+)') | itemRegexp = re.compile(r'^([a-zA-Z0-9\/]+)') | def getIOStats(self): self.checksLogger.debug('getIOStats: start') ioStats = {} if sys.platform == 'linux2': self.checksLogger.debug('getIOStats: linux2') headerRegexp = re.compile(r'([%\\/\-a-zA-Z0-9]+)[\s+]?') itemRegexp = re.compile(r'^([a-zA-Z0-9]+)') valueRegexp = re.compile(r'\d+\.\d+') try: stats = subproces... |
device = re.match(itemRegexp, row).groups()[0] | deviceMatch = re.match(itemRegexp, row) if deviceMatch is not None: device = deviceMatch.groups()[0] | def getIOStats(self): self.checksLogger.debug('getIOStats: start') ioStats = {} if sys.platform == 'linux2': self.checksLogger.debug('getIOStats: linux2') headerRegexp = re.compile(r'([%\\/\-a-zA-Z0-9]+)[\s+]?') itemRegexp = re.compile(r'^([a-zA-Z0-9]+)') valueRegexp = re.compile(r'\d+\.\d+') try: stats = subproces... |
enrollment_start_planned = forms.CharField( label=_('Planned Date of First Enrollment'), max_length=10, required=False) | enrollment_start_planned = forms.DateField( label=_('Planned Date of First Enrollment'), required=False) | def as_table(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." normal_row = u''' <tr><th>%(label)s</th> <td>%(errors)s%(field)s</td> <td class="help"> <img src="/static/help.png" rel="#%(help_id)s"/> <div id="%(help_id)s" class="help">%(help_text)s</div> <div class="issue">%(issue)s</d... |
fields = ['interest','description'] | fields = ['description','interest'] | def save_m2m(): for form in self.saved_forms: form.save_m2m() |
return self.indexed(recruitment_status='recruiting') | return self.indexed(recruitment_status='recruiting').published() | def recruiting(self): return self.indexed(recruitment_status='recruiting') |
for lang in languages: try: context[self.var] = [t for t in self.get_translations(self.get_value(obj, 'translations')) if self.get_value(t, 'language') == lang][0] except IndexError: context[self.var] = obj self.set_language(obj, lang) | if obj: for lang in languages: try: context[self.var] = [t for t in self.get_translations(self.get_value(obj, 'translations')) if self.get_value(t, 'language') == lang][0] except IndexError: context[self.var] = obj self.set_language(obj, lang) | def render(self, context): output = [] languages = context['languages'] |
return obj[key] | try: return obj[key] except TypeError: return None | def get_value(self, obj, key): return obj[key] |
consent_form = ConsentForm(request.POST, display_language=request.user.get_profile().preferred_language) | consent_form = ConsentForm(request.POST, display_language=request.LANGUAGE_CODE) | def new_submission(request): if request.method == 'POST': consent_form = ConsentForm(request.POST, display_language=request.user.get_profile().preferred_language) if consent_form.is_valid(): initial_form = InitialTrialForm(user=request.user) sponsor_form = PrimarySponsorForm() forms = [initial_form, sponsor_form] ret... |
consent_form = ConsentForm(display_language=request.user.get_profile().preferred_language) | consent_form = ConsentForm(display_language=request.LANGUAGE_CODE) | def new_submission(request): if request.method == 'POST': consent_form = ConsentForm(request.POST, display_language=request.user.get_profile().preferred_language) if consent_form.is_valid(): initial_form = InitialTrialForm(user=request.user) sponsor_form = PrimarySponsorForm() forms = [initial_form, sponsor_form] ret... |
if set(value) != set(self.queryset.values_list('pk', flat=True)): | if set(value) != set(map(unicode, self.queryset.values_list('pk', flat=True))): | def clean(self, value): if set(value) != set(self.queryset.values_list('pk', flat=True)): raise ValidationError(self.error_messages['consent']) qs = super(ModelMultipleChoiceAllFields, self).clean(value) return qs |
ticket = get_object_or_404(Ticket, id=int(object_id)) | def resolve_ticket(request, object_id): if request.method == 'POST': # If the forms were submitted... form = FollowupParcForm(request.POST) if form.is_valid(): desc = form.cleaned_data['description'] ticket = get_object_or_404(Ticket, id=int(object_id)) fw_lt = ticket.followup_set.latest() fw_nw = Followup(ticket=ticke... | |
'iteration_form': followup_form, 'ticket_id': object_id, | 'form': followup_form, 'ticket': ticket, | def resolve_ticket(request, object_id): if request.method == 'POST': # If the forms were submitted... form = FollowupParcForm(request.POST) if form.is_valid(): desc = form.cleaned_data['description'] ticket = get_object_or_404(Ticket, id=int(object_id)) fw_lt = ticket.followup_set.latest() fw_nw = Followup(ticket=ticke... |
if request.GET['next']: response = HttpResponseRedirect(request.GET['next']) | next = request.GET.get('next', '') if next: response = HttpResponseRedirect(next) | def user_profile(request): profile, created = UserProfile.objects.get_or_create(user=request.user) if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance=profile) password_form = PasswordChangeForm(request.user,request.POST) if user_fo... |
ret = map(int, value.split('-')[:2]) ret.reverse() | if '-' in value: ret = map(int, value.split('-')[:2]) ret.reverse() elif '/' in value: ret = map(int, value.split('/')[-2:]) else: ret = ['', ''] | def decompress(self, value): if not value: ret = ['', ''] else: ret = map(int, value.split('-')[:2]) ret.reverse() return ret |
value = self._translations[lang_format(self._language)][name] | value_trans = self._translations[lang_format(self._language)][name] if value_trans: value = value_trans | def __getattr__(self, name): value = super(FossilClinicalTrial, self).__getattr__(name) |
for submission in Submission.objects.all(): ct = submission.trial ct.language = submission.language ct.save() | def forwards(self, orm): # Adding field 'ClinicalTrial.language' db.add_column('repository_clinicaltrial', 'language', self.gf('django.db.models.fields.CharField')(default='pt-BR', max_length=10), keep_default=False) | |
('pending', _('Pending')), ('acknowledged', _('Acknowledged')), ('verified', _('Verified')), ] | ('pending', _('Pending')), ('acknowledged', _('Acknowledged')), ('verified', _('Verified')), ] REMARK_TRANSITIONS = { 'pending':['acknowledged', 'verified'], 'acknowledged':['verified', 'pending'], 'verified':['pending'], } | def get_absolute_url(self): # TODO: use reverse to replace absolute path return '/accounts/submission/%s/' % self.id |
self._translations = dict([(lang_format(t['language']), t) | self._translations = dict([(lang_format(t.get('language', '').lower()), t) | def _load_translations(self): if self._translations is None: self._translations = dict([(lang_format(t['language']), t) for t in self.object_fossil.translations]) |
value = [t for t in value['translations'] if t['language'].lower() == self._language.lower()][0] | value = [t for t in value['translations'] if t.get('language', '').lower() == self._language.lower()][0] | def __getattr__(self, name): value = super(FossilClinicalTrial, self).__getattr__(name) |
return [t for t in item['translations'] if t['language'].lower() == self._language.lower()][0] | return [t for t in item['translations'] if t.get('language', '').lower() == self._language.lower()][0] | def get_trans(item): try: return [t for t in item['translations'] if t['language'].lower() == self._language.lower()][0] except IndexError: return item |
return [t for t in country['translations'] if t['language'].lower() == self._language.lower()][0] | return [t for t in country['translations'] if t.get('language', '').lower() == self._language.lower()][0] | def country(self): country = super(FossilContact, self).__getattr__('country') |
new_contact = contactform.save() | new_contact = contactform.save(commit=False) new_contact.creator = request.user new_contact.save() | def step_8(request, trial_pk): ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) contact_type = { 'PublicContact': (PublicContact,make_public_contact_form(request.user)), 'ScientificContact': (ScientificContact,make_scientifc_contact_form(request.user)), 'SiteContact': (SiteContact,make_site_contact_form(request... |
langs.add(self.trial.primary_sponsor.country.submission_language) | if self.trial.primary_sponsor is not None: langs.add(self.trial.primary_sponsor.country.submission_language) | def get_mandatory_languages(self): langs = set([u'en']) langs.add(self.trial.primary_sponsor.country.submission_language) |
if value=instance.recruitment_status: | if value == instance.recruitment_status: | def clinicaltrial_post_save(sender, instance, signal, **kwargs): # This signal calls validation method to validate the instance according to # rules made with mandatory fields but aren't obligatory on the model trial_validator.validate(instance) # Creates a fossil if the status is equal to 'published' if instance.stat... |
cmd = mysqldump_bin+' --opt --compact --skip-add-locks -u %s -p%s %s | bzip2 -c' % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME) print cmd | def export_database(request): #output backup stdin,stdout = os.popen2(r'which mysqldump') stdin.close() mysqldump_bin = stdout.readline().replace('\n','') stdout.close() cmd = mysqldump_bin+' --opt --compact --skip-add-locks -u %s -p%s %s | bzip2 -c' % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DAT... | |
<h1>version.txt</h1> %(version)s <h1>svnversion</h1> | <h1>Revision</h1> | def sys_info(request): template = u''' <h1>version.txt</h1> %(version)s <h1>svnversion</h1> %(svn_version)s <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>Site.objects.get_current()</h1> <table> <tr><th>id</th><td>%(site.pk)s</td></tr> <tr><th>domain</th><td>%(site.domain)s</td></tr> <tr><th>name</th><td>%(site... |
version = open(os.path.join(settings.PROJECT_PATH, 'version.txt')).read() svn_version, svn_version_err = Popen('svnversion', shell=True, stdout=PIPE).communicate() | svn_version, svn_version_err = Popen(['svnversion', settings.PROJECT_PATH], stdout=PIPE).communicate() | def sys_info(request): template = u''' <h1>version.txt</h1> %(version)s <h1>svnversion</h1> %(svn_version)s <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>Site.objects.get_current()</h1> <table> <tr><th>id</th><td>%(site.pk)s</td></tr> <tr><th>domain</th><td>%(site.domain)s</td></tr> <tr><th>name</th><td>%(site... |
svnout, svnerr = Popen(['svn', 'info', '-r', 'HEAD', settings.PROJECT_PATH], stdout=PIPE).communicate() | svnout, svnerr = Popen(['svn', 'info','--non-interactive','--username=anonymous','--password=4guests@','-r', 'HEAD', settings.PROJECT_PATH], stdout=PIPE).communicate() | def sys_info(request): template = u''' <h1>version.txt</h1> %(version)s <h1>svnversion</h1> %(svn_version)s <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>Site.objects.get_current()</h1> <table> <tr><th>id</th><td>%(site.pk)s</td></tr> <tr><th>domain</th><td>%(site.domain)s</td></tr> <tr><th>name</th><td>%(site... |
'version':version, | def sys_info(request): template = u''' <h1>version.txt</h1> %(version)s <h1>svnversion</h1> %(svn_version)s <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>Site.objects.get_current()</h1> <table> <tr><th>id</th><td>%(site.pk)s</td></tr> <tr><th>domain</th><td>%(site.domain)s</td></tr> <tr><th>name</th><td>%(site... | |
self.queryset = kwargs.pop('queryset') | try: self.queryset = kwargs.pop('queryset') except KeyError: self.queryset = kwargs.pop('model').objects.all() | def __init__(self, *args, **kwargs): self.queryset = kwargs.pop('queryset') self.label_field = kwargs.pop('label_field') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.