idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
1,300 | def filter_variant_sequences ( variant_sequences , preferred_sequence_length , min_variant_sequence_coverage = MIN_VARIANT_SEQUENCE_COVERAGE , ) : variant_sequences = trim_variant_sequences ( variant_sequences , min_variant_sequence_coverage ) return filter_variant_sequences_by_length ( variant_sequences = variant_sequ... | Drop variant sequences which are shorter than request or don t have enough supporting reads . |
1,301 | def reads_generator_to_sequences_generator ( variant_and_reads_generator , min_alt_rna_reads = MIN_ALT_RNA_READS , min_variant_sequence_coverage = MIN_VARIANT_SEQUENCE_COVERAGE , preferred_sequence_length = VARIANT_SEQUENCE_LENGTH , variant_sequence_assembly = VARIANT_SEQUENCE_ASSEMBLY ) : for variant , variant_reads i... | For each variant collect all possible sequence contexts around the variant which are spanned by at least min_reads . |
1,302 | def contains ( self , other ) : return ( self . alt == other . alt and self . prefix . endswith ( other . prefix ) and self . suffix . startswith ( other . suffix ) ) | Is the other VariantSequence a subsequence of this one? |
1,303 | def left_overlaps ( self , other , min_overlap_size = 1 ) : if self . alt != other . alt : return False if len ( other . prefix ) > len ( self . prefix ) : return False elif len ( other . suffix ) < len ( self . suffix ) : return False sequence_overlaps = ( self . prefix . endswith ( other . prefix ) and other . suffix... | Does this VariantSequence overlap another on the left side? |
1,304 | def add_reads ( self , reads ) : if len ( reads ) == 0 : return self new_reads = self . reads . union ( reads ) if len ( new_reads ) > len ( self . reads ) : return VariantSequence ( prefix = self . prefix , alt = self . alt , suffix = self . suffix , reads = new_reads ) else : return self | Create another VariantSequence with more supporting reads . |
1,305 | def variant_indices ( self ) : variant_start_index = len ( self . prefix ) variant_len = len ( self . alt ) variant_end_index = variant_start_index + variant_len return variant_start_index , variant_end_index | When we combine prefix + alt + suffix into a single string what are is base - 0 index interval which gets us back the alt sequence? First returned index is inclusive the second is exclusive . |
1,306 | def coverage ( self ) : variant_start_index , variant_end_index = self . variant_indices ( ) n_nucleotides = len ( self ) coverage_array = np . zeros ( n_nucleotides , dtype = "int32" ) for read in self . reads : coverage_array [ max ( 0 , variant_start_index - len ( read . prefix ) ) : min ( n_nucleotides , variant_en... | Returns NumPy array indicating number of reads covering each nucleotides of this sequence . |
1,307 | def trim_by_coverage ( self , min_reads ) : read_count_array = self . coverage ( ) logger . info ( "Coverage: %s (len=%d)" % ( read_count_array , len ( read_count_array ) ) ) sufficient_coverage_mask = read_count_array >= min_reads sufficient_coverage_indices = np . argwhere ( sufficient_coverage_mask ) if len ( suffic... | Given the min number of reads overlapping each nucleotide of a variant sequence trim this sequence by getting rid of positions which are overlapped by fewer reads than specified . |
1,308 | def trim_N_nucleotides ( prefix , suffix ) : if 'N' in prefix : rightmost_index = prefix . rfind ( 'N' ) logger . debug ( "Trimming %d nucleotides from read prefix '%s'" , rightmost_index + 1 , prefix ) prefix = prefix [ rightmost_index + 1 : ] if 'N' in suffix : leftmost_index = suffix . find ( 'N' ) logger . debug ( ... | Drop all occurrences of N from prefix and suffix nucleotide strings by trimming . |
1,309 | def convert_from_bytes_if_necessary ( prefix , suffix ) : if isinstance ( prefix , bytes ) : prefix = prefix . decode ( 'ascii' ) if isinstance ( suffix , bytes ) : suffix = suffix . decode ( 'ascii' ) return prefix , suffix | Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides . For consistency and simplicity we want to only use strings in the rest of our code . |
1,310 | def publish ( self , data , ** kwargs ) : assert data . get ( 'op' ) in { 'index' , 'create' , 'delete' , 'update' } return super ( Producer , self ) . publish ( data , ** kwargs ) | Validate operation type . |
1,311 | def index ( self , record ) : index , doc_type = self . record_to_index ( record ) return self . client . index ( id = str ( record . id ) , version = record . revision_id , version_type = self . _version_type , index = index , doc_type = doc_type , body = self . _prepare_record ( record , index , doc_type ) , ) | Index a record . |
1,312 | def process_bulk_queue ( self , es_bulk_kwargs = None ) : with current_celery_app . pool . acquire ( block = True ) as conn : consumer = Consumer ( connection = conn , queue = self . mq_queue . name , exchange = self . mq_exchange . name , routing_key = self . mq_routing_key , ) req_timeout = current_app . config [ 'IN... | Process bulk indexing queue . |
1,313 | def _bulk_op ( self , record_id_iterator , op_type , index = None , doc_type = None ) : with self . create_producer ( ) as producer : for rec in record_id_iterator : producer . publish ( dict ( id = str ( rec ) , op = op_type , index = index , doc_type = doc_type ) ) | Index record in Elasticsearch asynchronously . |
1,314 | def _actionsiter ( self , message_iterator ) : for message in message_iterator : payload = message . decode ( ) try : if payload [ 'op' ] == 'delete' : yield self . _delete_action ( payload ) else : yield self . _index_action ( payload ) message . ack ( ) except NoResultFound : message . reject ( ) except Exception : m... | Iterate bulk actions . |
1,315 | def _delete_action ( self , payload ) : index , doc_type = payload . get ( 'index' ) , payload . get ( 'doc_type' ) if not ( index and doc_type ) : record = Record . get_record ( payload [ 'id' ] ) index , doc_type = self . record_to_index ( record ) return { '_op_type' : 'delete' , '_index' : index , '_type' : doc_typ... | Bulk delete action . |
1,316 | def _index_action ( self , payload ) : record = Record . get_record ( payload [ 'id' ] ) index , doc_type = self . record_to_index ( record ) return { '_op_type' : 'index' , '_index' : index , '_type' : doc_type , '_id' : str ( record . id ) , '_version' : record . revision_id , '_version_type' : self . _version_type ,... | Bulk index action . |
1,317 | def _prepare_record ( record , index , doc_type ) : if current_app . config [ 'INDEXER_REPLACE_REFS' ] : data = copy . deepcopy ( record . replace_refs ( ) ) else : data = record . dumps ( ) data [ '_created' ] = pytz . utc . localize ( record . created ) . isoformat ( ) if record . created else None data [ '_updated' ... | Prepare record data for indexing . |
1,318 | def greedy_merge_helper ( variant_sequences , min_overlap_size = MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE ) : merged_variant_sequences = { } merged_any = False unmerged_variant_sequences = set ( variant_sequences ) for i in range ( len ( variant_sequences ) ) : sequence1 = variant_sequences [ i ] for j in range ( i +... | Returns a list of merged VariantSequence objects and True if any were successfully merged . |
1,319 | def greedy_merge ( variant_sequences , min_overlap_size = MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE ) : merged_any = True while merged_any : variant_sequences , merged_any = greedy_merge_helper ( variant_sequences , min_overlap_size = min_overlap_size ) return variant_sequences | Greedily merge overlapping sequences into longer sequences . |
1,320 | def collapse_substrings ( variant_sequences ) : if len ( variant_sequences ) <= 1 : return variant_sequences extra_reads_from_substrings = defaultdict ( set ) result_list = [ ] for short_variant_sequence in sorted ( variant_sequences , key = lambda seq : - len ( seq ) ) : found_superstring = False for long_variant_sequ... | Combine shorter sequences which are fully contained in longer sequences . |
1,321 | def iterative_overlap_assembly ( variant_sequences , min_overlap_size = MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE ) : if len ( variant_sequences ) <= 1 : return variant_sequences n_before_collapse = len ( variant_sequences ) variant_sequences = collapse_substrings ( variant_sequences ) n_after_collapse = len ( variant... | Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequence which contains them . |
1,322 | def groupby ( xs , key_fn ) : result = defaultdict ( list ) for x in xs : key = key_fn ( x ) result [ key ] . append ( x ) return result | Group elements of the list xs by keys generated from calling key_fn . |
1,323 | def ortho_basis ( normal , ref_vec = None ) : import numpy as np from scipy import linalg as spla from scipy import random as sprnd from . . const import PRM from . . error import VectorError RAND_MAG = 0.25 if not len ( normal . shape ) == 1 : raise ValueError ( "'normal' is not a vector" ) if not normal . shape [ 0 ]... | Generates an orthonormal basis in the plane perpendicular to normal |
1,324 | def orthonorm_check ( a , tol = _DEF . ORTHONORM_TOL , report = False ) : import numpy as np from . base import delta_fxn orth = True n_fail = [ ] o_fail = [ ] if len ( a . shape ) == 1 : a_mx = np . matrix ( a , dtype = np . float_ ) . T else : a_mx = np . matrix ( a , dtype = np . float_ ) a_split = np . hsplit ( a_m... | Checks orthonormality of the column vectors of a matrix . |
1,325 | def parallel_check ( vec1 , vec2 ) : from . . const import PRM import numpy as np par = False for n , v in enumerate ( [ vec1 , vec2 ] ) : if not len ( v . shape ) == 1 : raise ValueError ( "Bad shape for vector #{0}" . format ( n ) ) if not vec1 . shape [ 0 ] == vec2 . shape [ 0 ] : raise ValueError ( "Vector length m... | Checks whether two vectors are parallel OR anti - parallel . |
1,326 | def proj ( vec , vec_onto ) : import numpy as np if not len ( vec . shape ) == 1 : raise ValueError ( "'vec' is not a vector" ) if not len ( vec_onto . shape ) == 1 : raise ValueError ( "'vec_onto' is not a vector" ) if not vec . shape [ 0 ] == vec_onto . shape [ 0 ] : raise ValueError ( "Shape mismatch between vectors... | Vector projection . |
1,327 | def rej ( vec , vec_onto ) : import numpy as np rej_vec = vec - proj ( vec , vec_onto ) return rej_vec | Vector rejection . |
1,328 | def vec_angle ( vec1 , vec2 ) : import numpy as np from scipy import linalg as spla from . . const import PRM if len ( vec1 . shape ) != 1 : raise ValueError ( "'vec1' is not a vector" ) if len ( vec2 . shape ) != 1 : raise ValueError ( "'vec2' is not a vector" ) if vec1 . shape [ 0 ] != vec2 . shape [ 0 ] : raise Valu... | Angle between two R - dimensional vectors . |
1,329 | def new_module ( name ) : parent = None if '.' in name : parent_name = name . rsplit ( '.' , 1 ) [ 0 ] parent = __import__ ( parent_name , fromlist = [ '' ] ) module = imp . new_module ( name ) sys . modules [ name ] = module if parent : setattr ( parent , name . rsplit ( '.' , 1 ) [ 1 ] , module ) return module | Do all of the gruntwork associated with creating a new module . |
1,330 | def allele_counts_dataframe ( variant_and_allele_reads_generator ) : df_builder = DataFrameBuilder ( AlleleCount , extra_column_fns = { "gene" : lambda variant , _ : ";" . join ( variant . gene_names ) , } ) for variant , allele_reads in variant_and_allele_reads_generator : counts = count_alleles_at_variant_locus ( var... | Creates a DataFrame containing number of reads supporting the ref vs . alt alleles for each variant . |
1,331 | def install_extension ( conn , extension : str ) : query = 'CREATE EXTENSION IF NOT EXISTS "%s";' with conn . cursor ( ) as cursor : cursor . execute ( query , ( AsIs ( extension ) , ) ) installed = check_extension ( conn , extension ) if not installed : raise psycopg2 . ProgrammingError ( 'Postgres extension failed in... | Install Postgres extension . |
1,332 | def check_extension ( conn , extension : str ) -> bool : query = 'SELECT installed_version FROM pg_available_extensions WHERE name=%s;' with conn . cursor ( ) as cursor : cursor . execute ( query , ( extension , ) ) result = cursor . fetchone ( ) if result is None : raise psycopg2 . ProgrammingError ( 'Extension is not... | Check to see if an extension is installed . |
1,333 | def make_iterable ( obj , default = None ) : if obj is None : return default or [ ] if isinstance ( obj , ( compat . string_types , compat . integer_types ) ) : return [ obj ] return obj | Ensure obj is iterable . |
1,334 | def iter_documents ( self , fileids = None , categories = None , _destroy = False ) : doc_ids = self . _filter_ids ( fileids , categories ) for doc in imap ( self . get_document , doc_ids ) : yield doc if _destroy : doc . destroy ( ) | Return an iterator over corpus documents . |
1,335 | def _create_meta_cache ( self ) : try : with open ( self . _cache_filename , 'wb' ) as f : compat . pickle . dump ( self . _document_meta , f , 1 ) except ( IOError , compat . pickle . PickleError ) : pass | Try to dump metadata to a file . |
1,336 | def _load_meta_cache ( self ) : try : if self . _should_invalidate_cache ( ) : os . remove ( self . _cache_filename ) else : with open ( self . _cache_filename , 'rb' ) as f : self . _document_meta = compat . pickle . load ( f ) except ( OSError , IOError , compat . pickle . PickleError , ImportError , AttributeError )... | Try to load metadata from file . |
1,337 | def _compute_document_meta ( self ) : meta = OrderedDict ( ) bounds_iter = xml_utils . bounds ( self . filename , start_re = r'<text id="(\d+)"[^>]*name="([^"]*)"' , end_re = r'</text>' ) for match , bounds in bounds_iter : doc_id , title = str ( match . group ( 1 ) ) , match . group ( 2 ) title = xml_utils . unescape_... | Return documents meta information that can be used for fast document lookups . Meta information consists of documents titles categories and positions in file . |
1,338 | def _document_xml ( self , doc_id ) : doc_str = self . _get_doc_by_raw_offset ( str ( doc_id ) ) return compat . ElementTree . XML ( doc_str . encode ( 'utf8' ) ) | Return xml Element for the document document_id . |
1,339 | def _get_doc_by_line_offset ( self , doc_id ) : bounds = self . _get_meta ( ) [ str ( doc_id ) ] . bounds return xml_utils . load_chunk ( self . filename , bounds , slow = True ) | Load document from xml using line offset information . This is much slower than _get_doc_by_raw_offset but should work everywhere . |
1,340 | def _threeDdot_simple ( M , a ) : "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np . empty ( a . shape , dtype = a . dtype ) for i in range ( a . shape [ 0 ] ) : for j in range ( a . shape [ 1 ] ) : A = np . array ( [ a [ i , j , 0 ] , a [ i , j , 1 ] , a [ i , j , 2 ] ] ) . reshape ( ( 3... | Return Ma where M is a 3x3 transformation matrix for each pixel |
1,341 | def _swaplch ( LCH ) : "Reverse the order of an LCH numpy dstack or tuple for analysis." try : L , C , H = np . dsplit ( LCH , 3 ) return np . dstack ( ( H , C , L ) ) except : L , C , H = LCH return H , C , L | Reverse the order of an LCH numpy dstack or tuple for analysis . |
1,342 | def rgb_to_hsv ( self , RGB ) : "linear rgb to hsv" gammaRGB = self . _gamma_rgb ( RGB ) return self . _ABC_to_DEF_by_fn ( gammaRGB , rgb_to_hsv ) | linear rgb to hsv |
1,343 | def hsv_to_rgb ( self , HSV ) : "hsv to linear rgb" gammaRGB = self . _ABC_to_DEF_by_fn ( HSV , hsv_to_rgb ) return self . _ungamma_rgb ( gammaRGB ) | hsv to linear rgb |
1,344 | def image2working ( self , i ) : return self . colorspace . convert ( self . image_space , self . working_space , i ) | Transform images i provided into the specified working color space . |
1,345 | def working2analysis ( self , r ) : "Transform working space inputs to the analysis color space." a = self . colorspace . convert ( self . working_space , self . analysis_space , r ) return self . swap_polar_HSVorder [ self . analysis_space ] ( a ) | Transform working space inputs to the analysis color space . |
1,346 | def analysis2working ( self , a ) : "Convert back from the analysis color space to the working space." a = self . swap_polar_HSVorder [ self . analysis_space ] ( a ) return self . colorspace . convert ( self . analysis_space , self . working_space , a ) | Convert back from the analysis color space to the working space . |
1,347 | def load_chunk ( filename , bounds , encoding = 'utf8' , slow = False ) : if slow : return _load_chunk_slow ( filename , bounds , encoding ) with open ( filename , 'rb' ) as f : f . seek ( bounds . byte_start ) size = bounds . byte_end - bounds . byte_start return f . read ( size ) . decode ( encoding ) | Load a chunk from file using Bounds info . Pass slow = True for an alternative loading method based on line numbers . |
1,348 | def generate_numeric_range ( items , lower_bound , upper_bound ) : quantile_grid = create_quantiles ( items , lower_bound , upper_bound ) labels , bounds = ( zip ( * quantile_grid ) ) ranges = ( ( label , NumericRange ( * bound ) ) for label , bound in zip ( labels , bounds ) ) return ranges | Generate postgresql numeric range and label for insertion . |
1,349 | def edge_average ( a ) : "Return the mean value around the edge of an array." if len ( np . ravel ( a ) ) < 2 : return float ( a [ 0 ] ) else : top_edge = a [ 0 ] bottom_edge = a [ - 1 ] left_edge = a [ 1 : - 1 , 0 ] right_edge = a [ 1 : - 1 , - 1 ] edge_sum = np . sum ( top_edge ) + np . sum ( bottom_edge ) + np . sum... | Return the mean value around the edge of an array . |
1,350 | def _process_channels ( self , p , ** params_to_override ) : orig_image = self . _image for i in range ( len ( self . _channel_data ) ) : self . _image = self . _original_channel_data [ i ] self . _channel_data [ i ] = self . _reduced_call ( ** params_to_override ) self . _image = orig_image return self . _channel_data | Add the channel information to the channel_data attribute . |
1,351 | def set_matrix_dimensions ( self , * args ) : self . _image = None super ( FileImage , self ) . set_matrix_dimensions ( * args ) | Subclassed to delete the cached image when matrix dimensions are changed . |
1,352 | def _load_pil_image ( self , filename ) : self . _channel_data = [ ] self . _original_channel_data = [ ] im = Image . open ( filename ) self . _image = ImageOps . grayscale ( im ) im . load ( ) file_data = np . asarray ( im , float ) file_data = file_data / file_data . max ( ) if ( len ( file_data . shape ) == 3 ) : nu... | Load image using PIL . |
1,353 | def _load_npy ( self , filename ) : self . _channel_data = [ ] self . _original_channel_data = [ ] file_channel_data = np . load ( filename ) file_channel_data = file_channel_data / file_channel_data . max ( ) for i in range ( file_channel_data . shape [ 2 ] ) : self . _channel_data . append ( file_channel_data [ : , :... | Load image using Numpy . |
1,354 | def ok_kwarg ( val ) : import keyword try : return str . isidentifier ( val ) and not keyword . iskeyword ( val ) except TypeError : return False | Helper method for screening keyword arguments |
1,355 | def run ( delayed , concurrency , version_type = None , queue = None , raise_on_error = True ) : if delayed : celery_kwargs = { 'kwargs' : { 'version_type' : version_type , 'es_bulk_kwargs' : { 'raise_on_error' : raise_on_error } , } } click . secho ( 'Starting {0} tasks for indexing records...' . format ( concurrency ... | Run bulk record indexing . |
1,356 | def reindex ( pid_type ) : click . secho ( 'Sending records to indexing queue ...' , fg = 'green' ) query = ( x [ 0 ] for x in PersistentIdentifier . query . filter_by ( object_type = 'rec' , status = PIDStatus . REGISTERED ) . filter ( PersistentIdentifier . pid_type . in_ ( pid_type ) ) . values ( PersistentIdentifie... | Reindex all records . |
1,357 | def process_actions ( actions ) : queue = current_app . config [ 'INDEXER_MQ_QUEUE' ] with establish_connection ( ) as c : q = queue ( c ) for action in actions : q = action ( q ) | Process queue actions . |
1,358 | def init_queue ( ) : def action ( queue ) : queue . declare ( ) click . secho ( 'Indexing queue has been initialized.' , fg = 'green' ) return queue return action | Initialize indexing queue . |
1,359 | def purge_queue ( ) : def action ( queue ) : queue . purge ( ) click . secho ( 'Indexing queue has been purged.' , fg = 'green' ) return queue return action | Purge indexing queue . |
1,360 | def delete_queue ( ) : def action ( queue ) : queue . delete ( ) click . secho ( 'Indexing queue has been deleted.' , fg = 'green' ) return queue return action | Delete indexing queue . |
1,361 | def variant_matches_reference_sequence ( variant , ref_seq_on_transcript , strand ) : if strand == "-" : ref_seq_on_transcript = reverse_complement_dna ( ref_seq_on_transcript ) return ref_seq_on_transcript == variant . ref | Make sure that reference nucleotides we expect to see on the reference transcript from a variant are the same ones we encounter . |
1,362 | def from_variant_and_transcript ( cls , variant , transcript , context_size ) : full_transcript_sequence = transcript . sequence if full_transcript_sequence is None : logger . warn ( "Expected transcript %s (overlapping %s) to have sequence" , transcript . name , variant ) return None variant_start_offset , variant_end... | Extracts the reference sequence around a variant locus on a particular transcript . |
1,363 | def wrap ( lower , upper , x ) : range_ = upper - lower return lower + np . fmod ( x - lower + 2 * range_ * ( 1 - np . floor ( x / ( 2 * range_ ) ) ) , range_ ) | Circularly alias the numeric value x into the range [ lower upper ) . |
1,364 | def _pixelsize ( self , p ) : xpixelsize = 1. / float ( p . xdensity ) ypixelsize = 1. / float ( p . ydensity ) return max ( [ xpixelsize , ypixelsize ] ) | Calculate line width necessary to cover at least one pixel on all axes . |
1,365 | def _count_pixels_on_line ( self , y , p ) : h = line ( y , self . _effective_thickness ( p ) , 0.0 ) return h . sum ( ) | Count the number of pixels rendered on this line . |
1,366 | def num_channels ( self ) : if ( self . inspect_value ( 'index' ) is None ) : if ( len ( self . generators ) > 0 ) : return self . generators [ 0 ] . num_channels ( ) return 0 return self . get_current_generator ( ) . num_channels ( ) | Get the number of channels in the input generators . |
1,367 | def _set_frequency_spacing ( self , min_freq , max_freq ) : self . frequency_spacing = np . linspace ( min_freq , max_freq , num = self . _sheet_dimensions [ 0 ] + 1 , endpoint = True ) | Frequency spacing to use i . e . how to map the available frequency range to the discrete sheet rows . |
1,368 | def get_postgres_encoding ( python_encoding : str ) -> str : encoding = normalize_encoding ( python_encoding . lower ( ) ) encoding_ = aliases . aliases [ encoding . replace ( '_' , '' , 1 ) ] . upper ( ) pg_encoding = PG_ENCODING_MAP [ encoding_ . replace ( '_' , '' ) ] return pg_encoding | Python to postgres encoding map . |
1,369 | def en_last ( self ) : last_ens = dict ( ) for ( k , l ) in self . en . items ( ) : last_ens . update ( { k : l [ - 1 ] if l != [ ] else None } ) return last_ens | Report the energies from the last SCF present in the output . |
1,370 | def connect ( host = None , database = None , user = None , password = None , ** kwargs ) : host = host or os . environ [ 'PGHOST' ] database = database or os . environ [ 'PGDATABASE' ] user = user or os . environ [ 'PGUSER' ] password = password or os . environ [ 'PGPASSWORD' ] return psycopg2 . connect ( host = host ... | Create a database connection . |
1,371 | def _setup ( ) : _SOCKET . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) _SOCKET . bind ( ( '' , PORT ) ) udp = threading . Thread ( target = _listen , daemon = True ) udp . start ( ) | Set up module . |
1,372 | def discover ( timeout = DISCOVERY_TIMEOUT ) : hosts = { } payload = MAGIC + DISCOVERY for _ in range ( RETRIES ) : _SOCKET . sendto ( bytearray ( payload ) , ( '255.255.255.255' , PORT ) ) start = time . time ( ) while time . time ( ) < start + timeout : for host , data in _BUFFER . copy ( ) . items ( ) : if not _is_d... | Discover devices on the local network . |
1,373 | def _discover_mac ( self ) : mac = None mac_reversed = None cmd = MAGIC + DISCOVERY resp = self . _udp_transact ( cmd , self . _discovery_resp , broadcast = True , timeout = DISCOVERY_TIMEOUT ) if resp : ( mac , mac_reversed ) = resp if mac is None : raise S20Exception ( "Couldn't discover {}" . format ( self . host ) ... | Discovers MAC address of device . |
1,374 | def _subscribe ( self ) : cmd = MAGIC + SUBSCRIBE + self . _mac + PADDING_1 + self . _mac_reversed + PADDING_1 status = self . _udp_transact ( cmd , self . _subscribe_resp ) if status is not None : self . last_subscribed = time . time ( ) return status == ON else : raise S20Exception ( "No status could be found for {}"... | Subscribe to the device . |
1,375 | def _control ( self , state ) : if not self . _subscription_is_recent ( ) : self . _subscribe ( ) cmd = MAGIC + CONTROL + self . _mac + PADDING_1 + PADDING_2 + state _LOGGER . debug ( "Sending new state to %s: %s" , self . host , ord ( state ) ) ack_state = self . _udp_transact ( cmd , self . _control_resp , state ) if... | Control device state . |
1,376 | def _discovery_resp ( self , data ) : if _is_discovery_response ( data ) : _LOGGER . debug ( "Discovered MAC of %s: %s" , self . host , binascii . hexlify ( data [ 7 : 13 ] ) . decode ( ) ) return ( data [ 7 : 13 ] , data [ 19 : 25 ] ) | Handle a discovery response . |
1,377 | def _subscribe_resp ( self , data ) : if _is_subscribe_response ( data ) : status = bytes ( [ data [ 23 ] ] ) _LOGGER . debug ( "Successfully subscribed to %s, state: %s" , self . host , ord ( status ) ) return status | Handle a subscribe response . |
1,378 | def _control_resp ( self , data , state ) : if _is_control_response ( data ) : ack_state = bytes ( [ data [ 22 ] ] ) if state == ack_state : _LOGGER . debug ( "Received state ack from %s, state: %s" , self . host , ord ( ack_state ) ) return ack_state | Handle a control response . |
1,379 | def _udp_transact ( self , payload , handler , * args , broadcast = False , timeout = TIMEOUT ) : if self . host in _BUFFER : del _BUFFER [ self . host ] host = self . host if broadcast : host = '255.255.255.255' retval = None for _ in range ( RETRIES ) : _SOCKET . sendto ( bytearray ( payload ) , ( host , PORT ) ) sta... | Complete a UDP transaction . |
1,380 | def load ( source ) : parser = get_xml_parser ( ) return etree . parse ( source , parser = parser ) . getroot ( ) | Load OpenCorpora corpus . |
1,381 | def translation_generator ( variant_sequences , reference_contexts , min_transcript_prefix_length , max_transcript_mismatches , include_mismatches_after_variant , protein_sequence_length = None ) : for reference_context in reference_contexts : for variant_sequence in variant_sequences : translation = Translation . from... | Given all detected VariantSequence objects for a particular variant and all the ReferenceContext objects for that locus translate multiple protein sequences up to the number specified by the argument max_protein_sequences_per_variant . |
1,382 | def translate_variant_reads ( variant , variant_reads , protein_sequence_length , transcript_id_whitelist = None , min_alt_rna_reads = MIN_ALT_RNA_READS , min_variant_sequence_coverage = MIN_VARIANT_SEQUENCE_COVERAGE , min_transcript_prefix_length = MIN_TRANSCRIPT_PREFIX_LENGTH , max_transcript_mismatches = MAX_REFEREN... | Given a variant and its associated alt reads construct variant sequences and translate them into Translation objects . |
1,383 | def as_translation_key ( self ) : return TranslationKey ( ** { name : getattr ( self , name ) for name in TranslationKey . _fields } ) | Project Translation object or any other derived class into just a TranslationKey which has fewer fields and can be used as a dictionary key . |
1,384 | def from_variant_sequence_and_reference_context ( cls , variant_sequence , reference_context , min_transcript_prefix_length , max_transcript_mismatches , include_mismatches_after_variant , protein_sequence_length = None ) : variant_sequence_in_reading_frame = match_variant_sequence_to_reference_context ( variant_sequen... | Attempt to translate a single VariantSequence using the reading frame from a single ReferenceContext . |
1,385 | def postComponents ( self , name , status , ** kwargs ) : kwargs [ 'name' ] = name kwargs [ 'status' ] = status return self . __postRequest ( '/components' , kwargs ) | Create a new component . |
1,386 | def postIncidents ( self , name , message , status , visible , ** kwargs ) : kwargs [ 'name' ] = name kwargs [ 'message' ] = message kwargs [ 'status' ] = status kwargs [ 'visible' ] = visible return self . __postRequest ( '/incidents' , kwargs ) | Create a new incident . |
1,387 | def postMetrics ( self , name , suffix , description , default_value , ** kwargs ) : kwargs [ 'name' ] = name kwargs [ 'suffix' ] = suffix kwargs [ 'description' ] = description kwargs [ 'default_value' ] = default_value return self . __postRequest ( '/metrics' , kwargs ) | Create a new metric . |
1,388 | def postMetricsPointsByID ( self , id , value , ** kwargs ) : kwargs [ 'value' ] = value return self . __postRequest ( '/metrics/%s/points' % id , kwargs ) | Add a metric point to a given metric . |
1,389 | def ctr_mass ( geom , masses ) : import numpy as np from . base import safe_cast as scast if len ( geom . shape ) != 1 : raise ValueError ( "Geometry is not a vector" ) if len ( masses . shape ) != 1 : raise ValueError ( "Masses cannot be parsed as a vector" ) if not geom . shape [ 0 ] % 3 == 0 : raise ValueError ( "Ge... | Calculate the center of mass of the indicated geometry . |
1,390 | def ctr_geom ( geom , masses ) : import numpy as np shift = np . tile ( ctr_mass ( geom , masses ) , geom . shape [ 0 ] / 3 ) ctr_geom = geom - shift return ctr_geom | Returns geometry shifted to center of mass . |
1,391 | def inertia_tensor ( geom , masses ) : import numpy as np geom = ctr_geom ( geom , masses ) if geom . shape [ 0 ] == 3 * masses . shape [ 0 ] : masses = masses . repeat ( 3 ) tensor = np . zeros ( ( 3 , 3 ) ) for i in range ( 3 ) : for j in range ( i , 3 ) : if i == j : ind = np . concatenate ( [ np . array ( list ( ma... | Generate the 3x3 moment - of - inertia tensor . |
1,392 | def rot_consts ( geom , masses , units = _EURC . INV_INERTIA , on_tol = _DEF . ORTHONORM_TOL ) : import numpy as np from . . const import EnumTopType as ETT , EnumUnitsRotConst as EURC , PRM , PHYS if not units in EURC : raise ValueError ( "'{0}' is not a valid units value" . format ( units ) ) mom , ax , top = princip... | Rotational constants for a given molecular system . |
1,393 | def _fadn_orth ( vec , geom ) : import numpy as np from scipy import linalg as spla from . . const import PRM from . . error import InertiaError from . vector import orthonorm_check as onchk if not ( len ( geom . shape ) == 1 and geom . shape [ 0 ] % 3 == 0 ) : raise ValueError ( "Geometry is not length 3N" ) if not ve... | First non - zero Atomic Displacement Non - Orthogonal to Vec |
1,394 | def _fadn_par ( vec , geom ) : import numpy as np from scipy import linalg as spla from . . const import PRM from . . error import InertiaError from . vector import parallel_check as parchk if not ( len ( geom . shape ) == 1 and geom . shape [ 0 ] % 3 == 0 ) : raise ValueError ( "Geometry is not length 3N" ) if not vec... | First non - zero Atomic Displacement that is Non - Parallel with Vec |
1,395 | def reference_contexts_for_variants ( variants , context_size , transcript_id_whitelist = None ) : result = OrderedDict ( ) for variant in variants : result [ variant ] = reference_contexts_for_variant ( variant = variant , context_size = context_size , transcript_id_whitelist = transcript_id_whitelist ) return result | Extract a set of reference contexts for each variant in the collection . |
1,396 | def variants_to_reference_contexts_dataframe ( variants , context_size , transcript_id_whitelist = None ) : df_builder = DataFrameBuilder ( ReferenceContext , exclude = [ "variant" ] , converters = dict ( transcripts = lambda ts : ";" . join ( t . name for t in ts ) ) , extra_column_fns = { "gene" : lambda variant , _ ... | Given a collection of variants find all reference sequence contexts around each variant . |
1,397 | def exponential ( x , y , xscale , yscale ) : if xscale == 0.0 or yscale == 0.0 : return x * 0.0 with float_error_ignore ( ) : x_w = np . divide ( x , xscale ) y_h = np . divide ( y , yscale ) return np . exp ( - np . sqrt ( x_w * x_w + y_h * y_h ) ) | Two - dimensional oriented exponential decay pattern . |
1,398 | def line ( y , thickness , gaussian_width ) : distance_from_line = abs ( y ) gaussian_y_coord = distance_from_line - thickness / 2.0 sigmasq = gaussian_width * gaussian_width if sigmasq == 0.0 : falloff = y * 0.0 else : with float_error_ignore ( ) : falloff = np . exp ( np . divide ( - gaussian_y_coord * gaussian_y_coo... | Infinite - length line with a solid central region then Gaussian fall - off at the edges . |
1,399 | def disk ( x , y , height , gaussian_width ) : disk_radius = height / 2.0 distance_from_origin = np . sqrt ( x ** 2 + y ** 2 ) distance_outside_disk = distance_from_origin - disk_radius sigmasq = gaussian_width * gaussian_width if sigmasq == 0.0 : falloff = x * 0.0 else : with float_error_ignore ( ) : falloff = np . ex... | Circular disk with Gaussian fall - off after the solid central region . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.