idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
10,100 | def trimSegments ( self , minPermanence = None , minNumSyns = None ) : if minPermanence is None : minPermanence = self . connectedPerm if minNumSyns is None : minNumSyns = self . activationThreshold totalSegsRemoved , totalSynsRemoved = 0 , 0 for c , i in product ( xrange ( self . numberOfCols ) , xrange ( self . cells... | This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining . |
10,101 | def checkPrediction2 ( self , patternNZs , output = None , confidence = None , details = False ) : numPatterns = len ( patternNZs ) orAll = set ( ) orAll = orAll . union ( * patternNZs ) if output is None : assert self . currentOutput is not None output = self . currentOutput output = set ( output . sum ( axis = 1 ) . ... | This function will replace checkPrediction . |
10,102 | def isSegmentActive ( self , seg , activeState ) : return isSegmentActive ( seg . syns , activeState , self . connectedPerm , self . activationThreshold ) | A segment is active if it has > = activationThreshold connected synapses that are active due to activeState . |
10,103 | def getActiveSegment ( self , c , i , timeStep ) : nSegments = len ( self . cells [ c ] [ i ] ) bestActivation = self . activationThreshold which = - 1 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , self . activeState [ timeStep ] , connectedSynapsesOnly = True ) i... | For a given cell return the segment with the strongest _connected_ activation i . e . sum up the activations of the connected synapses of the segments only . That is a segment is active only if it has enough connected synapses . |
10,104 | def chooseCellsToLearnFrom ( self , c , i , s , n , timeStep ) : if n <= 0 : return [ ] tmpCandidates = [ ] if timeStep == 't-1' : tmpCandidates = numpy . where ( self . learnState [ 't-1' ] == 1 ) else : tmpCandidates = numpy . where ( self . learnState [ 't' ] == 1 ) if len ( tmpCandidates [ 0 ] ) == 0 : return [ ] i... | Choose n random cells to learn from . |
10,105 | def getBestMatchingCell ( self , c , activeState ) : bestActivityInCol = self . minThreshold bestSegIdxInCol = - 1 bestCellInCol = - 1 for i in xrange ( self . cellsPerColumn ) : maxSegActivity = 0 maxSegIdx = 0 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , active... | Find weakly activated cell in column . Returns index and segment of most activated segment above minThreshold . |
10,106 | def getBestMatchingSegment ( self , c , i , activeState ) : maxActivity , which = self . minThreshold , - 1 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , activeState , connectedSynapsesOnly = False ) if activity >= maxActivity : maxActivity , which = activity , j ... | For the given cell find the segment with the largest number of active synapses . This routine is aggressive in finding the best match . The permanence value of synapses is allowed to be below connectedPerm . The number of active synapses is allowed to be below activationThreshold but must be above minThreshold . The ro... |
10,107 | def getLeastUsedCell ( self , c ) : segmentsPerCell = numpy . zeros ( self . cellsPerColumn , dtype = 'uint32' ) for i in range ( self . cellsPerColumn ) : segmentsPerCell [ i ] = self . getNumSegmentsInCell ( c , i ) cellMinUsage = numpy . where ( segmentsPerCell == segmentsPerCell . min ( ) ) [ 0 ] self . _random . g... | For the least used cell in a column |
10,108 | def updateSynapses ( self , segment , synapses , delta ) : reached0 = False if delta > 0 : for synapse in synapses : segment [ synapse ] [ 2 ] = newValue = segment [ synapse ] [ 2 ] + delta if newValue > self . permanenceMax : segment [ synapse ] [ 2 ] = self . permanenceMax else : for synapse in synapses : segment [ s... | Update a set of synapses of the given segment delta can be permanenceInc or permanenceDec . |
10,109 | def adaptSegment ( self , segUpdate , positiveReinforcement ) : trimSegment = False c , i , segment = segUpdate . columnIdx , segUpdate . cellIdx , segUpdate . segment activeSynapses = segUpdate . activeSynapses synToUpdate = set ( [ syn for syn in activeSynapses if type ( syn ) == int ] ) if segment is not None : if p... | This function applies segment update information to a segment in a cell . |
10,110 | def getSegmentInfo ( self , collectActiveData = False ) : nSegments , nSynapses = 0 , 0 nActiveSegs , nActiveSynapses = 0 , 0 distSegSizes , distNSegsPerCell = { } , { } distPermValues = { } numAgeBuckets = 20 distAges = [ ] ageBucketSize = int ( ( self . lrnIterationIdx + 20 ) / 20 ) for i in range ( numAgeBuckets ) :... | Returns information about the distribution of segments synapses and permanence values in the current TP . If requested also returns information regarding the number of currently active segments and synapses . |
10,111 | def updateSynapses ( self , synapses , delta ) : reached0 = False if delta > 0 : for synapse in synapses : self . syns [ synapse ] [ 2 ] = newValue = self . syns [ synapse ] [ 2 ] + delta if newValue > self . tp . permanenceMax : self . syns [ synapse ] [ 2 ] = self . tp . permanenceMax else : for synapse in synapses :... | Update a set of synapses in the segment . |
10,112 | def maxEntropy ( n , k ) : s = float ( k ) / n if s > 0.0 and s < 1.0 : entropy = - s * math . log ( s , 2 ) - ( 1 - s ) * math . log ( 1 - s , 2 ) else : entropy = 0 return n * entropy | The maximum enropy we could get with n units and k winners |
10,113 | def binaryEntropy ( x ) : entropy = - x * x . log2 ( ) - ( 1 - x ) * ( 1 - x ) . log2 ( ) entropy [ x * ( 1 - x ) == 0 ] = 0 return entropy , entropy . sum ( ) | Calculate entropy for a list of binary random variables |
10,114 | def plotDutyCycles ( dutyCycle , filePath ) : _ , entropy = binaryEntropy ( dutyCycle ) bins = np . linspace ( 0.0 , 0.3 , 200 ) plt . hist ( dutyCycle , bins , alpha = 0.5 , label = 'All cols' ) plt . title ( "Histogram of duty cycles, entropy=" + str ( float ( entropy ) ) ) plt . xlabel ( "Duty cycle" ) plt . ylabel ... | Create plot showing histogram of duty cycles |
10,115 | def compute ( self , inputVector , learn , activeArray ) : super ( SpatialPoolerWrapper , self ) . compute ( inputVector , learn , activeArray ) self . _updateAvgActivityPairs ( activeArray ) | This method resembles the primary public method of the SpatialPooler class . |
10,116 | def computeMaxPool ( input_width ) : wout = math . floor ( ( input_width + 2 * PADDING - KERNEL_SIZE ) / STRIDE + 1 ) return int ( math . floor ( wout / 2.0 ) ) | Compute CNN max pool width . see cnn_sdr . py |
10,117 | def createRandomObjects ( self , numObjects , numPoints , numLocations = None , numFeatures = None ) : if numObjects > 0 : if numLocations is None : numLocations = numPoints if numFeatures is None : numFeatures = numPoints assert ( numPoints <= numLocations ) , ( "Number of points in object cannot be " "greater than nu... | Creates a set of random objects and adds them to the machine . If numLocations and numFeatures and not specified they will be set to the desired number of points . |
10,118 | def getUniqueFeaturesLocationsInObject ( self , name ) : uniqueFeatures = set ( ) uniqueLocations = set ( ) for pair in self . objects [ name ] : uniqueLocations = uniqueLocations . union ( { pair [ 0 ] } ) uniqueFeatures = uniqueFeatures . union ( { pair [ 1 ] } ) return uniqueLocations , uniqueFeatures | Return two sets . The first set contains the unique locations Ids in the object . The second set contains the unique feature Ids in the object . |
10,119 | def _generateLocations ( self ) : size = self . externalInputSize bits = self . numInputBits random . seed ( self . seed ) self . locations = [ ] for _ in xrange ( self . numColumns ) : self . locations . append ( [ self . _generatePattern ( bits , size ) for _ in xrange ( self . numLocations ) ] ) | Generates a pool of locations to be used for the experiments . |
10,120 | def getDetectorClassConstructors ( detectors ) : detectorConstructors = { d : globals ( ) [ detectorNameToClass ( d ) ] for d in detectors } return detectorConstructors | Takes in names of detectors . Collects class names that correspond to those detectors and returns them in a dict . The dict maps detector name to class names . Assumes the detectors have been imported . |
10,121 | def select_action ( self , state ) : value = 0 if self . steps < self . min_steps : action = np . random . randint ( self . actions ) else : self . eps = max ( self . eps_end , self . eps * self . eps_decay ) if random . random ( ) < self . eps : action = np . random . randint ( self . actions ) else : self . local . e... | Select the best action for the given state using e - greedy exploration to minimize overfitting |
10,122 | def inferObjects ( self , bodyPlacement , maxTouches = 2 ) : for monitor in self . monitors . itervalues ( ) : monitor . afterBodyWorldLocationChanged ( bodyPlacement ) numTouchesRequired = collections . defaultdict ( int ) for objectName , objectFeatures in self . objects . iteritems ( ) : self . reset ( ) objectPlace... | Touch each object with multiple sensors twice . |
10,123 | def plotAccuracy ( suite , name ) : path = suite . cfgparser . get ( name , "path" ) path = os . path . join ( path , name ) accuracy = defaultdict ( list ) sensations = defaultdict ( list ) for exp in suite . get_exps ( path = path ) : params = suite . get_params ( exp ) maxTouches = params [ "num_sensations" ] cells ... | Plots classification accuracy |
10,124 | def get_error ( data , labels , pos_neurons , neg_neurons = [ ] , add_noise = True ) : num_correct = 0 num_false_positives = 0 num_false_negatives = 0 classifications = numpy . zeros ( data . nRows ( ) ) for neuron in pos_neurons : classifications += neuron . calculate_on_entire_dataset ( data ) for neuron in neg_neuro... | Calculates error including number of false positives and false negatives . |
10,125 | def computeActivity ( self , activeInputsBySource , permanenceThreshold = None ) : overlaps = None for source , connections in self . connectionsBySource . iteritems ( ) : o = connections . computeActivity ( activeInputsBySource [ source ] , permanenceThreshold ) if overlaps is None : overlaps = o else : overlaps += o ... | Calculate the number of active synapses per segment . |
10,126 | def createSegments ( self , cells ) : segments = None for connections in self . connectionsBySource . itervalues ( ) : created = connections . createSegments ( cells ) if segments is None : segments = created else : np . testing . assert_equal ( segments , created ) return segments | Create a segment on each of the specified cells . |
10,127 | def growSynapses ( self , segments , activeInputsBySource , initialPermanence ) : for source , connections in self . connectionsBySource . iteritems ( ) : connections . growSynapses ( segments , activeInputsBySource [ source ] , initialPermanence ) | Grow synapses to each of the specified inputs on each specified segment . |
10,128 | def setPermanences ( self , segments , presynapticCellsBySource , permanence ) : permanences = np . repeat ( np . float32 ( permanence ) , len ( segments ) ) for source , connections in self . connectionsBySource . iteritems ( ) : if source in presynapticCellsBySource : connections . matrix . setElements ( segments , p... | Set the permanence of a specific set of synapses . Any synapses that don t exist will be initialized . Any existing synapses will be overwritten . |
10,129 | def loadImage ( t , filename = "cajal.jpg" ) : image = Image . open ( "cajal.jpg" ) . convert ( "1" ) image . load ( ) box = ( 0 , 0 , t . inputWidth , t . inputHeight ) image = image . crop ( box ) a = np . asarray ( image ) im = np . ones ( ( t . inputWidth , t . inputHeight ) ) im [ a ] = 0 return im | Load the given gray scale image . Threshold it to black and white and crop it to be the dimensions of the FF input for the thalamus . Return a binary numpy matrix where 1 corresponds to black and 0 corresponds to white . |
10,130 | def inferThalamus ( t , l6Input , ffInput ) : print ( "\n-----------" ) t . reset ( ) t . deInactivateCells ( l6Input ) ffOutput = t . computeFeedForwardActivity ( ffInput ) return ffOutput | Compute the effect of this feed forward input given the specific L6 input . |
10,131 | def filtered ( w = 250 ) : kernels = [ ] for theta in range ( 4 ) : theta = theta / 4. * np . pi for sigma in ( 1 , 3 ) : for frequency in ( 0.05 , 0.25 ) : kernel = np . real ( gabor_kernel ( frequency , theta = theta , sigma_x = sigma , sigma_y = sigma ) ) kernels . append ( kernel ) print ( "Initializing thalamus" )... | In this example we filter the image into several channels using gabor filters . L6 activity is used to select one of those channels . Only activity selected by those channels burst . |
10,132 | def get_delimited_message_bytes ( byte_stream , nr = 4 ) : ( length , pos ) = decoder . _DecodeVarint32 ( byte_stream . read ( nr ) , 0 ) if log . getEffectiveLevel ( ) == logging . DEBUG : log . debug ( "Delimited message length (pos %d): %d" % ( pos , length ) ) delimiter_bytes = nr - pos byte_stream . rewind ( delim... | Parse a delimited protobuf message . This is done by first getting a protobuf varint from the stream that represents the length of the message then reading that amount of from the message and then parse it . Since the int can be represented as max 4 bytes first get 4 bytes and try to decode . The decoder returns the va... |
10,133 | def read ( self , n ) : bytes_wanted = n - self . buffer_length + self . pos + 1 if bytes_wanted > 0 : self . _buffer_bytes ( bytes_wanted ) end_pos = self . pos + n ret = self . buffer [ self . pos + 1 : end_pos + 1 ] self . pos = end_pos return ret | Reads n bytes into the internal buffer |
10,134 | def rewind ( self , places ) : log . debug ( "Rewinding pos %d with %d places" % ( self . pos , places ) ) self . pos -= places log . debug ( "Reset buffer to pos %d" % self . pos ) | Rewinds the current buffer to a position . Needed for reading varints because we might read bytes that belong to the stream after the varint . |
10,135 | def create_rpc_request_header ( self ) : rpcheader = RpcRequestHeaderProto ( ) rpcheader . rpcKind = 2 rpcheader . rpcOp = 0 rpcheader . callId = self . call_id rpcheader . retryCount = - 1 rpcheader . clientId = self . client_id [ 0 : 16 ] if self . call_id == - 3 : self . call_id = 0 else : self . call_id += 1 s_rpcH... | Creates and serializes a delimited RpcRequestHeaderProto message . |
10,136 | def send_rpc_message ( self , method , request ) : log . debug ( "############## SENDING ##############" ) rpc_request_header = self . create_rpc_request_header ( ) request_header = self . create_request_header ( method ) param = request . SerializeToString ( ) if log . getEffectiveLevel ( ) == logging . DEBUG : log_pr... | Sends a Hadoop RPC request to the NameNode . |
10,137 | def parse_response ( self , byte_stream , response_class ) : log . debug ( "############## PARSING ##############" ) log . debug ( "Payload class: %s" % response_class ) len_bytes = byte_stream . read ( 4 ) total_length = struct . unpack ( "!I" , len_bytes ) [ 0 ] log . debug ( "Total response length: %s" % total_lengt... | Parses a Hadoop RPC response . |
10,138 | def close_socket ( self ) : log . debug ( "Closing socket" ) if self . sock : try : self . sock . close ( ) except : pass self . sock = None | Closes the socket and resets the channel . |
10,139 | def CallMethod ( self , method , controller , request , response_class , done ) : try : self . validate_request ( request ) if not self . sock : self . get_connection ( self . host , self . port ) self . send_rpc_message ( method , request ) byte_stream = self . recv_rpc_message ( ) return self . parse_response ( byte_... | Call the RPC method . The naming doesn t confirm PEP8 since it s a method called by protobuf |
10,140 | def getLogger ( name ) : log = logging . getLogger ( name ) log . addHandler ( _NullHandler ( ) ) return log | Create and return a logger with the specified name . |
10,141 | def put ( self , src , dst ) : src = "%s%s" % ( self . _testfiles_path , src ) return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-put' , src , self . _full_hdfs_path ( dst ) ] , True ) | Upload a file to HDFS |
10,142 | def ls ( self , src , extra_args = [ ] ) : src = [ self . _full_hdfs_path ( x ) for x in src ] output = self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-ls' ] + extra_args + src , True ) return self . _transform_ls_output ( output , self . hdfs_url ) | List files in a directory |
10,143 | def df ( self , src ) : return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-df' , self . _full_hdfs_path ( src ) ] , True ) | Perform df on a path |
10,144 | def du ( self , src , extra_args = [ ] ) : src = [ self . _full_hdfs_path ( x ) for x in src ] return self . _transform_du_output ( self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-du' ] + extra_args + src , True ) , self . hdfs_url ) | Perform du on a path |
10,145 | def count ( self , src ) : src = [ self . _full_hdfs_path ( x ) for x in src ] return self . _transform_count_output ( self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-count' ] + src , True ) , self . hdfs_url ) | Perform count on a path |
10,146 | def handleError ( self , error_code , message ) : self . _fail = True self . reason = error_code self . _error = message | Log and set the controller state . |
10,147 | def ls ( self , paths , recurse = False , include_toplevel = False , include_children = True ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) for item in self . _find_items ( paths , self . _handle_ls , include_toplevel = include_toplevel , include_children = include_chi... | Issues ls command and returns a list of maps that contain fileinfo |
10,148 | def _handle_ls ( self , path , node ) : entry = { } entry [ "file_type" ] = self . FILETYPES [ node . fileType ] entry [ "permission" ] = node . permission . perm entry [ "path" ] = path for attribute in self . LISTING_ATTRIBUTES : entry [ attribute ] = node . __getattribute__ ( attribute ) return entry | Handle every node received for an ls request |
10,149 | def chmod ( self , paths , mode , recurse = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "chmod: no path given" ) if not mode : raise InvalidInputException ( "chmod: no mode given" ) processor = lambda path , node , ... | Change the mode for paths . This returns a list of maps containing the resut of the operation . |
10,150 | def count ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "count: no path given" ) for item in self . _find_items ( paths , self . _handle_count , include_toplevel = True , include_children = False , recurse = ... | Count files in a path |
10,151 | def df ( self ) : processor = lambda path , node : self . _handle_df ( path , node ) return list ( self . _find_items ( [ '/' ] , processor , include_toplevel = True , include_children = False , recurse = False ) ) [ 0 ] | Get FS information |
10,152 | def du ( self , paths , include_toplevel = False , include_children = True ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "du: no path given" ) processor = lambda path , node : self . _handle_du ( path , node ) for item in s... | Returns size information for paths |
10,153 | def rmdir ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "rmdir: no path given" ) processor = lambda path , node : self . _handle_rmdir ( path , node ) for item in self . _find_items ( paths , processor , incl... | Delete a directory |
10,154 | def touchz ( self , paths , replication = None , blocksize = None ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "touchz: no path given" ) if not replication or not blocksize : defaults = self . serverdefaults ( ) if not rep... | Create a zero length file or updates the timestamp on a zero length file |
10,155 | def setrep ( self , paths , replication , recurse = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "setrep: no path given" ) if not replication : raise InvalidInputException ( "setrep: no replication given" ) processor... | Set the replication factor for paths |
10,156 | def cat ( self , paths , check_crc = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "cat: no path given" ) processor = lambda path , node , check_crc = check_crc : self . _handle_cat ( path , node , check_crc ) for ite... | Fetch all files that match the source file pattern and display their content on stdout . |
10,157 | def copyToLocal ( self , paths , dst , check_crc = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "copyToLocal: no path given" ) if not dst : raise InvalidInputException ( "copyToLocal: no destination given" ) dst = se... | Copy files that match the file source pattern to the local name . Source is kept . When copying multiple files the destination must be a directory . |
10,158 | def getmerge ( self , path , dst , newline = False , check_crc = False ) : if not path : raise InvalidInputException ( "getmerge: no path given" ) if not dst : raise InvalidInputException ( "getmerge: no destination given" ) temporary_target = "%s._COPYING_" % dst f = open ( temporary_target , 'w' ) processor = lambda ... | Get all the files in the directories that match the source file pattern and merge and sort them to only one file on local fs . |
10,159 | def stat ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "stat: no path given" ) processor = lambda path , node : self . _handle_stat ( path , node ) return list ( self . _find_items ( paths , processor , inclu... | Stat a fileCount |
10,160 | def tail ( self , path , tail_length = 1024 , append = False ) : if not path : raise InvalidInputException ( "tail: no path given" ) block_size = self . serverdefaults ( ) [ 'blockSize' ] if tail_length > block_size : raise InvalidInputException ( "tail: currently supports length up to the block size (%d)" % ( block_si... | Show the end of the file - default 1KB supports up to the Hadoop block size . |
10,161 | def mkdir ( self , paths , create_parent = False , mode = 0o755 ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "mkdirs: no path given" ) for path in paths : if not path . startswith ( "/" ) : path = self . _join_user_path ( ... | Create a directoryCount |
10,162 | def serverdefaults ( self , force_reload = False ) : if not self . _server_defaults or force_reload : request = client_proto . GetServerDefaultsRequestProto ( ) response = self . service . getServerDefaults ( request ) . serverDefaults self . _server_defaults = { 'blockSize' : response . blockSize , 'bytesPerChecksum' ... | Get server defaults caching the results . If there are no results saved or the force_reload flag is True it will query the HDFS server for its default parameter values . Otherwise it will simply return the results it has already queried . |
10,163 | def _glob_find ( self , path , processor , include_toplevel ) : path_elements = path . split ( "/" ) for i , element in enumerate ( path_elements ) : if glob . has_magic ( element ) : first_magic = i break if first_magic == 1 : check_path = "/" else : check_path = "/" . join ( path_elements [ : first_magic ] ) match_pa... | Handle globs in paths . This is done by listing the directory before a glob and checking which node matches the initial glob . If there are more globs in the path we don t add the found children to the result but traverse into paths that did have a match . |
10,164 | def _ha_return_method ( func ) : def wrapped ( self , * args , ** kw ) : self . _reset_retries ( ) while ( True ) : try : return func ( self , * args , ** kw ) except RequestError as e : self . __handle_request_error ( e ) except socket . error as e : self . __handle_socket_error ( e ) return wrapped | Method decorator for return type methods |
10,165 | def _ha_gen_method ( func ) : def wrapped ( self , * args , ** kw ) : self . _reset_retries ( ) while ( True ) : try : results = func ( self , * args , ** kw ) while ( True ) : yield results . next ( ) except RequestError as e : self . __handle_request_error ( e ) except socket . error as e : self . __handle_socket_err... | Method decorator for generator type methods |
10,166 | def _validate_number_sequence ( self , seq , n ) : if seq is None : return np . zeros ( n ) if len ( seq ) is n : try : l = [ float ( e ) for e in seq ] except ValueError : raise ValueError ( "One or more elements in sequence <" + repr ( seq ) + "> cannot be interpreted as a real number" ) else : return np . asarray ( ... | Validate a sequence to be of a certain length and ensure it s a numpy array of floats . |
10,167 | def _from_axis_angle ( cls , axis , angle ) : mag_sq = np . dot ( axis , axis ) if mag_sq == 0.0 : raise ZeroDivisionError ( "Provided rotation axis has no length" ) if ( abs ( 1.0 - mag_sq ) > 1e-12 ) : axis = axis / sqrt ( mag_sq ) theta = angle / 2.0 r = cos ( theta ) i = axis * sin ( theta ) return cls ( r , i [ 0 ... | Initialise from axis and angle representation |
10,168 | def random ( cls ) : r1 , r2 , r3 = np . random . random ( 3 ) q1 = sqrt ( 1.0 - r1 ) * ( sin ( 2 * pi * r2 ) ) q2 = sqrt ( 1.0 - r1 ) * ( cos ( 2 * pi * r2 ) ) q3 = sqrt ( r1 ) * ( sin ( 2 * pi * r3 ) ) q4 = sqrt ( r1 ) * ( cos ( 2 * pi * r3 ) ) return cls ( q1 , q2 , q3 , q4 ) | Generate a random unit quaternion . |
10,169 | def conjugate ( self ) : return self . __class__ ( scalar = self . scalar , vector = - self . vector ) | Quaternion conjugate encapsulated in a new instance . |
10,170 | def inverse ( self ) : ss = self . _sum_of_squares ( ) if ss > 0 : return self . __class__ ( array = ( self . _vector_conjugate ( ) / ss ) ) else : raise ZeroDivisionError ( "a zero quaternion (0 + 0i + 0j + 0k) cannot be inverted" ) | Inverse of the quaternion object encapsulated in a new instance . |
10,171 | def _fast_normalise ( self ) : if not self . is_unit ( ) : mag_squared = np . dot ( self . q , self . q ) if ( mag_squared == 0 ) : return if ( abs ( 1.0 - mag_squared ) < 2.107342e-08 ) : mag = ( ( 1.0 + mag_squared ) / 2.0 ) else : mag = sqrt ( mag_squared ) self . q = self . q / mag | Normalise the object to a unit quaternion using a fast approximation method if appropriate . |
10,172 | def rotate ( self , vector ) : if isinstance ( vector , Quaternion ) : return self . _rotate_quaternion ( vector ) q = Quaternion ( vector = vector ) a = self . _rotate_quaternion ( q ) . vector if isinstance ( vector , list ) : l = [ x for x in a ] return l elif isinstance ( vector , tuple ) : l = [ x for x in a ] ret... | Rotate a 3D vector by the rotation stored in the Quaternion object . |
10,173 | def exp ( cls , q ) : tolerance = 1e-17 v_norm = np . linalg . norm ( q . vector ) vec = q . vector if v_norm > tolerance : vec = vec / v_norm magnitude = exp ( q . scalar ) return Quaternion ( scalar = magnitude * cos ( v_norm ) , vector = magnitude * sin ( v_norm ) * vec ) | Quaternion Exponential . |
10,174 | def log ( cls , q ) : v_norm = np . linalg . norm ( q . vector ) q_norm = q . norm tolerance = 1e-17 if q_norm < tolerance : return Quaternion ( scalar = - float ( 'inf' ) , vector = float ( 'nan' ) * q . vector ) if v_norm < tolerance : return Quaternion ( scalar = log ( q_norm ) , vector = [ 0 , 0 , 0 ] ) vec = q . v... | Quaternion Logarithm . |
10,175 | def sym_exp_map ( cls , q , eta ) : sqrt_q = q ** 0.5 return sqrt_q * Quaternion . exp ( eta ) * sqrt_q | Quaternion symmetrized exponential map . |
10,176 | def sym_log_map ( cls , q , p ) : inv_sqrt_q = ( q ** ( - 0.5 ) ) return Quaternion . log ( inv_sqrt_q * p * inv_sqrt_q ) | Quaternion symmetrized logarithm map . |
10,177 | def absolute_distance ( cls , q0 , q1 ) : q0_minus_q1 = q0 - q1 q0_plus_q1 = q0 + q1 d_minus = q0_minus_q1 . norm d_plus = q0_plus_q1 . norm if ( d_minus < d_plus ) : return d_minus else : return d_plus | Quaternion absolute distance . |
10,178 | def distance ( cls , q0 , q1 ) : q = Quaternion . log_map ( q0 , q1 ) return q . norm | Quaternion intrinsic distance . |
10,179 | def sym_distance ( cls , q0 , q1 ) : q = Quaternion . sym_log_map ( q0 , q1 ) return q . norm | Quaternion symmetrized distance . |
10,180 | def intermediates ( cls , q0 , q1 , n , include_endpoints = False ) : step_size = 1.0 / ( n + 1 ) if include_endpoints : steps = [ i * step_size for i in range ( 0 , n + 2 ) ] else : steps = [ i * step_size for i in range ( 1 , n + 1 ) ] for step in steps : yield cls . slerp ( q0 , q1 , step ) | Generator method to get an iterable sequence of n evenly spaced quaternion rotations between any two existing quaternion endpoints lying on the unit radius hypersphere . |
10,181 | def derivative ( self , rate ) : rate = self . _validate_number_sequence ( rate , 3 ) return 0.5 * self * Quaternion ( vector = rate ) | Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector rate |
10,182 | def integrate ( self , rate , timestep ) : self . _fast_normalise ( ) rate = self . _validate_number_sequence ( rate , 3 ) rotation_vector = rate * timestep rotation_norm = np . linalg . norm ( rotation_vector ) if rotation_norm > 0 : axis = rotation_vector / rotation_norm angle = rotation_norm q2 = Quaternion ( axis =... | Advance a time varying quaternion to its value at a time timestep in the future . |
10,183 | def rotation_matrix ( self ) : self . _normalise ( ) product_matrix = np . dot ( self . _q_matrix ( ) , self . _q_bar_matrix ( ) . conj ( ) . transpose ( ) ) return product_matrix [ 1 : ] [ : , 1 : ] | Get the 3x3 rotation matrix equivalent of the quaternion rotation . |
10,184 | def transformation_matrix ( self ) : t = np . array ( [ [ 0.0 ] , [ 0.0 ] , [ 0.0 ] ] ) Rt = np . hstack ( [ self . rotation_matrix , t ] ) return np . vstack ( [ Rt , np . array ( [ 0.0 , 0.0 , 0.0 , 1.0 ] ) ] ) | Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation . |
10,185 | def yaw_pitch_roll ( self ) : self . _normalise ( ) yaw = np . arctan2 ( 2 * ( self . q [ 0 ] * self . q [ 3 ] - self . q [ 1 ] * self . q [ 2 ] ) , 1 - 2 * ( self . q [ 2 ] ** 2 + self . q [ 3 ] ** 2 ) ) pitch = np . arcsin ( 2 * ( self . q [ 0 ] * self . q [ 2 ] + self . q [ 3 ] * self . q [ 1 ] ) ) roll = np . arcta... | Get the equivalent yaw - pitch - roll angles aka . intrinsic Tait - Bryan angles following the z - y - x convention |
10,186 | def get_axis ( self , undefined = np . zeros ( 3 ) ) : tolerance = 1e-17 self . _normalise ( ) norm = np . linalg . norm ( self . vector ) if norm < tolerance : return undefined else : return self . vector / norm | Get the axis or vector about which the quaternion rotation occurs |
10,187 | def req_string ( self , model ) : if model not in self . models : model = self . models if self . min_ykver and self . max_ykver : return "%s %d.%d..%d.%d" % ( model , self . min_ykver [ 0 ] , self . min_ykver [ 1 ] , self . max_ykver [ 0 ] , self . max_ykver [ 1 ] , ) if self . max_ykver : return "%s <= %d.%d" % ( mod... | Return string describing model and version requirement . |
10,188 | def is_compatible ( self , model , version ) : if not model in self . models : return False if self . max_ykver : return ( version >= self . min_ykver and version <= self . max_ykver ) else : return version >= self . min_ykver | Check if this flag is compatible with a YubiKey of version ver . |
10,189 | def get_set ( self , flag , new ) : old = self . _is_set ( flag ) if new is True : self . _set ( flag ) elif new is False : self . _clear ( flag ) return old | Return the boolean value of flag . If new is set the flag is updated and the value before update is returned . |
10,190 | def _read_capabilities ( self ) : frame = yubikey_frame . YubiKeyFrame ( command = SLOT . YK4_CAPABILITIES ) self . _device . _write ( frame ) response = self . _device . _read_response ( ) r_len = yubico_util . ord_byte ( response [ 0 ] ) if not yubico_util . validate_crc16 ( response [ : r_len + 3 ] ) : raise YubiKey... | Read the capabilities list from a YubiKey > = 4 . 0 . 0 |
10,191 | def status ( self ) : data = self . _read ( ) self . _status = YubiKeyUSBHIDStatus ( data ) return self . _status | Poll YubiKey for status . |
10,192 | def _write_config ( self , cfg , slot ) : old_pgm_seq = self . _status . pgm_seq frame = cfg . to_frame ( slot = slot ) self . _debug ( "Writing %s frame :\n%s\n" % ( yubikey_config . command2str ( frame . command ) , cfg ) ) self . _write ( frame ) self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) self . status... | Write configuration to YubiKey . |
10,193 | def _read_response ( self , may_block = False ) : res = self . _waitfor_set ( yubikey_defs . RESP_PENDING_FLAG , may_block ) [ : 7 ] while True : this = self . _read ( ) flags = yubico_util . ord_byte ( this [ 7 ] ) if flags & yubikey_defs . RESP_PENDING_FLAG : seq = flags & 0b00011111 if res and ( seq == 0 ) : break r... | Wait for a response to become available and read it . |
10,194 | def _read ( self ) : request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN value = _REPORT_TYPE_FEATURE << 8 recv = self . _usb_handle . controlMsg ( request_type , _HID_GET_REPORT , _FEATURE_RPT_SIZE , value = value , timeout = _USB_TIMEOUT_MS ) if len ( recv ) != _FEATURE_RPT_SIZE : self . _debug (... | Read a USB HID feature report from the YubiKey . |
10,195 | def _write ( self , frame ) : for data in frame . to_feature_reports ( debug = self . debug ) : debug_str = None if self . debug : ( data , debug_str ) = data self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) self . _raw_write ( data , debug_str ) return True | Write a YubiKeyFrame to the USB HID . |
10,196 | def _write_reset ( self ) : data = b'\x00\x00\x00\x00\x00\x00\x00\x8f' self . _raw_write ( data ) self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) return True | Reset read mode by issuing a dummy write . |
10,197 | def _raw_write ( self , data , debug_str = None ) : if self . debug : if not debug_str : debug_str = '' hexdump = yubico_util . hexdump ( data , colorize = True ) [ : - 1 ] self . _debug ( "WRITE : %s %s\n" % ( hexdump , debug_str ) ) request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_OUT value = _RE... | Write data to YubiKey . |
10,198 | def _waitfor ( self , mode , mask , may_block , timeout = 2 ) : finished = False sleep = 0.01 wait_num = ( timeout * 2 ) - 1 + 6 resp_timeout = False while not finished : time . sleep ( sleep ) this = self . _read ( ) flags = yubico_util . ord_byte ( this [ 7 ] ) if flags & yubikey_defs . RESP_TIMEOUT_WAIT_FLAG : if no... | Wait for the YubiKey to either turn ON or OFF certain bits in the status byte . |
10,199 | def _open ( self , skip = 0 ) : usb_device = self . _get_usb_device ( skip ) if usb_device : usb_conf = usb_device . configurations [ 0 ] self . _usb_int = usb_conf . interfaces [ 0 ] [ 0 ] else : raise YubiKeyUSBHIDError ( 'No USB YubiKey found' ) try : self . _usb_handle = usb_device . open ( ) self . _usb_handle . d... | Perform HID initialization |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.