Example #1
0
    def LoadTabs(self, tabs, autoselecttab = 1, settingsID = None, iconOnly = False, silently = False):
        self._iconOnly = iconOnly
        self.sr.tabs = []
        self.sr.mytabs = []
        self.sr.tabsmenu = None
        self.Flush()
        self.Prepare_LeftSide_()
        maxTextHeight = 0
        for data in tabs:
            newtab = self.GetTabClass()(parent=self)
            self.sr.mytabs.append(newtab)
            newtab.Startup(self, data)
            newtab.align = uiconst.TOLEFT
            self.sr.Set('%s_tab' % data.label, newtab)
            self.sr.tabs.append(newtab)
            maxTextHeight = max(maxTextHeight, newtab.sr.label.textheight)
            if newtab.sr.icon:
                maxTextHeight = max(maxTextHeight, newtab.sr.icon.height)

        self.Prepare_RightSide_()
        self.height = max(MINTABGROUPHEIGHT, int(maxTextHeight * 1.7))
        self._inited = 1
        self._settingsID = settingsID
        self.UpdateSizes()
        if autoselecttab:
            self.AutoSelect(silently)
Example #2
0
    def set_size(self, width, height, ease):
        if ease:
            self.save_easing_state()
            self.set_easing_duration(600)
            self.background.save_easing_state()
            self.background.set_easing_duration(600)
            self.border.save_easing_state()
            self.border.set_easing_duration(600)
            self.preview.save_easing_state()
            self.preview.set_easing_duration(600)
            if self.rightHandle:
                self.rightHandle.save_easing_state()
                self.rightHandle.set_easing_duration(600)

        self.marquee.set_size(width, height)
        self.background.props.width = max(width - 2, 1)
        self.background.props.height = max(height - 2, 1)
        self.border.props.width = width
        self.border.props.height = height
        self.props.width = width
        self.props.height = height
        self.preview.set_size(max(width - 2, 1), max(height - 2, 1))
        if self.rightHandle:
            self.rightHandle.set_position(
                width - self.rightHandle.props.width, 0)

        if ease:
            self.background.restore_easing_state()
            self.border.restore_easing_state()
            self.preview.restore_easing_state()
            if self.rightHandle:
                self.rightHandle.restore_easing_state()
            self.restore_easing_state()
Example #3
0
 def computeSourceRevision(self, changes):
     if not changes:
         return None
     lastChange = max([c.when for c in changes])
     lastSubmit = max([br.submittedAt for br in self.build.requests])
     when = (lastChange + lastSubmit) / 2
     return formatdate(when)
def sentence_similarity(idx, ob, mode):

    s_list = list()
    pbar = ProgressBar(widgets=['%s: image ' % mode, SimpleProgress()],
                       maxval=len(sentences)).start()

    for im_idx, sentence_group in enumerate(np.array(sentences)[idx, :]):

        pbar.update(im_idx + 1)
        for sent in sentence_group:

            words = analyze(sent)

            sim = list()
            for w in words:

                syn1 = wn.synsets(w)
                syn2 = wn.synsets(ob)

                if syn1 and syn2:
                    sim.append(max(s1.path_similarity(s2) for (s1, s2)
                                   in product(syn1, syn2)))
                else:
                    # ignore word if no synset combination was found on wordnet
                    sim.append(None)

            if max(sim):
                s_list.append(max(sim))
            else:
                # ignore sentence if no word was similar enough
                s_list.append(float('nan'))

    pbar.finish()
    return s_list
Example #5
0
 def evaluate(self,  u):
 
     eps = 1e-10
     
     if u<min(self.knots)+eps:
         u = min(self.knots)+eps
         
     if u>=max(self.knots)-eps:
         u=max(self.knots)-eps
         
     # scale
     weighted_pts = [vscale(pt[0:-1],pt[-1])+[pt[-1]] for pt in self.pts]
     
             
     pts = []
     for i in range(len(self.pts)):
         pts.append(vscale(weighted_pts[i], self.N(i, self.order, u)))
         
     eval_pt = reduce(vadd, pts)
     
     
     # unscale
     if eval_pt[-1]!=0:
         unweighted_pt = vscale(eval_pt[0:-1], 1.0/eval_pt[-1]) 
     else:
         unweighted_pt = eval_pt[0:-1]
         
     
     return unweighted_pt
Example #6
0
    def createContext(self, item, plot, onlimits):
        self.origin = item.getOrigin()
        self.scale = item.getScale()

        self.data = item.getData(copy=True)

        if onlimits:
            minX, maxX = plot.getXAxis().getLimits()
            minY, maxY = plot.getYAxis().getLimits()

            XMinBound = int((minX - self.origin[0]) / self.scale[0])
            YMinBound = int((minY - self.origin[1]) / self.scale[1])
            XMaxBound = int((maxX - self.origin[0]) / self.scale[0])
            YMaxBound = int((maxY - self.origin[1]) / self.scale[1])

            XMinBound = max(XMinBound, 0)
            YMinBound = max(YMinBound, 0)

            if XMaxBound <= XMinBound or YMaxBound <= YMinBound:
                self.data = None
            else:
                self.data = self.data[YMinBound:YMaxBound + 1,
                                      XMinBound:XMaxBound + 1]
        if self.data.size > 0:
            self.min, self.max = min_max(self.data)
        else:
            self.min, self.max = None, None
        self.values = self.data

        if self.values is not None:
            self.axes = (self.origin[1] + self.scale[1] * numpy.arange(self.data.shape[0]),
                         self.origin[0] + self.scale[0] * numpy.arange(self.data.shape[1]))
Example #7
0
def show_level(level, path=[]):
    """ Displays a level via a print statement.

    Args:
        level: The level to be displayed.
        path: A continuous path to be displayed over the level, if provided.

    """
    xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls'])))
    x_lo, x_hi = min(xs), max(xs)
    y_lo, y_hi = min(ys), max(ys)

    path_cells = set(path)

    chars = []
    inverted_waypoints = {point: char for char, point in level['waypoints'].items()}

    for j in range(y_lo, y_hi + 1):
        for i in range(x_lo, x_hi + 1):

            cell = (i, j)
            if cell in path_cells:
                chars.append('*')
            elif cell in level['walls']:
                chars.append('X')
            elif cell in inverted_waypoints:
                chars.append(inverted_waypoints[cell])
            elif cell in level['spaces']:
                chars.append(str(int(level['spaces'][cell])))
            else:
                chars.append(' ')

        chars.append('\n')

    print(''.join(chars))
Example #8
0
    def onMouse( self, event, x, y, flags, param ):
        """
        Mouse interactions with Main window:
            - Left mouse click gives pixel data under cursor
            - Left mouse drag selects rectangle

            - Right mouse button switches view mode
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            if not self.gui_frame == None:
                self.drag_start = (x, y)

        if event == cv2.EVENT_LBUTTONUP:
                self.drag_start = None

                if self.selection == None:
                    pixel = self.gui_frame[y, x]
                    print "[X,Y][B G R](H, S, V):", [x, y], pixel, utils.BGRpix2HSV(pixel)
                else:
                    #self.track_window = self.selection
                    print self.selection    #self.track_window

        if self.drag_start:
            xmin = min( x, self.drag_start[0] )
            ymin = min( y, self.drag_start[1] )
            xmax = max( x, self.drag_start[0] )
            ymax = max( y, self.drag_start[1] )

            if xmax - xmin < 2 and ymax - ymin < 2:
                self.selection = None
            else:
                self.selection = ( xmin, ymin, xmax - xmin, ymax - ymin )

        if event == cv2.EVENT_RBUTTONDOWN:
            pass
Example #9
0
def upgradeTier (card1, card2):
	defaultHealth = cards[card1.id][1]
	defaultAttack = cards[card1.id][2]
	if card1.isMaxLevel():
		delta1hp = card1.stats[0]*0.1
		delta1attack = card1.stats[1]*0.1
	else:
		delta1hp = card1.stats[0]*0.05
		delta1attack = card1.stats[1]*0.05

	if card2.isMaxLevel():
		delta2hp = card2.stats[0]*0.1
		delta2attack = card2.stats[1]*0.1
	else:
		delta2hp = card2.stats[0]*0.05
		delta2attack = card2.stats[1]*0.05     

	deltaHP = delta1hp + delta2hp
	print 
	deltaAttack = delta1attack + delta2attack
	
	if max(card1.tier,card2.tier)==1:
		koeff = 1.2
	elif max(card1.tier,card2.tier)==2:
		koeff = 1.5
	elif max(card1.tier,card2.tier)==3:
		koeff = 2
	newstats = [defaultHealth*koeff + deltaHP, defaultAttack*koeff + deltaAttack]
	newCard = Card (card1.id)
	newCard.stars = newstats
	newCard.tier = max(card1.tier,card2.tier)+1
	return newCard
Example #10
0
 def __handle_select_button_ccs(self, cc_no, cc_value):
     if cc_no == FX_SELECT_FIRST_BUTTON_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.__parent.toggle_lock()
     elif cc_no == FX_SELECT_ENCODER_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             new_index = min(
                 len(self.song().scenes) - 1,
                 max(0, list(self.song().scenes).index(self.song().view.selected_scene) - 1),
             )
             self.song().view.selected_scene = self.song().scenes[new_index]
     elif cc_no == FX_SELECT_SECOND_BUTTON_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             new_index = min(
                 len(self.song().scenes) - 1,
                 max(0, list(self.song().scenes).index(self.song().view.selected_scene) + 1),
             )
             self.song().view.selected_scene = self.song().scenes[new_index]
     elif cc_no == FX_SELECT_POTIE_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.song().view.selected_scene.fire_as_selected()
     elif cc_no == FX_SELECT_DRUM_PAD_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.song().stop_all_clips()
     else:
         raise False or AssertionError, "unknown select row midi message"
def getPartInfo( part ):
        points = part['points']
        n = len(points)
        area = cx = cy = 0
        xmin = ymin = 360
        xmax = ymax = -360
        pt = points[n-1];  xx = pt[0];  yy = pt[1]
        for pt in points:
                x = pt[0];  y = pt[1]
                # bounds
                xmin = min( x, xmin );  ymin = min( y, ymin )
                xmax = max( x, xmax );  ymax = max( y, ymax )
                # area and centroid
                a = xx * y - x * yy
                area += a
                cx += ( x + xx ) * a
                cy += ( y + yy ) * a
                # next
                xx = x;  yy = y
        area /= 2
        if area:
                centroid = [ cx / area / 6, cy / area / 6 ]
        else:
                centroid = None
        part.update({
                'area': abs(area),
                'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ],
                'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ],
                'centroid': centroid,
                'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ]
        })
Example #12
0
    def get_box_intersection(self, bounding_region):
        """
        Given a bounding_region object computes and returns a new BoundingRegion that
        corresponds to the intersection of the bounding box of the current object with the
        box of the region given as argument. Retuns an empty BoundingRegion if the interseciton
        is empty.

        :param bounding_region: A BoundingRegion object to compute intersection with
        :type bounding_region: BoundingRegion
        :return: Bounding region of the intersection of the boxes
        :rtype: BoundingRegion
        """
        x1_1 = self.box[0]
        y1_1 = self.box[1]
        x1_2 = self.box[0] + self.box[2]
        y1_2 = self.box[1] + self.box[3]
        box2 = bounding_region.get_box_pixels()
        x2_1 = box2[0]
        y2_1 = box2[1]
        x2_2 = box2[0] + box2[2]
        y2_2 = box2[1] + box2[3]

        x3_1 = max(x1_1, x2_1)
        y3_1 = max(y1_1, y2_1)
        width = max(-1, min(x1_2, x2_2) - x3_1)
        height = max(-1, min(y1_2, y2_2) - y3_1)
        if width * height >= 0:
            return BoundingRegion(image_shape=self.image_shape, box=(x3_1, y3_1, width, height))
        else:
            return BoundingRegion()
Example #13
0
    def getPixelData(self, event):
        global data

        x = event.pos().x()
        y = event.pos().y()
        self.area.append([x, y])

        value = qRgb(flag[self.color][0], flag[self.color][1], flag[self.color][2])

        # if there's 2 points, then add the whole zone to the data
        if len(self.area) == 2:
            xi = min(self.area[0][0], self.area[1][0] + 1)
            xf = max(self.area[0][0], self.area[1][0] + 1)
            yi = min(self.area[0][1], self.area[1][1] + 1)
            yf = max(self.area[0][1], self.area[1][1] + 1)

            print('zone [' + str(xi) + ',' + str(yi) + '][' + str(xf) + ',' + str(yf) + ']  => ' + self.color)

            for i in range(xi, xf):
                for j in range(yi, yf):
                    rgb = QColor(self.image.pixel(i, j)).toRgb()
                    r = rgb.red()
                    g = rgb.green()
                    b = rgb.blue()
                    data[self.color].append([i, j, r, g, b])

                    self.image.setPixel(i, j, value)

            # update image to show the already selected pixels
            self.label.setPixmap(QPixmap.fromImage(self.image))
            # reset list with the zone limits
            self.area = []
Example #14
0
def fit_CSU_edges(profile):
    fitter = fitting.LevMarLSQFitter()

    amp1_est = profile[profile == min(profile)][0]
    mean1_est = np.argmin(profile)
    amp2_est = profile[profile == max(profile)][0]
    mean2_est = np.argmax(profile)
    
    g_init1 = models.Gaussian1D(amplitude=amp1_est, mean=mean1_est, stddev=2.)
    g_init1.amplitude.max = 0
    g_init1.amplitude.min = amp1_est*0.9
    g_init1.stddev.max = 3
    g_init2 = models.Gaussian1D(amplitude=amp2_est, mean=mean2_est, stddev=2.)
    g_init2.amplitude.min = 0
    g_init2.amplitude.min = amp2_est*0.9
    g_init2.stddev.max = 3

    model = g_init1 + g_init2
    fit = fitter(model, range(0,profile.shape[0]), profile)
    
    # Check Validity of Fit
    if abs(fit.stddev_0.value) <= 3 and abs(fit.stddev_1.value) <= 3\
       and fit.amplitude_0.value < -1 and fit.amplitude_1.value > 1\
       and fit.mean_0.value > fit.mean_1.value:
        x = [fit.mean_0.value, fit.mean_1.value]
        x1 = int(np.floor(min(x)-1))
        x2 = int(np.ceil(max(x)+1))
    else:
        x1 = None
        x2 = None

    return x1, x2
Example #15
0
 def _find_common(self, lineset1, lineset2):
     """find similarities in the two given linesets"""
     lines1 = lineset1.enumerate_stripped
     lines2 = lineset2.enumerate_stripped
     find = lineset2.find
     index1 = 0
     min_lines = self.min_lines
     while index1 < len(lineset1):
         skip = 1
         num = 0
         for index2 in find(lineset1[index1]):
             non_blank = 0
             for num, ((_, line1), (_, line2)) in enumerate(
                 izip(lines1(index1), lines2(index2))):
                 if line1 != line2:
                     if non_blank > min_lines:
                         yield num, lineset1, index1, lineset2, index2
                     skip = max(skip, num)
                     break
                 if line1:
                     non_blank += 1
             else:
                 # we may have reach the end
                 num += 1
                 if non_blank > min_lines:
                     yield num, lineset1, index1, lineset2, index2
                 skip = max(skip, num)
         index1 += skip
Example #16
0
def point_inside_polygon(x,y,polygons):
    
    idxPolygons = []
    
    if polygons != None:
        for l in range(len(polygons)):
            inside = False
            poly = polygons[l]
            #print "poly: ",  poly
            if poly != None:
                n = len(poly)
                p1x,p1y = poly[0]
                for i in range(n+1):
                    p2x,p2y = poly[i % n]
                    if y > min(p1y,p2y):
                        if y <= max(p1y,p2y):
                            if x <= max(p1x,p2x):
                                if p1y != p2y:
                                    xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                                if p1x == p2x or x <= xinters:
                                    inside = not inside
                    p1x,p1y = p2x,p2y
                if inside == True:
                    idxPolygons.append(l)
            
    return idxPolygons
Example #17
0
def group_by(a, b):
    '''Return a hash table of 0..len(a)-1 by (a,b) value.'''
    a_max, b_max = max(a), max(b)
    g = np.zeros((a_max + 1, b_max + 1), dtype=np.object)
    for i, j in it.product(xrange(a_max + 1), xrange(b_max + 1)): g[i, j] = list()
    for k in xrange(n): g[a[k], b[k]].append(k)
    return g
    def plotResult(self, nn):
        cmask = np.where(self.y==1);
        plot(self.X[cmask,0], self.X[cmask,1], 'or', markersize=4)
        cmask = np.where(self.y==2);
        plot(self.X[cmask,0], self.X[cmask,1], 'ob', markersize=4)
        cmask = np.where(self.y==3);
        plot(self.X[cmask,0], self.X[cmask,1], 'og', markersize=4)

        minX = min(self.X[:,0])
        minY = min(self.X[:,1])
        maxX = max(self.X[:,0])
        maxY = max(self.X[:,1])

        grid_range = [minX, maxX, minY, maxY];
        delta = 0.05; levels = 100
        a = arange(grid_range[0],grid_range[1],delta)
        b = arange(grid_range[2],grid_range[3],delta)
        A, B = meshgrid(a, b)
        values = np.zeros(A.shape)

        for i in range(len(a)):
            for j in range(len(b)):
                values[j,i] = nn.getNetworkOutput( [ a[i], b[j] ] )
        contour(A, B, values, levels=[1], colors=['k'], linestyles='dashed')
        contourf(A, B, values, levels=linspace(values.min(),values.max(),levels), cmap=cm.RdBu)
Example #19
0
def getframeinfo(frame, context=1):
    """Get information about a frame or traceback object.

    A tuple of five things is returned: the filename, the line number of
    the current line, the function name, a list of lines of context from
    the source code, and the index of the current line within that list.
    The optional second argument specifies the number of lines of context
    to return, which are centered around the current line."""
    if istraceback(frame):
        lineno = frame.tb_lineno
        frame = frame.tb_frame
    else:
        lineno = frame.f_lineno
    if not isframe(frame):
        raise TypeError('{!r} is not a frame or traceback object'.format(frame))

    filename = getsourcefile(frame) or getfile(frame)
    if context > 0:
        start = lineno - 1 - context//2
        try:
            lines, lnum = findsource(frame)
        except IOError:
            lines = index = None
        else:
            start = max(start, 1)
            start = max(0, min(start, len(lines) - context))
            lines = lines[start:start+context]
            index = lineno - 1 - start
    else:
        lines = index = None

    return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
Example #20
0
def cost_config(pos_,Qnet,Pnet,counts):
    p_wind=pos_[0]*WINDS_PRICE_DEVICE
    p_pv=pos_[1]*PV_PRICE_BAT1
    counts.append(int(max(Pnet)))
    counts.append(abs(int(min(Pnet))))
    Qmin=min(Qnet)
    print 'Qmin:%f   '%Qmin
    Qmax=max(max(Qnet),abs(min(Qnet)))
    Pmax=max(max(Pnet),abs(min(Pnet)))
    maxVol=recyclemodule.tank_svgas(recyclemodule.ele_mkgas(Qmax))
    max_tank_Volumn.append(abs(maxVol)) 
    print 'maxVol :%f'%maxVol
    counts.append(abs(maxVol/100.0))
    q=(Qmax/BAT_POWER)*BAT_PRICE_DEVICE
    if abs(q)>ELE_PRICE_DEVICE+TANK_PRICE_DEVICE+FC_PRICE_DEVICE:
        p_cycle=ELE_PRICE_DEVICE*counts[0]+TANK_PRICE_DEVICE*counts[2]+FC_PRICE_DEVICE*counts[1]
        counts.append(round(Pmax))            
        p_bat=(Pmax)/BAT_POWER*BAT_PRICE_DEVICE
        #print 'cycle price :%f'%p_cycle
        #print 'bat   price :%f'%p_bat
           
    else:
        counts.append(0.0)
        p_bat=q
        p_cycle=0
        #print 'cycle not use'
        #print q

    print 'ele: %d fc : %d tank : %d bat : %d'%(counts[0],counts[1],counts[2],counts[3])       
    return p_wind+p_pv+p_bat+p_cycle
Example #21
0
def save_level_costs(level, costs, filename='distance_map.csv'):
    """ Displays cell costs from an origin point over the given level.

    Args:
        level: The level to be displayed.
        costs: A dictionary containing a mapping of cells to costs from an origin point.
        filename: The name of the csv file to be created.

    """
    xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls'])))
    x_lo, x_hi = min(xs), max(xs)
    y_lo, y_hi = min(ys), max(ys)

    rows = []
    for j in range(y_lo, y_hi + 1):
        row = []

        for i in range(x_lo, x_hi + 1):
            cell = (i, j)
            if cell not in costs:
                row.append(inf)
            else:
                row.append(costs[cell])

        rows.append(row)

    assert '.csv' in filename, 'Error: filename does not contain file type.'
    with open(filename, 'w', newline='') as f:
        csv_writer = writer(f)
        for row in rows:
            csv_writer.writerow(row)
            
    
    print("Saved file:", filename)
Example #22
0
def calculate_hand_rank(hand):
    ranks = card_ranks(hand)
    suits = [s for r,s in hand]

    if flush(suits) and straight(ranks): 
        return ((8, max(ranks)), 'Straight Flush')
    elif n_of_kind(ranks, 4):
        return ((7, n_of_kind(ranks, 4), n_of_kind(ranks, 1)), 'Four of a Kind')
    elif n_of_kind(ranks, 3) and n_of_kind(ranks, 2):
        return ((6, n_of_kind(ranks, 3), n_of_kind(ranks, 2)), 'Full House')
    elif flush(suits):
        return ((5, ranks), 'Flush')
    elif straight(ranks):
        return ((4, max(ranks)), 'Straight')
    elif n_of_kind(ranks, 3):
        return ((3, n_of_kind(ranks, 3), single_cards(ranks)[0], single_cards(ranks)[1]), 
                 'Three of a Kind')
    elif two_pair(ranks):
        return ((2, two_pair(ranks)[0], two_pair(ranks)[1], n_of_kind(ranks, 1)), 
                 'Two Pair')
    elif n_of_kind(ranks, 2):
        return ((1, n_of_kind(ranks, 2), single_cards(ranks)[0], single_cards(ranks)[1], 
                 single_cards(ranks)[2]), 'A Pair')
    else:
        return ((0, ranks), 'High Card')
Example #23
0
    def get_budgets(self):  # {{{
        # Get categories
        categories = self.get_categories()

        # Issue request for budget utilization
        first_of_this_month = date.today().replace(day=1)
        eleven_months_ago = (first_of_this_month - timedelta(days=330)).replace(day=1)
        url = "{}/getBudget.xevent".format(MINT_ROOT_URL)
        params = {
            'startDate': eleven_months_ago.strftime('%m/%d/%Y'),
            'endDate': first_of_this_month.strftime('%m/%d/%Y'),
            'rnd': Mint.get_rnd(),
        }
        response = json.loads(self.get(url, params=params, headers=JSON_HEADER).text)

        # Make the skeleton return structure
        budgets = {
            'income': response['data']['income'][
                str(max(map(int, response['data']['income'].keys())))
            ]['bu'],
            'spend': response['data']['spending'][
                str(max(map(int, response['data']['income'].keys())))
            ]['bu']
        }

        # Fill in the return structure
        for direction in budgets.keys():
            for budget in budgets[direction]:
                budget['cat'] = self.get_category_from_id(
                    budget['cat'],
                    categories
                )

        return budgets
Example #24
0
def twopad(attrlist):
    width = findattr(attrlist, "width")
    padwidth = findattr(attrlist, "padwidth")
    padheight = findattr(attrlist, "padheight")
    polyclear = findattr(attrlist, "polyclear")
    maskclear = findattr(attrlist, "maskclear")
    silkwidth = findattr(attrlist, "silkwidth")
    silkboxwidth = findattr(attrlist, "silkboxwidth")
    silkboxheight = findattr(attrlist, "silkboxheight")
    silkoffset = findattr(attrlist, "silkoffset")
    silkpolarity = findattr(attrlist, "silkpolarity")
    silkcustom = findattr(attrlist, "silkcustom")
    
    twopadelt = element(attrlist)
    twopadelt = twopadelt + rowofpads([0,0], width+padwidth, "right", padwidth, padheight, 1, 2, maskclear, polyclear)
    silkx = max((width+2*padwidth)/2 + silkoffset,silkboxwidth/2)
    silky = max(padheight/2 + silkoffset, silkboxheight/2)
    twopadelt = twopadelt + box(silkx,silky,-silkx,-silky,silkwidth)
    if (silkpolarity == "yes"):
        polx = silkx + 2*silkoffset
        twopadelt = twopadelt + silk(silkx, silky, polx, silky, silkwidth)
        twopadelt = twopadelt + silk(silkx, -silky, polx, -silky, silkwidth)
        twopadelt = twopadelt + silk(polx, -silky, polx, silky, silkwidth)
    for line in silkcustom:
        twopadelt += "\t" + str(line) + "\n"
    return twopadelt+")\n"
Example #25
0
    def Slow(self):
        """Set slow timing values

        Currently this changes the timing in the following ways:
        timeouts = default timeouts * 10
        waits = default waits * 3
        retries = default retries * 3

        (if existing times are slower then keep existing times)
        """
        for setting in TimeConfig.__default_timing:
            if "_timeout" in setting:
                TimeConfig._timings[setting] = max(
                    TimeConfig.__default_timing[setting] * 10,
                    TimeConfig._timings[setting])

            if "_wait" in setting:
                TimeConfig._timings[setting] = max(
                    TimeConfig.__default_timing[setting] * 3,
                    TimeConfig._timings[setting])

            elif setting.endswith("_retry"):
                TimeConfig._timings[setting] = max(
                    TimeConfig.__default_timing[setting] * 3,
                    TimeConfig._timings[setting])

            if TimeConfig._timings[setting] < .2:
                TimeConfig._timings[setting]= .2
def standardMC_european_option(K, T, R, V, S0, N, option_type, path_num=10000):
    dt = T / N
    sigma = V
    drift = math.exp((R - 0.5 * sigma * sigma) * dt)
    sigma_sqrt = sigma * math.sqrt(dt)
    exp_RT = math.exp(-R * T)
    european_payoff = []
    for i in xrange(path_num):
        former = S0
        for j in xrange(int(N)):
            former = former * drift * math.exp(sigma_sqrt * numpy.random.normal(0, 1))
        european_option = former

        if option_type == 1.0:
            european_payoff_call = exp_RT * max(european_option - K, 0)
            european_payoff.append(european_payoff_call)
        elif option_type == 2.0:
            european_payoff_put = exp_RT * max(K - european_option, 0)
            european_payoff.append(european_payoff_put)

    # Standard Monte Carlo
    p_mean = numpy.mean(european_payoff)
    p_std = numpy.std(european_payoff)
    p_confmc = (p_mean - 1.96 * p_std / math.sqrt(path_num), p_mean + 1.96 * p_std / math.sqrt(path_num))
    return p_mean, p_std, p_confmc
Example #27
0
    def updateValue(self, delta_x, delta_y):
        newTs = self.tsStart + Zoomable.pixelToNs(delta_x)
        newValue = self.valueStart - (delta_y / EXPANDED_SIZE)

        # Don't overlap first and last keyframes.
        newTs = min(max(newTs, self.inpoint + 1),
                    self.duration + self.inpoint - 1)

        newValue = min(max(newValue, 0.0), 1.0)

        if not self.has_changeable_time:
            newTs = self.lastTs

        updating = self.timelineElement.updating_keyframes
        self.timelineElement.updating_keyframes = True
        self.timelineElement.source.unset(self.lastTs)
        if (self.timelineElement.source.set(newTs, newValue)):
            self.value = Gst.TimedValue()
            self.value.timestamp = newTs
            self.value.value = newValue
            self.lastTs = newTs

            self.timelineElement.setKeyframePosition(self, self.value)
            # Resort the keyframes list each time. Should be cheap as there should never be too much keyframes,
            # if optimization is needed, check if resorting is needed, should
            # not be in 99 % of the cases.
            self.timelineElement.keyframes = sorted(
                self.timelineElement.keyframes, key=lambda keyframe: keyframe.value.timestamp)
            self.timelineElement.drawLines(self.line)
            # This will update the viewer. nifty.
            if not self.line:
                self.timelineElement.timeline._container.seekInPosition(
                    newTs + self.start)

        self.timelineElement.updating_keyframes = updating
Example #28
0
def mostCommonColor(img):
    colorsDic = {}
    h,w,_ = img.shape
    for i in range(0, h):
        for j in range(0, w):
            bgr = tuple(img[i,j,:])
            if not colorsDic.has_key(bgr):
                colorsDic[bgr] = 1
            else:
                colorsDic[bgr] += 1
    values = list(colorsDic.values())
    keys = list(colorsDic.keys())
    if keys:
        v1 = max(values)
        c1 = keys[values.index(v1)]
        frac1 = v1 / float((h*w))
        values.remove(max(values))
        keys.remove(c1)
        if len(keys) > 0:
            v2 = max(values)
            c2 = keys[values.index(v2)]
            frac2 = v2 / float((h*w))
            return c1, frac1, c2, frac2
        else:
            return c1, frac1, None, 0
    return None, 0, None, 0
Example #29
0
            def propagateConstraints_int(x, y):
                if x is None or y is None:
                    return None, None
                x1, x2, y1, y2 = x.min, x.max, y.min, y.max
                if cmp_t == 'ge' or cmp_t == 'gt':
                    x1, x2, y1, y2 = y1, y2, x1, x2 

                #treat greater like less than swap before and afterwards
                if cmp_t == 'lt' or cmp_t == 'gt':
                    x2 = min(x2, y2-1)
                    y1 = max(x1+1, y1)
                elif cmp_t == 'le' or cmp_t == 'ge':
                    x2 = min(x2, y2)
                    y1 = max(x1, y1)
                elif cmp_t == 'eq':
                    x1 = y1 = max(x1, y1)
                    x2 = y2 = min(x2, y2)
                elif cmp_t == 'ne':
                    if x1 == x2 == y1 == y2:
                        return None, None
                    if x1 == x2:
                        y1 = y1 if y1 != x1 else y1+1
                        y2 = y2 if y2 != x2 else y2-1               
                    if y1 == y2:
                        x1 = x1 if x1 != y1 else x1+1
                        x2 = x2 if x2 != y2 else x2-1

                if cmp_t == 'ge' or cmp_t == 'gt':
                    x1, x2, y1, y2 = y1, y2, x1, x2 
                con1 = IntConstraint.range(x.width, x1, x2) if x1 <= x2 else None   
                con2 = IntConstraint.range(y.width, y1, y2) if y1 <= y2 else None   
                return con1, con2
Example #30
0
def compare_chebhist(dname, mylambda, c, Nbin = 25):


    if mylambda == 'Do not exist':
        print('--!!Warning: eig file does not exist, can not display compare histgram')
    else:
        mylambda = 1 - mylambda
        lmin = max(min(mylambda), -1)
        lmax = min(max(mylambda),  1)

        # print c
        cheb_file_content = '\n'.join([str(st) for st in c])
        x = np.linspace(lmin, lmax, Nbin + 1)
        y = plot_chebint(c, x)
        u = (x[1:] + x[:-1]) / 2
        v =  y[1:] - y[:-1]

        plt.clf()
        plt.hold(True)
        plt.hist(mylambda,Nbin)
        plt.plot(u, v, "r.", markersize=10)
        plt.hold(False)
        plt.show()
        filename = 'data/' + dname + '.png'
        plt.savefig(filename)

        cheb_filename = 'data/' + dname + '.cheb'
        f = open(cheb_filename, 'w+')
        f.write(cheb_file_content)
        f.close()