idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
1,300 | def left_overlaps ( self , other , min_overlap_size = 1 ) : if self . alt != other . alt : # allele must match! return False if len ( other . prefix ) > len ( self . prefix ) : # only consider strings that overlap like: # self: ppppAssss # other: ppAsssssss # which excludes cases where the other sequence has a longer #... | Does this VariantSequence overlap another on the left side? | 311 | 12 |
1,301 | 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 . | 80 | 10 |
1,302 | 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 . | 58 | 38 |
1,303 | 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 . | 119 | 17 |
1,304 | 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 . | 484 | 32 |
1,305 | def trim_N_nucleotides ( prefix , suffix ) : if 'N' in prefix : # trim prefix to exclude all occurrences of N 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_i... | Drop all occurrences of N from prefix and suffix nucleotide strings by trimming . | 152 | 16 |
1,306 | 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 . | 62 | 44 |
1,307 | def publish ( self , data , * * kwargs ) : assert data . get ( 'op' ) in { 'index' , 'create' , 'delete' , 'update' } return super ( Producer , self ) . publish ( data , * * kwargs ) | Validate operation type . | 59 | 5 |
1,308 | 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 . | 91 | 4 |
1,309 | 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 . | 183 | 6 |
1,310 | 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 . | 83 | 9 |
1,311 | 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 . | 122 | 5 |
1,312 | 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 . | 119 | 5 |
1,313 | 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 . | 131 | 5 |
1,314 | 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 . | 182 | 8 |
1,315 | def greedy_merge_helper ( variant_sequences , min_overlap_size = MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE ) : merged_variant_sequences = { } merged_any = False # here we'll keep track of sequences that haven't been merged yet, and add them in at the end unmerged_variant_sequences = set ( variant_sequences ) for i in ... | Returns a list of merged VariantSequence objects and True if any were successfully merged . | 342 | 17 |
1,316 | 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 . | 91 | 10 |
1,317 | def collapse_substrings ( variant_sequences ) : if len ( variant_sequences ) <= 1 : # if we don't have at least two VariantSequences then just # return your input return variant_sequences # dictionary mapping VariantSequence objects to lists of reads # they absorb from substring VariantSequences extra_reads_from_substr... | Combine shorter sequences which are fully contained in longer sequences . | 266 | 12 |
1,318 | def iterative_overlap_assembly ( variant_sequences , min_overlap_size = MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE ) : if len ( variant_sequences ) <= 1 : # if we don't have at least two sequences to start with then # skip the whole mess below return variant_sequences # reduce the number of inputs to the merge algorith... | 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 . | 226 | 31 |
1,319 | 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 . | 44 | 16 |
1,320 | def ortho_basis ( normal , ref_vec = None ) : # Imports for library functions import numpy as np from scipy import linalg as spla from scipy import random as sprnd from . . const import PRM from . . error import VectorError # Internal parameters # Magnitude of the perturbation from 'normal' in constructing a random rv ... | Generates an orthonormal basis in the plane perpendicular to normal | 628 | 13 |
1,321 | def orthonorm_check ( a , tol = _DEF . ORTHONORM_TOL , report = False ) : # Imports import numpy as np from . base import delta_fxn #!TODO? orthonorm_check Must add traps to ensure a is a single array, # that it is 2D, that it's all real? To enforce the limits stated # in the docstring? # Initialize return variables or... | Checks orthonormality of the column vectors of a matrix . | 416 | 14 |
1,322 | def parallel_check ( vec1 , vec2 ) : # Imports from . . const import PRM import numpy as np # Initialize False par = False # Shape check for n , v in enumerate ( [ vec1 , vec2 ] ) : if not len ( v . shape ) == 1 : raise ValueError ( "Bad shape for vector #{0}" . format ( n ) ) ## end if ## next v,n if not vec1 . shape ... | Checks whether two vectors are parallel OR anti - parallel . | 186 | 12 |
1,323 | def proj ( vec , vec_onto ) : # Imports import numpy as np # Ensure vectors if not len ( vec . shape ) == 1 : raise ValueError ( "'vec' is not a vector" ) ## end if if not len ( vec_onto . shape ) == 1 : raise ValueError ( "'vec_onto' is not a vector" ) ## end if if not vec . shape [ 0 ] == vec_onto . shape [ 0 ] : rai... | Vector projection . | 186 | 3 |
1,324 | def rej ( vec , vec_onto ) : # Imports import numpy as np # Calculate and return. rej_vec = vec - proj ( vec , vec_onto ) return rej_vec | Vector rejection . | 46 | 3 |
1,325 | def vec_angle ( vec1 , vec2 ) : # Imports import numpy as np from scipy import linalg as spla from . . const import PRM # Check shape and equal length if len ( vec1 . shape ) != 1 : raise ValueError ( "'vec1' is not a vector" ) ## end if if len ( vec2 . shape ) != 1 : raise ValueError ( "'vec2' is not a vector" ) ## en... | Angle between two R - dimensional vectors . | 330 | 9 |
1,326 | 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 . | 95 | 13 |
1,327 | 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 . | 128 | 21 |
1,328 | 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 . | 88 | 5 |
1,329 | 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 . | 107 | 9 |
1,330 | 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 . | 50 | 7 |
1,331 | 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 . | 67 | 7 |
1,332 | 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 . | 64 | 8 |
1,333 | 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 . | 101 | 7 |
1,334 | 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 . | 185 | 26 |
1,335 | 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 . | 57 | 10 |
1,336 | 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 . | 59 | 29 |
1,337 | def _threeDdot_simple ( M , a ) : 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 , 1 ) ) L = np . dot ( M , A ) result [ i , j , 0 ] = L [ 0 ] resul... | Return Ma where M is a 3x3 transformation matrix for each pixel | 153 | 14 |
1,338 | def _swaplch ( LCH ) : try : # Numpy array L , C , H = np . dsplit ( LCH , 3 ) return np . dstack ( ( H , C , L ) ) except : # Tuple L , C , H = LCH return H , C , L | Reverse the order of an LCH numpy dstack or tuple for analysis . | 66 | 18 |
1,339 | def rgb_to_hsv ( self , RGB ) : gammaRGB = self . _gamma_rgb ( RGB ) return self . _ABC_to_DEF_by_fn ( gammaRGB , rgb_to_hsv ) | linear rgb to hsv | 51 | 5 |
1,340 | def hsv_to_rgb ( self , HSV ) : gammaRGB = self . _ABC_to_DEF_by_fn ( HSV , hsv_to_rgb ) return self . _ungamma_rgb ( gammaRGB ) | hsv to linear rgb | 56 | 5 |
1,341 | 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 . | 32 | 11 |
1,342 | def working2analysis ( self , r ) : 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 . | 54 | 10 |
1,343 | def analysis2working ( self , a ) : 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 . | 54 | 13 |
1,344 | 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 . | 87 | 24 |
1,345 | 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 . | 81 | 12 |
1,346 | def edge_average ( a ) : 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 ( left_edge ) + np . sum ( right_edge ) num_values =... | Return the mean value around the edge of an array . | 157 | 11 |
1,347 | 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_da... | Add the channel information to the channel_data attribute . | 103 | 11 |
1,348 | 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 . | 40 | 14 |
1,349 | 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 the image has more than one channel, ... | Load image using PIL . | 181 | 6 |
1,350 | 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 . | 154 | 6 |
1,351 | def ok_kwarg ( val ) : import keyword try : return str . isidentifier ( val ) and not keyword . iskeyword ( val ) except TypeError : # Non-string values are never a valid keyword arg return False | Helper method for screening keyword arguments | 49 | 6 |
1,352 | 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 . | 230 | 6 |
1,353 | 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 . | 141 | 5 |
1,354 | 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 . | 54 | 4 |
1,355 | def init_queue ( ) : def action ( queue ) : queue . declare ( ) click . secho ( 'Indexing queue has been initialized.' , fg = 'green' ) return queue return action | Initialize indexing queue . | 43 | 6 |
1,356 | def purge_queue ( ) : def action ( queue ) : queue . purge ( ) click . secho ( 'Indexing queue has been purged.' , fg = 'green' ) return queue return action | Purge indexing queue . | 44 | 6 |
1,357 | def delete_queue ( ) : def action ( queue ) : queue . delete ( ) click . secho ( 'Indexing queue has been deleted.' , fg = 'green' ) return queue return action | Delete indexing queue . | 43 | 5 |
1,358 | 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 . | 69 | 25 |
1,359 | 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 # get the interbase range of offse... | Extracts the reference sequence around a variant locus on a particular transcript . | 485 | 16 |
1,360 | def wrap ( lower , upper , x ) : #I have no idea how I came up with this algorithm; it should be simplified. # # Note that Python's % operator works on floats and arrays; # usually one can simply use that instead. E.g. to wrap array or # scalar x into 0,2*pi, just use "x % (2*pi)". range_ = upper - lower return lower +... | Circularly alias the numeric value x into the range [ lower upper ) . | 125 | 16 |
1,361 | 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 . | 54 | 16 |
1,362 | 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 . | 46 | 10 |
1,363 | 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 . | 71 | 10 |
1,364 | 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 . | 64 | 22 |
1,365 | 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 . | 90 | 7 |
1,366 | def en_last ( self ) : # Initialize the return dict last_ens = dict ( ) # Iterate and store for ( k , l ) in self . en . items ( ) : last_ens . update ( { k : l [ - 1 ] if l != [ ] else None } ) ##next (k,l) # Should be ready to return? return last_ens | Report the energies from the last SCF present in the output . | 82 | 13 |
1,367 | 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 . | 118 | 5 |
1,368 | 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 . | 71 | 4 |
1,369 | 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 . | 237 | 7 |
1,370 | 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 . | 113 | 8 |
1,371 | 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 . | 111 | 5 |
1,372 | def _control ( self , state ) : # Renew subscription if necessary 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 ,... | Control device state . | 144 | 4 |
1,373 | 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 . | 83 | 5 |
1,374 | 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 . | 66 | 5 |
1,375 | 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 . | 85 | 5 |
1,376 | 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 . | 162 | 5 |
1,377 | def load ( source ) : parser = get_xml_parser ( ) return etree . parse ( source , parser = parser ) . getroot ( ) | Load OpenCorpora corpus . | 32 | 6 |
1,378 | 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 . | 185 | 45 |
1,379 | 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 . | 582 | 18 |
1,380 | 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 . | 36 | 26 |
1,381 | 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 . | 853 | 18 |
1,382 | def postComponents ( self , name , status , * * kwargs ) : kwargs [ 'name' ] = name kwargs [ 'status' ] = status return self . __postRequest ( '/components' , kwargs ) | Create a new component . | 54 | 5 |
1,383 | 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 . | 78 | 5 |
1,384 | 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 . | 85 | 5 |
1,385 | 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 . | 54 | 9 |
1,386 | def ctr_mass ( geom , masses ) : # Imports import numpy as np from . base import safe_cast as scast # Shape check if len ( geom . shape ) != 1 : raise ValueError ( "Geometry is not a vector" ) ## end if if len ( masses . shape ) != 1 : raise ValueError ( "Masses cannot be parsed as a vector" ) ## end if if not geom . s... | Calculate the center of mass of the indicated geometry . | 336 | 12 |
1,387 | def ctr_geom ( geom , masses ) : # Imports import numpy as np # Calculate the shift vector. Possible bad shape of geom or masses is # addressed internally by the ctr_mass call. shift = np . tile ( ctr_mass ( geom , masses ) , geom . shape [ 0 ] / 3 ) # Shift the geometry and return ctr_geom = geom - shift return ctr_ge... | Returns geometry shifted to center of mass . | 97 | 8 |
1,388 | def inertia_tensor ( geom , masses ) : # Imports import numpy as np # Center the geometry. Takes care of any improper shapes of geom or # masses via the internal call to 'ctr_mass' within the call to 'ctr_geom' geom = ctr_geom ( geom , masses ) # Expand the masses if required. Shape should only ever be (N,) or (3N,), #... | Generate the 3x3 moment - of - inertia tensor . | 464 | 14 |
1,389 | def rot_consts ( geom , masses , units = _EURC . INV_INERTIA , on_tol = _DEF . ORTHONORM_TOL ) : # Imports import numpy as np from . . const import EnumTopType as ETT , EnumUnitsRotConst as EURC , PRM , PHYS # Ensure units are valid if not units in EURC : raise ValueError ( "'{0}' is not a valid units value" . format (... | Rotational constants for a given molecular system . | 768 | 9 |
1,390 | def _fadn_orth ( vec , geom ) : # Imports 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 # Geom and vec must both be the right shape if not ( len ( geom . shape ) == 1 and geom . shape [ 0 ] % 3 == 0 ) : rais... | First non - zero Atomic Displacement Non - Orthogonal to Vec | 404 | 15 |
1,391 | def _fadn_par ( vec , geom ) : # Imports 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 # Geom and vec must both be the right shape if not ( len ( geom . shape ) == 1 and geom . shape [ 0 ] % 3 == 0 ) : raise... | First non - zero Atomic Displacement that is Non - Parallel with Vec | 377 | 15 |
1,392 | 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 . | 86 | 14 |
1,393 | 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 . | 184 | 14 |
1,394 | 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 . | 98 | 8 |
1,395 | 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 . | 136 | 20 |
1,396 | 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 . | 150 | 15 |
1,397 | def smooth_rectangle ( x , y , rec_w , rec_h , gaussian_width_x , gaussian_width_y ) : gaussian_x_coord = abs ( x ) - rec_w / 2.0 gaussian_y_coord = abs ( y ) - rec_h / 2.0 box_x = np . less ( gaussian_x_coord , 0.0 ) box_y = np . less ( gaussian_y_coord , 0.0 ) sigmasq_x = gaussian_width_x * gaussian_width_x sigmasq_y... | Rectangle with a solid central region then Gaussian fall - off at the edges . | 295 | 17 |
1,398 | def pack_tups ( * args ) : # Imports import numpy as np # Debug flag _DEBUG = False # Marker value for non-iterable items NOT_ITER = - 1 # Uninitialized test value UNINIT_VAL = - 1 # Print the input if in debug mode if _DEBUG : # pragma: no cover print ( "args = {0}" . format ( args ) ) # Non-iterable subclass of str c... | Pack an arbitrary set of iterables and non - iterables into tuples . | 485 | 16 |
1,399 | def safe_cast ( invar , totype ) : # Make the typecast. Just use Python built-in exceptioning outvar = totype ( invar ) # Check that the cast type matches if not isinstance ( outvar , totype ) : raise TypeError ( "Result of cast to '{0}' is '{1}'" . format ( totype , type ( outvar ) ) ) ## end if # Success; return the ... | Performs a safe typecast . | 100 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.