idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
18,900
def read_lengths_file ( name ) : chrom_to_length = { } f = file ( name , "rt" ) for line in f : line = line . strip ( ) if line == '' or line [ 0 ] == '#' : continue try : fields = line . split ( ) if len ( fields ) != 2 : raise chrom = fields [ 0 ] length = int ( fields [ 1 ] ) except : raise ValueError ( "bad length ...
Returns a hash from sequence name to length .
18,901
def IntervalReader ( f ) : current_chrom = None current_pos = None current_step = None strand = '+' mode = "bed" for line in f : if line . isspace ( ) or line . startswith ( "track" ) or line . startswith ( "#" ) or line . startswith ( "browser" ) : continue elif line . startswith ( "variableStep" ) : header = parse_he...
Iterator yielding chrom start end strand value . Values are zero - based half - open . Regions which lack a score are ignored .
18,902
def fuse_list ( mafs ) : last = None for m in mafs : if last is None : last = m else : fused = fuse ( last , m ) if fused : last = fused else : yield last last = m if last : yield last
Try to fuse a list of blocks by progressively fusing each adjacent pair .
18,903
def setBreak ( self , breakFlag = True ) : if breakFlag : _parseMethod = self . _parse def breaker ( instring , loc , doActions = True , callPreParse = True ) : import pdb pdb . set_trace ( ) _parseMethod ( instring , loc , doActions , callPreParse ) breaker . _originalParseMethod = _parseMethod self . _parse = breaker...
Method to invoke the Python pdb debugger when this element is about to be parsed . Set breakFlag to True to enable False to disable .
18,904
def searchString ( self , instring , maxMatches = _MAX_INT ) : return ParseResults ( [ t for t , s , e in self . scanString ( instring , maxMatches ) ] )
Another extension to scanString simplifying the access to the tokens found to match the given parse expression . May be called with optional maxMatches argument to clip searching after n matches are found .
18,905
def _strfactory ( cls , line ) : assert type ( line ) == str , "this is a factory from string" line = line . rstrip ( ) . split ( ) [ 1 : ] tup = [ t [ 0 ] ( t [ 1 ] ) for t in zip ( [ int , str , int , str , int , int , str , int , str , int , int , str ] , line ) ] return tuple . __new__ ( cls , tup )
factory class method for Chain
18,906
def bedInterval ( self , who ) : "return a BED6 entry, thus DOES coordinate conversion for minus strands" if who == 't' : st , en = self . tStart , self . tEnd if self . tStrand == '-' : st , en = self . tSize - en , self . tSize - st return ( self . tName , st , en , self . id , self . score , self . tStrand ) else : ...
return a BED6 entry thus DOES coordinate conversion for minus strands
18,907
def _strfactory ( cls , line ) : cmp = line . rstrip ( ) . split ( ) chrom = cmp [ 2 ] if not chrom . startswith ( "chr" ) : chrom = "chr%s" % chrom instance = tuple . __new__ ( cls , ( cmp [ 0 ] , cmp [ 1 ] , chrom , int ( cmp [ 3 ] ) , int ( cmp [ 4 ] ) , { '1' : '+' , '-1' : '-' } [ cmp [ 5 ] ] , cmp [ 6 ] ) ) span ...
factory method for an EPOitem
18,908
def binned_bitsets_proximity ( f , chrom_col = 0 , start_col = 1 , end_col = 2 , strand_col = 5 , upstream = 0 , downstream = 0 ) : last_chrom = None last_bitset = None bitsets = dict ( ) for line in f : if line . startswith ( "#" ) : continue fields = line . split ( ) strand = "+" if len ( fields ) >= strand_col + 1 :...
Read a file into a dictionary of bitsets
18,909
def binned_bitsets_from_list ( list = [ ] ) : last_chrom = None last_bitset = None bitsets = dict ( ) for l in list : chrom = l [ 0 ] if chrom != last_chrom : if chrom not in bitsets : bitsets [ chrom ] = BinnedBitSet ( MAX ) last_chrom = chrom last_bitset = bitsets [ chrom ] start , end = int ( l [ 1 ] ) , int ( l [ 2...
Read a list into a dictionary of bitsets
18,910
def binned_bitsets_by_chrom ( f , chrom , chrom_col = 0 , start_col = 1 , end_col = 2 ) : bitset = BinnedBitSet ( MAX ) for line in f : if line . startswith ( "#" ) : continue fields = line . split ( ) if fields [ chrom_col ] == chrom : start , end = int ( fields [ start_col ] ) , int ( fields [ end_col ] ) bitset . se...
Read a file by chrom name into a bitset
18,911
def _double_as_bytes ( dval ) : "Use struct.unpack to decode a double precision float into eight bytes" tmp = list ( struct . unpack ( '8B' , struct . pack ( 'd' , dval ) ) ) if not _big_endian : tmp . reverse ( ) return tmp
Use struct . unpack to decode a double precision float into eight bytes
18,912
def _mantissa ( dval ) : bb = _double_as_bytes ( dval ) mantissa = bb [ 1 ] & 0x0f << 48 mantissa += bb [ 2 ] << 40 mantissa += bb [ 3 ] << 32 mantissa += bb [ 4 ] return mantissa
Extract the _mantissa bits from a double - precision floating point value .
18,913
def _zero_mantissa ( dval ) : bb = _double_as_bytes ( dval ) return ( ( bb [ 1 ] & 0x0f ) | reduce ( operator . or_ , bb [ 2 : ] ) ) == 0
Determine whether the mantissa bits of the given double are all zero .
18,914
def load_scores_wiggle ( fname ) : scores_by_chrom = dict ( ) for chrom , pos , val in bx . wiggle . Reader ( misc . open_compressed ( fname ) ) : if chrom not in scores_by_chrom : scores_by_chrom [ chrom ] = BinnedArray ( ) scores_by_chrom [ chrom ] [ pos ] = val return scores_by_chrom
Read a wiggle file and return a dict of BinnedArray objects keyed by chromosome .
18,915
def new ( self , min , max ) : assert MIN <= min <= max <= MAX self . min = min self . max = max self . offsets = offsets_for_max_size ( max ) self . bin_count = bin_for_range ( max - 1 , max , offsets = self . offsets ) + 1 self . bins = [ [ ] for i in range ( self . bin_count ) ]
Create an empty index for intervals in the range min max
18,916
def seek ( self , offset , whence = 0 ) : if whence == 0 : target_pos = offset elif whence == 1 : target_pos = self . file_pos + offset elif whence == 2 : target_pos = self . size - offset else : raise Exception ( "Invalid `whence` argument: %r" , whence ) if target_pos == self . file_pos : return assert 0 <= target_po...
Move the file pointer to a particular offset .
18,917
def mtime ( self , key ) : if key not in self . __dict : raise CacheKeyError ( key ) else : node = self . __dict [ key ] return node . mtime
Return the last modification time for the cache record with key . May be useful for cache instances where the stored values can get stale such as caching file or network resource contents .
18,918
def class_space ( classlevel = 3 ) : "returns the calling class' name and dictionary" frame = sys . _getframe ( classlevel ) classname = frame . f_code . co_name classdict = frame . f_locals return classname , classdict
returns the calling class name and dictionary
18,919
def build_alignment ( self , score , pieces ) : self . open_seqs ( ) text1 = text2 = "" end1 = end2 = None for ( start1 , start2 , length , pctId ) in pieces : if ( end1 != None ) : if ( start1 == end1 ) : text1 += self . seq1_gap * ( start2 - end2 ) text2 += self . seq2_file . get ( end2 , start2 - end2 ) else : text1...
converts a score and pieces to an alignment
18,920
def bits_clear_in_range ( bits , range_start , range_end ) : end = range_start while 1 : start = bits . next_clear ( end ) if start >= range_end : break end = min ( bits . next_set ( start ) , range_end ) yield start , end
Yield start end tuples for each span of clear bits in [ range_start range_end )
18,921
def iterprogress ( sized_iterable ) : pb = ProgressBar ( 0 , len ( sized_iterable ) ) for i , value in enumerate ( sized_iterable ) : yield value pb . update_and_print ( i , sys . stderr )
Iterate something printing progress bar to stdout
18,922
def to_file ( Class , dict , file , is_little_endian = True ) : io = BinaryFileWriter ( file , is_little_endian = is_little_endian ) start_offset = io . tell ( ) io . seek ( start_offset + ( 8 * 256 ) ) subtables = [ [ ] for i in range ( 256 ) ] for key , value in dict . items ( ) : pair_offset = io . tell ( ) io . wri...
For constructing a CDB structure in a file . Able to calculate size on disk and write to a file
18,923
def read_len ( f ) : mapping = dict ( ) for line in f : fields = line . split ( ) mapping [ fields [ 0 ] ] = int ( fields [ 1 ] ) return mapping
Read a LEN file and return a mapping from chromosome to length
18,924
def eps_logo ( matrix , base_width , height , colors = DNA_DEFAULT_COLORS ) : alphabet = matrix . sorted_alphabet rval = StringIO ( ) header = Template ( pkg_resources . resource_string ( __name__ , "template.ps" ) ) rval . write ( header . substitute ( bounding_box_width = ceil ( base_width * matrix . width ) + PAD , ...
Return an EPS document containing a sequence logo for matrix where each bases is shown as a column of base_width points and the total logo height is height points . If colors is provided it is a mapping from characters to rgb color strings .
18,925
def transform ( elem , chain_CT_CQ , max_gap ) : ( chain , CT , CQ ) = chain_CT_CQ start , end = max ( elem [ 'start' ] , chain . tStart ) - chain . tStart , min ( elem [ 'end' ] , chain . tEnd ) - chain . tStart assert np . all ( ( CT [ : , 1 ] - CT [ : , 0 ] ) == ( CQ [ : , 1 ] - CQ [ : , 0 ] ) ) to_chrom = chain . q...
transform the coordinates of this elem into the other species .
18,926
def loadChains ( path ) : "name says it." EPO = epo . Chain . _parse_file ( path , True ) for i in range ( len ( EPO ) ) : ch , S , T , Q = EPO [ i ] if ch . tStrand == '-' : ch = ch . _replace ( tEnd = ch . tSize - ch . tStart , tStart = ch . tSize - ch . tEnd ) if ch . qStrand == '-' : ch = ch . _replace ( qEnd = ch ...
name says it .
18,927
def loadFeatures ( path , opt ) : log . info ( "loading from %s ..." % path ) data = [ ] if opt . in_format == "BED" : with open ( path ) as fd : for line in fd : cols = line . split ( ) data . append ( ( cols [ 0 ] , int ( cols [ 1 ] ) , int ( cols [ 2 ] ) , cols [ 3 ] ) ) data = np . array ( data , dtype = elem_t ) e...
Load features . For BED only BED4 columns are loaded . For narrowPeak all columns are loaded .
18,928
def add ( self , chrom , element ) : self . _trees . setdefault ( chrom , IntervalTree ( ) ) . insert_interval ( element )
insert an element . use this method as the IntervalTree one . this will simply call the IntervalTree . add method on the right tree
18,929
def find ( self , chrom , start , end ) : tree = self . _trees . get ( chrom , None ) if tree : return tree . find ( start , end ) return [ ]
find the intersecting elements
18,930
def create_from_other ( Class , other , values = None ) : m = Class ( ) m . alphabet = other . alphabet m . sorted_alphabet = other . sorted_alphabet m . char_to_index = other . char_to_index if values is not None : m . values = values else : m . values = other . values return m
Create a new Matrix with attributes taken from other but with the values taken from values if provided
18,931
def to_logodds_scoring_matrix ( self , background = None , correction = DEFAULT_CORRECTION ) : alphabet_size = len ( self . alphabet ) if background is None : background = ones ( alphabet_size , float32 ) / alphabet_size totals = numpy . sum ( self . values , 1 ) [ : , newaxis ] values = log2 ( maximum ( self . values ...
Create a standard logodds scoring matrix .
18,932
def score_string ( self , string ) : rval = zeros ( len ( string ) , float32 ) rval [ : ] = nan _pwm . score_string ( self . values , self . char_to_index , string , rval ) return rval
Score each valid position in string using this scoring matrix . Positions which were not scored are set to nan .
18,933
def _calc_resp ( password_hash , server_challenge ) : password_hash += b'\x00' * ( 21 - len ( password_hash ) ) res = b'' dobj = DES ( DES . key56_to_key64 ( password_hash [ 0 : 7 ] ) ) res = res + dobj . encrypt ( server_challenge [ 0 : 8 ] ) dobj = DES ( DES . key56_to_key64 ( password_hash [ 7 : 14 ] ) ) res = res +...
Generate the LM response given a 16 - byte password hash and the challenge from the CHALLENGE_MESSAGE
18,934
def encrypt ( self , data , pad = True ) : encrypted_data = b"" for i in range ( 0 , len ( data ) , 8 ) : block = data [ i : i + 8 ] block_length = len ( block ) if block_length != 8 and pad : block += b"\x00" * ( 8 - block_length ) elif block_length != 8 : raise ValueError ( "DES encryption must be a multiple of 8 " "...
DES encrypts the data based on the key it was initialised with .
18,935
def decrypt ( self , data ) : decrypted_data = b"" for i in range ( 0 , len ( data ) , 8 ) : block = data [ i : i + 8 ] block_length = len ( block ) if block_length != 8 : raise ValueError ( "DES decryption must be a multiple of 8 " "bytes" ) decrypted_data += self . _decode_block ( block ) return decrypted_data
DES decrypts the data based on the key it was initialised with .
18,936
def key56_to_key64 ( key ) : if len ( key ) != 7 : raise ValueError ( "DES 7-byte key is not 7 bytes in length, " "actual: %d" % len ( key ) ) new_key = b"" for i in range ( 0 , 8 ) : if i == 0 : new_value = struct . unpack ( "B" , key [ i : i + 1 ] ) [ 0 ] elif i == 7 : new_value = struct . unpack ( "B" , key [ 6 : 7 ...
This takes in an a bytes string of 7 bytes and converts it to a bytes string of 8 bytes with the odd parity bit being set to every 8 bits
18,937
def visit_Method ( self , method ) : resolved_method = method . resolved . type def get_params ( method , extra_bindings ) : result = [ ] for param in method . params : resolved_param = texpr ( param . resolved . type , param . resolved . bindings , extra_bindings ) result . append ( resolved_param . id ) return result...
Ensure method has the same signature matching method on parent interface .
18,938
def get_doc ( node ) : res = " " . join ( get_doc_annotations ( node ) ) if not res : res = "(%s)" % node . __class__ . __name__ . lower ( ) return res
Return a node s documentation as a string pulling from annotations or constructing a simple fake as needed .
18,939
def get_code ( node , coder = Coder ( ) ) : return cgi . escape ( str ( coder . code ( node ) ) , quote = True )
Return a node s code
18,940
def setup_environ ( self ) : SimpleHandler . setup_environ ( self ) self . environ [ 'ws4py.socket' ] = get_connection ( self . environ [ 'wsgi.input' ] ) self . http_version = self . environ [ 'SERVER_PROTOCOL' ] . rsplit ( '/' ) [ - 1 ]
Setup the environ dictionary and add the ws4py . socket key . Its associated value is the real socket underlying socket .
18,941
def handle ( self ) : self . raw_requestline = self . rfile . readline ( ) if not self . parse_request ( ) : return handler = self . WebSocketWSGIHandler ( self . rfile , self . wfile , self . get_stderr ( ) , self . get_environ ( ) ) handler . request_handler = self handler . run ( self . server . get_app ( ) )
Unfortunately the base class forces us to override the whole method to actually provide our wsgi handler .
18,942
def configure ( self , voltage_range = RANGE_32V , gain = GAIN_AUTO , bus_adc = ADC_12BIT , shunt_adc = ADC_12BIT ) : self . __validate_voltage_range ( voltage_range ) self . _voltage_range = voltage_range if self . _max_expected_amps is not None : if gain == self . GAIN_AUTO : self . _auto_gain_enabled = True self . _...
Configures and calibrates how the INA219 will take measurements .
18,943
def wake ( self ) : configuration = self . _read_configuration ( ) self . _configuration_register ( configuration | 0x0007 ) time . sleep ( 0.00004 )
Wake the INA219 from power down mode
18,944
def _return_response_and_status_code ( response , json_results = True ) : if response . status_code == requests . codes . ok : return dict ( results = response . json ( ) if json_results else response . content , response_code = response . status_code ) elif response . status_code == 400 : return dict ( error = 'packag...
Output the requests response content or content as json and status code
18,945
def put_comments ( self , resource , comment , timeout = None ) : params = { 'apikey' : self . api_key , 'resource' : resource , 'comment' : comment } try : response = requests . post ( self . base + 'comments/put' , params = params , proxies = self . proxies , timeout = timeout ) except requests . RequestException as ...
Post a comment on a file or URL .
18,946
def get_ip_report ( self , this_ip , timeout = None ) : params = { 'apikey' : self . api_key , 'ip' : this_ip } try : response = requests . get ( self . base + 'ip-address/report' , params = params , proxies = self . proxies , timeout = timeout ) except requests . RequestException as e : return dict ( error = str ( e )...
Get IP address reports .
18,947
def get_domain_report ( self , this_domain , timeout = None ) : params = { 'apikey' : self . api_key , 'domain' : this_domain } try : response = requests . get ( self . base + 'domain/report' , params = params , proxies = self . proxies , timeout = timeout ) except requests . RequestException as e : return dict ( error...
Get information about a given domain .
18,948
def get_upload_url ( self , timeout = None ) : params = { 'apikey' : self . api_key } try : response = requests . get ( self . base + 'file/scan/upload_url' , params = params , proxies = self . proxies , timeout = timeout ) if response . status_code == requests . codes . ok : return response . json ( ) . get ( 'upload_...
Get a special URL for submitted files bigger than 32MB .
18,949
def file_search ( self , query , offset = None , timeout = None ) : params = dict ( apikey = self . api_key , query = query , offset = offset ) try : response = requests . get ( self . base + 'file/search' , params = params , proxies = self . proxies , timeout = timeout ) except requests . RequestException as e : retur...
Search for samples .
18,950
def get_file_clusters ( self , this_date , timeout = None ) : params = { 'apikey' : self . api_key , 'date' : this_date } try : response = requests . get ( self . base + 'file/clusters' , params = params , proxies = self . proxies , timeout = timeout ) except requests . RequestException as e : return dict ( error = str...
File similarity clusters for a given time frame .
18,951
def get_url_distribution ( self , after = None , reports = 'true' , limit = 1000 , timeout = None ) : params = { 'apikey' : self . api_key , 'after' : after , 'reports' : reports , 'limit' : limit } try : response = requests . get ( self . base + 'url/distribution' , params = params , proxies = self . proxies , timeout...
Get a live feed with the lastest URLs submitted to VirusTotal .
18,952
def get_url_feed ( self , package = None , timeout = None ) : if package is None : now = datetime . utcnow ( ) five_minutes_ago = now - timedelta ( minutes = now . minute % 5 + 5 , seconds = now . second , microseconds = now . microsecond ) package = five_minutes_ago . strftime ( '%Y%m%dT%H%M' ) params = { 'apikey' : s...
Get a live file feed with the latest files submitted to VirusTotal .
18,953
def get_intel_notifications_feed ( self , page = None , timeout = None ) : params = { 'apikey' : self . api_key , 'next' : page } try : response = requests . get ( self . base + 'hunting/notifications-feed/' , params = params , proxies = self . proxies , timeout = timeout ) if len ( response . content ) == 0 : response...
Get notification feed in JSON for further processing .
18,954
def delete_intel_notifications ( self , ids , timeout = None ) : if not isinstance ( ids , list ) : raise TypeError ( "ids must be a list" ) data = json . dumps ( ids ) try : response = requests . post ( self . base + 'hunting/delete-notifications/programmatic/?key=' + self . api_key , data = data , proxies = self . pr...
Programmatically delete notifications via the Intel API .
18,955
def get_credentials ( self ) : return Credentials ( access_key = self . aws_access_key_id , secret_key = self . aws_secret_access_key , token = self . aws_session_token )
Returns botocore . credential . Credential object .
18,956
def form_valid ( self , form ) : form_valid_from_parent = super ( HostCreate , self ) . form_valid ( form ) messages . success ( self . request , 'Host {} Successfully Created' . format ( self . object ) ) return form_valid_from_parent
First call the parent s form valid then let the user know it worked .
18,957
def post ( self , * args , ** kwargs ) : existing_ssh = models . SSHConfig . objects . all ( ) if existing_ssh . exists ( ) : return self . get_view ( ) remote_user = self . request . POST . get ( 'remote_user' , 'root' ) create_ssh_config ( remote_user = remote_user ) return self . get_view ( )
Create the SSH file & then return the normal get method ...
18,958
def update_sandbox_site ( comment_text ) : file_to_deliver = NamedTemporaryFile ( delete = False ) file_text = "Deployed at: {} <br /> Comment: {}" . format ( datetime . datetime . now ( ) . strftime ( '%c' ) , cgi . escape ( comment_text ) ) file_to_deliver . write ( file_text ) file_to_deliver . close ( ) put ( file_...
put s a text file on the server
18,959
def web_hooks ( self , include_global = True ) : from fabric_bolt . web_hooks . models import Hook ors = [ Q ( project = self ) ] if include_global : ors . append ( Q ( project = None ) ) hooks = Hook . objects . filter ( reduce ( operator . or_ , ors ) ) return hooks
Get all web hooks for this project . Includes global hooks .
18,960
def get_deployment_count ( self ) : ret = self . stage_set . annotate ( num_deployments = Count ( 'deployment' ) ) . aggregate ( total_deployments = Sum ( 'num_deployments' ) ) return ret [ 'total_deployments' ]
Utility function to get the number of deployments a given project has
18,961
def get_configurations ( self ) : project_configurations_dictionary = { } project_configurations = self . project . project_configurations ( ) for config in project_configurations : project_configurations_dictionary [ config . key ] = config stage_configurations_dictionary = { } stage_configurations = self . stage_conf...
Generates a dictionary that s made up of the configurations on the project . Any configurations on a project that are duplicated on a stage the stage configuration will take precedence .
18,962
def get_absolute_url ( self ) : if self . stage : url = reverse ( 'projects_stage_view' , args = ( self . project . pk , self . stage . pk ) ) else : url = self . project . get_absolute_url ( ) return url
Determine where I am coming from and where I am going
18,963
def gravatar ( self , size = 20 ) : default = "mm" gravatar_url = "//www.gravatar.com/avatar/" + hashlib . md5 ( self . email . lower ( ) ) . hexdigest ( ) + "?" gravatar_url += urllib . urlencode ( { 'd' : default , 's' : str ( size ) } ) return gravatar_url
Construct a gravatar image address for the user
18,964
def hooks ( self , project ) : return self . get_queryset ( ) . filter ( Q ( project = None ) | Q ( project = project ) ) . distinct ( 'url' )
Look up the urls we need to post to
18,965
def web_hook_receiver ( sender , ** kwargs ) : deployment = Deployment . objects . get ( pk = kwargs . get ( 'deployment_id' ) ) hooks = deployment . web_hooks if not hooks : return for hook in hooks : data = payload_generator ( deployment ) deliver_hook ( deployment , hook . url , data )
Generic receiver for the web hook firing piece .
18,966
def paginate ( self , klass = Paginator , per_page = None , page = 1 , * args , ** kwargs ) : self . per_page_options = [ 25 , 50 , 100 , 200 ] self . per_page = per_page = per_page or self . _meta . per_page self . paginator = klass ( self . rows , per_page , * args , ** kwargs ) self . page = self . paginator . page ...
Paginates the table using a paginator and creates a page property containing information for the current page .
18,967
def get_fabric_tasks ( self , project ) : cache_key = 'project_{}_fabfile_tasks' . format ( project . pk ) cached_result = cache . get ( cache_key ) if cached_result : return cached_result try : fabfile_path , activate_loc = self . get_fabfile_path ( project ) if activate_loc : output = self . check_output ( 'source {}...
Generate a list of fabric tasks that are available
18,968
def get_initial ( self ) : initial = super ( ProjectCopy , self ) . get_initial ( ) if self . copy_object : initial . update ( { 'name' : '%s copy' % self . copy_object . name , 'description' : self . copy_object . description , 'use_repo_fabfile' : self . copy_object . use_repo_fabfile , 'fabfile_requirements' : self ...
Returns the initial data to use for forms on this view .
18,969
def get_success_url ( self ) : if self . stage_id : url = reverse ( 'projects_stage_view' , args = ( self . project_id , self . stage_id ) ) else : url = reverse ( 'projects_project_view' , args = ( self . project_id , ) ) return url
Get the url depending on what type of configuration I deleted .
18,970
def create_ssh_config ( remote_user = 'root' , name = 'Auto Generated SSH Key' , file_name = 'fabricbolt_private.key' , email = 'deployments@fabricbolt.io' , public_key_text = None , private_key_text = None ) : if not private_key_text and not public_key_text : key = RSA . generate ( 2048 ) pubkey = key . publickey ( ) ...
Create SSH Key
18,971
def convert ( self , json = "" , table_attributes = 'border="1"' , clubbing = True , encode = False , escape = True ) : self . table_init_markup = "<table %s>" % table_attributes self . clubbing = clubbing self . escape = escape json_input = None if not json : json_input = { } elif type ( json ) in text_types : try : j...
Convert JSON to HTML Table format
18,972
def column_headers_from_list_of_dicts ( self , json_input ) : if not json_input or not hasattr ( json_input , '__getitem__' ) or not hasattr ( json_input [ 0 ] , 'keys' ) : return None column_headers = json_input [ 0 ] . keys ( ) for entry in json_input : if not hasattr ( entry , 'keys' ) or not hasattr ( entry , '__it...
This method is required to implement clubbing . It tries to come up with column headers for your input
18,973
def convert_list ( self , list_input ) : if not list_input : return "" converted_output = "" column_headers = None if self . clubbing : column_headers = self . column_headers_from_list_of_dicts ( list_input ) if column_headers is not None : converted_output += self . table_init_markup converted_output += '<thead>' conv...
Iterate over the JSON list and process it to generate either an HTML table or a HTML list depending on what s inside . If suppose some key has array of objects and all the keys are same instead of creating a new row for each such entry club such values thus it makes more sense and more readable table .
18,974
def convert_object ( self , json_input ) : if not json_input : return "" converted_output = self . table_init_markup + "<tr>" converted_output += "</tr><tr>" . join ( [ "<th>%s</th><td>%s</td>" % ( self . convert_json_node ( k ) , self . convert_json_node ( v ) ) for k , v in json_input . items ( ) ] ) converted_output...
Iterate over the JSON object and process it to generate the super awesome HTML Table format
18,975
def personsAtHome ( self , home = None ) : if not home : home = self . default_home home_data = self . homeByName ( home ) atHome = [ ] for p in home_data [ 'persons' ] : if 'pseudo' in p : if not p [ "out_of_sight" ] : atHome . append ( p [ 'pseudo' ] ) return atHome
Return the list of known persons who are currently at home
18,976
def getProfileImage ( self , name ) : for p in self . persons : if 'pseudo' in self . persons [ p ] : if name == self . persons [ p ] [ 'pseudo' ] : image_id = self . persons [ p ] [ 'face' ] [ 'id' ] key = self . persons [ p ] [ 'face' ] [ 'key' ] return self . getCameraPicture ( image_id , key ) return None , None
Retrieve the face of a given person
18,977
def updateEvent ( self , event = None , home = None ) : if not home : home = self . default_home if not event : listEvent = dict ( ) for cam_id in self . lastEvent : listEvent [ self . lastEvent [ cam_id ] [ 'time' ] ] = self . lastEvent [ cam_id ] event = listEvent [ sorted ( listEvent ) [ 0 ] ] home_data = self . hom...
Update the list of event with the latest ones
18,978
def personSeenByCamera ( self , name , home = None , camera = None ) : try : cam_id = self . cameraByName ( camera = camera , home = home ) [ 'id' ] except TypeError : logger . warning ( "personSeenByCamera: Camera name or home is unknown" ) return False if self . lastEvent [ cam_id ] [ 'type' ] == 'person' : person_id...
Return True if a specific person has been seen by a camera
18,979
def someoneKnownSeen ( self , home = None , camera = None ) : try : cam_id = self . cameraByName ( camera = camera , home = home ) [ 'id' ] except TypeError : logger . warning ( "personSeenByCamera: Camera name or home is unknown" ) return False if self . lastEvent [ cam_id ] [ 'type' ] == 'person' : if self . lastEven...
Return True if someone known has been seen
18,980
def motionDetected ( self , home = None , camera = None ) : try : cam_id = self . cameraByName ( camera = camera , home = home ) [ 'id' ] except TypeError : logger . warning ( "personSeenByCamera: Camera name or home is unknown" ) return False if self . lastEvent [ cam_id ] [ 'type' ] == 'movement' : return True return...
Return True if movement has been detected
18,981
def batch ( sequence , callback , size = 100 , ** kwargs ) : batch_len , rem = divmod ( len ( sequence ) , size ) if rem > 0 : batch_len += 1 for i in range ( batch_len ) : offset = i * size yield callback ( sequence [ offset : offset + size ] , ** kwargs )
Helper to setup batch requests .
18,982
def _handle_retry ( self , resp ) : exc_t , exc_v , exc_tb = sys . exc_info ( ) if exc_t is None : raise TypeError ( 'Must be called in except block.' ) retry_on_exc = tuple ( ( x for x in self . _retry_on if inspect . isclass ( x ) ) ) retry_on_codes = tuple ( ( x for x in self . _retry_on if isinstance ( x , int ) ) ...
Handle any exceptions during API request or parsing its response status code .
18,983
def notification_redirect ( request , ctx ) : if request . is_ajax ( ) : return JsonResponse ( ctx ) else : next_page = request . POST . get ( 'next' , reverse ( 'notifications:all' ) ) if not ctx [ 'success' ] : return HttpResponseBadRequest ( ctx [ 'msg' ] ) if is_safe_url ( next_page ) : return HttpResponseRedirect ...
Helper to handle HTTP response after an action is performed on notification
18,984
def mark ( request ) : notification_id = request . POST . get ( 'id' , None ) action = request . POST . get ( 'action' , None ) success = True if notification_id : try : notification = Notification . objects . get ( pk = notification_id , recipient = request . user ) if action == 'read' : notification . mark_as_read ( ...
Handles marking of individual notifications as read or unread . Takes notification id and mark action as POST data .
18,985
def mark_all ( request ) : action = request . POST . get ( 'action' , None ) success = True if action == 'read' : request . user . notifications . read_all ( ) msg = _ ( "Marked all notifications as read" ) elif action == 'unread' : request . user . notifications . unread_all ( ) msg = _ ( "Marked all notifications as ...
Marks notifications as either read or unread depending of POST parameters . Takes action as POST data it can either be read or unread .
18,986
def delete ( request ) : notification_id = request . POST . get ( 'id' , None ) success = True if notification_id : try : notification = Notification . objects . get ( pk = notification_id , recipient = request . user ) soft_delete = getattr ( settings , 'NOTIFY_SOFT_DELETE' , True ) if soft_delete : notification . del...
Deletes notification of supplied notification ID .
18,987
def notification_update ( request ) : flag = request . GET . get ( 'flag' , None ) target = request . GET . get ( 'target' , 'box' ) last_notification = int ( flag ) if flag . isdigit ( ) else None if last_notification : new_notifications = request . user . notifications . filter ( id__gt = last_notification ) . active...
Handles live updating of notifications follows ajax - polling approach .
18,988
def read_and_redirect ( request , notification_id ) : notification_page = reverse ( 'notifications:all' ) next_page = request . GET . get ( 'next' , notification_page ) if is_safe_url ( next_page ) : target = next_page else : target = notification_page try : user_nf = request . user . notifications . get ( pk = notific...
Marks the supplied notification as read and then redirects to the supplied URL from the next URL parameter .
18,989
def get_motion_detection ( self ) : url = ( '%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection' ) % self . root_url try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) except ( requests . exceptions . RequestException , requests . exceptions . ConnectionError ) as err : _LOGGING . err...
Fetch current motion state from camera
18,990
def _set_motion_detection ( self , enable ) : url = ( '%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection' ) % self . root_url enabled = self . _motion_detection_xml . find ( self . element_query ( 'enabled' ) ) if enabled is None : _LOGGING . error ( "Couldn't find 'enabled' in the xml" ) _LOGGING . error ( 'X...
Set desired motion detection state on camera
18,991
def add_update_callback ( self , callback , sensor ) : self . _updateCallbacks . append ( [ callback , sensor ] ) _LOGGING . debug ( 'Added update callback to %s on %s' , callback , sensor )
Register as callback for when a matching device sensor changes .
18,992
def initialize ( self ) : device_info = self . get_device_info ( ) if device_info is None : self . name = None self . cam_id = None self . event_states = None return for key in device_info : if key == 'deviceName' : self . name = device_info [ key ] elif key == 'deviceID' : if len ( device_info [ key ] ) > 10 : self . ...
Initialize deviceInfo and available events .
18,993
def get_event_triggers ( self ) : events = { } nvrflag = False event_xml = [ ] url = '%s/ISAPI/Event/triggers' % self . root_url try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) if response . status_code == requests . codes . not_found : _LOGGING . debug ( 'Using alternate triggers URL.' ) ...
Returns dict of supported events . Key = Event Type List = Channels that have that event activated
18,994
def get_device_info ( self ) : device_info = { } url = '%s/ISAPI/System/deviceInfo' % self . root_url using_digest = False try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) if response . status_code == requests . codes . unauthorized : _LOGGING . debug ( 'Basic authentication failed. Using d...
Parse deviceInfo into dictionary .
18,995
def watchdog_handler ( self ) : _LOGGING . debug ( '%s Watchdog expired. Resetting connection.' , self . name ) self . watchdog . stop ( ) self . reset_thrd . set ( )
Take care of threads if wachdog expires .
18,996
def disconnect ( self ) : _LOGGING . debug ( 'Disconnecting from stream: %s' , self . name ) self . kill_thrd . set ( ) self . thrd . join ( ) _LOGGING . debug ( 'Event stream thread for %s is stopped' , self . name ) self . kill_thrd . clear ( )
Disconnect from event stream .
18,997
def alert_stream ( self , reset_event , kill_event ) : _LOGGING . debug ( 'Stream Thread Started: %s, %s' , self . name , self . cam_id ) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self . root_url while True : try : stream = self . hik_request . get ( url , st...
Open event stream .
18,998
def process_stream ( self , tree ) : try : etype = SENSOR_MAP [ tree . find ( self . element_query ( 'eventType' ) ) . text . lower ( ) ] estate = tree . find ( self . element_query ( 'eventState' ) ) . text echid = tree . find ( self . element_query ( 'channelID' ) ) if echid is None : echid = tree . find ( self . ele...
Process incoming event stream packets .
18,999
def update_stale ( self ) : for etype , echannels in self . event_states . items ( ) : for eprop in echannels : if eprop [ 3 ] is not None : sec_elap = ( ( datetime . datetime . now ( ) - eprop [ 3 ] ) . total_seconds ( ) ) if sec_elap > 5 and eprop [ 0 ] is True : _LOGGING . debug ( 'Updating stale event %s on CH(%s)'...
Update stale active statuses