idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
62,900 | def bound_symbols ( self ) : if self . _bound_symbols is None : res = set . union ( set ( [ ] ) , * [ _bound_symbols ( val ) for val in self . kwargs . values ( ) ] ) res . update ( set ( [ ] ) , * [ _bound_symbols ( arg ) for arg in self . args ] ) self . _bound_symbols = res return self . _bound_symbols | Set of bound SymPy symbols in the expression |
62,901 | def download ( url , dest ) : u = urllib . FancyURLopener ( ) logger . info ( "Downloading %s..." % url ) u . retrieve ( url , dest ) logger . info ( 'Done, see %s' % dest ) return dest | Platform - agnostic downloader . |
62,902 | def logged_command ( cmds ) : "helper function to log a command and then run it" logger . info ( ' ' . join ( cmds ) ) os . system ( ' ' . join ( cmds ) ) | helper function to log a command and then run it |
62,903 | def get_cufflinks ( ) : "Download cufflinks GTF files" for size , md5 , url in cufflinks : cuff_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) ) if not _up_to_date ( md5 , cuff_gtf ) : download ( url , cuff_gtf ) | Download cufflinks GTF files |
62,904 | def get_bams ( ) : for size , md5 , url in bams : bam = os . path . join ( args . data_dir , os . path . basename ( url ) . replace ( '.bam' , '_%s.bam' % CHROM ) ) if not _up_to_date ( md5 , bam ) : logger . info ( 'Downloading reads on chromosome %s from %s to %s' % ( CHROM , url , bam ) ) cmds = [ 'samtools' , 'view... | Download BAM files if needed extract only chr17 reads and regenerate . bai |
62,905 | def get_gtf ( ) : size , md5 , url = GTF full_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) ) subset_gtf = os . path . join ( args . data_dir , os . path . basename ( url ) . replace ( '.gtf.gz' , '_%s.gtf' % CHROM ) ) if not _up_to_date ( md5 , subset_gtf ) : download ( url , full_gtf ) cmds ... | Download GTF file from Ensembl only keeping the chr17 entries . |
62,906 | def make_db ( ) : size , md5 , fn = DB if not _up_to_date ( md5 , fn ) : gffutils . create_db ( fn . replace ( '.db' , '' ) , fn , verbose = True , force = True ) | Create gffutils database |
62,907 | def cufflinks_conversion ( ) : for size , md5 , fn in cufflinks_tables : fn = os . path . join ( args . data_dir , fn ) table = fn . replace ( '.gtf.gz' , '.table' ) if not _up_to_date ( md5 , table ) : logger . info ( "Converting Cufflinks GTF %s to table" % fn ) fout = open ( table , 'w' ) fout . write ( 'id\tscore\t... | convert Cufflinks output GTF files into tables of score and FPKM . |
62,908 | def plot ( self , feature ) : if isinstance ( feature , gffutils . Feature ) : feature = asinterval ( feature ) self . make_fig ( ) axes = [ ] for ax , method in self . panels ( ) : feature = method ( ax , feature ) axes . append ( ax ) return axes | Spawns a new figure showing data for feature . |
62,909 | def example_panel ( self , ax , feature ) : txt = '%s:%s-%s' % ( feature . chrom , feature . start , feature . stop ) ax . text ( 0.5 , 0.5 , txt , transform = ax . transAxes ) return feature | A example panel that just prints the text of the feature . |
62,910 | def signal_panel ( self , ax , feature ) : for gs , kwargs in zip ( self . genomic_signal_objs , self . plotting_kwargs ) : x , y = gs . local_coverage ( feature , ** self . local_coverage_kwargs ) ax . plot ( x , y , ** kwargs ) ax . axis ( 'tight' ) return feature | Plots each genomic signal as a line using the corresponding plotting_kwargs |
62,911 | def panels ( self ) : ax1 = self . fig . add_subplot ( 211 ) ax2 = self . fig . add_subplot ( 212 , sharex = ax1 ) return ( ax2 , self . gene_panel ) , ( ax1 , self . signal_panel ) | Add 2 panels to the figure top for signal and bottom for gene models |
62,912 | def simple ( ) : MAX_VALUE = 100 bar = Bar ( max_value = MAX_VALUE , fallback = True ) bar . cursor . clear_lines ( 2 ) bar . cursor . save ( ) for i in range ( MAX_VALUE + 1 ) : sleep ( 0.1 * random . random ( ) ) bar . cursor . restore ( ) bar . draw ( value = i ) | Simple example using just the Bar class |
62,913 | def tree ( ) : leaf_values = [ Value ( 0 ) for i in range ( 6 ) ] bd_defaults = dict ( type = Bar , kwargs = dict ( max_value = 10 ) ) test_d = { "Warp Jump" : { "1) Prepare fuel" : { "Load Tanks" : { "Tank 1" : BarDescriptor ( value = leaf_values [ 0 ] , ** bd_defaults ) , "Tank 2" : BarDescriptor ( value = leaf_value... | Example showing tree progress view |
62,914 | def ci_plot ( x , arr , conf = 0.95 , ax = None , line_kwargs = None , fill_kwargs = None ) : if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) line_kwargs = line_kwargs or { } fill_kwargs = fill_kwargs or { } m , lo , hi = ci ( arr , conf ) ax . plot ( x , m , ** line_kwargs ) ax . fill_between ( x... | Plots the mean and 95% ci for the given array on the given axes |
62,915 | def add_labels_to_subsets ( ax , subset_by , subset_order , text_kwargs = None , add_hlines = True , hline_kwargs = None ) : _text_kwargs = dict ( transform = ax . get_yaxis_transform ( ) ) if text_kwargs : _text_kwargs . update ( text_kwargs ) _hline_kwargs = dict ( color = 'k' ) if hline_kwargs : _hline_kwargs . upda... | Helper function for adding labels to subsets within a heatmap . |
62,916 | def calculate_limits ( array_dict , method = 'global' , percentiles = None , limit = ( ) ) : if percentiles is not None : for percentile in percentiles : if not 0 <= percentile <= 100 : raise ValueError ( "percentile (%s) not between [0, 100]" ) if method == 'global' : all_arrays = np . concatenate ( [ i . ravel ( ) fo... | Calculate limits for a group of arrays in a flexible manner . |
62,917 | def ci ( arr , conf = 0.95 ) : m = arr . mean ( axis = 0 ) n = len ( arr ) se = arr . std ( axis = 0 ) / np . sqrt ( n ) h = se * stats . t . _ppf ( ( 1 + conf ) / 2. , n - 1 ) return m , m - h , m + h | Column - wise confidence interval . |
62,918 | def nice_log ( x ) : neg = x < 0 xi = np . log2 ( np . abs ( x ) + 1 ) xi [ neg ] = - xi [ neg ] return xi | Uses a log scale but with negative numbers . |
62,919 | def tip_fdr ( a , alpha = 0.05 ) : zscores = tip_zscores ( a ) pvals = stats . norm . pdf ( zscores ) rejected , fdrs = fdrcorrection ( pvals ) return fdrs | Returns adjusted TIP p - values for a particular alpha . |
62,920 | def prepare_logged ( x , y ) : xi = np . log2 ( x ) yi = np . log2 ( y ) xv = np . isfinite ( xi ) yv = np . isfinite ( yi ) global_min = min ( xi [ xv ] . min ( ) , yi [ yv ] . min ( ) ) global_max = max ( xi [ xv ] . max ( ) , yi [ yv ] . max ( ) ) xi [ ~ xv ] = global_min yi [ ~ yv ] = global_min return xi , yi | Transform x and y to a log scale while dealing with zeros . |
62,921 | def _updatecopy ( orig , update_with , keys = None , override = False ) : d = orig . copy ( ) if keys is None : keys = update_with . keys ( ) for k in keys : if k in update_with : if k in d and not override : continue d [ k ] = update_with [ k ] return d | Update a copy of dest with source . If keys is a list then only update with those keys . |
62,922 | def append ( self , x , y , scatter_kwargs , hist_kwargs = None , xhist_kwargs = None , yhist_kwargs = None , num_ticks = 3 , labels = None , hist_share = False , marginal_histograms = True ) : scatter_kwargs = scatter_kwargs or { } hist_kwargs = hist_kwargs or { } xhist_kwargs = xhist_kwargs or { } yhist_kwargs = yhis... | Adds a new scatter to self . scatter_ax as well as marginal histograms for the same data borrowing addtional room from the axes . |
62,923 | def add_legends ( self , xhists = True , yhists = False , scatter = True , ** kwargs ) : axs = [ ] if xhists : axs . extend ( self . hxs ) if yhists : axs . extend ( self . hys ) if scatter : axs . extend ( self . ax ) for ax in axs : ax . legend ( ** kwargs ) | Add legends to axes . |
62,924 | def genomic_signal ( fn , kind ) : try : klass = _registry [ kind . lower ( ) ] except KeyError : raise ValueError ( 'No support for %s format, choices are %s' % ( kind , _registry . keys ( ) ) ) m = klass ( fn ) m . kind = kind return m | Factory function that makes the right class for the file format . |
62,925 | def genome ( self ) : f = self . adapter . fileobj d = { } for ref , length in zip ( f . references , f . lengths ) : d [ ref ] = ( 0 , length ) return d | genome dictionary ready for pybedtools based on the BAM header . |
62,926 | def mapped_read_count ( self , force = False ) : if self . _readcount and not force : return self . _readcount if os . path . exists ( self . fn + '.mmr' ) and not force : for line in open ( self . fn + '.mmr' ) : if line . startswith ( '#' ) : continue self . _readcount = float ( line . strip ( ) ) return self . _read... | Counts total reads in a BAM file . |
62,927 | def print_2x2_table ( table , row_labels , col_labels , fmt = "%d" ) : grand = sum ( table ) t11 , t12 , t21 , t22 = table r1 = t11 + t12 r2 = t21 + t22 c1 = t11 + t21 c2 = t12 + t22 t11 , t12 , t21 , t22 , c1 , c2 , r1 , r2 , grand = [ fmt % i for i in [ t11 , t12 , t21 , t22 , c1 , c2 , r1 , r2 , grand ] ] rows = [ [... | Prints a table used for Fisher s exact test . Adds row column and grand totals . |
62,928 | def print_row_perc_table ( table , row_labels , col_labels ) : r1c1 , r1c2 , r2c1 , r2c2 = map ( float , table ) row1 = r1c1 + r1c2 row2 = r2c1 + r2c2 blocks = [ ( r1c1 , row1 ) , ( r1c2 , row1 ) , ( r2c1 , row2 ) , ( r2c2 , row2 ) ] new_table = [ ] for cell , row in blocks : try : x = cell / row except ZeroDivisionErr... | given a table print the percentages rather than the totals |
62,929 | def print_col_perc_table ( table , row_labels , col_labels ) : r1c1 , r1c2 , r2c1 , r2c2 = map ( float , table ) col1 = r1c1 + r2c1 col2 = r1c2 + r2c2 blocks = [ ( r1c1 , col1 ) , ( r1c2 , col2 ) , ( r2c1 , col1 ) , ( r2c2 , col2 ) ] new_table = [ ] for cell , row in blocks : try : x = cell / row except ZeroDivisionErr... | given a table print the cols as percentages |
62,930 | def draw ( self , tree , bar_desc = None , save_cursor = True , flush = True ) : if save_cursor : self . cursor . save ( ) tree = deepcopy ( tree ) lines_required = self . lines_required ( tree ) ensure ( lines_required <= self . cursor . term . height , LengthOverflowError , "Terminal is not long ({} rows) enough to f... | Draw tree to the terminal |
62,931 | def make_room ( self , tree ) : lines_req = self . lines_required ( tree ) self . cursor . clear_lines ( lines_req ) | Clear lines in terminal below current cursor position as required |
62,932 | def lines_required ( self , tree , count = 0 ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : return sum ( self . lines_required ( v , count = count ) for v in tree . values ( ) ) + 2 elif isinstance ( tree , BarDescriptor ) : if tree . get ( "kwargs" , { } ) . get ( "title_pos" ) in [ "... | Calculate number of lines required to draw tree |
62,933 | def _calculate_values ( self , tree , bar_d ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : max_val = 0 value = 0 for k in tree : bar_desc = self . _calculate_values ( tree [ k ] , bar_d ) tree [ k ] = ( bar_desc , tree [ k ] ) value += bar_desc [ "value" ] . value max_val += bar_desc .... | Calculate values for drawing bars of non - leafs in tree |
62,934 | def _draw ( self , tree , indent = 0 ) : if all ( [ isinstance ( tree , dict ) , type ( tree ) != BarDescriptor ] ) : for k , v in sorted ( tree . items ( ) ) : bar_desc , subdict = v [ 0 ] , v [ 1 ] args = [ self . cursor . term ] + bar_desc . get ( "args" , [ ] ) kwargs = dict ( title_pos = "above" , indent = indent ... | Recurse through tree and draw all nodes |
62,935 | def load_features_and_arrays ( prefix , mmap_mode = 'r' ) : features = pybedtools . BedTool ( prefix + '.features' ) arrays = np . load ( prefix + '.npz' , mmap_mode = mmap_mode ) return features , arrays | Returns the features and NumPy arrays that were saved with save_features_and_arrays . |
62,936 | def save_features_and_arrays ( features , arrays , prefix , compressed = False , link_features = False , overwrite = False ) : if link_features : if isinstance ( features , pybedtools . BedTool ) : assert isinstance ( features . fn , basestring ) features_filename = features . fn else : assert isinstance ( features , b... | Saves NumPy arrays of processed data along with the features that correspond to each row to files for later use . |
62,937 | def list_all ( fritz , args ) : devices = fritz . get_devices ( ) for device in devices : print ( '#' * 30 ) print ( 'name=%s' % device . name ) print ( ' ain=%s' % device . ain ) print ( ' id=%s' % device . identifier ) print ( ' productname=%s' % device . productname ) print ( ' manufacturer=%s' % device . manufa... | Command that prints all device information . |
62,938 | def device_statistics ( fritz , args ) : stats = fritz . get_device_statistics ( args . ain ) print ( stats ) | Command that prints the device statistics . |
62,939 | def chunker ( f , n ) : f = iter ( f ) x = [ ] while 1 : if len ( x ) < n : try : x . append ( f . next ( ) ) except StopIteration : if len ( x ) > 0 : yield tuple ( x ) break else : yield tuple ( x ) x = [ ] | Utility function to split iterable f into n chunks |
62,940 | def split_feature ( f , n ) : if not isinstance ( n , int ) : raise ValueError ( 'n must be an integer' ) orig_feature = copy ( f ) step = ( f . stop - f . start ) / n for i in range ( f . start , f . stop , step ) : f = copy ( orig_feature ) start = i stop = min ( i + step , orig_feature . stop ) f . start = start f .... | Split an interval into n roughly equal portions |
62,941 | def tointerval ( s ) : if isinstance ( s , basestring ) : m = coord_re . search ( s ) if m . group ( 'strand' ) : return pybedtools . create_interval_from_list ( [ m . group ( 'chrom' ) , m . group ( 'start' ) , m . group ( 'stop' ) , '.' , '0' , m . group ( 'strand' ) ] ) else : return pybedtools . create_interval_fro... | If string then convert to an interval ; otherwise just return the input |
62,942 | def max_width ( self ) : value , unit = float ( self . _width_str [ : - 1 ] ) , self . _width_str [ - 1 ] ensure ( unit in [ "c" , "%" ] , ValueError , "Width unit must be either 'c' or '%'" ) if unit == "c" : ensure ( value <= self . columns , ValueError , "Terminal only has {} columns, cannot draw " "bar of size {}."... | Get maximum width of progress bar |
62,943 | def full_line_width ( self ) : bar_str_len = sum ( [ self . _indent , ( ( len ( self . title ) + 1 ) if self . _title_pos in [ "left" , "right" ] else 0 ) , len ( self . start_char ) , self . max_width , len ( self . end_char ) , 1 , len ( str ( self . max_value ) ) * 2 + 1 ] ) return bar_str_len | Find actual length of bar_str |
62,944 | def _supports_colors ( term , raise_err , colors ) : for color in colors : try : if isinstance ( color , str ) : req_colors = 16 if "bright" in color else 8 ensure ( term . number_of_colors >= req_colors , ColorUnsupportedError , "{} is unsupported by your terminal." . format ( color ) ) elif isinstance ( color , int )... | Check if term supports colors |
62,945 | def _get_format_callable ( term , color , back_color ) : if isinstance ( color , str ) : ensure ( any ( isinstance ( back_color , t ) for t in [ str , type ( None ) ] ) , TypeError , "back_color must be a str or NoneType" ) if back_color : return getattr ( term , "_" . join ( [ color , "on" , back_color ] ) ) elif back... | Get string - coloring callable |
62,946 | def draw ( self , value , newline = True , flush = True ) : self . _measure_terminal ( ) amount_complete = 1.0 if self . max_value == 0 else value / self . max_value fill_amount = int ( floor ( amount_complete * self . max_width ) ) empty_amount = self . max_width - fill_amount amount_complete_str = ( u"{}/{}" . format... | Draw the progress bar |
62,947 | def get_text ( nodelist ) : value = [ ] for node in nodelist : if node . nodeType == node . TEXT_NODE : value . append ( node . data ) return '' . join ( value ) | Get the value from a text node . |
62,948 | def _request ( self , url , params = None , timeout = 10 ) : rsp = self . _session . get ( url , params = params , timeout = timeout ) rsp . raise_for_status ( ) return rsp . text . strip ( ) | Send a request with parameters . |
62,949 | def _login_request ( self , username = None , secret = None ) : url = 'http://' + self . _host + '/login_sid.lua' params = { } if username : params [ 'username' ] = username if secret : params [ 'response' ] = secret plain = self . _request ( url , params ) dom = xml . dom . minidom . parseString ( plain ) sid = get_te... | Send a login request with paramerters . |
62,950 | def _logout_request ( self ) : _LOGGER . debug ( 'logout' ) url = 'http://' + self . _host + '/login_sid.lua' params = { 'security:command/logout' : '1' , 'sid' : self . _sid } self . _request ( url , params ) | Send a logout request . |
62,951 | def _create_login_secret ( challenge , password ) : to_hash = ( challenge + '-' + password ) . encode ( 'UTF-16LE' ) hashed = hashlib . md5 ( to_hash ) . hexdigest ( ) return '{0}-{1}' . format ( challenge , hashed ) | Create a login secret . |
62,952 | def _aha_request ( self , cmd , ain = None , param = None , rf = str ) : url = 'http://' + self . _host + '/webservices/homeautoswitch.lua' params = { 'switchcmd' : cmd , 'sid' : self . _sid } if param : params [ 'param' ] = param if ain : params [ 'ain' ] = ain plain = self . _request ( url , params ) if plain == 'inv... | Send an AHA request . |
62,953 | def login ( self ) : try : ( sid , challenge ) = self . _login_request ( ) if sid == '0000000000000000' : secret = self . _create_login_secret ( challenge , self . _password ) ( sid2 , challenge ) = self . _login_request ( username = self . _user , secret = secret ) if sid2 == '0000000000000000' : _LOGGER . warning ( "... | Login and get a valid session ID . |
62,954 | def get_device_elements ( self ) : plain = self . _aha_request ( 'getdevicelistinfos' ) dom = xml . dom . minidom . parseString ( plain ) _LOGGER . debug ( dom ) return dom . getElementsByTagName ( "device" ) | Get the DOM elements for the device list . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.