_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q19400
ItModule.bruteVersionStr
train
def bruteVersionStr(self, valu): ''' Brute force the version out of a string. Args: valu (str): String to attempt to get version information for. Notes: This first attempts to parse strings using the it:semver normalization before attempting to extract version parts out of the string. Returns: int, dict: The system normalized version integer and a subs dictionary. ''' try: valu, info = self.core.model.type('it:semver').norm(valu) subs = info.get('subs') return valu, subs except s_exc.BadTypeValu: # Try doing version part extraction by noming through the string
python
{ "resource": "" }
q19401
chopurl
train
def chopurl(url): ''' A sane "stand alone" url parser. Example: info = chopurl(url) ''' ret = {} if url.find('://') == -1: raise s_exc.BadUrl(':// not found in [{}]!'.format(url)) scheme, remain = url.split('://', 1) ret['scheme'] = scheme.lower() # carve query params from the end if remain.find('?') != -1: query = {} remain, queryrem = remain.split('?', 1) for qkey in queryrem.split('&'): qval = None if qkey.find('=') != -1: qkey, qval = qkey.split('=', 1) query[qkey] = qval ret['query'] = query pathrem = '' slashoff = remain.find('/') if slashoff != -1: pathrem = remain[slashoff:] remain = remain[:slashoff] # detect user[:passwd]@netloc syntax if remain.find('@') != -1: user, remain = remain.rsplit('@', 1) if user.find(':') != -1: user, passwd = user.split(':', 1) ret['passwd'] = passwd ret['user'] = user # remain should be down to host[:port] # detect ipv6 [addr]:port
python
{ "resource": "" }
q19402
HashSet.eatfd
train
def eatfd(self, fd): ''' Consume all the bytes from a file like object. Example: hset = HashSet() hset.eatfd(fd) ''' fd.seek(0)
python
{ "resource": "" }
q19403
HashSet.update
train
def update(self, byts): ''' Update all the hashes in the set with the given bytes. '''
python
{ "resource": "" }
q19404
claim
train
def claim(typ, **info): ''' Add an entry to the provenance stack for the duration of the context ''' stack = s_task.varget('provstack') if len(stack) > 256: # pragma: no cover
python
{ "resource": "" }
q19405
dupstack
train
def dupstack(newtask): ''' Duplicate the current provenance stack onto another task '''
python
{ "resource": "" }
q19406
ProvStor.getProvStack
train
def getProvStack(self, iden: bytes): ''' Returns the provenance stack given the iden to it
python
{ "resource": "" }
q19407
ProvStor.provStacks
train
def provStacks(self, offs, size): ''' Returns a stream of provenance stacks at the given offset ''' for _, iden in self.provseq.slice(offs, size):
python
{ "resource": "" }
q19408
ProvStor.getProvIden
train
def getProvIden(self, provstack): ''' Returns the iden corresponding to a provenance stack and stores if it hasn't seen it before ''' iden = _providen(provstack) misc, frames = provstack # Convert each frame back from (k, v) tuples to a dict dictframes = [(typ, {k: v for (k, v) in info}) for
python
{ "resource": "" }
q19409
ProvStor.commit
train
def commit(self): ''' Writes the current provenance stack to storage if it wasn't already there and returns it Returns (Tuple[bool, str, List[]]): Whether the stack was not cached, the iden of the prov stack, and the provstack ''' providen, provstack = get()
python
{ "resource": "" }
q19410
SlabSeqn.save
train
def save(self, items): ''' Save a series of items to a sequence. Args: items (tuple): The series of items to save into the sequence. Returns: The index of the first item ''' rows = [] indx = self.indx size = 0 tick = s_common.now() for item in items: byts = s_msgpack.en(item) size += len(byts) lkey = s_common.int64en(indx)
python
{ "resource": "" }
q19411
SlabSeqn.nextindx
train
def nextindx(self): ''' Determine the next insert offset according to storage. Returns: int: The next insert offset. ''' indx = 0 with s_lmdbslab.Scan(self.slab, self.db) as curs:
python
{ "resource": "" }
q19412
SlabSeqn.iter
train
def iter(self, offs): ''' Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item. ''' startkey = s_common.int64en(offs)
python
{ "resource": "" }
q19413
SlabSeqn.rows
train
def rows(self, offs): ''' Iterate over raw indx, bytes tuples from a given offset. ''' lkey = s_common.int64en(offs) for lkey, byts
python
{ "resource": "" }
q19414
near
train
def near(point, dist, points): ''' Determine if the given point is within dist of any of points. Args: point ((float,float)): A latitude, longitude float tuple. dist (int): A distance in mm ( base units ) points (list): A list of latitude, longitude float tuples
python
{ "resource": "" }
q19415
SumoLogic.search_metrics
train
def search_metrics(self, query, fromTime=None, toTime=None, requestedDataPoints=600, maxDataPoints=800): '''Perform a single Sumo metrics query''' def millisectimestamp(ts): '''Convert UNIX timestamp to milliseconds''' if ts > 10**12: ts = ts/(10**(len(str(ts))-13)) else: ts = ts*10**(12-len(str(ts))) return int(ts) params = {'query': [{"query":query, "rowId":"A"}],
python
{ "resource": "" }
q19416
CardConnectionDecorator.connect
train
def connect(self, protocol=None, mode=None, disposition=None):
python
{ "resource": "" }
q19417
translateprotocolmask
train
def translateprotocolmask(protocol): """Translate CardConnection protocol mask into PCSC protocol mask.""" pcscprotocol = 0 if None != protocol: if CardConnection.T0_protocol & protocol: pcscprotocol |= SCARD_PROTOCOL_T0 if CardConnection.T1_protocol & protocol: pcscprotocol |= SCARD_PROTOCOL_T1
python
{ "resource": "" }
q19418
translateprotocolheader
train
def translateprotocolheader(protocol): """Translate protocol into PCSC protocol header.""" pcscprotocol = 0 if None != protocol: if CardConnection.T0_protocol == protocol: pcscprotocol = SCARD_PCI_T0 if CardConnection.T1_protocol == protocol:
python
{ "resource": "" }
q19419
PCSCCardConnection.connect
train
def connect(self, protocol=None, mode=None, disposition=None): """Connect to the card. If protocol is not specified, connect with the default connection protocol. If mode is not specified, connect with SCARD_SHARE_SHARED.""" CardConnection.connect(self, protocol) pcscprotocol = translateprotocolmask(protocol) if 0 == pcscprotocol: pcscprotocol = self.getProtocol() if mode == None: mode = SCARD_SHARE_SHARED # store the way to dispose the card if disposition == None: disposition = SCARD_UNPOWER_CARD self.disposition = disposition hresult, self.hcard, dwActiveProtocol = SCardConnect( self.hcontext, str(self.reader), mode, pcscprotocol) if hresult != 0: self.hcard = None if hresult in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD): raise NoCardException('Unable to connect', hresult=hresult) else: raise CardConnectionException( 'Unable to connect with protocol: ' + \
python
{ "resource": "" }
q19420
PCSCCardConnection.disconnect
train
def disconnect(self): """Disconnect from the card.""" # when __del__() is invoked in response to a module being deleted, # e.g., when execution of the program is done, other globals referenced # by the __del__() method may already have been deleted. # this causes CardConnection.disconnect to except with a TypeError try: CardConnection.disconnect(self) except TypeError: pass if None != self.hcard:
python
{ "resource": "" }
q19421
PCSCCardConnection.getATR
train
def getATR(self): """Return card ATR""" CardConnection.getATR(self) if None == self.hcard: raise CardConnectionException('Card not connected') hresult, reader, state, protocol, atr = SCardStatus(self.hcard) if hresult != 0:
python
{ "resource": "" }
q19422
PCSCCardConnection.doTransmit
train
def doTransmit(self, bytes, protocol=None): """Transmit an apdu to the card and return response apdu. @param bytes: command apdu to transmit (list of bytes) @param protocol: the transmission protocol, from CardConnection.T0_protocol, CardConnection.T1_protocol, or CardConnection.RAW_protocol @return: a tuple (response, sw1, sw2) where sw1 is status word 1, e.g. 0x90 sw2 is status word 2, e.g. 0x1A response are the response bytes excluding status words """ if None == protocol: protocol = self.getProtocol() CardConnection.doTransmit(self, bytes, protocol) pcscprotocolheader = translateprotocolheader(protocol) if 0 == pcscprotocolheader: raise CardConnectionException( 'Invalid protocol in transmit: must be ' + \ 'CardConnection.T0_protocol, ' + \ 'CardConnection.T1_protocol, or ' + \ 'CardConnection.RAW_protocol') if None == self.hcard:
python
{ "resource": "" }
q19423
PCSCCardConnection.doControl
train
def doControl(self, controlCode, bytes=[]): """Transmit a control command to the reader and return response. controlCode: control command bytes: command data to transmit (list of bytes) return: response are the response bytes (if any) """ CardConnection.doControl(self, controlCode, bytes) hresult, response = SCardControl(self.hcard,
python
{ "resource": "" }
q19424
PCSCCardConnection.doGetAttrib
train
def doGetAttrib(self, attribId): """get an attribute attribId: Identifier for the attribute to get return: response are the attribute byte array """
python
{ "resource": "" }
q19425
pcscdiag.OnExpandAll
train
def OnExpandAll(self): """ expand all nodes """ root = self.tree.GetRootItem()
python
{ "resource": "" }
q19426
pcscdiag.traverse
train
def traverse(self, traverseroot, function, cookie=0): """ recursivly walk tree control """ if self.tree.ItemHasChildren(traverseroot): firstchild, cookie = self.tree.GetFirstChild(traverseroot) function(firstchild) self.traverse(firstchild, function, cookie)
python
{ "resource": "" }
q19427
module_path
train
def module_path(): """ This will get us the program's directory, even if we are frozen using py2exe. From WhereAmI page on py2exe wiki."""
python
{ "resource": "" }
q19428
CardConnection.getAttrib
train
def getAttrib(self, attribId): """return the requested attribute @param attribId: attribute id like SCARD_ATTR_VENDOR_NAME """ Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent(
python
{ "resource": "" }
q19429
PyroReader.createConnection
train
def createConnection(self): """Return a card connection thru a remote reader."""
python
{ "resource": "" }
q19430
SampleAPDUManagerPanel.OnActivateCard
train
def OnActivateCard(self, card): """Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation."""
python
{ "resource": "" }
q19431
SimpleSCardApp.OnInit
train
def OnInit(self): """Create and display application frame.""" self.frame = SimpleSCardAppFrame( self.appname, self.apppanel, self.appstyle, self.appicon,
python
{ "resource": "" }
q19432
PyroNameServer.getShutdownArgs
train
def getShutdownArgs(self): """return command line arguments for shutting down the server; this command line is built from the name server startup arguments.""" shutdownArgs = [] if self.host: shutdownArgs += ['-h', self.host] if self.bcport:
python
{ "resource": "" }
q19433
PyroNameServer.stop
train
def stop(self): """Shutdown pyro naming server."""
python
{ "resource": "" }
q19434
Card.createConnection
train
def createConnection(self): """Return a CardConnection to the Card object.""" readerobj = None if isinstance(self.reader, Reader): readerobj = self.reader elif type(self.reader) == str: for reader in readers(): if self.reader == str(reader): readerobj = reader if readerobj:
python
{ "resource": "" }
q19435
pcscinnerreadergroups.getreadergroups
train
def getreadergroups(self): """ Returns the list of smartcard reader groups.""" innerreadergroups.getreadergroups(self) hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != 0: raise EstablishContextException(hresult) hresult, readers = SCardListReaderGroups(hcontext) if
python
{ "resource": "" }
q19436
pcscinnerreadergroups.addreadergroup
train
def addreadergroup(self, newgroup): """Add a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if 0 != hresult: raise error( 'Failed to establish context: ' + \ SCardGetErrorMessage(hresult)) try: hresult = SCardIntroduceReaderGroup(hcontext, newgroup) if 0 != hresult: raise error( 'Unable to introduce reader group: ' + \
python
{ "resource": "" }
q19437
parseFeatureRequest
train
def parseFeatureRequest(response): """ Get the list of Part10 features supported by the reader. @param response: result of CM_IOCTL_GET_FEATURE_REQUEST commmand @rtype: list @return: a list of list [[tag1, value1], [tag2, value2]] """ features = [] while (len(response) > 0): tag = response[0] control = ((((((response[2] << 8) + response[3]) << 8) +
python
{ "resource": "" }
q19438
hasFeature
train
def hasFeature(featureList, feature): """ return the controlCode for a feature or None @param feature: feature to look for @param featureList: feature list as returned by L{getFeatureRequest()} @return: feature value or None
python
{ "resource": "" }
q19439
getPinProperties
train
def getPinProperties(cardConnection, featureList=None, controlCode=None): """ return the PIN_PROPERTIES structure @param cardConnection: L{CardConnection} object @param featureList: feature list as returned by L{getFeatureRequest()} @param controlCode: control code for L{FEATURE_IFD_PIN_PROPERTIES} @rtype: dict @return: a dict """ if controlCode is None: if featureList is None: featureList = getFeatureRequest(cardConnection) controlCode = hasFeature(featureList, FEATURE_IFD_PIN_PROPERTIES) if controlCode is None: return {'raw': []}
python
{ "resource": "" }
q19440
RemoteReader.createConnection
train
def createConnection(self): """Return a card connection thru the reader.""" connection = RemoteCardConnection(self.readerobj.createConnection())
python
{ "resource": "" }
q19441
RemoteReaderServer.update
train
def update(self, observable, actions): """Called when a local reader is added or removed. Create remote pyro reader objects for added readers. Delete remote pyro reader objects for removed readers.""" (addedreaders, removedreaders) = actions for reader in addedreaders: remotereader = RemoteReader(reader)
python
{ "resource": "" }
q19442
ReaderMonitor.addObserver
train
def addObserver(self, observer): """Add an observer.""" Observable.addObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread only runs when there are observers. if self.startOnDemand: if 0 < self.countObservers(): if not self.rmthread: self.rmthread = ReaderMonitoringThread( self, self.readerProc, self.period) # start reader monitoring thread in another thread to # avoid a deadlock; addObserver and notifyObservers called # in the ReaderMonitoringThread run() method are # synchronized try:
python
{ "resource": "" }
q19443
ReaderMonitor.deleteObserver
train
def deleteObserver(self, observer): """Remove an observer.""" Observable.deleteObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread is stopped when there are no more observers. if self.startOnDemand:
python
{ "resource": "" }
q19444
ulist.__remove_duplicates
train
def __remove_duplicates(self, _other): """Remove from other items already in list.""" if not isinstance(_other, type(self)) \ and not isinstance(_other, type(list)) \ and not isinstance(_other, type([])): other = [_other] else: other = list(_other) # remove items already in self newother = [] for i in range(0, len(other)): item = other.pop(0) if not list.__contains__(self, item):
python
{ "resource": "" }
q19445
APDUTracerPanel.update
train
def update(self, cardconnection, ccevent): '''CardConnectionObserver callback.''' apduline = "" if 'connect' == ccevent.type: apduline += 'connecting to ' + cardconnection.getReader() elif 'disconnect' == ccevent.type: apduline += 'disconnecting from ' + cardconnection.getReader() elif 'command' == ccevent.type: apduline += '> ' + toHexString(ccevent.args[0]) elif 'response' == ccevent.type: if [] == ccevent.args[0]:
python
{ "resource": "" }
q19446
synchronize
train
def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" # basestring does not exist on Python 3 try: basestring except NameError: basestring = (str, bytes) if isinstance(names, basestring): names = names.split()
python
{ "resource": "" }
q19447
ExclusiveTransmitCardConnection.lock
train
def lock(self): '''Lock card with SCardBeginTransaction.''' component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection): hresult = SCardBeginTransaction(component.hcard) if 0 != hresult: raise CardConnectionException( 'Failed to lock with SCardBeginTransaction: ' +
python
{ "resource": "" }
q19448
ExclusiveTransmitCardConnection.unlock
train
def unlock(self): '''Unlock card with SCardEndTransaction.''' component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection): hresult = SCardEndTransaction(component.hcard,
python
{ "resource": "" }
q19449
ExclusiveTransmitCardConnection.transmit
train
def transmit(self, bytes, protocol=None): '''Gain exclusive access to card during APDU transmission for if this decorator decorates a PCSCCardConnection.'''
python
{ "resource": "" }
q19450
ReaderFactory.createReader
train
def createReader(clazz, readername): """Static method to create a reader from a reader clazz. @param clazz: the reader class name @param readername: the reader name """ if not clazz in ReaderFactory.factories:
python
{ "resource": "" }
q19451
ReaderComboBox.update
train
def update(self, observable, handlers): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""" addedreaders, removedreaders = handlers for reader in addedreaders: item = self.Append(str(reader)) self.SetClientData(item, reader)
python
{ "resource": "" }
q19452
Session.sendCommandAPDU
train
def sendCommandAPDU(self, command): """Send an APDU command to the connected smartcard. @param command: list of APDU bytes, e.g. [0xA0, 0xA4, 0x00, 0x00, 0x02] @return: a tuple (response, sw1, sw2) where
python
{ "resource": "" }
q19453
ErrorCheckingChain.next
train
def next(self): """Returns next error checking strategy.""" # Where this link is in the chain: location = self.chain.index(self)
python
{ "resource": "" }
q19454
ErrorCheckingChain.addFilterException
train
def addFilterException(self, exClass): """Add an exception filter to the error checking chain. @param exClass: the exception to exclude, e.g. L{smartcard.sw.SWExceptions.WarningProcessingException} A filtered
python
{ "resource": "" }
q19455
PCSCReader.addtoreadergroup
train
def addtoreadergroup(self, groupname): """Add reader to a reader group.""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if 0 != hresult: raise EstablishContextException(hresult) try: hresult = SCardIntroduceReader(hcontext, self.name, self.name)
python
{ "resource": "" }
q19456
PCSCReader.removefromreadergroup
train
def removefromreadergroup(self, groupname): """Remove a reader from a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if 0 != hresult: raise EstablishContextException(hresult) try:
python
{ "resource": "" }
q19457
TreeAndUserPanelPanel.ActivateCard
train
def ActivateCard(self, card): """Activate a card.""" if not hasattr(card, 'connection'): card.connection = card.createConnection()
python
{ "resource": "" }
q19458
TreeAndUserPanelPanel.DeactivateCard
train
def DeactivateCard(self, card): """Deactivate a card.""" if hasattr(card, 'connection'): card.connection.disconnect()
python
{ "resource": "" }
q19459
TreeAndUserPanelPanel.OnActivateReader
train
def OnActivateReader(self, event): """Called when the user activates a reader in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.ActivateCard(itemdata)
python
{ "resource": "" }
q19460
TreeAndUserPanelPanel.OnCardRightClick
train
def OnCardRightClick(self, event): """Called when user right-clicks a node in the card tree control.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"):
python
{ "resource": "" }
q19461
TreeAndUserPanelPanel.OnSelectCard
train
def OnSelectCard(self, event): """Called when the user selects a card in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card):
python
{ "resource": "" }
q19462
TreeAndUserPanelPanel.OnSelectReader
train
def OnSelectReader(self, event): """Called when the user selects a reader in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.dialogpanel.OnSelectCard(itemdata)
python
{ "resource": "" }
q19463
SimpleSCardAppFrame.OnReaderComboBox
train
def OnReaderComboBox(self, event): """Called when the user activates a reader in the toolbar combo box.""" cb = event.GetEventObject() reader = cb.GetClientData(cb.GetSelection())
python
{ "resource": "" }
q19464
get_func
train
def get_func(fullFuncName): """Retrieve a function object from a full dotted-package name.""" # Parse out the path, module, and function lastDot = fullFuncName.rfind(u".") funcName = fullFuncName[lastDot + 1:] modPath = fullFuncName[:lastDot] aMod = get_mod(modPath) aFunc = getattr(aMod, funcName) # Assert that the function is a *callable*
python
{ "resource": "" }
q19465
PCSCCardRequest.getReaderNames
train
def getReaderNames(self): """Returns the list or PCSC readers on which to wait for cards.""" # get inserted readers hresult, pcscreaders = SCardListReaders(self.hcontext, []) if 0 != hresult and SCARD_E_NO_READERS_AVAILABLE != hresult: raise ListReadersException(hresult) readers = [] # if no readers asked, use all inserted readers if None == self.readersAsked: readers = pcscreaders # otherwise use only the asked readers that are inserted
python
{ "resource": "" }
q19466
PCSCCardRequest.waitforcardevent
train
def waitforcardevent(self): """Wait for card insertion or removal.""" AbstractCardRequest.waitforcardevent(self) presentcards = [] evt = threading.Event() # for non infinite timeout, a timer will signal the end of the time-out if INFINITE == self.timeout: timertimeout = 1 else: timertimeout = self.timeout timer = threading.Timer( timertimeout, signalEvent, [evt, INFINITE == self.timeout]) # get status change until time-out, e.g. evt is set readerstates = {} timerstarted = False while not evt.isSet(): if not timerstarted: timerstarted = True timer.start() time.sleep(self.pollinginterval) # reinitialize at each iteration just in case a new reader appeared readernames = self.getReaderNames() for reader in readernames: # create a dictionary entry for new readers if not reader in readerstates: readerstates[reader] = (reader, SCARD_STATE_UNAWARE) # remove dictionary entry for readers that disappeared for oldreader in list(readerstates.keys()): if oldreader not in readernames: del readerstates[oldreader] # get status change if {} != readerstates: hresult, newstates = SCardGetStatusChange( self.hcontext, 0, list(readerstates.values())) else: hresult = 0 newstates = [] # time-out if SCARD_E_TIMEOUT == hresult: if evt.isSet(): raise CardRequestTimeoutException() # the reader was unplugged during the loop elif SCARD_E_UNKNOWN_READER == hresult: pass # some
python
{ "resource": "" }
q19467
strToGUID
train
def strToGUID(s): """Converts a GUID string into a list of bytes. >>> strToGUID('{AD4F1667-EA75-4124-84D4-641B3B197C65}') [103, 22, 79, 173, 117, 234, 36, 65, 132, 212, 100, 27, 59, 25, 124, 101] """ dat = uuid.UUID(hex=s) if isinstance(dat.bytes_le, str): #
python
{ "resource": "" }
q19468
GUIDToStr
train
def GUIDToStr(g): """Converts a GUID sequence of bytes into a string. >>> GUIDToStr([103,22,79,173, 117,234, 36,65, ... 132, 212, 100, 27, 59, 25, 124, 101]) '{AD4F1667-EA75-4124-84D4-641B3B197C65}' """
python
{ "resource": "" }
q19469
ATRCardType.matches
train
def matches(self, atr, reader=None): """Returns true if the atr matches the masked CardType atr. @param atr: the atr to chek for matching @param reader: the reader (optional); default is None When atr is compared to the CardType ATR, matches returns true if
python
{ "resource": "" }
q19470
SamplePanel.OnActivateReader
train
def OnActivateReader(self, reader): """Called when a reader is activated by double-clicking on the reader tree control or toolbar."""
python
{ "resource": "" }
q19471
SamplePanel.OnDeactivateCard
train
def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar."""
python
{ "resource": "" }
q19472
ATR.getSupportedProtocols
train
def getSupportedProtocols(self): """Returns a dictionnary of supported protocols.""" protocols = {} for td in self.TD: if td is not None: strprotocol = "T=%d" % (td
python
{ "resource": "" }
q19473
ATR.dump
train
def dump(self): """Dump the details of an ATR.""" for i in range(0, len(self.TA)): if self.TA[i] is not None: print("TA%d: %x" % (i + 1, self.TA[i])) if self.TB[i] is not None: print("TB%d: %x" % (i + 1, self.TB[i])) if self.TC[i] is not None: print("TC%d: %x" % (i + 1, self.TC[i])) if self.TD[i] is not None: print("TD%d: %x" % (i + 1, self.TD[i])) print('supported protocols ' + ','.join(self.getSupportedProtocols())) print('T=0 supported: ' + str(self.isT0Supported())) print('T=1 supported: ' + str(self.isT1Supported())) if self.getChecksum(): print('checksum: %d' % self.getChecksum()) print('\tclock rate conversion factor: ' +
python
{ "resource": "" }
q19474
CardTreeCtrl.OnAddCards
train
def OnAddCards(self, addedcards): """Called when a card is inserted. Adds a smart card to the smartcards tree.""" parentnode = self.root for cardtoadd in addedcards: childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr)) self.SetItemText(childCard, toHexString(cardtoadd.atr)) self.SetPyData(childCard, cardtoadd) self.SetItemImage(
python
{ "resource": "" }
q19475
CardTreeCtrl.OnRemoveCards
train
def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes a card from the tree.""" parentnode = self.root for cardtoremove in removedcards: (childCard, cookie) = self.GetFirstChild(parentnode) while childCard.IsOk(): if self.GetItemText(childCard) == \ toHexString(cardtoremove.atr):
python
{ "resource": "" }
q19476
ReaderTreeCtrl.AddATR
train
def AddATR(self, readernode, atr): """Add an ATR to a reader node.""" capchild = self.AppendItem(readernode, atr) self.SetPyData(capchild, None)
python
{ "resource": "" }
q19477
ReaderTreeCtrl.OnAddCards
train
def OnAddCards(self, addedcards): """Called when a card is inserted. Adds the smart card child to the reader node.""" self.mutex.acquire() try: parentnode = self.root for cardtoadd in addedcards: (childReader, cookie) = self.GetFirstChild(parentnode) found = False while childReader.IsOk() and not found: if self.GetItemText(childReader) == str(cardtoadd.reader): (childCard, cookie2) = self.GetFirstChild(childReader) self.SetItemText(childCard, toHexString(cardtoadd.atr)) self.SetPyData(childCard, cardtoadd) found = True else: (childReader, cookie) = self.GetNextChild(
python
{ "resource": "" }
q19478
ReaderTreeCtrl.OnAddReaders
train
def OnAddReaders(self, addedreaders): """Called when a reader is inserted. Adds the smart card reader to the smartcard readers tree.""" self.mutex.acquire() try: parentnode = self.root for readertoadd in addedreaders: # is the reader already here? found = False (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk() and not found: if self.GetItemText(childReader) == str(readertoadd): found = True else: (childReader, cookie) = self.GetNextChild( parentnode, cookie) if not found: childReader = self.AppendItem(parentnode, str(readertoadd)) self.SetPyData(childReader, readertoadd)
python
{ "resource": "" }
q19479
ReaderTreeCtrl.OnRemoveCards
train
def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes the card from the tree.""" self.mutex.acquire() try: parentnode = self.root for cardtoremove in removedcards: (childReader, cookie) = self.GetFirstChild(parentnode) found = False while childReader.IsOk() and not found:
python
{ "resource": "" }
q19480
ReaderTreeCtrl.OnRemoveReaders
train
def OnRemoveReaders(self, removedreaders): """Called when a reader is removed. Removes the reader from the smartcard readers tree.""" self.mutex.acquire() try: parentnode = self.root for readertoremove in removedreaders: (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk(): if self.GetItemText(childReader) == str(readertoremove): self.Delete(childReader)
python
{ "resource": "" }
q19481
CardAndReaderTreePanel.OnDestroy
train
def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers if hasattr(self, 'cardmonitor'): self.cardmonitor.deleteObserver(self.cardtreecardobserver) if hasattr(self, 'readermonitor'):
python
{ "resource": "" }
q19482
ExclusiveConnectCardConnection.connect
train
def connect(self, protocol=None, mode=None, disposition=None): '''Disconnect and reconnect in exclusive mode PCSCCardconnections.''' CardConnectionDecorator.connect(self, protocol, mode, disposition) component = self.component while True: if isinstance(component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection): pcscprotocol = PCSCCardConnection.translateprotocolmask( protocol) if 0 == pcscprotocol: pcscprotocol = component.getProtocol() if component.hcard is not None: hresult = SCardDisconnect(component.hcard, SCARD_LEAVE_CARD) if hresult != 0: raise CardConnectionException(
python
{ "resource": "" }
q19483
build_module
train
def build_module(name, objs, doc='', source=None, mode='ignore'): """Create a module from imported objects. Parameters ---------- name : str New module name. objs : dict Dictionary of the objects (or their name) to import into the module, keyed by the name they will take in the created module. doc : str Docstring of the new module. source : Module object Module where objects are defined if not explicitly given. mode : {'raise', 'warn', 'ignore'} How to deal with missing objects. Returns ------- ModuleType A module built from a list of objects' name. """ import types import warnings import logging logging.captureWarnings(capture=True) try: out = types.ModuleType(name, doc) except TypeError: msg = "Module '{}' is not properly formatted".format(name) raise TypeError(msg) for key, obj in objs.items(): if isinstance(obj, str) and source is not None: module_mappings = getattr(source, obj, None) else: module_mappings = obj if module_mappings is None:
python
{ "resource": "" }
q19484
base_flow_index
train
def base_flow_index(q, freq='YS'): r"""Base flow index Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow. Parameters ---------- q : xarray.DataArray Rate of river discharge [m³/s] freq : str, optional Resampling frequency Returns ------- xarray.DataArrray Base flow index. Notes ----- Let :math:`\mathbf{q}=q_0, q_1, \ldots, q_n` be the sequence of daily discharge and :math:`\overline{\mathbf{q}}` the mean flow over the period. The base flow index is given by: .. math::
python
{ "resource": "" }
q19485
cold_spell_duration_index
train
def cold_spell_duration_index(tasmin, tn10, window=6, freq='YS'): r"""Cold spell duration index Number of days with at least six consecutive days where the daily minimum temperature is below the 10th percentile. Parameters ---------- tasmin : xarray.DataArray Minimum daily temperature. tn10 : float 10th percentile of daily minimum temperature. window : int Minimum number of days with temperature below threshold to qualify as a cold spell. Default: 6. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Count of days with at least six consecutive days where the daily minimum temperature is below the 10th percentile [days]. Notes ----- Let :math:`TN_i` be the minimum daily temperature for the day of the year :math:`i` and :math:`TN10_i` the 10th percentile of the minimum daily temperature over the 1961-1990 period for day of the year :math:`i`, the cold spell duration index over period :math:`\phi` is defined as: .. math:: \sum_{i \in \phi} \prod_{j=i}^{i+6} \left[ TN_j < TN10_j \right] where :math:`[P]` is 1 if :math:`P` is true, and 0 if false. References ---------- From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI). Example ------- >>> tn10 = percentile_doy(historical_tasmin, per=.1) >>> cold_spell_duration_index(reference_tasmin, tn10) """ if 'dayofyear' not in tn10.coords.keys():
python
{ "resource": "" }
q19486
cold_spell_days
train
def cold_spell_days(tas, thresh='-10 degC', window=5, freq='AS-JUL'): r"""Cold spell days The number of days that are part of a cold spell, defined as five or more consecutive days with mean daily temperature below a threshold in °C. Parameters ---------- tas : xarrray.DataArray Mean daily temperature [℃] or [K] thresh : str Threshold temperature below which a cold spell begins [℃] or [K]. Default : '-10 degC' window : int Minimum number of days with temperature below threshold to qualify as a cold spell. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Cold spell days. Notes -----
python
{ "resource": "" }
q19487
daily_pr_intensity
train
def daily_pr_intensity(pr, thresh='1 mm/day', freq='YS'): r"""Average daily precipitation intensity Return the average precipitation over wet days. Parameters ---------- pr : xarray.DataArray Daily precipitation [mm/d or kg/m²/s] thresh : str precipitation value over which a day is considered wet. Default : '1 mm/day' freq : str, optional Resampling frequency defining the periods defined in http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling. Default : '1 mm/day' Returns ------- xarray.DataArray The average precipitation over wet days for each period Notes ----- Let :math:`\mathbf{p} = p_0, p_1, \ldots, p_n` be the daily precipitation and :math:`thresh` be the precipitation threshold defining wet days. Then the daily precipitation intensity is defined as .. math:: \frac{\sum_{i=0}^n p_i [p_i \leq thresh]}{\sum_{i=0}^n [p_i \leq thresh]} where :math:`[P]` is 1 if :math:`P` is true, and 0 if false. Examples
python
{ "resource": "" }
q19488
maximum_consecutive_dry_days
train
def maximum_consecutive_dry_days(pr, thresh='1 mm/day', freq='YS'): r"""Maximum number of consecutive dry days Return the maximum number of consecutive days within the period where precipitation is below a certain threshold. Parameters ---------- pr : xarray.DataArray Mean daily precipitation flux [mm] thresh : str Threshold precipitation on which to base evaluation [mm]. Default : '1 mm/day' freq : str, optional Resampling frequency Returns ------- xarray.DataArray The maximum number of consecutive dry days. Notes ----- Let :math:`\mathbf{p}=p_0, p_1, \ldots, p_n` be a daily precipitation series and :math:`thresh` the threshold under which a day is considered dry. Then let :math:`\mathbf{s}` be the sorted vector of indices :math:`i` where :math:`[p_i < thresh] \neq [p_{i+1} < thresh]`, that is, the days when the temperature crosses the threshold.
python
{ "resource": "" }
q19489
daily_freezethaw_cycles
train
def daily_freezethaw_cycles(tasmax, tasmin, freq='YS'): r"""Number of days with a diurnal freeze-thaw cycle The number of days where Tmax > 0℃ and Tmin < 0℃. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] tasmin : xarray.DataArray Minimum daily temperature values [℃] or [K] freq : str Resampling frequency Returns ------- xarray.DataArray
python
{ "resource": "" }
q19490
daily_temperature_range
train
def daily_temperature_range(tasmax, tasmin, freq='YS'): r"""Mean of daily temperature range. The mean difference between the daily maximum temperature and the daily minimum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature values [℃] or [K] tasmin : xarray.DataArray Minimum daily temperature values [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray The average variation in daily temperature range for the given time period. Notes ----- Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at day :math:`i`
python
{ "resource": "" }
q19491
daily_temperature_range_variability
train
def daily_temperature_range_variability(tasmax, tasmin, freq="YS"): r"""Mean absolute day-to-day variation in daily temperature range. Mean absolute day-to-day variation in daily temperature range. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature values [℃] or [K] tasmin : xarray.DataArray Minimum daily temperature values [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray The average day-to-day variation in daily temperature range for the given time period. Notes ----- Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at day :math:`i` of period :math:`j`. Then
python
{ "resource": "" }
q19492
extreme_temperature_range
train
def extreme_temperature_range(tasmax, tasmin, freq='YS'): r"""Extreme intra-period temperature range. The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature values [℃] or [K] tasmin : xarray.DataArray Minimum daily temperature values [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Extreme intra-period temperature range for the given time period. Notes ----- Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at day :math:`i`
python
{ "resource": "" }
q19493
freshet_start
train
def freshet_start(tas, thresh='0 degC', window=5, freq='YS'): r"""First day consistently exceeding threshold temperature. Returns first day of period where a temperature threshold is exceeded over a given number of days. Parameters ---------- tas : xarray.DataArray Mean daily temperature [℃] or [K] thresh : str Threshold temperature on which to base evaluation [℃] or [K]. Default '0 degC' window : int Minimum number of days with temperature above threshold needed for evaluation freq : str, optional Resampling frequency Returns ------- float Day of the year when temperature exceeds threshold over a given number of days for the first time. If there are no such day, return np.nan. Notes ----- Let :math:`x_i` be
python
{ "resource": "" }
q19494
frost_days
train
def frost_days(tasmin, freq='YS'): r"""Frost days index Number of days where daily minimum temperatures are below 0℃. Parameters ---------- tasmin : xarray.DataArray Minimum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray
python
{ "resource": "" }
q19495
growing_season_length
train
def growing_season_length(tas, thresh='5.0 degC', window=6, freq='YS'): r"""Growing season length. The number of days between the first occurrence of at least six consecutive days with mean daily temperature over 5℃ and the first occurrence of at least six consecutive days with mean daily temperature below 5℃ after July 1st in the northern hemisphere and January 1st in the southern hemisphere. Parameters --------- tas : xarray.DataArray Mean daily temperature [℃] or [K] thresh : str Threshold temperature on which to base evaluation [℃] or [K]. Default: '5.0 degC'. window : int Minimum number of days with temperature above threshold to mark the beginning and end of growing season. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Growing season length. Notes ----- Let :math:`TG_{ij}` be the mean temperature at day :math:`i` of period :math:`j`. Then counted is the number of days between the first occurrence of at least 6 consecutive days with: .. math:: TG_{ij} > 5 ℃ and the first occurrence after 1 July of at least 6 consecutive days with: .. math:: TG_{ij} < 5 ℃ """ # i = xr.DataArray(np.arange(tas.time.size), dims='time') # ind = xr.broadcast(i, tas)[0] # # c = ((tas > thresh) * 1).rolling(time=window).sum() # i1 = ind.where(c == window).resample(time=freq).min(dim='time') # # # Resample sets the time to T00:00. # i11 = i1.reindex_like(c, method='ffill') # # # TODO: Adjust for southern hemisphere # # #i2 =
python
{ "resource": "" }
q19496
heat_wave_frequency
train
def heat_wave_frequency(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS'): # Dev note : we should decide if it is deg K or C r"""Heat wave frequency Number of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceeds specific thresholds over a minimum number of days. Parameters ---------- tasmin : xarrray.DataArray Minimum daily temperature [℃] or [K] tasmax : xarrray.DataArray Maximum daily temperature [℃] or [K] thresh_tasmin : str The minimum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '22 degC' thresh_tasmax : str The maximum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '30 degC' window : int Minimum number of days with temperatures above thresholds to qualify as a heatwave. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Number of heatwave at the wanted frequency Notes ----- The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities (Casati et al., 2013). In Robinson (2001), the parameters would be `thresh_tasmin=27.22, thresh_tasmax=39.44, window=2` (81F, 103F).
python
{ "resource": "" }
q19497
heat_wave_index
train
def heat_wave_index(tasmax, thresh='25.0 degC', window=5, freq='YS'): r"""Heat wave index. Number of days that are part of a heatwave, defined as five or more consecutive days over 25℃. Parameters ---------- tasmax : xarrray.DataArray Maximum daily temperature [℃] or [K] thresh : str Threshold temperature on which to designate a heatwave [℃] or [K]. Default: '25.0 degC'. window : int Minimum number of days with temperature above threshold to qualify
python
{ "resource": "" }
q19498
heat_wave_max_length
train
def heat_wave_max_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS'): # Dev note : we should decide if it is deg K or C r"""Heat wave max length Maximum length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceeds specific thresholds over a minimum number of days. By definition heat_wave_max_length must be >= window. Parameters ---------- tasmin : xarrray.DataArray Minimum daily temperature [℃] or [K] tasmax : xarrray.DataArray Maximum daily temperature [℃] or [K] thresh_tasmin : str The minimum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '22 degC' thresh_tasmax : str The maximum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '30 degC' window : int Minimum number of days with temperatures above thresholds to qualify as a heatwave. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Maximum length of heatwave at the wanted frequency Notes ----- The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities (Casati et al., 2013). In Robinson (2001), the parameters would be `thresh_tasmin=27.22, thresh_tasmax=39.44, window=2`
python
{ "resource": "" }
q19499
heating_degree_days
train
def heating_degree_days(tas, thresh='17.0 degC', freq='YS'): r"""Heating degree days Sum of degree days below the temperature threshold at which spaces are heated. Parameters ---------- tas : xarray.DataArray Mean daily temperature [℃] or [K] thresh : str Threshold temperature on which to base evaluation [℃] or [K]. Default: '17.0 degC'. freq : str, optional Resampling frequency Returns ------- xarray.DataArray Heating degree days index. Notes ----- Let :math:`TG_{ij}` be the daily mean temperature at day :math:`i` of period :math:`j`. Then
python
{ "resource": "" }