idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
12,200
def estimategaps ( args ) : p = OptionParser ( estimategaps . __doc__ ) p . add_option ( "--minsize" , default = 100 , type = "int" , help = "Minimum gap size" ) p . add_option ( "--maxsize" , default = 500000 , type = "int" , help = "Maximum gap size" ) p . add_option ( "--links" , default = 10 , type = "int" , help = "Only use linkage grounds with matchings more than" ) p . set_verbose ( help = "Print details for each gap calculation" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputbed , = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] agpfile = pf + ".chr.agp" bedfile = pf + ".lifted.bed" cc = Map ( bedfile , scaffold_info = True ) agp = AGP ( agpfile ) minsize , maxsize = opts . minsize , opts . maxsize links = opts . links verbose = opts . verbose outagpfile = pf + ".estimategaps.agp" fw = must_open ( outagpfile , "w" ) for ob , components in agp . iter_object ( ) : components = list ( components ) s = Scaffold ( ob , cc ) mlg_counts = s . mlg_counts gaps = [ x for x in components if x . is_gap ] gapsizes = [ None ] * len ( gaps ) for mlg , count in mlg_counts . items ( ) : if count < links : continue g = GapEstimator ( cc , agp , ob , mlg ) g . compute_all_gaps ( minsize = minsize , maxsize = maxsize , verbose = verbose ) assert len ( g . gapsizes ) == len ( gaps ) for i , gs in enumerate ( gapsizes ) : gg = g . gapsizes [ i ] if gs is None : gapsizes [ i ] = gg elif gg : gapsizes [ i ] = min ( gs , gg ) print ( gapsizes ) i = 0 for x in components : if x . is_gap : x . gap_length = gapsizes [ i ] or minsize x . component_type = 'U' if x . gap_length == 100 else 'N' i += 1 print ( x , file = fw ) fw . close ( ) reindex ( [ outagpfile , "--inplace" ] )
%prog estimategaps input . bed
12,201
def merge ( args ) : p = OptionParser ( merge . __doc__ ) p . add_option ( "-w" , "--weightsfile" , default = "weights.txt" , help = "Write weights to file" ) p . set_outfile ( "out.bed" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) maps = args outfile = opts . outfile fp = must_open ( maps ) b = Bed ( ) mapnames = set ( ) for row in fp : mapname = filename_to_mapname ( fp . filename ( ) ) mapnames . add ( mapname ) try : m = CSVMapLine ( row , mapname = mapname ) if m . cm < 0 : logging . error ( "Ignore marker with negative genetic distance" ) print ( row . strip ( ) , file = sys . stderr ) else : b . append ( BedLine ( m . bedline ) ) except ( IndexError , ValueError ) : continue b . print_to_file ( filename = outfile , sorted = True ) logging . debug ( "A total of {0} markers written to `{1}`." . format ( len ( b ) , outfile ) ) assert len ( maps ) == len ( mapnames ) , "You have a collision in map names" write_weightsfile ( mapnames , weightsfile = opts . weightsfile )
%prog merge map1 map2 map3 ...
12,202
def mergebed ( args ) : p = OptionParser ( mergebed . __doc__ ) p . add_option ( "-w" , "--weightsfile" , default = "weights.txt" , help = "Write weights to file" ) p . set_outfile ( "out.bed" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) maps = args outfile = opts . outfile fp = must_open ( maps ) b = Bed ( ) mapnames = set ( ) for row in fp : mapname = filename_to_mapname ( fp . filename ( ) ) mapnames . add ( mapname ) try : m = BedLine ( row ) m . accn = "{0}-{1}" . format ( mapname , m . accn ) m . extra = [ "{0}:{1}" . format ( m . seqid , m . start ) ] b . append ( m ) except ( IndexError , ValueError ) : continue b . print_to_file ( filename = outfile , sorted = True ) logging . debug ( "A total of {0} markers written to `{1}`." . format ( len ( b ) , outfile ) ) assert len ( maps ) == len ( mapnames ) , "You have a collision in map names" write_weightsfile ( mapnames , weightsfile = opts . weightsfile )
%prog mergebed map1 . bed map2 . bed map3 . bed ...
12,203
def summary ( args ) : p = OptionParser ( summary . __doc__ ) p . set_table ( sep = "|" , align = True ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) inputbed , scaffolds = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] mapbed = pf + ".bed" chr_agp = pf + ".chr.agp" sep = opts . sep align = opts . align cc = Map ( mapbed ) mapnames = cc . mapnames s = Sizes ( scaffolds ) total , l50 , n50 = s . summary r = { } maps = [ ] fw = must_open ( opts . outfile , "w" ) print ( "*** Summary for each individual map ***" , file = fw ) for mapname in mapnames : markers = [ x for x in cc if x . mapname == mapname ] ms = MapSummary ( markers , l50 , s ) r [ "Linkage Groups" , mapname ] = ms . num_lgs ms . export_table ( r , mapname , total ) maps . append ( ms ) print ( tabulate ( r , sep = sep , align = align ) , file = fw ) r = { } agp = AGP ( chr_agp ) print ( "*** Summary for consensus map ***" , file = fw ) consensus_scaffolds = set ( x . component_id for x in agp if not x . is_gap ) oriented_scaffolds = set ( x . component_id for x in agp if ( not x . is_gap ) and x . orientation != '?' ) unplaced_scaffolds = set ( s . mapping . keys ( ) ) - consensus_scaffolds for mapname , sc in ( ( "Anchored" , consensus_scaffolds ) , ( "Oriented" , oriented_scaffolds ) , ( "Unplaced" , unplaced_scaffolds ) ) : markers = [ x for x in cc if x . seqid in sc ] ms = MapSummary ( markers , l50 , s , scaffolds = sc ) ms . export_table ( r , mapname , total ) print ( tabulate ( r , sep = sep , align = align ) , file = fw )
%prog summary input . bed scaffolds . fasta
12,204
def build ( args ) : p = OptionParser ( build . __doc__ ) p . add_option ( "--cleanup" , default = False , action = "store_true" , help = "Clean up bulky FASTA files, useful for plotting" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) inputbed , scaffolds = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] mapbed = pf + ".bed" chr_agp = pf + ".chr.agp" chr_fasta = pf + ".chr.fasta" if need_update ( ( chr_agp , scaffolds ) , chr_fasta ) : agp_build ( [ chr_agp , scaffolds , chr_fasta ] ) unplaced_agp = pf + ".unplaced.agp" if need_update ( ( chr_agp , scaffolds ) , unplaced_agp ) : write_unplaced_agp ( chr_agp , scaffolds , unplaced_agp ) unplaced_fasta = pf + ".unplaced.fasta" if need_update ( ( unplaced_agp , scaffolds ) , unplaced_fasta ) : agp_build ( [ unplaced_agp , scaffolds , unplaced_fasta ] ) combined_agp = pf + ".agp" if need_update ( ( chr_agp , unplaced_agp ) , combined_agp ) : FileMerger ( ( chr_agp , unplaced_agp ) , combined_agp ) . merge ( ) combined_fasta = pf + ".fasta" if need_update ( ( chr_fasta , unplaced_fasta ) , combined_fasta ) : FileMerger ( ( chr_fasta , unplaced_fasta ) , combined_fasta ) . merge ( ) chainfile = pf + ".chain" if need_update ( ( combined_agp , scaffolds , combined_fasta ) , chainfile ) : fromagp ( [ combined_agp , scaffolds , combined_fasta ] ) liftedbed = mapbed . rsplit ( "." , 1 ) [ 0 ] + ".lifted.bed" if need_update ( ( mapbed , chainfile ) , liftedbed ) : cmd = "liftOver -minMatch=1 {0} {1} {2} unmapped" . format ( mapbed , chainfile , liftedbed ) sh ( cmd , check = True ) if opts . cleanup : FileShredder ( [ chr_fasta , unplaced_fasta , combined_fasta , chainfile , unplaced_agp , combined_fasta + ".sizes" , "unmapped" ] ) sort ( [ liftedbed , "-i" ] )
%prog build input . bed scaffolds . fasta
12,205
def plotall ( xargs ) : p = OptionParser ( plotall . __doc__ ) add_allmaps_plot_options ( p ) opts , args , iopts = p . set_image_options ( xargs , figsize = "10x6" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputbed , = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] agpfile = pf + ".chr.agp" agp = AGP ( agpfile ) objects = [ ob for ob , lines in agp . iter_object ( ) ] for seqid in natsorted ( objects ) : plot ( xargs + [ seqid ] )
%prog plotall input . bed
12,206
def get_orientation ( self , si , sj ) : if not si or not sj : return 0 a = lms ( si + sj ) b = lms ( sj + si ) c = lms ( si + sj [ : : - 1 ] ) d = lms ( sj [ : : - 1 ] + si ) return max ( a , b ) [ 0 ] - max ( c , d ) [ 0 ]
si sj are two number series . To compute whether these two series have same orientation or not . We combine them in the two orientation configurations and compute length of the longest monotonic series .
12,207
def fix_tour ( self , tour ) : scaffolds , oos = zip ( * tour ) keep = set ( ) for mlg in self . linkage_groups : lg = mlg . lg for s , o in tour : i = scaffolds . index ( s ) L = [ self . get_series ( lg , x , xo ) for x , xo in tour [ : i ] ] U = [ self . get_series ( lg , x , xo ) for x , xo in tour [ i + 1 : ] ] L , U = list ( flatten ( L ) ) , list ( flatten ( U ) ) M = self . get_series ( lg , s , o ) score_with = lms ( L + M + U ) [ 0 ] score_without = lms ( L + U ) [ 0 ] assert score_with >= score_without if score_with > score_without : keep . add ( s ) dropped = len ( tour ) - len ( keep ) logging . debug ( "Dropped {0} minor scaffolds" . format ( dropped ) ) return [ ( s , o ) for ( s , o ) in tour if s in keep ]
Test each scaffold if dropping does not decrease LMS .
12,208
def fix_orientation ( self , tour ) : orientations = dict ( tour ) scaffold_oo = defaultdict ( list ) scaffolds , oos = zip ( * tour ) for mlg in self . linkage_groups : lg = mlg . lg mapname = mlg . mapname for s , o in tour : i = scaffolds . index ( s ) L = [ self . get_series ( lg , x , xo ) for x , xo in tour [ : i ] ] U = [ self . get_series ( lg , x , xo ) for x , xo in tour [ i + 1 : ] ] L , U = list ( flatten ( L ) ) , list ( flatten ( U ) ) M = self . get_series ( lg , s ) plus = lms ( L + M + U ) minus = lms ( L + M [ : : - 1 ] + U ) d = plus [ 0 ] - minus [ 0 ] if not d : continue scaffold_oo [ s ] . append ( ( d , mapname ) ) fixed = 0 for s , v in scaffold_oo . items ( ) : d = self . weighted_mean ( v ) old_d = orientations [ s ] new_d = np . sign ( d ) if new_d != old_d : orientations [ s ] = new_d fixed += 1 tour = [ ( x , orientations [ x ] ) for x in scaffolds ] logging . debug ( "Fixed orientations for {0} scaffolds." . format ( fixed ) ) return tour
Test each scaffold if flipping will increass longest monotonic chain length .
12,209
def spin ( self ) : for x in self . spinchars : self . string = self . msg + "...\t" + x + "\r" self . out . write ( self . string . encode ( 'utf-8' ) ) self . out . flush ( ) time . sleep ( self . waittime )
Perform a single spin
12,210
def make_sequence ( seq , name = "S" ) : return [ "{}_{}_{}" . format ( name , i , x ) for i , x in enumerate ( seq ) ]
Make unique nodes for sequence graph .
12,211
def sequence_to_graph ( G , seq , color = 'black' ) : for x in seq : if x . endswith ( "_1" ) : G . node ( x , color = color , width = "0.1" , shape = "circle" , label = "" ) else : G . node ( x , color = color ) for a , b in pairwise ( seq ) : G . edge ( a , b , color = color )
Automatically construct graph given a sequence of characters .
12,212
def zip_sequences ( G , allseqs , color = "white" ) : for s in zip ( * allseqs ) : groups = defaultdict ( list ) for x in s : part = x . split ( '_' , 1 ) [ 1 ] groups [ part ] . append ( x ) for part , g in groups . items ( ) : with G . subgraph ( name = "cluster_" + part ) as c : for x in g : c . node ( x ) c . attr ( style = "invis" )
Fuse certain nodes together if they contain same data except for the sequence name .
12,213
def gallery ( args ) : from jcvi . apps . base import iglob from jcvi . utils . iter import grouper p = OptionParser ( gallery . __doc__ ) p . add_option ( "--columns" , default = 3 , type = "int" , help = "How many cells per row" ) p . add_option ( "--width" , default = 200 , type = "int" , help = "Image width" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , link_prefix = args width = opts . width images = iglob ( folder , "*.jpg,*.JPG,*.png" ) td = '<td>{0}<br><a href="{1}"><img src="{1}" width="{2}"></a></td>' print ( "<table>" ) for ims in grouper ( images , opts . columns ) : print ( '<tr height="{0}" valign="top">' . format ( width + 5 ) ) for im in ims : if not im : continue im = op . basename ( im ) pf = im . split ( '.' ) [ 0 ] . replace ( '_' , '-' ) link = link_prefix . rstrip ( "/" ) + "/" + im print ( td . format ( pf , link , width ) ) print ( "</tr>" ) print ( "</table>" )
%prog gallery folder link_prefix
12,214
def links ( args ) : p = OptionParser ( links . __doc__ ) p . add_option ( "--img" , default = False , action = "store_true" , help = "Extract <img> tags [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) url , = args img = opts . img htmlfile = download ( url ) page = open ( htmlfile ) . read ( ) soup = BeautifulSoup ( page ) tag = 'img' if img else 'a' src = 'src' if img else 'href' aa = soup . findAll ( tag ) for a in aa : link = a . get ( src ) link = urljoin ( url , link ) print ( link )
%prog links url
12,215
def unescape ( s , unicode_action = "replace" ) : import HTMLParser hp = HTMLParser . HTMLParser ( ) s = hp . unescape ( s ) s = s . encode ( 'ascii' , unicode_action ) s = s . replace ( "\n" , "" ) . strip ( ) return s
Unescape HTML strings and convert &amp ; etc .
12,216
def table ( args ) : import csv p = OptionParser ( table . __doc__ ) p . set_sep ( sep = "," ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) htmlfile , = args page = open ( htmlfile ) . read ( ) soup = BeautifulSoup ( page ) for i , tabl in enumerate ( soup . findAll ( 'table' ) ) : nrows = 0 csvfile = htmlfile . rsplit ( "." , 1 ) [ 0 ] + ".{0}.csv" . format ( i ) writer = csv . writer ( open ( csvfile , "w" ) , delimiter = opts . sep ) rows = tabl . findAll ( 'tr' ) for tr in rows : cols = tr . findAll ( 'td' ) if not cols : cols = tr . findAll ( 'th' ) row = [ ] for td in cols : try : cell = "" . join ( td . find ( text = True ) ) cell = unescape ( cell ) except TypeError : cell = "" row . append ( cell ) writer . writerow ( row ) nrows += 1 logging . debug ( "Table with {0} rows written to `{1}`." . format ( nrows , csvfile ) )
%prog table page . html
12,217
def blast ( args ) : p = OptionParser ( blast . __doc__ ) p . add_option ( "--dist" , default = 100 , type = "int" , help = "Merge adjacent HSPs separated by [default: %default]" ) p . add_option ( "--db" , help = "Use a different database rather than UniVec_Core" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args fastaprefix = fastafile . split ( "." , 1 ) [ 0 ] univec = opts . db or download ( "ftp://ftp.ncbi.nih.gov/pub/UniVec/UniVec_Core" ) uniprefix = univec . split ( "." , 1 ) [ 0 ] fastablast = fastaprefix + ".{0}.blast" . format ( uniprefix ) prog = run_megablast if opts . db else run_vecscreen prog ( infile = fastafile , outfile = fastablast , db = univec , pctid = 95 , hitlen = 50 ) fp = open ( fastablast ) ranges = [ ] for row in fp : b = BlastLine ( row ) ranges . append ( ( b . query , b . qstart , b . qstop ) ) merged_ranges = range_merge ( ranges , dist = opts . dist ) bedfile = fastaprefix + ".{0}.bed" . format ( uniprefix ) fw = must_open ( bedfile , "w" ) for seqid , start , end in merged_ranges : print ( "\t" . join ( str ( x ) for x in ( seqid , start - 1 , end , uniprefix ) ) , file = fw ) return bedfile
%prog blast fastafile
12,218
def check_exists ( filename , oappend = False ) : if op . exists ( filename ) : if oappend : return oappend logging . error ( "`{0}` found, overwrite (Y/N)?" . format ( filename ) ) overwrite = ( raw_input ( ) == 'Y' ) else : overwrite = True return overwrite
Avoid overwriting some files accidentally .
12,219
def must_open ( filename , mode = "r" , checkexists = False , skipcheck = False , oappend = False ) : if isinstance ( filename , list ) : assert "r" in mode if filename [ 0 ] . endswith ( ( ".gz" , ".bz2" ) ) : filename = " " . join ( filename ) else : import fileinput return fileinput . input ( filename ) if filename . startswith ( "s3://" ) : from jcvi . utils . aws import pull_from_s3 filename = pull_from_s3 ( filename ) if filename in ( "-" , "stdin" ) : assert "r" in mode fp = sys . stdin elif filename == "stdout" : assert "w" in mode fp = sys . stdout elif filename == "stderr" : assert "w" in mode fp = sys . stderr elif filename == "tmp" and mode == "w" : from tempfile import NamedTemporaryFile fp = NamedTemporaryFile ( delete = False ) elif filename . endswith ( ".gz" ) : if 'r' in mode : cmd = "gunzip -c {0}" . format ( filename ) fp = popen ( cmd , debug = False ) elif 'w' in mode : import gzip fp = gzip . open ( filename , mode ) elif filename . endswith ( ".bz2" ) : if 'r' in mode : cmd = "bzcat {0}" . format ( filename ) fp = popen ( cmd , debug = False ) elif 'w' in mode : import bz2 fp = bz2 . BZ2File ( filename , mode ) else : if checkexists : assert mode == "w" overwrite = ( not op . exists ( filename ) ) if skipcheck else check_exists ( filename , oappend ) if overwrite : if oappend : fp = open ( filename , "a" ) else : fp = open ( filename , "w" ) else : logging . debug ( "File `{0}` already exists. Skipped." . format ( filename ) ) return None else : fp = open ( filename , mode ) return fp
Accepts filename and returns filehandle .
12,220
def read_block ( handle , signal ) : signal_len = len ( signal ) it = ( x [ 1 ] for x in groupby ( handle , key = lambda row : row . strip ( ) [ : signal_len ] == signal ) ) found_signal = False for header in it : header = list ( header ) for h in header [ : - 1 ] : h = h . strip ( ) if h [ : signal_len ] != signal : continue yield h , [ ] header = header [ - 1 ] . strip ( ) if header [ : signal_len ] != signal : continue found_signal = True seq = list ( s . strip ( ) for s in next ( it ) ) yield header , seq if not found_signal : handle . seek ( 0 ) seq = list ( s . strip ( ) for s in handle ) yield None , seq
Useful for reading block - like file formats for example FASTA or OBO file such file usually startswith some signal and in - between the signals are a record
12,221
def get_number ( s , cast = int ) : import string d = "" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d )
Try to get a number out of a string and cast it .
12,222
def seqids ( args ) : p = OptionParser ( seqids . __doc__ ) p . add_option ( "--pad0" , default = 0 , help = "How many zeros to pad" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) prefix , start , end = args pad0 = opts . pad0 start , end = int ( start ) , int ( end ) step = 1 if start <= end else - 1 print ( "," . join ( [ "{}{:0{}d}" . format ( prefix , x , pad0 ) for x in xrange ( start , end + step , step ) ] ) )
%prog seqids prefix start end
12,223
def pairwise ( args ) : from itertools import combinations p = OptionParser ( pairwise . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args ids = SetFile ( idsfile ) ids = sorted ( ids ) fw = open ( idsfile + ".pairs" , "w" ) for a , b in combinations ( ids , 2 ) : print ( "\t" . join ( ( a , b ) ) , file = fw ) fw . close ( )
%prog pairwise ids
12,224
def truncate ( args ) : p = OptionParser ( truncate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) number , filename = args number = int ( number ) count = 0 f = open ( filename , "r+b" ) f . seek ( 0 , os . SEEK_END ) while f . tell ( ) > 0 : f . seek ( - 1 , os . SEEK_CUR ) char = f . read ( 1 ) if char == '\n' : count += 1 if count == number + 1 : f . truncate ( ) print ( "Removed {0} lines from end of file" . format ( number ) , file = sys . stderr ) return number f . seek ( - 1 , os . SEEK_CUR ) if count < number + 1 : print ( "No change: requested removal would leave empty file" , file = sys . stderr ) return - 1
%prog truncate linecount filename
12,225
def flatten ( args ) : from six . moves import zip_longest p = OptionParser ( flatten . __doc__ ) p . set_sep ( sep = "," ) p . add_option ( "--zipflatten" , default = None , dest = "zipsep" , help = "Specify if columns of the file should be zipped before" + " flattening. If so, specify delimiter separating column elements" + " [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) tabfile , = args zipsep = opts . zipsep fp = must_open ( tabfile ) for row in fp : if zipsep : row = row . rstrip ( ) atoms = row . split ( opts . sep ) frows = [ ] for atom in atoms : frows . append ( atom . split ( zipsep ) ) print ( "\n" . join ( [ zipsep . join ( x ) for x in list ( zip_longest ( * frows , fillvalue = "na" ) ) ] ) ) else : print ( row . strip ( ) . replace ( opts . sep , "\n" ) )
%prog flatten filename > ids
12,226
def reorder ( args ) : import csv p = OptionParser ( reorder . __doc__ ) p . set_sep ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) tabfile , order = args sep = opts . sep order = [ int ( x ) - 1 for x in order . split ( "," ) ] reader = csv . reader ( must_open ( tabfile ) , delimiter = sep ) writer = csv . writer ( sys . stdout , delimiter = sep ) for row in reader : newrow = [ row [ x ] for x in order ] writer . writerow ( newrow )
%prog reorder tabfile 1 2 4 3 > newtabfile
12,227
def split ( args ) : p = OptionParser ( split . __doc__ ) mode_choices = ( "batch" , "cycle" , "optimal" ) p . add_option ( "--all" , default = False , action = "store_true" , help = "split all records [default: %default]" ) p . add_option ( "--mode" , default = "optimal" , choices = mode_choices , help = "Mode when splitting records [default: %default]" ) p . add_option ( "--format" , choices = ( "fasta" , "fastq" , "txt" , "clust" ) , help = "input file format [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) filename , outdir , N = args fs = FileSplitter ( filename , outputdir = outdir , format = opts . format , mode = opts . mode ) if opts . all : logging . debug ( "option -all override N" ) N = fs . num_records else : N = min ( fs . num_records , int ( N ) ) assert N > 0 , "N must be > 0" logging . debug ( "split file into %d chunks" % N ) fs . split ( N ) return fs
%prog split file outdir N
12,228
def setop ( args ) : from jcvi . utils . natsort import natsorted p = OptionParser ( setop . __doc__ ) p . add_option ( "--column" , default = 0 , type = "int" , help = "The column to extract, 0-based, -1 to disable [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) statement , = args fa , op , fb = statement . split ( ) assert op in ( '|' , '&' , '-' , '^' ) column = opts . column fa = SetFile ( fa , column = column ) fb = SetFile ( fb , column = column ) if op == '|' : t = fa | fb elif op == '&' : t = fa & fb elif op == '-' : t = fa - fb elif op == '^' : t = fa ^ fb for x in natsorted ( t ) : print ( x )
%prog setop fileA & fileB > newfile
12,229
def _batch_iterator ( self , N = 1 ) : batch_size = math . ceil ( self . num_records / float ( N ) ) handle = self . _open ( self . filename ) while True : batch = list ( islice ( handle , batch_size ) ) if not batch : break yield batch
Returns N lists of records .
12,230
def extract ( args ) : p = OptionParser ( extract . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) idsfile , sizesfile = args sizes = Sizes ( sizesfile ) . mapping fp = open ( idsfile ) for row in fp : name = row . strip ( ) size = sizes [ name ] print ( "\t" . join ( str ( x ) for x in ( name , size ) ) )
%prog extract idsfile sizesfile
12,231
def _reversedict ( d ) : return dict ( list ( zip ( list ( d . values ( ) ) , list ( d . keys ( ) ) ) ) )
Internal helper for generating reverse mappings ; given a dictionary returns a new dictionary with keys and values swapped .
12,232
def _percent_to_integer ( percent ) : num = float ( percent . split ( '%' ) [ 0 ] ) / 100.0 * 255 e = num - math . floor ( num ) return e < 0.5 and int ( math . floor ( num ) ) or int ( math . ceil ( num ) )
Internal helper for converting a percentage value to an integer between 0 and 255 inclusive .
12,233
def closest_color ( requested_color ) : logging . disable ( logging . DEBUG ) colors = [ ] for key , name in css3_hex_to_names . items ( ) : diff = color_diff ( hex_to_rgb ( key ) , requested_color ) colors . append ( ( diff , name ) ) logging . disable ( logging . NOTSET ) min_diff , min_color = min ( colors ) return min_color
Find closest color name for the request RGB tuple .
12,234
def offdiag ( args ) : p = OptionParser ( offdiag . __doc__ ) p . set_beds ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) anchorsfile , = args qbed , sbed , qorder , sorder , is_self = check_beds ( anchorsfile , p , opts ) fp = open ( anchorsfile ) pf = "-" . join ( anchorsfile . split ( "." ) [ : 2 ] ) header = "Block-id|Napus|Diploid|Napus-chr|Diploid-chr|RBH?" . split ( "|" ) print ( "\t" . join ( header ) ) i = - 1 for row in fp : if row [ 0 ] == '#' : i += 1 continue q , s , score = row . split ( ) rbh = 'no' if score [ - 1 ] == 'L' else 'yes' qi , qq = qorder [ q ] si , ss = sorder [ s ] oqseqid = qseqid = qq . seqid osseqid = sseqid = ss . seqid sseqid = sseqid . split ( "_" ) [ 0 ] [ - 3 : ] if qseqid [ 0 ] == 'A' : qseqid = qseqid [ - 3 : ] elif qseqid [ 0 ] == 'C' : qseqid = 'C0' + qseqid [ - 1 ] else : continue if qseqid == sseqid or sseqid [ - 2 : ] == 'nn' : continue block_id = pf + "-block-{0}" . format ( i ) print ( "\t" . join ( ( block_id , q , s , oqseqid , osseqid , rbh ) ) )
%prog offdiag diploid . napus . 1x1 . lifted . anchors
12,235
def diff ( args ) : from jcvi . utils . cbook import SummaryStats p = OptionParser ( diff . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) simplefile , = args fp = open ( simplefile ) data = [ x . split ( ) for x in fp ] spans = [ ] for block_id , ab in groupby ( data [ 1 : ] , key = lambda x : x [ 0 ] ) : a , b = list ( ab ) aspan , bspan = a [ 4 ] , b [ 4 ] aspan , bspan = int ( aspan ) , int ( bspan ) spans . append ( ( aspan , bspan ) ) aspans , bspans = zip ( * spans ) dspans = [ b - a for a , b , in spans ] s = SummaryStats ( dspans ) print ( "For a total of {0} blocks:" . format ( len ( dspans ) ) , file = sys . stderr ) print ( "Sum of A: {0}" . format ( sum ( aspans ) ) , file = sys . stderr ) print ( "Sum of B: {0}" . format ( sum ( bspans ) ) , file = sys . stderr ) print ( "Sum of Delta: {0} ({1})" . format ( sum ( dspans ) , s ) , file = sys . stderr )
%prog diff simplefile
12,236
def estimate_size ( accns , bed , order , conservative = True ) : accns = [ order [ x ] for x in accns ] ii , bb = zip ( * accns ) mini , maxi = min ( ii ) , max ( ii ) if not conservative : mini -= 1 maxi += 1 minb = bed [ mini ] maxb = bed [ maxi ] assert minb . seqid == maxb . seqid distmode = "ss" if conservative else "ee" ra = ( minb . seqid , minb . start , minb . end , "+" ) rb = ( maxb . seqid , maxb . start , maxb . end , "+" ) dist , orientation = range_distance ( ra , rb , distmode = distmode ) assert dist != - 1 return dist
Estimate the bp length for the deletion tracks indicated by the gene accns . True different levels of estimates vary on conservativeness .
12,237
def merge ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( merge . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) quartets , registry , lost = args qq = DictFile ( registry , keypos = 1 , valuepos = 3 ) lost = DictFile ( lost , keypos = 1 , valuepos = 0 , delimiter = '|' ) qq . update ( lost ) fp = open ( quartets ) cases = { "AN,CN" : 4 , "BO,AN,CN" : 8 , "BO,CN" : 2 , "BR,AN" : 1 , "BR,AN,CN" : 6 , "BR,BO" : 3 , "BR,BO,AN" : 5 , "BR,BO,AN,CN" : 9 , "BR,BO,CN" : 7 , } ip = { "syntenic_model" : "Syntenic_model_excluded_by_OMG" , "complete" : "Predictable" , "partial" : "Truncated" , "pseudogene" : "Pseudogene" , "random" : "Match_random" , "real_ns" : "Transposed" , "gmap_fail" : "GMAP_fail" , "AN LOST" : "AN_LOST" , "CN LOST" : "CN_LOST" , "BR LOST" : "BR_LOST" , "BO LOST" : "BO_LOST" , "outside" : "Outside_synteny_blocks" , "[NF]" : "Not_found" , } for row in fp : atoms = row . strip ( ) . split ( "\t" ) genes = atoms [ : 4 ] tag = atoms [ 4 ] a , b , c , d = [ qq . get ( x , "." ) . rsplit ( "-" , 1 ) [ - 1 ] for x in genes ] qqs = [ c , d , a , b ] for i , q in enumerate ( qqs ) : if atoms [ i ] != '.' : qqs [ i ] = "syntenic_model" comment = "Case{0}" . format ( cases [ tag ] ) dots = sum ( [ 1 for x in genes if x == '.' ] ) if dots == 1 : idx = genes . index ( "." ) status = qqs [ idx ] status = ip [ status ] comment += "-" + status print ( row . strip ( ) + "\t" + "\t" . join ( qqs + [ comment ] ) )
%prog merge protein - quartets registry LOST
12,238
def gffselect ( args ) : from jcvi . formats . bed import intersectBed_wao p = OptionParser ( gffselect . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) gmapped , expected , idsfile , tag = args data = get_tags ( idsfile ) completeness = dict ( ( a . replace ( "mrna" , "path" ) , c ) for ( a , b , c ) in data ) seen = set ( ) idsfile = expected . rsplit ( "." , 1 ) [ 0 ] + ".ids" fw = open ( idsfile , "w" ) cnt = 0 for a , b in intersectBed_wao ( expected , gmapped ) : if b is None : continue aname , bbname = a . accn , b . accn bname = bbname . split ( "." ) [ 0 ] if completeness [ bbname ] != tag : continue if aname == bname : if bname in seen : continue seen . add ( bname ) print ( bbname , file = fw ) cnt += 1 fw . close ( ) logging . debug ( "Total {0} records written to `{1}`." . format ( cnt , idsfile ) )
%prog gffselect gmaplocation . bed expectedlocation . bed translated . ids tag
12,239
def gaps ( args ) : from jcvi . formats . base import DictFile from jcvi . apps . base import popen from jcvi . utils . cbook import percentage p = OptionParser ( gaps . __doc__ ) p . add_option ( "--bdist" , default = 0 , type = "int" , help = "Base pair distance [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) idsfile , frfile , gapsbed = args bdist = opts . bdist d = DictFile ( frfile , keypos = 1 , valuepos = 2 ) bedfile = idsfile + ".bed" fw = open ( bedfile , "w" ) fp = open ( idsfile ) total = 0 for row in fp : id = row . strip ( ) hit = d [ id ] tag , pos = get_tag ( hit , None ) seqid , start , end = pos start , end = max ( start - bdist , 1 ) , end + bdist print ( "\t" . join ( str ( x ) for x in ( seqid , start - 1 , end , id ) ) , file = fw ) total += 1 fw . close ( ) cmd = "intersectBed -a {0} -b {1} -v | wc -l" . format ( bedfile , gapsbed ) not_in_gaps = popen ( cmd ) . read ( ) not_in_gaps = int ( not_in_gaps ) in_gaps = total - not_in_gaps print ( "Ids in gaps: {1}" . format ( total , percentage ( in_gaps , total ) ) , file = sys . stderr )
%prog gaps idsfile fractionationfile gapsbed
12,240
def genestatus ( args ) : p = OptionParser ( genestatus . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args data = get_tags ( idsfile ) key = lambda x : x [ 0 ] . split ( "." ) [ 0 ] for gene , cc in groupby ( data , key = key ) : cc = list ( cc ) tags = [ x [ - 1 ] for x in cc ] if "complete" in tags : tag = "complete" elif "partial" in tags : tag = "partial" else : tag = "pseudogene" print ( "\t" . join ( ( gene , tag ) ) )
%prog genestatus diploid . gff3 . exon . ids
12,241
def validate ( args ) : from jcvi . formats . bed import intersectBed_wao p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fractionation , cdsbed = args fp = open ( fractionation ) sbed = "S.bed" fw = open ( sbed , "w" ) for row in fp : a , b , c = row . split ( ) if not c . startswith ( "[S]" ) : continue tag , ( seqid , start , end ) = get_tag ( c , None ) print ( "\t" . join ( str ( x ) for x in ( seqid , start - 1 , end , b ) ) , file = fw ) fw . close ( ) pairs = { } for a , b in intersectBed_wao ( sbed , cdsbed ) : if b is None : continue pairs [ a . accn ] = b . accn validated = fractionation + ".validated" fw = open ( validated , "w" ) fp . seek ( 0 ) fixed = 0 for row in fp : a , b , c = row . split ( ) if b in pairs : assert c . startswith ( "[S]" ) c = pairs [ b ] fixed += 1 print ( "\t" . join ( ( a , b , c ) ) , file = fw ) logging . debug ( "Fixed {0} [S] cases in `{1}`." . format ( fixed , validated ) ) fw . close ( )
%prog validate diploid . napus . fractionation cds . bed
12,242
def longest ( args ) : from jcvi . formats . fasta import Fasta , SeqIO from jcvi . formats . sizes import Sizes p = OptionParser ( longest . __doc__ ) p . add_option ( "--prefix" , default = "pasa" , help = "Replace asmbl_ with prefix [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , subclusters = args prefix = fastafile . rsplit ( "." , 1 ) [ 0 ] idsfile = prefix + ".fl.ids" fw = open ( idsfile , "w" ) sizes = Sizes ( fastafile ) . mapping name_convert = lambda x : x . replace ( "asmbl" , opts . prefix ) keep = set ( ) fp = open ( subclusters ) nrecs = 0 for row in fp : if not row . startswith ( "sub-cluster:" ) : continue asmbls = row . split ( ) [ 1 : ] longest_asmbl = max ( asmbls , key = lambda x : sizes [ x ] ) longest_size = sizes [ longest_asmbl ] print ( name_convert ( longest_asmbl ) , file = fw ) nrecs += 1 cutoff = max ( longest_size / 2 , 200 ) keep . update ( set ( x for x in asmbls if sizes [ x ] >= cutoff ) ) fw . close ( ) logging . debug ( "{0} fl-cDNA records written to `{1}`." . format ( nrecs , idsfile ) ) f = Fasta ( fastafile , lazy = True ) newfastafile = prefix + ".clean.fasta" fw = open ( newfastafile , "w" ) nrecs = 0 for name , rec in f . iteritems_ordered ( ) : if name not in keep : continue rec . id = name_convert ( name ) rec . description = "" SeqIO . write ( [ rec ] , fw , "fasta" ) nrecs += 1 fw . close ( ) logging . debug ( "{0} valid records written to `{1}`." . format ( nrecs , newfastafile ) )
%prog longest pasa . fasta output . subclusters . out
12,243
def ids ( args ) : p = OptionParser ( ids . __doc__ ) p . add_option ( "--prefix" , type = "int" , help = "Find rep id for prefix of len [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clstrfile , = args cf = ClstrFile ( clstrfile ) prefix = opts . prefix if prefix : reads = list ( cf . iter_reps_prefix ( prefix = prefix ) ) else : reads = list ( cf . iter_reps ( ) ) nreads = len ( reads ) idsfile = clstrfile . replace ( ".clstr" , ".ids" ) fw = open ( idsfile , "w" ) for i , name in reads : print ( "\t" . join ( str ( x ) for x in ( i , name ) ) , file = fw ) logging . debug ( "A total of {0} unique reads written to `{1}`." . format ( nreads , idsfile ) ) fw . close ( ) return idsfile
%prog ids cdhit . clstr
12,244
def summary ( args ) : from jcvi . graphics . histogram import loghistogram p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clstrfile , = args cf = ClstrFile ( clstrfile ) data = list ( cf . iter_sizes ( ) ) loghistogram ( data , summary = True )
%prog summary cdhit . clstr
12,245
def deduplicate ( args ) : p = OptionParser ( deduplicate . __doc__ ) p . set_align ( pctid = 96 , pctcov = 0 ) p . add_option ( "--fast" , default = False , action = "store_true" , help = "Place sequence in the first cluster" ) p . add_option ( "--consensus" , default = False , action = "store_true" , help = "Compute consensus sequences" ) p . add_option ( "--reads" , default = False , action = "store_true" , help = "Use `cd-hit-454` to deduplicate [default: %default]" ) p . add_option ( "--samestrand" , default = False , action = "store_true" , help = "Enforce same strand alignment" ) p . set_home ( "cdhit" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args identity = opts . pctid / 100. fastafile , qualfile = fasta ( [ fastafile , "--seqtk" ] ) ocmd = "cd-hit-454" if opts . reads else "cd-hit-est" cmd = op . join ( opts . cdhit_home , ocmd ) cmd += " -c {0}" . format ( identity ) if ocmd == "cd-hit-est" : cmd += " -d 0" if opts . samestrand : cmd += " -r 0" if not opts . fast : cmd += " -g 1" if opts . pctcov != 0 : cmd += " -aL {0} -aS {0}" . format ( opts . pctcov / 100. ) dd = fastafile + ".P{0}.cdhit" . format ( opts . pctid ) clstr = dd + ".clstr" cmd += " -M 0 -T {0} -i {1} -o {2}" . format ( opts . cpus , fastafile , dd ) if need_update ( fastafile , ( dd , clstr ) ) : sh ( cmd ) if opts . consensus : cons = dd + ".consensus" cmd = op . join ( opts . cdhit_home , "cdhit-cluster-consensus" ) cmd += " clustfile={0} fastafile={1} output={2} maxlen=1" . format ( clstr , fastafile , cons ) if need_update ( ( clstr , fastafile ) , cons ) : sh ( cmd ) return dd
%prog deduplicate fastafile
12,246
def extract_blocks ( ubi ) : blocks = { } ubi . file . seek ( ubi . file . start_offset ) peb_count = 0 cur_offset = 0 bad_blocks = [ ] for i in range ( ubi . file . start_offset , ubi . file . end_offset , ubi . file . block_size ) : try : buf = ubi . file . read ( ubi . file . block_size ) except Exception as e : if settings . warn_only_block_read_errors : error ( extract_blocks , 'Error' , 'PEB: %s: %s' % ( ubi . first_peb_num + peb_count , str ( e ) ) ) continue else : error ( extract_blocks , 'Fatal' , 'PEB: %s: %s' % ( ubi . first_peb_num + peb_count , str ( e ) ) ) if buf . startswith ( UBI_EC_HDR_MAGIC ) : blk = description ( buf ) blk . file_offset = i blk . peb_num = ubi . first_peb_num + peb_count blk . size = ubi . file . block_size blocks [ blk . peb_num ] = blk peb_count += 1 log ( extract_blocks , blk ) verbose_log ( extract_blocks , 'file addr: %s' % ( ubi . file . last_read_addr ( ) ) ) ec_hdr_errors = '' vid_hdr_errors = '' if blk . ec_hdr . errors : ec_hdr_errors = ',' . join ( blk . ec_hdr . errors ) if blk . vid_hdr and blk . vid_hdr . errors : vid_hdr_errors = ',' . join ( blk . vid_hdr . errors ) if ec_hdr_errors or vid_hdr_errors : if blk . peb_num not in bad_blocks : bad_blocks . append ( blk . peb_num ) log ( extract_blocks , 'PEB: %s has possible issue EC_HDR [%s], VID_HDR [%s]' % ( blk . peb_num , ec_hdr_errors , vid_hdr_errors ) ) verbose_display ( blk ) else : cur_offset += ubi . file . block_size ubi . first_peb_num = cur_offset / ubi . file . block_size ubi . file . start_offset = cur_offset return blocks
Get a list of UBI block objects from file
12,247
def by_image_seq ( blocks , image_seq ) : return list ( filter ( lambda block : blocks [ block ] . ec_hdr . image_seq == image_seq , blocks ) )
Filter blocks to return only those associated with the provided image_seq number .
12,248
def by_vol_id ( blocks , slist = None ) : vol_blocks = { } for i in blocks : if slist and i not in slist : continue elif not blocks [ i ] . is_valid : continue if blocks [ i ] . vid_hdr . vol_id not in vol_blocks : vol_blocks [ blocks [ i ] . vid_hdr . vol_id ] = [ ] vol_blocks [ blocks [ i ] . vid_hdr . vol_id ] . append ( blocks [ i ] . peb_num ) return vol_blocks
Sort blocks by volume id
12,249
def by_type ( blocks , slist = None ) : layout = [ ] data = [ ] int_vol = [ ] unknown = [ ] for i in blocks : if slist and i not in slist : continue if blocks [ i ] . is_vtbl and blocks [ i ] . is_valid : layout . append ( i ) elif blocks [ i ] . is_internal_vol and blocks [ i ] . is_valid : int_vol . append ( i ) elif blocks [ i ] . is_valid : data . append ( i ) else : unknown . append ( i ) return layout , data , int_vol , unknown
Sort blocks into layout internal volume data or unknown
12,250
def get_newest ( blocks , layout_blocks ) : layout_temp = list ( layout_blocks ) for i in range ( 0 , len ( layout_temp ) ) : for k in range ( 0 , len ( layout_blocks ) ) : if blocks [ layout_temp [ i ] ] . ec_hdr . image_seq != blocks [ layout_blocks [ k ] ] . ec_hdr . image_seq : continue if blocks [ layout_temp [ i ] ] . leb_num != blocks [ layout_blocks [ k ] ] . leb_num : continue if blocks [ layout_temp [ i ] ] . vid_hdr . sqnum > blocks [ layout_blocks [ k ] ] . vid_hdr . sqnum : del layout_blocks [ k ] break return layout_blocks
Filter out old layout blocks from list
12,251
def group_pairs ( blocks , layout_blocks_list ) : image_dict = { } for block_id in layout_blocks_list : image_seq = blocks [ block_id ] . ec_hdr . image_seq if image_seq not in image_dict : image_dict [ image_seq ] = [ block_id ] else : image_dict [ image_seq ] . append ( block_id ) log ( group_pairs , 'Layout blocks found at PEBs: %s' % list ( image_dict . values ( ) ) ) return list ( image_dict . values ( ) )
Sort a list of layout blocks into pairs
12,252
def associate_blocks ( blocks , layout_pairs , start_peb_num ) : seq_blocks = [ ] for layout_pair in layout_pairs : seq_blocks = sort . by_image_seq ( blocks , blocks [ layout_pair [ 0 ] ] . ec_hdr . image_seq ) layout_pair . append ( seq_blocks ) return layout_pairs
Group block indexes with appropriate layout pairs
12,253
def get_volumes ( blocks , layout_info ) : volumes = { } vol_blocks_lists = sort . by_vol_id ( blocks , layout_info [ 2 ] ) for vol_rec in blocks [ layout_info [ 0 ] ] . vtbl_recs : vol_name = vol_rec . name . strip ( b'\x00' ) . decode ( 'utf-8' ) if vol_rec . rec_index not in vol_blocks_lists : vol_blocks_lists [ vol_rec . rec_index ] = [ ] volumes [ vol_name ] = description ( vol_rec . rec_index , vol_rec , vol_blocks_lists [ vol_rec . rec_index ] ) return volumes
Get a list of UBI volume objects from list of blocks
12,254
def parse_key ( key ) : hkey , lkey = struct . unpack ( '<II' , key [ 0 : UBIFS_SK_LEN ] ) ino_num = hkey & UBIFS_S_KEY_HASH_MASK key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS khash = lkey return { 'type' : key_type , 'ino_num' : ino_num , 'khash' : khash }
Parse node key
12,255
def decompress ( ctype , unc_len , data ) : if ctype == UBIFS_COMPR_LZO : try : return lzo . decompress ( b'' . join ( ( b'\xf0' , struct . pack ( '>I' , unc_len ) , data ) ) ) except Exception as e : error ( decompress , 'Warn' , 'LZO Error: %s' % e ) elif ctype == UBIFS_COMPR_ZLIB : try : return zlib . decompress ( data , - 11 ) except Exception as e : error ( decompress , 'Warn' , 'ZLib Error: %s' % e ) else : return data
Decompress data .
12,256
def guess_leb_size ( path ) : f = open ( path , 'rb' ) f . seek ( 0 , 2 ) file_size = f . tell ( ) + 1 f . seek ( 0 ) block_size = None for _ in range ( 0 , file_size , FILE_CHUNK_SZ ) : buf = f . read ( FILE_CHUNK_SZ ) for m in re . finditer ( UBIFS_NODE_MAGIC , buf ) : start = m . start ( ) chdr = nodes . common_hdr ( buf [ start : start + UBIFS_COMMON_HDR_SZ ] ) if chdr and chdr . node_type == UBIFS_SB_NODE : sb_start = start + UBIFS_COMMON_HDR_SZ sb_end = sb_start + UBIFS_SB_NODE_SZ if chdr . len != len ( buf [ sb_start : sb_end ] ) : f . seek ( sb_start ) buf = f . read ( UBIFS_SB_NODE_SZ ) else : buf = buf [ sb_start : sb_end ] sbn = nodes . sb_node ( buf ) block_size = sbn . leb_size f . close ( ) return block_size f . close ( ) return block_size
Get LEB size from superblock
12,257
def guess_peb_size ( path ) : file_offset = 0 offsets = [ ] f = open ( path , 'rb' ) f . seek ( 0 , 2 ) file_size = f . tell ( ) + 1 f . seek ( 0 ) for _ in range ( 0 , file_size , FILE_CHUNK_SZ ) : buf = f . read ( FILE_CHUNK_SZ ) for m in re . finditer ( UBI_EC_HDR_MAGIC , buf ) : start = m . start ( ) if not file_offset : file_offset = start idx = start else : idx = start + file_offset offsets . append ( idx ) file_offset += FILE_CHUNK_SZ f . close ( ) occurances = { } for i in range ( 0 , len ( offsets ) ) : try : diff = offsets [ i ] - offsets [ i - 1 ] except : diff = offsets [ i ] if diff not in occurances : occurances [ diff ] = 0 occurances [ diff ] += 1 most_frequent = 0 block_size = None for offset in occurances : if occurances [ offset ] > most_frequent : most_frequent = occurances [ offset ] block_size = offset return block_size
Determine the most likely block size
12,258
def convert_to_int ( value ) : if not value : return None if isinstance ( value , str ) : value = value . strip ( ' px' ) try : return int ( value ) except ( TypeError , ValueError ) : return None
Attempts to convert a specified value to an integer
12,259
def parse_oembed_data ( oembed_data , data ) : data . update ( { 'oembed' : oembed_data , } ) _type = oembed_data . get ( 'type' ) provider_name = oembed_data . get ( 'provider_name' ) if not _type : return data if oembed_data . get ( 'title' ) : data . update ( { 'title' : oembed_data . get ( 'title' ) , } ) if _type == 'video' : try : item = { 'width' : convert_to_int ( oembed_data . get ( 'width' ) ) , 'height' : convert_to_int ( oembed_data . get ( 'height' ) ) } if provider_name in [ 'YouTube' , ] : item [ 'src' ] = HYPERLINK_PATTERN . search ( oembed_data . get ( 'html' ) ) . group ( 0 ) data [ 'videos' ] . append ( item ) except Exception : pass if oembed_data . get ( 'thumbnail_url' ) : item = { 'width' : convert_to_int ( oembed_data . get ( 'thumbnail_width' ) ) , 'height' : convert_to_int ( oembed_data . get ( 'thumbnail_height' ) ) , 'src' : oembed_data . get ( 'thumbnail_url' ) } data [ 'images' ] . append ( item ) return data
Parse OEmbed resposne data to inject into lassie s response dict .
12,260
def _filter_meta_data ( self , source , soup , data , url = None ) : meta = FILTER_MAPS [ 'meta' ] [ source ] meta_map = meta [ 'map' ] html = soup . find_all ( 'meta' , { meta [ 'key' ] : meta [ 'pattern' ] } ) image = { } video = { } for line in html : prop = line . get ( meta [ 'key' ] ) value = line . get ( 'content' ) _prop = meta_map . get ( prop ) if prop in meta_map and _prop and not data . get ( _prop ) : image_prop = meta [ 'image_key' ] video_prop = meta [ 'video_key' ] if prop . startswith ( ( image_prop , video_prop ) ) and prop . endswith ( ( 'width' , 'height' ) ) : if prop . endswith ( ( 'width' , 'height' ) ) : value = convert_to_int ( value ) if meta_map [ prop ] == 'locale' : locale = normalize_locale ( value ) if locale : data [ 'locale' ] = locale if prop == 'keywords' : if isinstance ( value , str ) : value = [ v . strip ( ) for v in value . split ( ',' ) ] else : value = [ ] if image_prop and prop . startswith ( image_prop ) and value : if prop == 'og:image' and url : value = urljoin ( url , value ) image [ meta_map [ prop ] ] = value elif video_prop and prop . startswith ( video_prop ) and value : video [ meta_map [ prop ] ] = value else : data [ meta_map [ prop ] ] = value if image : image [ 'type' ] = image_prop data [ 'images' ] . append ( image ) if video : data [ 'videos' ] . append ( video )
This method filters the web page content for meta tags that match patterns given in the FILTER_MAPS
12,261
def _filter_link_tag_data ( self , source , soup , data , url ) : link = FILTER_MAPS [ 'link' ] [ source ] html = soup . find_all ( 'link' , { link [ 'key' ] : link [ 'pattern' ] } ) if link [ 'type' ] == 'url' : for line in html : data [ 'url' ] = line . get ( 'href' ) else : for line in html : data [ 'images' ] . append ( { 'src' : urljoin ( url , line . get ( 'href' ) ) , 'type' : link [ 'type' ] , } )
This method filters the web page content for link tags that match patterns given in the FILTER_MAPS
12,262
def _find_all_images ( self , soup , data , url ) : all_images = soup . find_all ( 'img' ) for image in all_images : item = normalize_image_data ( image , url ) data [ 'images' ] . append ( item )
This method finds all images in the web page content
12,263
def decode_mail_header ( value , default_charset = 'us-ascii' ) : try : headers = decode_header ( value ) except email . errors . HeaderParseError : return str_decode ( str_encode ( value , default_charset , 'replace' ) , default_charset ) else : for index , ( text , charset ) in enumerate ( headers ) : logger . debug ( "Mail header no. {index}: {data} encoding {charset}" . format ( index = index , data = str_decode ( text , charset or 'utf-8' , 'replace' ) , charset = charset ) ) try : headers [ index ] = str_decode ( text , charset or default_charset , 'replace' ) except LookupError : headers [ index ] = str_decode ( text , default_charset , 'replace' ) return '' . join ( headers )
Decode a header value into a unicode string .
12,264
def get_mail_addresses ( message , header_name ) : headers = [ h for h in message . get_all ( header_name , [ ] ) ] addresses = email . utils . getaddresses ( headers ) for index , ( address_name , address_email ) in enumerate ( addresses ) : addresses [ index ] = { 'name' : decode_mail_header ( address_name ) , 'email' : address_email } logger . debug ( "{} Mail address in message: <{}> {}" . format ( header_name . upper ( ) , address_name , address_email ) ) return addresses
Retrieve all email addresses from one message header .
12,265
def generate ( self , state ) : if self . count >= random . randint ( DharmaConst . VARIABLE_MIN , DharmaConst . VARIABLE_MAX ) : return "%s%d" % ( self . var , random . randint ( 1 , self . count ) ) var = random . choice ( self ) prefix = self . eval ( var [ 0 ] , state ) suffix = self . eval ( var [ 1 ] , state ) self . count += 1 element_name = "%s%d" % ( self . var , self . count ) self . default += "%s%s%s\n" % ( prefix , element_name , suffix ) return element_name
Return a random variable if any otherwise create a new default variable .
12,266
def process_settings ( self , settings ) : logging . debug ( "Using configuration from: %s" , settings . name ) exec ( compile ( settings . read ( ) , settings . name , 'exec' ) , globals ( ) , locals ( ) )
A lazy way of feeding Dharma with configuration settings .
12,267
def parse_xrefs ( self , token ) : out , end = [ ] , 0 token = token . replace ( "\\n" , "\n" ) for m in re . finditer ( self . xref_registry , token , re . VERBOSE | re . DOTALL ) : if m . start ( 0 ) > end : out . append ( String ( token [ end : m . start ( 0 ) ] , self . current_obj ) ) end = m . end ( 0 ) if m . group ( "type" ) : xref_type = { "+" : ValueXRef , "!" : VariableXRef , "@" : ElementXRef } [ m . group ( "type" ) ] out . append ( xref_type ( m . group ( "xref" ) , self . current_obj ) ) elif m . group ( "uri" ) is not None : path = m . group ( "uri" ) out . append ( MetaURI ( path , self . current_obj ) ) elif m . group ( "repeat" ) is not None : repeat , separator , nodups = m . group ( "repeat" , "separator" , "nodups" ) if separator is None : separator = "" if nodups is None : nodups = "" out . append ( MetaRepeat ( self . parse_xrefs ( repeat ) , separator , nodups , self . current_obj ) ) elif m . group ( "block" ) is not None : path = m . group ( "block" ) out . append ( MetaBlock ( path , self . current_obj ) ) elif m . group ( "choices" ) is not None : choices = m . group ( "choices" ) out . append ( MetaChoice ( choices , self . current_obj ) ) else : startval , endval = m . group ( "start" , "end" ) out . append ( MetaRange ( startval , endval , self . current_obj ) ) if end < len ( token ) : out . append ( String ( token [ end : ] , self . current_obj ) ) return out
Search token for + value + and !variable! style references . Be careful to not xref a new variable .
12,268
def calculate_leaf_paths ( self ) : reverse_xref = { } leaves = set ( ) for v in self . value . values ( ) : if v . leaf : leaves . add ( v ) for xref in v . value_xref : reverse_xref . setdefault ( xref , [ ] ) . append ( v . ident ) for leaf in leaves : self . calculate_leaf_path ( leaf , reverse_xref )
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves .
12,269
def generate_content ( self ) : if not self . variance : logging . error ( "%s: No variance information %s" , self . id ( ) , self . variance ) sys . exit ( - 1 ) for var in self . variable . values ( ) : var . clear ( ) variances = [ ] for _ in range ( random . randint ( DharmaConst . VARIANCE_MIN , DharmaConst . VARIANCE_MAX ) ) : var = random . choice ( list ( self . variance . values ( ) ) ) variances . append ( DharmaConst . VARIANCE_TEMPLATE % var . generate ( GenState ( ) ) ) variances . append ( "\n" ) variables = [ ] for var in self . variable . values ( ) : if var . default : variables . append ( DharmaConst . VARIANCE_TEMPLATE % var . default ) variables . append ( "\n" ) content = "" . join ( chain ( [ self . prefix ] , variables , variances , [ self . suffix ] ) ) if self . template : return Template ( self . template ) . safe_substitute ( testcase_content = content ) return content
Generates a test case as a string .
12,270
def process_grammars ( self , grammars ) : for path in self . default_grammars : grammars . insert ( 0 , open ( os . path . relpath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , os . path . normcase ( path ) ) ) ) ) for fo in grammars : logging . debug ( "Processing grammar content of %s" , fo . name ) self . set_namespace ( os . path . splitext ( os . path . basename ( fo . name ) ) [ 0 ] ) for line in fo : self . parse_line ( line ) self . handle_empty_line ( ) self . resolve_xref ( ) self . calculate_leaf_paths ( )
Process provided grammars by parsing them into Python objects .
12,271
def set_preferences ( request , dashboard_id ) : try : preferences = DashboardPreferences . objects . get ( user = request . user , dashboard_id = dashboard_id ) except DashboardPreferences . DoesNotExist : preferences = None if request . method == "POST" : form = DashboardPreferencesForm ( user = request . user , dashboard_id = dashboard_id , data = request . POST , instance = preferences ) if form . is_valid ( ) : preferences = form . save ( ) if request . is_ajax ( ) : return HttpResponse ( 'true' ) messages . success ( request , 'Preferences saved' ) elif request . is_ajax ( ) : return HttpResponse ( 'false' ) else : form = DashboardPreferencesForm ( user = request . user , dashboard_id = dashboard_id , instance = preferences ) return render_to_response ( 'admin_tools/dashboard/preferences_form.html' , { 'form' : form } )
This view serves and validates a preferences form .
12,272
def admin_tools_render_menu ( context , menu = None ) : if menu is None : menu = get_admin_menu ( context ) menu . init_with_context ( context ) has_bookmark_item = False bookmark = None if len ( [ c for c in menu . children if isinstance ( c , items . Bookmarks ) ] ) > 0 : has_bookmark_item = True url = context [ 'request' ] . get_full_path ( ) try : bookmark = Bookmark . objects . filter ( user = context [ 'request' ] . user , url = url ) [ 0 ] except : pass context . update ( { 'template' : menu . template , 'menu' : menu , 'has_bookmark_item' : has_bookmark_item , 'bookmark' : bookmark , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context ) ) , } ) return context
Template tag that renders the menu it takes an optional Menu instance as unique argument if not given the menu will be retrieved with the get_admin_menu function .
12,273
def admin_tools_render_menu_item ( context , item , index = None ) : item . init_with_context ( context ) context . update ( { 'template' : item . template , 'item' : item , 'index' : index , 'selected' : item . is_selected ( context [ 'request' ] ) , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context ) ) , } ) return context
Template tag that renders a given menu item it takes a MenuItem instance as unique parameter .
12,274
def admin_tools_render_menu_css ( context , menu = None ) : if menu is None : menu = get_admin_menu ( context ) context . update ( { 'template' : 'admin_tools/menu/css.html' , 'css_files' : menu . Media . css , } ) return context
Template tag that renders the menu css files it takes an optional Menu instance as unique argument if not given the menu will be retrieved with the get_admin_menu function .
12,275
def render_theming_css ( ) : css = getattr ( settings , 'ADMIN_TOOLS_THEMING_CSS' , False ) if not css : css = '/' . join ( [ 'admin_tools' , 'css' , 'theming.css' ] ) return mark_safe ( '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % staticfiles_storage . url ( css ) )
Template tag that renders the needed css files for the theming app .
12,276
def add_bookmark ( request ) : if request . method == "POST" : form = BookmarkForm ( user = request . user , data = request . POST ) if form . is_valid ( ) : bookmark = form . save ( ) if not request . is_ajax ( ) : messages . success ( request , 'Bookmark added' ) if request . POST . get ( 'next' ) : return HttpResponseRedirect ( request . POST . get ( 'next' ) ) return HttpResponse ( 'Added' ) return render_to_response ( 'admin_tools/menu/remove_bookmark_form.html' , { 'bookmark' : bookmark , 'url' : bookmark . url } ) else : form = BookmarkForm ( user = request . user ) return render_to_response ( 'admin_tools/menu/form.html' , { 'form' : form , 'title' : 'Add Bookmark' } )
This view serves and validates a bookmark form . If requested via ajax it also returns the drop bookmark form to replace the add bookmark form .
12,277
def remove_bookmark ( request , id ) : bookmark = get_object_or_404 ( Bookmark , id = id , user = request . user ) if request . method == "POST" : bookmark . delete ( ) if not request . is_ajax ( ) : messages . success ( request , 'Bookmark removed' ) if request . POST . get ( 'next' ) : return HttpResponseRedirect ( request . POST . get ( 'next' ) ) return HttpResponse ( 'Deleted' ) return render_to_response ( 'admin_tools/menu/add_bookmark_form.html' , { 'url' : request . POST . get ( 'next' ) , 'title' : '**title**' } ) return render_to_response ( 'admin_tools/menu/delete_confirm.html' , { 'bookmark' : bookmark , 'title' : 'Delete Bookmark' } )
This view deletes a bookmark . If requested via ajax it also returns the add bookmark form to replace the drop bookmark form .
12,278
def autodiscover ( blacklist = [ ] ) : import imp from django . conf import settings try : from importlib import import_module except ImportError : from django . utils . importlib import import_module blacklist . append ( 'admin_tools.dashboard' ) blacklist . append ( 'admin_tools.menu' ) blacklist . append ( 'admin_tools.theming' ) for app in settings . INSTALLED_APPS : if app in blacklist : continue try : app_path = import_module ( app ) . __path__ except AttributeError : continue try : imp . find_module ( 'dashboard' , app_path ) except ImportError : continue import_module ( '%s.dashboard' % app )
Automagically discover custom dashboards and menus for installed apps . Optionally you can pass a blacklist of apps that you don t want to provide their own app index dashboard .
12,279
def render_css_classes ( self ) : ret = [ 'dashboard-module' ] if not self . enabled : ret . append ( 'disabled' ) if self . draggable : ret . append ( 'draggable' ) if self . collapsible : ret . append ( 'collapsible' ) if self . deletable : ret . append ( 'deletable' ) ret += self . css_classes return ' ' . join ( ret )
Return a string containing the css classes for the module .
12,280
def is_empty ( self ) : if super ( Group , self ) . is_empty ( ) : return True for child in self . children : if not child . is_empty ( ) : return False return True
A group of modules is considered empty if it has no children or if all its children are empty .
12,281
def get_app_index_dashboard ( context ) : app = context [ 'app_list' ] [ 0 ] model_list = [ ] app_label = None app_title = app [ 'name' ] admin_site = get_admin_site ( context = context ) for model , model_admin in admin_site . _registry . items ( ) : if app [ 'app_label' ] == model . _meta . app_label : split = model . __module__ . find ( model . _meta . app_label ) app_label = model . __module__ [ 0 : split ] + model . _meta . app_label for m in app [ 'models' ] : if m [ 'name' ] == capfirst ( model . _meta . verbose_name_plural ) : mod = '%s.%s' % ( model . __module__ , model . __name__ ) model_list . append ( mod ) if app_label is not None and app_label in Registry . registry : return Registry . registry [ app_label ] ( app_title , model_list ) return _get_dashboard_cls ( getattr ( settings , 'ADMIN_TOOLS_APP_INDEX_DASHBOARD' , 'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard' ) , context ) ( app_title , model_list )
Returns the admin dashboard defined by the user or the default one .
12,282
def get_app_model_classes ( self ) : models = [ ] for m in self . models : mod , cls = m . rsplit ( '.' , 1 ) mod = import_module ( mod ) models . append ( getattr ( mod , cls ) ) return models
Helper method that returns a list of model classes for the current app .
12,283
def get_app_content_types ( self ) : from django . contrib . contenttypes . models import ContentType return [ ContentType . objects . get_for_model ( c ) for c in self . get_app_model_classes ( ) ]
Return a list of all content_types for this app .
12,284
def admin_tools_render_dashboard_module ( context , module ) : module . init_with_context ( context ) context . update ( { 'template' : module . template , 'module' : module , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context ) ) , } ) return context
Template tag that renders a given dashboard module it takes a DashboardModule instance as first parameter .
12,285
def is_selected ( self , request ) : current_url = request . get_full_path ( ) return self . url == current_url or len ( [ c for c in self . children if c . is_selected ( request ) ] ) > 0
Helper method that returns True if the menu item is active . A menu item is considered as active if it s URL or one of its descendants URL is equals to the current URL .
12,286
def uniquify ( value , seen_values ) : id = 1 new_value = value while new_value in seen_values : new_value = "%s%s" % ( value , id ) id += 1 seen_values . add ( new_value ) return new_value
Adds value to seen_values set and ensures it is unique
12,287
def default_create_thread ( callback ) : thread = threading . Thread ( None , callback ) thread . daemon = True thread . start ( ) return thread
Default thread creation - used to create threads when the client doesn t want to provide their own thread creation .
12,288
def parse_headers ( lines , offset = 0 ) : headers = { } for header_line in lines [ offset : ] : header_match = HEADER_LINE_RE . match ( header_line ) if header_match : key = header_match . group ( 'key' ) key = re . sub ( r'\\.' , _unescape_header , key ) if key not in headers : value = header_match . group ( 'value' ) value = re . sub ( r'\\.' , _unescape_header , value ) headers [ key ] = value return headers
Parse the headers in a STOMP response
12,289
def parse_frame ( frame ) : f = Frame ( ) if frame == b'\x0a' : f . cmd = 'heartbeat' return f mat = PREAMBLE_END_RE . search ( frame ) if mat : preamble_end = mat . start ( ) body_start = mat . end ( ) else : preamble_end = len ( frame ) body_start = preamble_end preamble = decode ( frame [ 0 : preamble_end ] ) preamble_lines = LINE_END_RE . split ( preamble ) preamble_len = len ( preamble_lines ) f . body = frame [ body_start : ] first_line = 0 while first_line < preamble_len and len ( preamble_lines [ first_line ] ) == 0 : first_line += 1 if first_line >= preamble_len : return None f . cmd = preamble_lines [ first_line ] f . headers = parse_headers ( preamble_lines , first_line + 1 ) return f
Parse a STOMP frame into a Frame object .
12,290
def merge_headers ( header_map_list ) : headers = { } for header_map in header_map_list : if header_map : headers . update ( header_map ) return headers
Helper function for combining multiple header maps into one .
12,291
def calculate_heartbeats ( shb , chb ) : ( sx , sy ) = shb ( cx , cy ) = chb x = 0 y = 0 if cx != 0 and sy != '0' : x = max ( cx , int ( sy ) ) if cy != 0 and sx != '0' : y = max ( cy , int ( sx ) ) return x , y
Given a heartbeat string from the server and a heartbeat tuple from the client calculate what the actual heartbeat settings should be .
12,292
def convert_frame ( frame , body_encoding = None ) : lines = [ ] body = None if frame . body : if body_encoding : body = encode ( frame . body , body_encoding ) else : body = encode ( frame . body ) if HDR_CONTENT_LENGTH in frame . headers : frame . headers [ HDR_CONTENT_LENGTH ] = len ( body ) if frame . cmd : lines . append ( encode ( frame . cmd ) ) lines . append ( ENC_NEWLINE ) for key , vals in sorted ( frame . headers . items ( ) ) : if vals is None : continue if type ( vals ) != tuple : vals = ( vals , ) for val in vals : lines . append ( encode ( "%s:%s\n" % ( key , val ) ) ) lines . append ( ENC_NEWLINE ) if body : lines . append ( body ) if frame . cmd : lines . append ( ENC_NULL ) return lines
Convert a frame to a list of lines separated by newlines .
12,293
def on_send ( self , frame ) : if frame . cmd == CMD_CONNECT or frame . cmd == CMD_STOMP : if self . heartbeats != ( 0 , 0 ) : frame . headers [ HDR_HEARTBEAT ] = '%s,%s' % self . heartbeats if self . next_outbound_heartbeat is not None : self . next_outbound_heartbeat = monotonic ( ) + self . send_sleep
Add the heartbeat header to the frame when connecting and bump next outbound heartbeat timestamp .
12,294
def on_receipt ( self , headers , body ) : if 'receipt-id' in headers and headers [ 'receipt-id' ] == self . receipt : with self . receipt_condition : self . received = True self . receipt_condition . notify ( )
If the receipt id can be found in the headers then notify the waiting thread .
12,295
def wait_on_receipt ( self ) : with self . receipt_condition : while not self . received : self . receipt_condition . wait ( ) self . received = False
Wait until we receive a message receipt .
12,296
def send_frame ( self , cmd , headers = None , body = '' ) : frame = utils . Frame ( cmd , headers , body ) self . transport . transmit ( frame )
Encode and send a stomp frame through the underlying transport .
12,297
def abort ( self , transaction , headers = None , ** keyword_headers ) : assert transaction is not None , "'transaction' is required" headers = utils . merge_headers ( [ headers , keyword_headers ] ) headers [ HDR_TRANSACTION ] = transaction self . send_frame ( CMD_ABORT , headers )
Abort a transaction .
12,298
def ack ( self , id , transaction = None , receipt = None ) : assert id is not None , "'id' is required" headers = { HDR_MESSAGE_ID : id } if transaction : headers [ HDR_TRANSACTION ] = transaction if receipt : headers [ HDR_RECEIPT ] = receipt self . send_frame ( CMD_ACK , headers )
Acknowledge consumption of a message by id .
12,299
def commit ( self , transaction = None , headers = None , ** keyword_headers ) : assert transaction is not None , "'transaction' is required" headers = utils . merge_headers ( [ headers , keyword_headers ] ) headers [ HDR_TRANSACTION ] = transaction self . send_frame ( CMD_COMMIT , headers )
Commit a transaction .