function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def _dimensions_compatible(nrows, nvals, uniform_row_length): """Returns true if the given dimensions are compatible.""" nrows = tensor_shape.dimension_value(nrows[0]) nvals = tensor_shape.dimension_value(nvals[0]) ncols = tensor_shape.dimension_value(uniform_row_length[0]) if nrows == 0 and nvals not in (0, None): return False # can't have values if we have no rows. if ncols == 0 and nvals not in (0, None): return False # can't have values if we have no values in each row. if ncols is not None and nvals is not None: if ncols != 0 and nvals % ncols != 0: return False # rows aren't uniform. if nrows is not None and nvals != ncols * nrows: return False # inconsistent number of values. return True
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def _assert_monotonic_increasing(tensor, message=None): return check_ops.assert_non_negative( tensor[1:] - tensor[:-1], message=message)
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def _cast_if_not_none(tensor, dtype): return None if tensor is None else math_ops.cast(tensor, dtype)
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def _get_dtype_or_none(value): if isinstance(value, ops.Tensor): return value.dtype return None
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def _convert_all_to_tensors(values, dtype=None, dtype_hint=None): """Convert a list of objects to tensors of the same dtype.""" target_dtype = _get_target_dtype([x for (x, _) in values], dtype, dtype_hint) # If dtype is None, we use convert behavior. # If dtype is not None, we use cast behavior. convert_behavior = dtype is None if convert_behavior: return [ None if x is None else ops.convert_to_tensor( x, dtype=target_dtype, name=name) for (x, name) in values ] else: return [ None if x is None else math_ops.cast(x, dtype=target_dtype, name=name) for (x, name) in values ]
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def __init__(self): # Default domain self._domain = 'idn'
pyk/rojak
[ 98, 48, 98, 15, 1475386424 ]
def translate(self, domain): dic = {} dic['idn'] = { # Month 'Januari': 'January', 'Februari': 'February', 'Maret': 'March', 'April': 'April', 'Mei': 'May', 'Juni': 'June', 'Juli': 'July', 'Agustus': 'August', 'September': 'September', 'Oktober': 'October', 'November': 'November', 'Desember': 'December', # Month abbrevation 'Jan': 'Jan', 'Feb': 'Feb', 'Mar': 'Mar', 'Apr': 'Apr', 'Mei': 'May', 'Jun': 'Jun', 'Jul': 'Jul', 'Agt': 'Aug', 'Sep': 'Sep', 'Okt': 'Oct', 'Nov': 'Nov', 'Des': 'Dec', } return dic[domain] if domain in dic else {}
pyk/rojak
[ 98, 48, 98, 15, 1475386424 ]
def __init__(self, name='', label='', vtype='Scalar', value='', units='', type_choices=None):
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def __init__(self, n_variables=1): #----------------- # First approach #----------------- ## self.variables = [] ## for each in range(n_variables): ## self.variables.append( TF_Variable_Info() ) #------------------------------------------ # Alternate approach with some advantages #------------------------------------------ self.var_names = [] self.var_labels = [] self.var_types = [] self.var_values = [] self.var_units = [] self.var_type_choices = []
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def __init__(self, name='Infiltration', n_layers=1, n_variables=1): #---------------------------------------- # Each layer has a list of TF variables #---------------------------------------- self.n_layers = n_layers self.n_variables = n_variables # (per layer) self.layers = [] for each in range(n_layers): self.layers.append( TF_In_Variable_List(n_variables=n_variables) )
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def __init__(self, parent=None, id=-1, main_frame=None, xml_file="infil_richards_1D.xml"): #----------------------- # Try to find XML file #----------------------- files = glob.glob(xml_file) if (len(files) == 0): msg = "Can't find the XML file:\n\n" msg += (xml_file + "\n") dialog = wx.MessageBox(msg, caption='SORRY,') return
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def In_Variable_Notebook(self):
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def In_Variable_Wizard(self): pass
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def Timestep_Box(self): #--------------------------------------------- # Create sizer box for the process timestep #--------------------------------------------- time_info = self.proc_info.timestep unit_str = "[" + time_info.units + "]" ## unit_str = "[" + time_info.units + " / timestep]" L1 = wx.StaticText(self.panel, -1, time_info.label + ":") text = wx.TextCtrl(self.panel, -1, time_info.value) L2 = wx.StaticText(self.panel, -1, unit_str) #------------------------------------------------------- box = wx.BoxSizer(wx.HORIZONTAL) box.Add((3*self.hgap, 3*self.hgap), 1) box.Add(L1) box.Add((self.hgap, self.hgap), 1) box.Add(text) box.Add((self.hgap, self.hgap), 1) box.Add(L2) # self.SetSizer(box) ## (Bad to do this here.) return box
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def Button_Box(self): #---------------------------- # Create bottom button bar #---------------------------- okay_btn = wx.Button(self.panel, -1, "OK") help_btn = wx.Button(self.panel, -1, "Help") cancel_btn = wx.Button(self.panel, -1, "Cancel") #------------------------------------------------- box = wx.BoxSizer(wx.HORIZONTAL) proportion = 0 border = 5 box.Add((20,20), proportion, border) box.Add(okay_btn, proportion, border) box.Add((10,10), proportion, border) box.Add(help_btn, proportion, border) box.Add((10,10), proportion, border) box.Add(cancel_btn, proportion, border) box.Add((10,10), proportion, border) # box.AddMany([okay_btn, help_btn, cancel_btn]) #----------------------------------------------------- self.Bind(wx.EVT_BUTTON, self.On_OK, okay_btn) self.Bind(wx.EVT_BUTTON, self.On_Help, help_btn) self.Bind(wx.EVT_BUTTON, self.On_Cancel, cancel_btn) return box
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def On_OK(self, event): ################################################ # Need to now include "layer" as well when # saving values from text boxes to parent. # # Make sure that timestep gets saved also. ################################################ if (self.parent == None): print 'Sorry: This dialog has no parent dialog,' print 'so collected values cannot be saved.' print ' ' return
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def On_Help(self, event):
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def On_Cancel(self, event): self.Destroy()
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def Read_XML_Info(self): #--------------------------------------------------------- # Notes: It is helpful to have a look at the DOM specs, # which can be found online at: # http://www.w3.org/TR/1998/REC-DOM-Level-1- # 19981001/introduction.html # (see the tree diagram) # http://www.w3.org/TR/1998/REC-DOM-Level-1- # 19981001/level-one-core.html # (search for "firstChild") #---------------------------------------------------------
peckhams/topoflow
[ 25, 18, 25, 2, 1400880163 ]
def get_rect_height(name, obj): ''' calculate rectangle height ''' nlines = 1.5 nlines += len(getattr(obj, '_all_attrs', [])) nlines += len(getattr(obj, '_single_child_objects', [])) nlines += len(getattr(obj, '_multi_child_objects', [])) nlines += len(getattr(obj, '_multi_parent_objects', [])) return nlines*line_heigth
CINPLA/expipe-dev
[ 2, 2, 2, 3, 1494700368 ]
def calc_coordinates(pos, height): x = pos[0] y = pos[1] + height - line_heigth*.5 return pos[0], y
CINPLA/expipe-dev
[ 2, 2, 2, 3, 1494700368 ]
def generate_diagram_simple(): figsize = (18, 12) rw = rect_width = 3. bf = blank_fact = 1.2 rect_pos = {'Block': (.5+rw*bf*0, 4), 'Segment': (.5+rw*bf*1, .5), 'Event': (.5+rw*bf*4, 3.0), 'Epoch': (.5+rw*bf*4, 1.0), 'ChannelIndex': (.5+rw*bf*1, 7.5), 'Unit': (.5+rw*bf*2., 9.9), 'SpikeTrain': (.5+rw*bf*3, 7.5), 'IrregularlySampledSignal': (.5+rw*bf*3, 0.5), 'AnalogSignal': (.5+rw*bf*3, 4.9), } generate_diagram('simple_generated_diagram.svg', rect_pos, rect_width, figsize) generate_diagram('simple_generated_diagram.png', rect_pos, rect_width, figsize)
CINPLA/expipe-dev
[ 2, 2, 2, 3, 1494700368 ]
def _async_find_matching_config_entry(hass): for entry in hass.config_entries.async_entries(DOMAIN): if entry.source == config_entries.SOURCE_IMPORT: return entry
tchellomello/home-assistant
[ 7, 1, 7, 6, 1467778429 ]
def _start_auto_update() -> None: """Start isy auto update.""" _LOGGER.debug("ISY Starting Event Stream and automatic updates") isy.auto_update = True
tchellomello/home-assistant
[ 7, 1, 7, 6, 1467778429 ]
def _async_import_options_from_data_if_missing( hass: HomeAssistant, entry: config_entries.ConfigEntry
tchellomello/home-assistant
[ 7, 1, 7, 6, 1467778429 ]
def _stop_auto_update() -> None: """Start isy auto update.""" _LOGGER.debug("ISY Stopping Event Stream and automatic updates") isy.auto_update = False
tchellomello/home-assistant
[ 7, 1, 7, 6, 1467778429 ]
def drawSymbol(painter, symbol, size, pen, brush): if symbol is None: return painter.scale(size, size) painter.setPen(pen) painter.setBrush(brush) if isinstance(symbol, basestring): symbol = Symbols[symbol] if np.isscalar(symbol): symbol = list(Symbols.values())[symbol % len(Symbols)] painter.drawPath(symbol)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def makeSymbolPixmap(size, pen, brush, symbol): ## deprecated img = renderSymbol(symbol, size, pen, brush) return QtGui.QPixmap(img)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def __init__(self): # symbol key : QRect(...) coordinates where symbol can be found in atlas. # note that the coordinate list will always be the same list object as # long as the symbol is in the atlas, but the coordinates may # change if the atlas is rebuilt. # weak value; if all external refs to this list disappear, # the symbol will be forgotten. self.symbolMap = weakref.WeakValueDictionary() self.atlasData = None # numpy array of atlas image self.atlas = None # atlas as QPixmap self.atlasValid = False self.max_width=0
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def buildAtlas(self): # get rendered array for all symbols, keep track of avg/max width rendered = {} avgWidth = 0.0 maxWidth = 0 images = [] for key, sourceRect in self.symbolMap.items(): if sourceRect.width() == 0: img = renderSymbol(key[0], key[1], sourceRect.pen, sourceRect.brush) images.append(img) ## we only need this to prevent the images being garbage collected immediately arr = fn.imageToArray(img, copy=False, transpose=False) else: (y,x,h,w) = sourceRect.getRect() arr = self.atlasData[int(x):int(x+w), int(y):int(y+w)] rendered[key] = arr w = arr.shape[0] avgWidth += w maxWidth = max(maxWidth, w) nSymbols = len(rendered) if nSymbols > 0: avgWidth /= nSymbols width = max(maxWidth, avgWidth * (nSymbols**0.5)) else: avgWidth = 0 width = 0 # sort symbols by height symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True) self.atlasRows = [] x = width y = 0 rowheight = 0 for key in symbols: arr = rendered[key] w,h = arr.shape[:2] if x+w > width: y += rowheight x = 0 rowheight = h self.atlasRows.append([y, rowheight, 0]) self.symbolMap[key].setRect(y, x, h, w) x += w self.atlasRows[-1][2] = x height = y + rowheight self.atlasData = np.zeros((int(width), int(height), 4), dtype=np.ubyte) for key in symbols: y, x, h, w = self.symbolMap[key].getRect() self.atlasData[int(x):int(x+w), int(y):int(y+h)] = rendered[key] self.atlas = None self.atlasValid = True self.max_width = maxWidth
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def __init__(self, *args, **kargs): """ Accepts the same arguments as setData() """ profiler = debug.Profiler() GraphicsObject.__init__(self) self.picture = None # QPicture used for rendering when pxmode==False self.fragmentAtlas = SymbolAtlas() self.data = np.empty(0, dtype=[('x', float), ('y', float), ('size', float), ('symbol', object), ('pen', object), ('brush', object), ('data', object), ('item', object), ('sourceRect', object), ('targetRect', object), ('width', float)]) self.bounds = [None, None] ## caches data bounds self._maxSpotWidth = 0 ## maximum size of the scale-variant portion of all spots self._maxSpotPxWidth = 0 ## maximum size of the scale-invariant portion of all spots self.opts = { 'pxMode': True, 'useCache': True, ## If useCache is False, symbols are re-drawn on every paint. 'antialias': getConfigOption('antialias'), 'name': None, } self.setPen(fn.mkPen(getConfigOption('foreground')), update=False) self.setBrush(fn.mkBrush(100,100,150), update=False) self.setSymbol('o', update=False) self.setSize(7, update=False) profiler() self.setData(*args, **kargs) profiler('setData') #self.setCacheMode(self.DeviceCoordinateCache)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def addPoints(self, *args, **kargs): """ Add new points to the scatter plot. Arguments are the same as setData() """ ## deal with non-keyword arguments if len(args) == 1: kargs['spots'] = args[0] elif len(args) == 2: kargs['x'] = args[0] kargs['y'] = args[1] elif len(args) > 2: raise Exception('Only accepts up to two non-keyword arguments.') ## convert 'pos' argument to 'x' and 'y' if 'pos' in kargs: pos = kargs['pos'] if isinstance(pos, np.ndarray): kargs['x'] = pos[:,0] kargs['y'] = pos[:,1] else: x = [] y = [] for p in pos: if isinstance(p, QtCore.QPointF): x.append(p.x()) y.append(p.y()) else: x.append(p[0]) y.append(p[1]) kargs['x'] = x kargs['y'] = y ## determine how many spots we have if 'spots' in kargs: numPts = len(kargs['spots']) elif 'y' in kargs and kargs['y'] is not None: numPts = len(kargs['y']) else: kargs['x'] = [] kargs['y'] = [] numPts = 0 ## Extend record array oldData = self.data self.data = np.empty(len(oldData)+numPts, dtype=self.data.dtype) ## note that np.empty initializes object fields to None and string fields to '' self.data[:len(oldData)] = oldData #for i in range(len(oldData)): #oldData[i]['item']._data = self.data[i] ## Make sure items have proper reference to new array newData = self.data[len(oldData):] newData['size'] = -1 ## indicates to use default size if 'spots' in kargs: spots = kargs['spots'] for i in range(len(spots)): spot = spots[i] for k in spot: if k == 'pos': pos = spot[k] if isinstance(pos, QtCore.QPointF): x,y = pos.x(), pos.y() else: x,y = pos[0], pos[1] newData[i]['x'] = x newData[i]['y'] = y elif k == 'pen': newData[i][k] = fn.mkPen(spot[k]) elif k == 'brush': newData[i][k] = fn.mkBrush(spot[k]) elif k in ['x', 'y', 'size', 'symbol', 'brush', 'data']: newData[i][k] = spot[k] else: raise Exception("Unknown spot parameter: %s" % k) elif 'y' in kargs: newData['x'] = kargs['x'] newData['y'] = kargs['y'] if 'pxMode' in kargs: self.setPxMode(kargs['pxMode']) if 'antialias' in kargs: self.opts['antialias'] = kargs['antialias'] ## Set any extra parameters provided in keyword arguments for k in ['pen', 'brush', 'symbol', 'size']: if k in kargs: setMethod = getattr(self, 'set' + k[0].upper() + k[1:]) setMethod(kargs[k], update=False, dataSet=newData, mask=kargs.get('mask', None)) if 'data' in kargs: self.setPointData(kargs['data'], dataSet=newData) self.prepareGeometryChange() self.informViewBoundsChanged() self.bounds = [None, None] self.invalidate() self.updateSpots(newData) self.sigPlotChanged.emit(self)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def getData(self): return self.data['x'], self.data['y']
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def implements(self, interface=None): ints = ['plotData'] if interface is None: return ints return interface in ints
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setPen(self, *args, **kargs): """Set the pen(s) used to draw the outline around each spot. If a list or array is provided, then the pen for each spot will be set separately. Otherwise, the arguments are passed to pg.mkPen and used as the default pen for all spots which do not have a pen explicitly set.""" update = kargs.pop('update', True) dataSet = kargs.pop('dataSet', self.data) if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): pens = args[0] if 'mask' in kargs and kargs['mask'] is not None: pens = pens[kargs['mask']] if len(pens) != len(dataSet): raise Exception("Number of pens does not match number of points (%d != %d)" % (len(pens), len(dataSet))) dataSet['pen'] = pens else: self.opts['pen'] = fn.mkPen(*args, **kargs) dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setSymbol(self, symbol, update=True, dataSet=None, mask=None): """Set the symbol(s) used to draw each spot. If a list or array is provided, then the symbol for each spot will be set separately. Otherwise, the argument will be used as the default symbol for all spots which do not have a symbol explicitly set.""" if dataSet is None: dataSet = self.data if isinstance(symbol, np.ndarray) or isinstance(symbol, list): symbols = symbol if mask is not None: symbols = symbols[mask] if len(symbols) != len(dataSet): raise Exception("Number of symbols does not match number of points (%d != %d)" % (len(symbols), len(dataSet))) dataSet['symbol'] = symbols else: self.opts['symbol'] = symbol self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setPointData(self, data, dataSet=None, mask=None): if dataSet is None: dataSet = self.data if isinstance(data, np.ndarray) or isinstance(data, list): if mask is not None: data = data[mask] if len(data) != len(dataSet): raise Exception("Length of meta data does not match number of points (%d != %d)" % (len(data), len(dataSet))) ## Bug: If data is a numpy record array, then items from that array must be copied to dataSet one at a time. ## (otherwise they are converted to tuples and thus lose their field names. if isinstance(data, np.ndarray) and (data.dtype.fields is not None)and len(data.dtype.fields) > 1: for i, rec in enumerate(data): dataSet['data'][i] = rec else: dataSet['data'] = data
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def updateSpots(self, dataSet=None): if dataSet is None: dataSet = self.data invalidate = False if self.opts['pxMode']: mask = np.equal(dataSet['sourceRect'], None) if np.any(mask): invalidate = True opts = self.getSpotOpts(dataSet[mask]) sourceRect = self.fragmentAtlas.getSymbolCoords(opts) dataSet['sourceRect'][mask] = sourceRect self.fragmentAtlas.getAtlas() # generate atlas so source widths are available. dataSet['width'] = np.array(list(imap(QtCore.QRectF.width, dataSet['sourceRect'])))/2 dataSet['targetRect'] = None self._maxSpotPxWidth = self.fragmentAtlas.max_width else: self._maxSpotWidth = 0 self._maxSpotPxWidth = 0 self.measureSpotSizes(dataSet) if invalidate: self.invalidate()
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def measureSpotSizes(self, dataSet): for rec in dataSet: ## keep track of the maximum spot size and pixel size symbol, size, pen, brush = self.getSpotOpts(rec) width = 0 pxWidth = 0 if self.opts['pxMode']: pxWidth = size + pen.widthF() else: width = size if pen.isCosmetic(): pxWidth += pen.widthF() else: width += pen.widthF() self._maxSpotWidth = max(self._maxSpotWidth, width) self._maxSpotPxWidth = max(self._maxSpotPxWidth, pxWidth) self.bounds = [None, None]
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def dataBounds(self, ax, frac=1.0, orthoRange=None): if frac >= 1.0 and orthoRange is None and self.bounds[ax] is not None: return self.bounds[ax] #self.prepareGeometryChange() if self.data is None or len(self.data) == 0: return (None, None) if ax == 0: d = self.data['x'] d2 = self.data['y'] elif ax == 1: d = self.data['y'] d2 = self.data['x'] if orthoRange is not None: mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1]) d = d[mask] d2 = d2[mask] if frac >= 1.0: self.bounds[ax] = (np.nanmin(d) - self._maxSpotWidth*0.7072, np.nanmax(d) + self._maxSpotWidth*0.7072) return self.bounds[ax] elif frac <= 0.0: raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac)) else: mask = np.isfinite(d) d = d[mask] return np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)])
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def boundingRect(self): (xmn, xmx) = self.dataBounds(ax=0) (ymn, ymx) = self.dataBounds(ax=1) if xmn is None or xmx is None: xmn = 0 xmx = 0 if ymn is None or ymx is None: ymn = 0 ymx = 0 px = py = 0.0 pxPad = self.pixelPadding() if pxPad > 0: # determine length of pixel in local x, y directions px, py = self.pixelVectors() try: px = 0 if px is None else px.length() except OverflowError: px = 0 try: py = 0 if py is None else py.length() except OverflowError: py = 0 # return bounds expanded by pixel size px *= pxPad py *= pxPad return QtCore.QRectF(xmn-px, ymn-py, (2*px)+xmx-xmn, (2*py)+ymx-ymn)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setExportMode(self, *args, **kwds): GraphicsObject.setExportMode(self, *args, **kwds) self.invalidate()
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def getViewMask(self, pts): # Return bool mask indicating all points that are within viewbox # pts is expressed in *device coordiantes* vb = self.getViewBox() if vb is None: return None viewBounds = vb.mapRectToDevice(vb.boundingRect()) w = self.data['width'] mask = ((pts[0] + w > viewBounds.left()) & (pts[0] - w < viewBounds.right()) & (pts[1] + w > viewBounds.top()) & (pts[1] - w < viewBounds.bottom())) ## remove out of view points return mask
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def paint(self, p, *args): #p.setPen(fn.mkPen('r')) #p.drawRect(self.boundingRect()) if self._exportOpts is not False: aa = self._exportOpts.get('antialias', True) scale = self._exportOpts.get('resolutionScale', 1.0) ## exporting to image; pixel resolution may have changed else: aa = self.opts['antialias'] scale = 1.0 if self.opts['pxMode'] is True: p.resetTransform() # Map point coordinates to device pts = np.vstack([self.data['x'], self.data['y']]) pts = self.mapPointsToDevice(pts) if pts is None: return # Cull points that are outside view viewMask = self.getViewMask(pts) #pts = pts[:,mask] #data = self.data[mask] if self.opts['useCache'] and self._exportOpts is False: # Draw symbols from pre-rendered atlas atlas = self.fragmentAtlas.getAtlas() # Update targetRects if necessary updateMask = viewMask & np.equal(self.data['targetRect'], None) if np.any(updateMask): updatePts = pts[:,updateMask] width = self.data[updateMask]['width']*2 self.data['targetRect'][updateMask] = list(imap(QtCore.QRectF, updatePts[0,:], updatePts[1,:], width, width)) data = self.data[viewMask] if USE_PYSIDE or USE_PYQT5: list(imap(p.drawPixmap, data['targetRect'], repeat(atlas), data['sourceRect'])) else: p.drawPixmapFragments(data['targetRect'].tolist(), data['sourceRect'].tolist(), atlas) else: # render each symbol individually p.setRenderHint(p.Antialiasing, aa) data = self.data[viewMask] pts = pts[:,viewMask] for i, rec in enumerate(data): p.resetTransform() p.translate(pts[0,i] + rec['width'], pts[1,i] + rec['width']) drawSymbol(p, *self.getSpotOpts(rec, scale)) else: if self.picture is None: self.picture = QtGui.QPicture() p2 = QtGui.QPainter(self.picture) for rec in self.data: if scale != 1.0: rec = rec.copy() rec['size'] *= scale p2.resetTransform() p2.translate(rec['x'], rec['y']) drawSymbol(p2, *self.getSpotOpts(rec, scale)) p2.end() p.setRenderHint(p.Antialiasing, aa) self.picture.play(p)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def pointsAt(self, pos): x = pos.x() y = pos.y() pw = self.pixelWidth() ph = self.pixelHeight() pts = [] for s in self.points(): sp = s.pos() ss = s.size() sx = sp.x() sy = sp.y() s2x = s2y = ss * 0.5 if self.opts['pxMode']: s2x *= pw s2y *= ph if x > sx-s2x and x < sx+s2x and y > sy-s2y and y < sy+s2y: pts.append(s) #print "HIT:", x, y, sx, sy, s2x, s2y #else: #print "No hit:", (x, y), (sx, sy) #print " ", (sx-s2x, sy-s2y), (sx+s2x, sy+s2y) return pts[::-1]
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def __init__(self, data, plot): #GraphicsItem.__init__(self, register=False) self._data = data self._plot = plot #self.setParentItem(plot) #self.setPos(QtCore.QPointF(data['x'], data['y'])) #self.updateItem()
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def size(self): """Return the size of this spot. If the spot has no explicit size set, then return the ScatterPlotItem's default size instead.""" if self._data['size'] == -1: return self._plot.opts['size'] else: return self._data['size']
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def viewPos(self): return self._plot.mapToView(self.pos())
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def symbol(self): """Return the symbol of this spot. If the spot has no explicit symbol set, then return the ScatterPlotItem's default symbol instead. """ symbol = self._data['symbol'] if symbol is None: symbol = self._plot.opts['symbol'] try: n = int(symbol) symbol = list(Symbols.keys())[n % len(Symbols)] except: pass return symbol
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def pen(self): pen = self._data['pen'] if pen is None: pen = self._plot.opts['pen'] return fn.mkPen(pen)
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def resetPen(self): """Remove the pen set for this spot; the scatter plot's default pen will be used instead.""" self._data['pen'] = None ## Note this is NOT the same as calling setPen(None) self.updateItem()
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setBrush(self, *args, **kargs): """Set the fill brush for this spot""" brush = fn.mkBrush(*args, **kargs) self._data['brush'] = brush self.updateItem()
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def setData(self, data): """Set the user-data associated with this spot""" self._data['data'] = data
AOtools/soapy
[ 63, 29, 63, 26, 1411121358 ]
def addBeginEndInnerXMLTag(attributes, depth, innerText, localName, output, text=''): 'Add the begin and end xml tag and the inner text if any.' if len( innerText ) > 0: addBeginXMLTag(attributes, depth, localName, output, text) output.write( innerText ) addEndXMLTag(depth, localName, output) else: addClosedXMLTag(attributes, depth, localName, output, text)
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def addClosedXMLTag(attributes, depth, localName, output, text=''): 'Add the closed xml tag.' depthStart = '\t' * depth attributesString = getAttributesString(attributes) if len(text) > 0: output.write('%s<%s%s >%s</%s>\n' % (depthStart, localName, attributesString, text, localName)) else: output.write('%s<%s%s />\n' % (depthStart, localName, attributesString))
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def addXMLFromLoopComplexZ(attributes, depth, loop, output, z): 'Add xml from loop.' addBeginXMLTag(attributes, depth, 'path', output) for pointComplexIndex in xrange(len(loop)): pointComplex = loop[pointComplexIndex] addXMLFromXYZ(depth + 1, pointComplexIndex, output, pointComplex.real, pointComplex.imag, z) addEndXMLTag(depth, 'path', output)
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def addXMLFromVertexes(depth, output, vertexes): 'Add xml from loop.' for vertexIndex in xrange(len(vertexes)): vertex = vertexes[vertexIndex] addXMLFromXYZ(depth + 1, vertexIndex, output, vertex.x, vertex.y, vertex.z)
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def compareAttributeKeyAscending(key, otherKey): 'Get comparison in order to sort attribute keys in ascending order, with the id key first and name second.' if key == 'id': return - 1 if otherKey == 'id': return 1 if key == 'name': return - 1 if otherKey == 'name': return 1 if key < otherKey: return - 1 return int(key > otherKey)
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def getBeginGeometryXMLOutput(elementNode=None): 'Get the beginning of the string representation of this boolean geometry object info.' output = getBeginXMLOutput() attributes = {} if elementNode != None: documentElement = elementNode.getDocumentElement() attributes = documentElement.attributes addBeginXMLTag(attributes, 0, 'fabmetheus', output) return output
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def getDictionaryWithoutList(dictionary, withoutList): 'Get the dictionary without the keys in the list.' dictionaryWithoutList = {} for key in dictionary: if key not in withoutList: dictionaryWithoutList[key] = dictionary[key] return dictionaryWithoutList
dob71/x2swn
[ 13, 8, 13, 5, 1345256205 ]
def shout(self, sender, body, match): body = body.upper() #SHOUT IT self.broadcast(body)
mattlong/hermes
[ 132, 11, 132, 2, 1330490300 ]
def test_version_definitions(path): assert path.suffix == '.json', '{} has wrong extension'.format(path) assert re.match(r'^\d\.\d(?:\-32)?$', path.stem), \ '{} has invalid name'.format(path) with path.open() as f: data = json.load(f) schema = data.pop('type') possible_types = snafu.versions.InstallerType.__members__ assert schema in possible_types assert isinstance(data.pop('version_info'), list) if schema == 'cpython_msi': for key in ('x86', 'amd64'): d = data.pop(key) assert d.pop('url') assert re.match(r'^[a-f\d]{32}$', d.pop('md5_sum')) elif schema == 'cpython': assert data.pop('url') assert re.match(r'^[a-f\d]{32}$', data.pop('md5_sum')) assert not data, 'superfulous keys: {}'.format(', '.join(data.keys()))
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_get_version_cpython_msi_switch(): version = snafu.versions.get_version('3.4', force_32=True) assert version == snafu.versions.CPythonMSIVersion( name='3.4', url='https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi', md5_sum='e96268f7042d2a3d14f7e23b2535738b', version_info=(3, 4, 4), )
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_get_version_cpython_switch(): version = snafu.versions.get_version('3.5', force_32=True) assert version == snafu.versions.CPythonVersion( name='3.5-32', url='https://www.python.org/ftp/python/3.5.4/python-3.5.4.exe', md5_sum='9693575358f41f452d03fd33714f223f', version_info=(3, 5, 4), forced_32=True, )
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_str(name, force_32, result): version = snafu.versions.get_version(name, force_32=force_32) assert str(version) == result
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_python_major_command(mocker, name, force_32, cmd): mocker.patch.object(snafu.versions, 'configs', **{ 'get_scripts_dir_path.return_value': pathlib.Path(), }) version = snafu.versions.get_version(name, force_32=force_32) assert version.python_major_command == pathlib.Path(cmd)
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_arch_free_name(name, force_32, result): version = snafu.versions.get_version(name, force_32=force_32) assert version.arch_free_name == result
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def test_script_version_names(name, force_32, result): version = snafu.versions.get_version(name, force_32=force_32) assert version.script_version_names == result
uranusjr/snafu
[ 25, 1, 25, 7, 1506980534 ]
def __init__(self, name, device: str, interface: str = 'USB', port: int = 8004, server: str = '', **kw) -> None: """ Input arguments: name: (str) name of the instrument device (str) the name of the device e.g., "dev8008" interface (str) the name of the interface to use ('1GbE' or 'USB') port (int) the port to connect to for the ziDataServer (don't change) server: (str) the host where the ziDataServer is running """ t0 = time.time() # Our base class includes all the functionality needed to initialize # the parameters of the object. Those parameters are read from # instrument-specific JSON files stored in the zi_parameter_files # folder. super().__init__( name=name, device=device, interface=interface, server=server, port=port, awg_module=False, **kw) t1 = time.time() print('Initialized PQSC', self.devname, 'in %.2fs' % (t1 - t0))
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def _check_devtype(self): if self.devtype != 'PQSC': raise zibase.ziDeviceError('Device {} of type {} is not a PQSC \ instrument!'.format(self.devname, self.devtype))
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def _check_versions(self): """ Checks that sufficient versions of the firmware are available. """ if self.geti('system/fwrevision') < ZI_PQSC.MIN_FWREVISION: raise zibase.ziVersionError( 'Insufficient firmware revision detected! Need {}, got {}!'. format(ZI_PQSC.MIN_FWREVISION, self.geti('system/fwrevision'))) if self.geti('system/fpgarevision') < ZI_PQSC.MIN_FPGAREVISION: raise zibase.ziVersionError( 'Insufficient FPGA revision detected! Need {}, got {}!'.format( ZI_PQSC.MIN_FPGAREVISION, self.geti('system/fpgarevision')))
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def clock_freq(self): return 300e6
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def check_errors(self, errors_to_ignore=None) -> None: """ Checks the instrument for errors. """ errors = json.loads(self.getv('raw/error/json/errors')) # If this is the first time we are called, log the detected errors, # but don't raise any exceptions if self._errors is None: raise_exceptions = False self._errors = {} else: raise_exceptions = True # Asserted in case errors were found found_errors = False # Combine errors_to_ignore with commandline _errors_to_ignore = copy.copy(self._errors_to_ignore) if errors_to_ignore is not None: _errors_to_ignore += errors_to_ignore # Go through the errors and update our structure, raise exceptions if # anything changed for m in errors['messages']: code = m['code'] count = m['count'] severity = m['severity'] message = m['message'] if not raise_exceptions: self._errors[code] = { 'count' : count, 'severity': severity, 'message' : message} log.warning(f'{self.devname}: Code {code}: "{message}" ({severity})') else: # Check if there are new errors if code not in self._errors or count > self._errors[code]['count']: if code in _errors_to_ignore: log.warning(f'{self.devname}: {message} ({code}/{severity})') else: log.error(f'{self.devname}: {message} ({code}/{severity})') found_errors = True if code in self._errors: self._errors[code]['count'] = count else: self._errors[code] = { 'count' : count, 'severity': severity, 'message' : message} if found_errors: raise zibase.ziRuntimeError('Errors detected during run-time!')
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def set_holdoff(self, holdoff: float): '''Sets the interval between triggers in seconds. Set to 1e-3 for generating triggers at 1kHz, etc.''' self.set('execution_holdoff', holdoff)
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def track_progress(self): '''Prints a progress bar.''' # TODO
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def stop(self): log.info('Stopping {}'.format(self.name)) # Stop the execution unit self.set('execution_enable', 0) self.check_errors()
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def reader(fname): bcvocab = {} with open(fname, 'r') as fin: for line in fin: items = line.strip().split('\t') bcvocab[items[1]] = items[0] return bcvocab
jiyfeng/DPLP
[ 112, 36, 112, 6, 1397147848 ]
def test(self, term): for ch in term: if ord(ch) > 2048: return False return True
west-tandon/ReSearch
[ 2, 1, 2, 5, 1481640884 ]
def __init__(self): self.stopwords = set(stopwords.words('english'))
west-tandon/ReSearch
[ 2, 1, 2, 5, 1481640884 ]
def check_barrier(): barrier.acquire() barrier.value += 1 barrier.release() while barrier.value < CLI_PROC_COUNT * CLI_THR_COUNT: pass
dsiroky/snakemq
[ 123, 29, 123, 2, 1338287743 ]
def srv(): s = snakemq.link.Link() container = {"start_time": None, "cli_count": 0, "count": 0} def on_connect(conn_id): container["cli_count"] += 1 if container["cli_count"] == CLI_PROC_COUNT * CLI_THR_COUNT: container["start_time"] = time.time() print "all connected" def on_packet_recv(conn_id, packet): assert len(packet) == DATA_SIZE container["count"] += 1 if container["count"] >= PACKETS_COUNT * CLI_PROC_COUNT * CLI_THR_COUNT: s.stop() s.add_listener(("", PORT)) tr = snakemq.packeter.Packeter(s) tr.on_connect = on_connect tr.on_packet_recv = on_packet_recv s.loop() s.cleanup() diff = time.time() - container["start_time"] count = container["count"] print "flow: %.02f MBps, total %i pkts, %i pkts/s" % ( DATA_SIZE * count / diff / 1024**2, count, count / diff)
dsiroky/snakemq
[ 123, 29, 123, 2, 1338287743 ]
def cli(): s = snakemq.link.Link() def on_connect(conn_id): check_barrier() for i in xrange(PACKETS_COUNT): tr.send_packet(conn_id, "x" * DATA_SIZE) def on_disconnect(conn_id): s.stop() # listen queue on the server is short so the reconnect interval needs to be # short because all clients are trying to connect almost at the same time s.add_connector(("localhost", PORT), reconnect_interval=0.3) # spread the connections time.sleep(random.randint(0, 1000) / 1000.0) tr = snakemq.packeter.Packeter(s) tr.on_connect = on_connect tr.on_disconnect = on_disconnect s.loop() s.cleanup()
dsiroky/snakemq
[ 123, 29, 123, 2, 1338287743 ]
def __unicode__(self): return self.name or self.device_id or self.registration_id
amyth/django-instapush
[ 15, 4, 15, 3, 1438939624 ]
def send_message(self, message, **kwargs): """ Sends a push notification to this device via GCM """ from ..libs.gcm import gcm_send_message data = kwargs.pop("extra", {}) if message is not None: data["message"] = message return gcm_send_message(registration_id=self.registration_id, data=data, **kwargs)
amyth/django-instapush
[ 15, 4, 15, 3, 1438939624 ]
def convert_24hour(time): """ Takes 12 hour time as a string and converts it to 24 hour time. """ if len(time[:-2].split(':')) < 2: hour = time[:-2] minute = '00' else: hour, minute = time[:-2].split(':') if time[-2:] == 'AM': time_formatted = hour + ':' + minute elif time[-2:] == 'PM': time_formatted = str(int(hour)+ 12) + ':' + minute if time_formatted in ['24:00','0:00','00:00']: time_formatted = '23:59' return time_formatted
iandees/all-the-places
[ 379, 151, 379, 602, 1465952958 ]
def parse(self, response): state_urls = response.xpath('//li[@class="col-sm-12 col-md-4"]/a/@href').extract() is_store_details_urls = response.xpath('//a[@class="store-details-link"]/@href').extract() if not state_urls and is_store_details_urls: for url in is_store_details_urls: yield scrapy.Request(response.urljoin(url), callback=self.parse_store) else: for url in state_urls: yield scrapy.Request(response.urljoin(url))
iandees/all-the-places
[ 379, 151, 379, 602, 1465952958 ]
def __init__(self, parent=None, suffix='', siPrefix=False, averageTime=0, formatStr=None): """ Arguments: *suffix* (str or None) The suffix to place after the value *siPrefix* (bool) Whether to add an SI prefix to the units and display a scaled value *averageTime* (float) The length of time in seconds to average values. If this value is 0, then no averaging is performed. As this value increases the display value will appear to change more slowly and smoothly. *formatStr* (str) Optionally, provide a format string to use when displaying text. The text will be generated by calling formatStr.format(value=, avgValue=, suffix=) (see Python documentation on str.format) This option is not compatible with siPrefix """ QtGui.QLabel.__init__(self, parent) self.values = [] self.averageTime = averageTime ## no averaging by default self.suffix = suffix self.siPrefix = siPrefix if formatStr is None: formatStr = '{avgValue:0.2g} {suffix}' self.formatStr = formatStr
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def setValue(self, value): now = time() self.values.append((now, value)) cutoff = now - self.averageTime while len(self.values) > 0 and self.values[0][0] < cutoff: self.values.pop(0) self.update()
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def setFormatStr(self, text): self.formatStr = text self.update()
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def averageValue(self): return reduce(lambda a,b: a+b, [v[1] for v in self.values]) / float(len(self.values))
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def paintEvent(self, ev): self.setText(self.generateText()) return QtGui.QLabel.paintEvent(self, ev)
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def generateText(self): if len(self.values) == 0: return '' avg = self.averageValue() val = self.values[-1][1] if self.siPrefix: return pg.siFormat(avg, suffix=self.suffix) else: return self.formatStr.format(value=val, avgValue=avg, suffix=self.suffix)
robertsj/poropy
[ 6, 12, 6, 3, 1324137820 ]
def font(self): """ Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute.
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def font(self, val): self["font"] = val
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def side(self): """ Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute.
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def side(self, val): self["side"] = val
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def text(self): """ Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated.
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def text(self, val): self["text"] = val
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def _prop_descriptions(self): return """\ font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. """
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def shutdown_all(signum, frame): for bot in bots: if bot.state == PineappleBot.RUNNING: bot.shutdown() sys.exit("Shutdown complete")
Chronister/ananas
[ 59, 12, 59, 4, 1504080376 ]