Example #1
0
    def __init__(self, parent, widgetID, characterStyle, headerCharacterStyle,
                 *arguments, **keywords):
        if wx.Platform == "__WXMAC__":
            theStyle = wx.BORDER_SIMPLE
        else:
            theStyle = wx.BORDER_STATIC
        """
          Giant hack. Calling event.GetEventObject in OnShow of
          application, while the object is being created cause the
          object to get the wrong type because of a
          "feature" of SWIG. So we need to avoid OnShows in this case.
        """
        IgnoreSynchronizeWidget(True,
                                super(wxTable, self).__init__,
                                parent,
                                widgetID,
                                style=theStyle,
                                *arguments,
                                **keywords)

        self.SetDefaultCellFont(Styles.getFont(characterStyle))
        self.SetLabelFont(Styles.getFont(headerCharacterStyle))
        self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        self.SetRowLabelSize(0)
        self.AutoSizeRows()
        self.EnableDragCell(True)
        self.DisableDragRowSize()
        self.SetDefaultCellBackgroundColour(wx.WHITE)
        self.EnableCursor(False)
        self.SetLightSelectionBackground()
        self.SetScrollLineY(self.GetDefaultRowSize())
        self.SetUseVisibleColHeaderSelection(True)
        self.SetUseColSortArrows(True)

        # wxSidebar is subclassed from wxTable and depends on the binding of
        # OnLoseFocus so it can override OnLoseFocus in wxTable
        self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wxGrid.EVT_GRID_CELL_BEGIN_DRAG, self.OnItemDrag)
        self.Bind(wxGrid.EVT_GRID_COL_SIZE, self.OnColumnDrag)
        self.Bind(wxGrid.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
        self.Bind(wxGrid.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClicked)
        self.Bind(wxGrid.EVT_GRID_EDITOR_HIDDEN, self.OnEditorHidden)
        self.Bind(wxGrid.EVT_GRID_EDITOR_SHOWN, self.OnEditorShown)

        gridWindow = self.GetGridWindow()
        gridWindow.Bind(wx.EVT_PAINT, self.OnPaint)
        # wxSidebar is subclassed from wxTable and depends on the binding of
        # OnMouseEvents so it can override OnMouseEvents in wxTable
        gridWindow.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
        gridWindow.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnMouseCaptureLost)
        # It appears that wxGrid gobbles all the mouse events so we never get
        # context menu events. So bind right down to the context menu handler
        gridWindow.Bind(wx.EVT_RIGHT_DOWN, wx.GetApp().OnContextMenu)
Example #2
0
def stepper_mount_holes(d):
  conf=d["stepper"]
  thickness=d["thickness"]
  group=g();
  
  r=rect(2*conf["width"]/3,0,conf["width"]/3,thickness)
  r.set_style(Styles.get_cut_style(d))
  group.addElement(r);

  r=rect(0,0,conf["width"]/3,thickness)
  r.set_style(Styles.get_cut_style(d))
  group.addElement(r);

  return group
Example #3
0
    def __init__(self, parent, widgetID, characterStyle, headerCharacterStyle, *arguments, **keywords):
        if wx.Platform == "__WXMAC__":
            theStyle=wx.BORDER_SIMPLE
        else:
            theStyle=wx.BORDER_STATIC
        """
          Giant hack. Calling event.GetEventObject in OnShow of
          application, while the object is being created cause the
          object to get the wrong type because of a
          "feature" of SWIG. So we need to avoid OnShows in this case.
        """
        IgnoreSynchronizeWidget(True, super(wxTable, self).__init__,
                                parent, widgetID, style=theStyle,
                                *arguments, **keywords)

        self.SetDefaultCellFont(Styles.getFont(characterStyle))
        self.SetLabelFont(Styles.getFont(headerCharacterStyle))
        self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        self.SetRowLabelSize(0)
        self.AutoSizeRows()
        self.EnableDragCell(True)
        self.DisableDragRowSize()
        self.SetDefaultCellBackgroundColour(wx.WHITE)
        self.EnableCursor (False)
        self.SetLightSelectionBackground()
        self.SetScrollLineY (self.GetDefaultRowSize())
        self.SetUseVisibleColHeaderSelection(True)
        self.SetUseColSortArrows(True)

        # wxSidebar is subclassed from wxTable and depends on the binding of
        # OnLoseFocus so it can override OnLoseFocus in wxTable
        self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wxGrid.EVT_GRID_CELL_BEGIN_DRAG, self.OnItemDrag)
        self.Bind(wxGrid.EVT_GRID_COL_SIZE, self.OnColumnDrag)
        self.Bind(wxGrid.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
        self.Bind(wxGrid.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClicked)
        self.Bind(wxGrid.EVT_GRID_EDITOR_HIDDEN, self.OnEditorHidden)
        self.Bind(wxGrid.EVT_GRID_EDITOR_SHOWN, self.OnEditorShown)

        gridWindow = self.GetGridWindow()
        gridWindow.Bind(wx.EVT_PAINT, self.OnPaint)
        # wxSidebar is subclassed from wxTable and depends on the binding of
        # OnMouseEvents so it can override OnMouseEvents in wxTable
        gridWindow.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
        gridWindow.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnMouseCaptureLost)
        # It appears that wxGrid gobbles all the mouse events so we never get
        # context menu events. So bind right down to the context menu handler
        gridWindow.Bind(wx.EVT_RIGHT_DOWN, wx.GetApp().OnContextMenu)
 def btn_setstyle(params):
     context.chat_data['style'] = int(params)
     stylename = Lang.get("keyboard.setstyle.random",
                          lang) if int(params) < 0 else Styles.get(
                              int(params)).get_name(lang)
     update.callback_query.message.reply_text(
         Lang.get('command.setstyle.changed', lang, style=stylename))
Example #5
0
 def __init__(self, *args, **kwargs):
     super(ExtrinsicAcquisitionWidget, self).__init__(*args, **kwargs)
     self.loadForm()
     self.initUI()
     self.viewAutoAcquisition = ViewAutomaticAcquisition(self.window)
     self.viewManualAcquisition = ViewManualAcquisition(self.window)
     Styles(self)
Example #6
0
def solenoid_hole(d):
  conf=d["solenoid"]
  x=0
  y=0
  trough_width = 8
  trough_length= 8
  s_width=conf["width"]
  s_length=conf["length"]
  lip = (conf["width"]-trough_width)/2


  p = path("M%f,%f" % (x,y))
  p.appendLineToPath(x+s_width,y,False)
  p.appendLineToPath(x+s_width,y+s_length,False)
  p.appendLineToPath(x+s_width-lip,y+s_length,False)
  p.appendLineToPath(x+s_width-lip,y+s_length+trough_length,False)
  p.appendLineToPath(x+lip,y+s_length+trough_length,False)
  p.appendLineToPath(x+lip,y+s_length,False)
  p.appendLineToPath(x,y+s_length,False)
  p.appendLineToPath(x,y,False)
  p.set_style(Styles.get_cut_style(d))
  
  #bbox=(s_length+trough_length, s_width)
  conf["total_length"]=s_length+trough_length
  conf["total_width"]=s_width
  return p
Example #7
0
def stepper(d):
    conf=d["stepper"]
    conf["back_x"]=conf["front_x"]-conf["length"]
    conf["top_y"]=conf["center_line_y"]-conf["width"]/2

    r=rect(conf["back_x"],conf["top_y"],conf["length"],conf["width"])
    r.set_style(Styles.get_construction_style(d))
    return r
def draw_histogram_dict( histograms, suffix="new" ):
	"""Draw all histograms in this directory and save it as pdf."""
	# disable open canvas
	ROOT.gROOT.SetBatch()
	import Styles
	Styles.tdrStyle2D()
	can = ROOT.TCanvas()
	can.cd()
	dataset = ROOT.TPaveText(.4,.9,.6,.98, "ndc")
	dataset.SetFillColor(0)
	dataset.SetBorderSize(0)
	dataset.AddText( suffix )
	for name, histo in histograms.iteritems():
		name = name.replace(".","")
		histo.Draw("colz")
		dataset.Draw()
		can.SaveAs("plots/%s_%s.pdf"%(name,suffix))
Example #9
0
def draw_histogram_dict(histograms, suffix="new"):
    """Draw all histograms in this directory and save it as pdf."""
    # disable open canvas
    ROOT.gROOT.SetBatch()
    import Styles
    Styles.tdrStyle2D()
    can = ROOT.TCanvas()
    can.cd()
    dataset = ROOT.TPaveText(.4, .9, .6, .98, "ndc")
    dataset.SetFillColor(0)
    dataset.SetBorderSize(0)
    dataset.AddText(suffix)
    for name, histo in histograms.iteritems():
        name = name.replace(".", "")
        histo.Draw("colz")
        dataset.Draw()
        can.SaveAs("plots/%s_%s.pdf" % (name, suffix))
Example #10
0
def achlang(update: Update, context: CallbackContext) -> None:
    keyboard = []

    for lang in Styles.get(context.chat_data.get('style')).get_langs():
        keyboard.append([
            InlineKeyboardButton(Lang.get_lang(lang),
                                 callback_data=f"achlang.{lang}")
        ])

    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(Lang.get('command.achlang.select',
                                       context.chat_data.get('lang')),
                              reply_markup=reply_markup)
Example #11
0
def stepper_support(d):
  group=g();
  conf=d["stepper"]
  thickness=d["thickness"]
  conf["support_height"]=thickness+conf["height"]+thickness
  x=0
  y=0
  p = path("M%f,%f" % (x,y))
  p.appendLineToPath(conf["width"]/3,0)
  p.appendLineToPath(0,thickness)
  p.appendLineToPath(conf["width"]/3,0)
  p.appendLineToPath(0,-thickness)
  p.appendLineToPath(conf["width"]/3,0)
  p.appendLineToPath(0,conf["support_height"])
  p.appendLineToPath(-conf["width"]/3,0)
  p.appendLineToPath(0,-thickness)
  p.appendLineToPath(-conf["width"]/3,0)
  p.appendLineToPath(0,+thickness)
  p.appendLineToPath(-conf["width"]/3,0)
  p.appendLineToPath(0,-conf["support_height"])
  p.set_style(Styles.get_cut_style(d))
  group.addElement(p)
 
  #bush mounting
  c=circle(conf["width"]/2,conf["support_height"]/2,conf["bush_radius"])
  c.set_style(Styles.get_cut_style(d))
  group.addElement(c)

  #mount holes
  import math
  mount_x=math.sqrt(math.pow(conf["mount_hole_distance"],2)/2)
  mount_y=mount_x
  for x in -mount_x, mount_x:
    for y in -mount_y, mount_y:
      c=circle(conf["width"]/2+x,conf["support_height"]/2+y,conf["hole_radius"])
      c.set_style(Styles.get_cut_style(d))
      group.addElement(c)

  return group;
Example #12
0
def create_achievement(update: Update, context: CallbackContext) -> None:
    lang = context.chat_data.get('lang')

    # Checking name & description
    vals = Achievement.parse_message(update.message.text
                                     or update.message.caption)
    for err in Achievement.check_values(**vals):
        update.message.reply_text(Lang.get(err, lang, **Achievement.LIMITS))
        vals = None
    if not vals:
        return

    # Icon & style
    image = None
    if update.message.photo:
        photos = update.message.photo
        image = photos[1 if len(photos) > 1 else 0].get_file().file_path
    elif context.chat_data.get('image_url'):
        image = context.chat_data.get('image_url')
        context.chat_data['image_url'] = None

    vals['icon'] = Tools.download_image(image
                                        or Tools.search_image(vals['name']))
    vals['style'] = Styles.get(context.chat_data.get('style'))

    # Setting language
    ach_lang = context.chat_data.get('ach_lang', 'ENG')
    if vals['style'].change_lang(ach_lang) != 'ok':
        update.message.reply_text(
            Lang.get('error.achievement.no_lang',
                     lang,
                     lang=ach_lang,
                     style=vals['style'].get_name(lang)))

    ach = Achievement(**vals)
    gen = ach.generate()
    if type(gen) is str:
        update.message.reply_text(Lang.get(gen, lang))
    else:
        update.message.reply_photo(gen)
        # Incrementing stats
        context.bot_data['ach_generated'] = context.bot_data.get(
            'ach_generated', 0) + 1
        context.chat_data['ach_generated'] = context.chat_data.get(
            'ach_generated', 0) + 1
Example #13
0
        self.master.config(menu=menubar)
        
    def onExit(self):
        '''
        Called on closing ColdControl.  Confirms the exit and safely closes the various UI's.
        '''
        
        exitConfirmation = tkMessageBox.askquestion("Please confirm exit",\
                                                    "Are you sure you want to close Cold Control?\nThis will release all DAQ cards and exit the program - unsaved information will be lost?",
                                                    icon='warning')
        if exitConfirmation == 'yes':
            print 'Closing camera connections...'
            self.camera_UI.closeCameras()
            print '...all camera connections closed.'
            print 'Releasing DAQ cards...'
            if not self.development_mode: self.daq_UI.daq_controller.releaseAll()
            print '...all cards released.'
            print 'Saving labbook...'
            self.labbook_UI.write()
            print '...labbook saved'
            root.destroy()
            print 'Cold Control closed - bye!'
 
if __name__ == "__main__":
    
    root = tk.Tk()
    root.geometry("1600x800")
    Styles.configureStyles()
    ColdControl_UI(root).pack(fill="both", expand=True)
    root.mainloop()
		print "%.2f standard deviations between theory and measurement"%Compare_val(xs,err_xs_stat,err_xs_sys, theo[1][i], theo[2][i])


if (__name__ == "__main__"):
	from argparse import ArgumentParser
	parser = ArgumentParser()
	parser.add_argument("-m", "--mcfile", dest="mcfile", default="mc_all_new.root/MCTree", help="MC file path")
	parser.add_argument("-d", "--datafile", dest="datafile", default="d0_new.root/MessTree", help="Data file path")
	parser.add_argument("-c", "--cut", dest="cut", default="met > 30 && el_et > 30", help="Cuts applied to all structures" )
	parser.add_argument("--save", action="store_true", default=False, help="Plots are not drawn, but saved as pdf")
	parser.add_argument("-p", "--plots", dest="plots", default= "mwt")
	parser.add_argument("-q", "--quiet", action="store_true", default = False)

	opts = parser.parse_args()
	import Styles # official cms style
	style = Styles.tdrStyle()
	mcTree = readTree( opts.mcfile )
	dataTree = readTree( opts.datafile )

	# set cut for el_et !!!!!!!!!!!!!!!! overwrites all!!!!!!!!!!!!!
	if opts.plots == "el_et":
		opts.cut = opts.cut + ' && mwt/el_et>1.9'

	m, e_m,e_m_sys = getMass( dataTree, mcTree, opts.cut, opts.save, opts.plots, opts.quiet )
	sin2_wein,err_sin2_wein_stat,err_sin2_wein_sys = getWeinberg( m, e_m ,e_m_sys)
	gamma,err_gamma_stat,err_gamma_sys = getWidth(m, e_m, e_m_sys )

	print "Mass: %.2f \pm %.2f/ (stat.) \pm %.2f (sys.) GeV"%(m, e_m,e_m_sys)
	print
	if not opts.quiet:
		xs,err_xs_stat,err_xs_sys = getXs(dataTree,mcTree,opts.plots,opts.cut)
Example #15
0
from math import sqrt

import ROOT
import Styles
import argparse
from prettifyFunctions import *
import ratios

# To use user defined help message, sys.arv has to be sent to python and not
# to TApplication.
ROOT.PyConfig.IgnoreCommandLineOptions = True

Styles.tdrStyle()
ROOT.gROOT.SetBatch()
ROOT.gSystem.Load("libTreeObjects.so")


def rebin2D(oldHist, xList, yList):
    """Rebins a TH2F.
	oldHist: input TH2F
	xList: list which mark the bin edges of the new xaxis
	yList: list which mark the bin edges of the new yaxis
	"""
    import ROOT
    import array
    newHist = ROOT.TH2F( oldHist.GetName()+randomName(), "%s;%s;%s"%(oldHist.GetTitle(),oldHist.GetXaxis().GetTitle(),oldHist.GetYaxis().GetTitle()), \
      len(xList)-1, array.array('d', xList), \
      len(yList)-1, array.array('d', yList) )
    newHist.Sumw2()
    for i in range(oldHist.GetNbinsX() + 2):
        for j in range(oldHist.GetNbinsY() + 2):
Example #16
0
def DrawWrappedText(dc, text, rect, measurements=None):
    """
    Simple wordwrap - draws the text into the current DC
    
    returns the height of the text that was written

    measurements is a FontMeasurements object as returned by
    Styles.getMeasurements()
    """

    if measurements is None:
        measurements = Styles.getMeasurements(dc.GetFont())

    lineHeight = measurements.height
    spaceWidth = measurements.spaceWidth
        
    (rectX, rectY, rectWidth, rectHeight) = rect
    y = rectY
    rectRight = rectX + rectWidth
    rectBottom = rectY + rectHeight

    # we hit this if you narrow the main window enough:
    # assert rectHeight >= lineHeight, "Don't have enough room to write anything (have %d, need %d)" % (rectHeight, lineHeight)
    if rectHeight < lineHeight: return 0 # Can't draw anything    
    
    for line in text.splitlines():
        x = rectX
        # accumulate text to be written on a line
        thisLine = u''
        for word in line.split():
            width = dc.GetTextExtent(word)[0]

            # if we wrapped but we still can't fit the word,
            # just truncate it    
            if (width > rectWidth and x == rectX):
                assert thisLine == u'', "Should be drawing first long word"
                DrawClippedText(dc, word, rectX, y, rectWidth, width)
                y += lineHeight
                continue

            # see if we want to jump to the next line
            if (x + width > rectRight):
                # wrapping, so draw the previous accumulated line if any
                if thisLine:
                    dc.DrawText(thisLine, rectX, y)
                    thisLine = u''
                y += lineHeight
                x = rectX
            
            # if we're out of vertical space, just return
            if (y + lineHeight > rectBottom):
                assert thisLine == u'', "shouldn't have any more to draw"
                return
                #return y - rectY # total height

            availableWidth = rectRight - x
            if width > availableWidth:
                assert x == rectX and thisLine == u'', "should be writing a long word at the beginning of a line"
                DrawClippedText(dc, word, rectX, y, availableWidth, width)
                x += width
                # x is now past rectRight, so this will force a wrap
            else:
                # rather than draw it, just accumulate it
                thisLine += word + u' '
                x += width + spaceWidth
        
        # draw the last words on this line, if any
        if thisLine:
            dc.DrawText(thisLine, rectX, y)        
        y += lineHeight
Example #17
0
#! /usr/bin/env python2
# -*- coding: utf-8 -*-

import ROOT
import argparse
import ConfigParser
import os.path
import Styles
Styles.tdrStyle()

axisConf = ConfigParser.SafeConfigParser()
axisConf.read("axis.cfg")

integratedLuminosity = 19.3 #fb

def readTree( filename, treename = "susyTree" ):
	"""
	filename: name of file containing the tree
	treename: name of the tree
	returns: TTree Object
	"""
	if not os.path.isfile(filename):
		print( "File %s does not exist"%filename)
	tree = ROOT.TChain( treename )
	tree.AddFile( filename )
	return tree

def createHistoFromTree2D(tree, variable, weight="", nBin=50):
	"""
	tree: tree to create histo from
	variable: variable to plot (must be a branch of the tree)
Example #18
0
        self.ok_png = tk.PhotoImage(
            file=os.path.join(self.imagepath, "checkmark-12.png"))
        self.warn_png = tk.PhotoImage(
            file=os.path.join(self.imagepath, "warning-16.png"))

        self.add(self.t_flow, text='Flow')
        self.add(self.t_speechmatics, text='Speechmatics')

    # add an image to a notebook tab
    def tab_image(self, tab, *image):
        # if image is not provided, the current image turns off
        self.tab(tab, image=image, compound=tk.RIGHT)


root = tk.Tk()
root.title('Flow Transcribe Control Panel')
Styles.defineStyles(root)

mainframe = ttk.Frame(root, padding='0 0 0 0', style='catdv.TFrame')
mainframe.pack(expand=tk.YES, fill=tk.BOTH)

notebook = NoteBookCatdv(mainframe)

notebook.tab_image(notebook.t_flow, notebook.warn_png)
notebook.tab_image(notebook.t_speechmatics, notebook.ok_png)
# notebook.tab_image(notebook.t_flow, '')

print(notebook.tab(1))

root.mainloop()
def DrawWrappedText(dc, text, rect, measurements=None):
    """
    Simple wordwrap - draws the text into the current DC
    
    returns the height of the text that was written

    measurements is a FontMeasurements object as returned by
    Styles.getMeasurements()
    """

    if measurements is None:
        measurements = Styles.getMeasurements(dc.GetFont())

    lineHeight = measurements.height
    spaceWidth = measurements.spaceWidth

    (rectX, rectY, rectWidth, rectHeight) = rect
    y = rectY
    rectRight = rectX + rectWidth
    rectBottom = rectY + rectHeight

    # we hit this if you narrow the main window enough:
    # assert rectHeight >= lineHeight, "Don't have enough room to write anything (have %d, need %d)" % (rectHeight, lineHeight)
    if rectHeight < lineHeight: return 0  # Can't draw anything

    for line in text.splitlines():
        x = rectX
        # accumulate text to be written on a line
        thisLine = u''
        for word in line.split():
            width = dc.GetTextExtent(word)[0]

            # if we wrapped but we still can't fit the word,
            # just truncate it
            if (width > rectWidth and x == rectX):
                assert thisLine == u'', "Should be drawing first long word"
                DrawClippedText(dc, word, rectX, y, rectWidth, width)
                y += lineHeight
                continue

            # see if we want to jump to the next line
            if (x + width > rectRight):
                # wrapping, so draw the previous accumulated line if any
                if thisLine:
                    dc.DrawText(thisLine, rectX, y)
                    thisLine = u''
                y += lineHeight
                x = rectX

            # if we're out of vertical space, just return
            if (y + lineHeight > rectBottom):
                assert thisLine == u'', "shouldn't have any more to draw"
                return
                #return y - rectY # total height

            availableWidth = rectRight - x
            if width > availableWidth:
                assert x == rectX and thisLine == u'', "should be writing a long word at the beginning of a line"
                DrawClippedText(dc, word, rectX, y, availableWidth, width)
                x += width
                # x is now past rectRight, so this will force a wrap
            else:
                # rather than draw it, just accumulate it
                thisLine += word + u' '
                x += width + spaceWidth

        # draw the last words on this line, if any
        if thisLine:
            dc.DrawText(thisLine, rectX, y)
        y += lineHeight
Example #20
0
def base_outline(d):
  conf=d["base"]
  r=rect(0,0,conf["width"],conf["length"],5,5) #rounded corners
  r.set_style(Styles.get_cut_style(d))
  return r