idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
62,500
def move_entry ( self , entry = None , group = None ) : if entry is None or group is None or type ( entry ) is not v1Entry or type ( group ) is not v1Group : raise KPError ( "Need an entry and a group." ) elif entry not in self . entries : raise KPError ( "No entry found." ) elif group in self . groups : entry . group ...
Move an entry to another group .
62,501
def move_entry_in_group ( self , entry = None , index = None ) : if entry is None or index is None or type ( entry ) is not v1Entry or type ( index ) is not int : raise KPError ( "Need an entry and an index." ) elif index < 0 or index > len ( entry . group . entries ) - 1 : raise KPError ( "Index is not valid." ) elif ...
Move entry to another position inside a group .
62,502
def _transform_key ( self , masterkey ) : aes = AES . new ( self . _transf_randomseed , AES . MODE_ECB ) for _ in range ( self . _key_transf_rounds ) : masterkey = aes . encrypt ( masterkey ) sha_obj = SHA256 . new ( ) sha_obj . update ( masterkey ) masterkey = sha_obj . digest ( ) sha_obj = SHA256 . new ( ) sha_obj . ...
This method creates the key to decrypt the database
62,503
def _get_filekey ( self ) : if not os . path . exists ( self . keyfile ) : raise KPError ( 'Keyfile not exists.' ) try : with open ( self . keyfile , 'rb' ) as handler : handler . seek ( 0 , os . SEEK_END ) size = handler . tell ( ) handler . seek ( 0 , os . SEEK_SET ) if size == 32 : return handler . read ( 32 ) elif ...
This method creates a key from a keyfile .
62,504
def _cbc_decrypt ( self , final_key , crypted_content ) : aes = AES . new ( final_key , AES . MODE_CBC , self . _enc_iv ) decrypted_content = aes . decrypt ( crypted_content ) padding = decrypted_content [ - 1 ] if sys . version > '3' : padding = decrypted_content [ - 1 ] else : padding = ord ( decrypted_content [ - 1 ...
This method decrypts the database
62,505
def _cbc_encrypt ( self , content , final_key ) : aes = AES . new ( final_key , AES . MODE_CBC , self . _enc_iv ) padding = ( 16 - len ( content ) % AES . block_size ) for _ in range ( padding ) : content += chr ( padding ) . encode ( ) temp = bytes ( content ) return aes . encrypt ( temp )
This method encrypts the content .
62,506
def _read_group_field ( self , group , levels , field_type , field_size , decrypted_content ) : if field_type == 0x0000 : pass elif field_type == 0x0001 : group . id_ = struct . unpack ( '<I' , decrypted_content [ : 4 ] ) [ 0 ] elif field_type == 0x0002 : try : group . title = struct . unpack ( '<{0}s' . format ( field...
This method handles the different fields of a group
62,507
def _read_entry_field ( self , entry , field_type , field_size , decrypted_content ) : if field_type == 0x0000 : pass elif field_type == 0x0001 : entry . uuid = decrypted_content [ : 16 ] elif field_type == 0x0002 : entry . group_id = struct . unpack ( '<I' , decrypted_content [ : 4 ] ) [ 0 ] elif field_type == 0x0003 ...
This method handles the different fields of an entry
62,508
def _get_date ( self , decrypted_content ) : date_field = struct . unpack ( '<5B' , decrypted_content [ : 5 ] ) dw1 = date_field [ 0 ] dw2 = date_field [ 1 ] dw3 = date_field [ 2 ] dw4 = date_field [ 3 ] dw5 = date_field [ 4 ] y = ( dw1 << 6 ) | ( dw2 >> 2 ) mon = ( ( dw2 & 0x03 ) << 2 ) | ( dw3 >> 6 ) d = ( dw3 >> 1 )...
This method is used to decode the packed dates of entries
62,509
def _pack_date ( self , date ) : y , mon , d , h , min_ , s = date . timetuple ( ) [ : 6 ] dw1 = 0x0000FFFF & ( ( y >> 6 ) & 0x0000003F ) dw2 = 0x0000FFFF & ( ( y & 0x0000003F ) << 2 | ( ( mon >> 2 ) & 0x00000003 ) ) dw3 = 0x0000FFFF & ( ( ( mon & 0x0000003 ) << 6 ) | ( ( d & 0x0000001F ) << 1 ) | ( ( h >> 4 ) & 0x0000...
This method is used to encode dates
62,510
def _create_group_tree ( self , levels ) : if levels [ 0 ] != 0 : raise KPError ( "Invalid group tree" ) for i in range ( len ( self . groups ) ) : if ( levels [ i ] == 0 ) : self . groups [ i ] . parent = self . root_group self . groups [ i ] . index = len ( self . root_group . children ) self . root_group . children ...
This method creates a group tree
62,511
def _save_group_field ( self , field_type , group ) : if field_type == 0x0000 : pass elif field_type == 0x0001 : if group . id_ is not None : return ( 4 , struct . pack ( '<I' , group . id_ ) ) elif field_type == 0x0002 : if group . title is not None : return ( len ( group . title . encode ( ) ) + 1 , ( group . title +...
This method packs a group field
62,512
def _save_entry_field ( self , field_type , entry ) : if field_type == 0x0000 : pass elif field_type == 0x0001 : if entry . uuid is not None : return ( 16 , entry . uuid ) elif field_type == 0x0002 : if entry . group_id is not None : return ( 4 , struct . pack ( '<I' , entry . group_id ) ) elif field_type == 0x0003 : i...
This group packs a entry field
62,513
def getsecret ( self , section , option , ** kwargs ) : raw = kwargs . get ( 'raw' , False ) value = self . get ( section , option , ** kwargs ) if raw : return value return self . custodia_client . get_secret ( value )
Get a secret from Custodia
62,514
def _load_plugin_class ( menu , name ) : group = 'custodia.{}' . format ( menu ) eps = list ( pkg_resources . iter_entry_points ( group , name ) ) if len ( eps ) > 1 : raise ValueError ( "Multiple entry points for {} {}: {}" . format ( menu , name , eps ) ) elif len ( eps ) == 1 : ep = eps [ 0 ] if hasattr ( ep , 'reso...
Load Custodia plugin
62,515
def _load_plugins ( config , cfgparser ) : os . umask ( config [ 'umask' ] ) for s in cfgparser . sections ( ) : if s in { 'ENV' , 'global' } : continue if s . startswith ( '/' ) : menu = 'consumers' path_chain = s . split ( '/' ) if path_chain [ - 1 ] == '' : path_chain = path_chain [ : - 1 ] name = tuple ( path_chain...
Load and initialize plugins
62,516
def get ( self , po ) : name = po . name typ = po . typ default = po . default handler = getattr ( self , '_get_{}' . format ( typ ) , None ) if handler is None : raise ValueError ( typ ) self . seen . add ( name ) if not self . parser . has_option ( self . section , name ) : if default is REQUIRED : raise NameError ( ...
Lookup value for a PluginOption instance
62,517
def parse ( self , msg , name ) : if msg is None : return if not isinstance ( msg , string_types ) : raise InvalidMessage ( "The 'value' attribute is not a string" ) self . name = name self . payload = msg self . msg_type = 'simple'
Parses a simple message
62,518
def krb5_unparse_principal_name ( name ) : prefix , realm = name . split ( u'@' ) if u'/' in prefix : service , host = prefix . rsplit ( u'/' , 1 ) return service , host , realm else : return None , prefix , realm
Split a Kerberos principal name into parts
62,519
def parse ( self , msg , name ) : try : jtok = JWT ( jwt = msg ) except Exception as e : raise InvalidMessage ( 'Failed to parse message: %s' % str ( e ) ) try : token = jtok . token if isinstance ( token , JWE ) : token . decrypt ( self . kkstore . server_keys [ KEY_USAGE_ENC ] ) payload = token . payload . decode ( '...
Parses the message .
62,520
def instance_name ( string ) : invalid = ':/@' if set ( string ) . intersection ( invalid ) : msg = 'Invalid instance name {}' . format ( string ) raise argparse . ArgumentTypeError ( msg ) return string
Check for valid instance name
62,521
def copy_magic_into_pyc ( input_pyc , output_pyc , src_version , dest_version ) : ( version , timestamp , magic_int , co , is_pypy , source_size ) = load_module ( input_pyc ) assert version == float ( src_version ) , ( "Need Python %s bytecode; got bytecode for version %s" % ( src_version , version ) ) magic_int = magi...
Bytecodes are the same except the magic number so just change that
62,522
def transform_26_27 ( inst , new_inst , i , n , offset , instructions , new_asm ) : if inst . opname in ( 'JUMP_IF_FALSE' , 'JUMP_IF_TRUE' ) : i += 1 assert i < n assert instructions [ i ] . opname == 'POP_TOP' new_inst . offset = offset new_inst . opname = ( 'POP_JUMP_IF_FALSE' if inst . opname == 'JUMP_IF_FALSE' else...
Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
62,523
def transform_32_33 ( inst , new_inst , i , n , offset , instructions , new_asm ) : add_size = xdis . op_size ( new_inst . opcode , opcode_33 ) if inst . opname in ( 'MAKE_FUNCTION' , 'MAKE_CLOSURE' ) : prev_inst = instructions [ i - 1 ] assert prev_inst . opname == 'LOAD_CONST' assert isinstance ( prev_inst . arg , in...
MAKEFUNCTION adds another const . probably MAKECLASS as well
62,524
def transform_33_32 ( inst , new_inst , i , n , offset , instructions , new_asm ) : add_size = xdis . op_size ( new_inst . opcode , opcode_33 ) if inst . opname in ( 'MAKE_FUNCTION' , 'MAKE_CLOSURE' ) : prev_inst = instructions [ i - 1 ] assert prev_inst . opname == 'LOAD_CONST' assert isinstance ( prev_inst . arg , in...
MAKE_FUNCTION and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not in Python 3 . 2 . Remove these .
62,525
def main ( conversion_type , input_pyc , output_pyc ) : shortname = osp . basename ( input_pyc ) if shortname . endswith ( '.pyc' ) : shortname = shortname [ : - 4 ] src_version = conversion_to_version ( conversion_type , is_dest = False ) dest_version = conversion_to_version ( conversion_type , is_dest = True ) if out...
Convert Python bytecode from one version to another .
62,526
def generate ( self , str = None , fpath = None ) : self . prepare_storage ( ) self . str = self . load_file ( fpath ) if fpath else self . sanitize ( str ) self . validate_config ( ) self . generate_kgrams ( ) self . hash_kgrams ( ) self . generate_fingerprints ( ) return self . fingerprints
generates fingerprints of the input . Either provide str to compute fingerprint directly from your string or fpath to compute fingerprint from the text of the file . Make sure to have your text decoded in utf - 8 format if you pass the input string .
62,527
def main ( pyc_file , asm_path ) : if os . stat ( asm_path ) . st_size == 0 : print ( "Size of assembly file %s is zero" % asm_path ) sys . exit ( 1 ) asm = asm_file ( asm_path ) if not pyc_file and asm_path . endswith ( '.pyasm' ) : pyc_file = asm_path [ : - len ( '.pyasm' ) ] + '.pyc' write_pycfile ( pyc_file , asm )
Create Python bytecode from a Python assembly file .
62,528
def expire ( self , secs ) : self . add_field ( 'exp' , lambda req : int ( time . time ( ) + secs ) )
Adds the standard exp field used to prevent replay attacks .
62,529
def _generate ( self , request ) : payload = { } for field , gen in self . _generators . items ( ) : value = None if callable ( gen ) : value = gen ( request ) else : value = gen if value : payload [ field ] = value return payload
Generate a payload for the given request .
62,530
def url2fs ( url ) : uri , extension = posixpath . splitext ( url ) return safe64 . dir ( uri ) + extension
encode a URL to be safe as a filename
62,531
def is_merc_projection ( srs ) : if srs . lower ( ) == '+init=epsg:900913' : return True srs = dict ( [ p . split ( '=' ) for p in srs . split ( ) if '=' in p ] ) gym = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null' gym = dict ( [ p . split ( '=' ) for p in gym...
Return true if the map projection matches that used by VEarth Google OSM etc . Is currently necessary for zoom - level shorthand for scale - denominator .
62,532
def extract_declarations ( map_el , dirs , scale = 1 , user_styles = [ ] ) : styles = [ ] for stylesheet in map_el . findall ( 'Stylesheet' ) : map_el . remove ( stylesheet ) content , mss_href = fetch_embedded_or_remote_src ( stylesheet , dirs ) if content : styles . append ( ( content , mss_href ) ) for stylesheet in...
Given a Map element and directories object remove and return a complete list of style declarations from any Stylesheet elements found within .
62,533
def is_applicable_selector ( selector , filter ) : for test in selector . allTests ( ) : if not test . isCompatible ( filter . tests ) : return False return True
Given a Selector and Filter return True if the Selector is compatible with the given Filter and False if they contradict .
62,534
def get_polygon_rules ( declarations ) : property_map = { 'polygon-fill' : 'fill' , 'polygon-opacity' : 'fill-opacity' , 'polygon-gamma' : 'gamma' , 'polygon-meta-output' : 'meta-output' , 'polygon-meta-writer' : 'meta-writer' } property_names = property_map . keys ( ) rules = [ ] for ( filter , values ) in filtered_pr...
Given a Map element a Layer element and a list of declarations create a new Style element with a PolygonSymbolizer add it to Map and refer to it in Layer .
62,535
def get_raster_rules ( declarations ) : property_map = { 'raster-opacity' : 'opacity' , 'raster-mode' : 'mode' , 'raster-scaling' : 'scaling' } property_names = property_map . keys ( ) rules = [ ] for ( filter , values ) in filtered_property_declarations ( declarations , property_names ) : sym_params = { } for prop , a...
Given a Map element a Layer element and a list of declarations create a new Style element with a RasterSymbolizer add it to Map and refer to it in Layer . The RasterSymbolizer will always created even if there are no applicable declarations .
62,536
def locally_cache_remote_file ( href , dir ) : scheme , host , remote_path , params , query , fragment = urlparse ( href ) assert scheme in ( 'http' , 'https' ) , 'Scheme must be either http or https, not "%s" (for %s)' % ( scheme , href ) head , ext = posixpath . splitext ( posixpath . basename ( remote_path ) ) head ...
Locally cache a remote resource using a predictable file name and awareness of modification date . Assume that files are normal which is to say they have filenames with extensions .
62,537
def post_process_symbolizer_image_file ( file_href , dirs ) : mapnik_auto_image_support = ( MAPNIK_VERSION >= 701 ) mapnik_requires_absolute_paths = ( MAPNIK_VERSION < 601 ) file_href = urljoin ( dirs . source . rstrip ( '/' ) + '/' , file_href ) scheme , n , path , p , q , f = urlparse ( file_href ) if scheme in ( 'ht...
Given an image file href and a set of directories modify the image file name so it s correct with respect to the output and cache directories .
62,538
def localize_shapefile ( shp_href , dirs ) : mapnik_requires_absolute_paths = ( MAPNIK_VERSION < 601 ) shp_href = urljoin ( dirs . source . rstrip ( '/' ) + '/' , shp_href ) scheme , host , path , p , q , f = urlparse ( shp_href ) if scheme in ( 'http' , 'https' ) : msg ( '%s | %s' % ( shp_href , dirs . cache ) ) schem...
Given a shapefile href and a set of directories modify the shapefile name so it s correct with respect to the output and cache directories .
62,539
def localize_file_datasource ( file_href , dirs ) : mapnik_requires_absolute_paths = ( MAPNIK_VERSION < 601 ) file_href = urljoin ( dirs . source . rstrip ( '/' ) + '/' , file_href ) scheme , n , path , p , q , f = urlparse ( file_href ) if scheme in ( 'http' , 'https' ) : scheme , path = '' , locally_cache_remote_file...
Handle localizing file - based datasources other than shapefiles . This will only work for single - file based types .
62,540
def midpoint ( self ) : minpoint = self . leftedge if self . leftop is gt : minpoint += 1 maxpoint = self . rightedge if self . rightop is lt : maxpoint -= 1 if minpoint is None : return maxpoint elif maxpoint is None : return minpoint else : return ( minpoint + maxpoint ) / 2
Return a point guranteed to fall within this range hopefully near the middle .
62,541
def isOpen ( self ) : if self . leftedge and self . rightedge and self . leftedge > self . rightedge : return False if self . leftedge == self . rightedge : if self . leftop is gt or self . rightop is lt : return False return True
Return true if this range has any room in it .
62,542
def toFilter ( self , property ) : if self . leftedge == self . rightedge and self . leftop is ge and self . rightop is le : return Filter ( style . SelectorAttributeTest ( property , '=' , self . leftedge ) ) try : return Filter ( style . SelectorAttributeTest ( property , opstr [ self . leftop ] , self . leftedge ) ,...
Convert this range to a Filter with a tests having a given property .
62,543
def isOpen ( self ) : equals = { } nequals = { } for test in self . tests : if test . op == '=' : if equals . has_key ( test . property ) and test . value != equals [ test . property ] : return False if nequals . has_key ( test . property ) and test . value in nequals [ test . property ] : return False equals [ test . ...
Return true if this filter is not trivially false i . e . self - contradictory .
62,544
def minusExtras ( self ) : assert self . isOpen ( ) trimmed = self . clone ( ) equals = { } for test in trimmed . tests : if test . op == '=' : equals [ test . property ] = test . value extras = [ ] for ( i , test ) in enumerate ( trimmed . tests ) : if test . op == '!=' and equals . has_key ( test . property ) and equ...
Return a new Filter that s equal to this one without extra terms that don t add meaning .
62,545
def add_preference ( hdf5_file , preference ) : Worker . hdf5_lock . acquire ( ) with tables . open_file ( hdf5_file , 'r+' ) as fileh : S = fileh . root . aff_prop_group . similarities diag_ind = np . diag_indices ( S . nrows ) S [ diag_ind ] = preference Worker . hdf5_lock . release ( )
Assign the value preference to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at hdf5_file .
62,546
def add_fluctuations ( hdf5_file , N_columns , N_processes ) : random_state = np . random . RandomState ( 0 ) slice_queue = multiprocessing . JoinableQueue ( ) pid_list = [ ] for i in range ( N_processes ) : worker = Fluctuations_worker ( hdf5_file , '/aff_prop_group/similarities' , random_state , N_columns , slice_que...
This procedure organizes the addition of small fluctuations on top of a matrix of similarities at hdf5_file across N_processes different processes . Each of those processes is an instance of the class Fluctuations_Worker defined elsewhere in this module .
62,547
def compute_responsibilities ( hdf5_file , N_columns , damping , N_processes ) : slice_queue = multiprocessing . JoinableQueue ( ) pid_list = [ ] for i in range ( N_processes ) : worker = Responsibilities_worker ( hdf5_file , '/aff_prop_group' , N_columns , damping , slice_queue ) worker . daemon = True worker . start ...
Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with damping as the eponymous damping parameter . Each of the processes concurrently involved in this task is an instance of the class Responsibilities_worker defined above .
62,548
def to_numpy_array ( multiprocessing_array , shape , dtype ) : return np . frombuffer ( multiprocessing_array . get_obj ( ) , dtype = dtype ) . reshape ( shape )
Convert a share multiprocessing array to a numpy array . No data copying involved .
62,549
def compute_rows_sum ( hdf5_file , path , N_columns , N_processes , method = 'Process' ) : assert isinstance ( method , str ) , "parameter 'method' must consist in a string of characters" assert method in ( 'Ordinary' , 'Pool' ) , "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary...
Parallel computation of the sums across the rows of two - dimensional array accessible at the node specified by path in the hdf5_file hierarchical data format .
62,550
def check_convergence ( hdf5_file , iteration , convergence_iter , max_iter ) : Worker . hdf5_lock . acquire ( ) with tables . open_file ( hdf5_file , 'r+' ) as fileh : A = fileh . root . aff_prop_group . availabilities R = fileh . root . aff_prop_group . responsibilities P = fileh . root . aff_prop_group . parallel_up...
If the estimated number of clusters has not changed for convergence_iter consecutive iterations in a total of max_iter rounds of message - passing the procedure herewith returns True . Otherwise returns False . Parameter iteration identifies the run of message - passing that has just completed .
62,551
def cluster_labels_A ( hdf5_file , c , lock , I , rows_slice ) : with Worker . hdf5_lock : with tables . open_file ( hdf5_file , 'r+' ) as fileh : S = fileh . root . aff_prop_group . similarities s = S [ rows_slice , ... ] s = np . argmax ( s [ : , I ] , axis = 1 ) with lock : c [ rows_slice ] = s [ : ] del s
One of the task to be performed by a pool of subprocesses as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering .
62,552
def cluster_labels_B ( hdf5_file , s_reduced , lock , I , ii , iix , rows_slice ) : with Worker . hdf5_lock : with tables . open_file ( hdf5_file , 'r+' ) as fileh : S = fileh . root . aff_prop_group . similarities s = S [ rows_slice , ... ] s = s [ : , ii ] s = s [ iix [ rows_slice ] ] with lock : s_reduced += s [ : ]...
Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified .
62,553
def output_clusters ( labels , cluster_centers_indices ) : here = os . getcwd ( ) try : output_directory = os . path . join ( here , 'concurrent_AP_output' ) os . makedirs ( output_directory ) except OSError : if not os . path . isdir ( output_directory ) : print ( "ERROR: concurrent_AP: output_clusters: cannot create ...
Write in tab - separated files the vectors of cluster identities and of indices of cluster centers .
62,554
def get_coin_snapshot ( fsym , tsym ) : url = build_url ( 'coinsnapshot' , fsym = fsym , tsym = tsym ) data = load_data ( url ) [ 'Data' ] return data
Get blockchain information aggregated data as well as data for the individual exchanges available for the specified currency pair .
62,555
def matches ( self , tag , id , classes ) : element = self . elements [ 0 ] unmatched_ids = [ name [ 1 : ] for name in element . names if name . startswith ( '#' ) ] unmatched_classes = [ name [ 1 : ] for name in element . names if name . startswith ( '.' ) ] unmatched_tags = [ name for name in element . names if name ...
Given an id and a list of classes return True if this selector would match .
62,556
def scaledBy ( self , scale ) : scaled = deepcopy ( self ) for test in scaled . elements [ 0 ] . tests : if type ( test . value ) in ( int , float ) : if test . property == 'scale-denominator' : test . value /= scale elif test . property == 'zoom' : test . value += log ( scale ) / log ( 2 ) return scaled
Return a new Selector with scale denominators scaled by a number .
62,557
def scaledBy ( self , scale ) : scaled = deepcopy ( self ) if type ( scaled . value ) in ( int , float ) : scaled . value *= scale elif isinstance ( scaled . value , numbers ) : scaled . value . values = tuple ( v * scale for v in scaled . value . values ) return scaled
Return a new Value scaled by a given number for ints and floats .
62,558
def get_mining_contracts ( ) : url = build_url ( 'miningcontracts' ) data = load_data ( url ) coin_data = data [ 'CoinData' ] mining_data = data [ 'MiningData' ] return coin_data , mining_data
Get all the mining contracts information available .
62,559
def get_mining_equipment ( ) : url = build_url ( 'miningequipment' ) data = load_data ( url ) coin_data = data [ 'CoinData' ] mining_data = data [ 'MiningData' ] return coin_data , mining_data
Get all the mining equipment information available .
62,560
def main ( src_file , dest_file , ** kwargs ) : mmap = mapnik . Map ( 1 , 1 ) mmap . srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null' load_kwargs = dict ( [ ( k , v ) for ( k , v ) in kwargs . items ( ) if k in ( 'cache_dir' , 'scale' , 'verbose' , 'datasou...
Given an input layers file and a directory print the compiled XML file to stdout and save any encountered external image files to the named directory .
62,561
def chunk ( url ) : chunks = lambda l , n : [ l [ x : x + n ] for x in xrange ( 0 , len ( l ) , n ) ] url_64 = base64 . urlsafe_b64encode ( url ) return chunks ( url_64 , 255 )
create filesystem - safe places for url - keyed data to be stored
62,562
def main ( filename ) : input = open ( filename , 'r' ) . read ( ) declarations = cascadenik . stylesheet_declarations ( input , is_merc = True ) for dec in declarations : print dec . selector , print '{' , print dec . property . name + ':' , if cascadenik . style . properties [ dec . property . name ] in ( cascadenik ...
Given an input file containing nothing but styles print out an unrolled list of declarations in cascade order .
62,563
def validate_gps ( value ) : try : latitude , longitude , altitude = value . split ( ',' ) vol . Coerce ( float ) ( latitude ) vol . Coerce ( float ) ( longitude ) vol . Coerce ( float ) ( altitude ) except ( TypeError , ValueError , vol . Invalid ) : raise vol . Invalid ( 'GPS value should be of format "latitude,longi...
Validate GPS value .
62,564
def _connect ( self ) : while self . protocol : _LOGGER . info ( 'Trying to connect to %s' , self . server_address ) try : sock = socket . create_connection ( self . server_address , self . reconnect_timeout ) except socket . timeout : _LOGGER . error ( 'Connecting to socket timed out for %s' , self . server_address ) ...
Connect to socket . This should be run in a new thread .
62,565
def _connect ( self ) : try : while True : _LOGGER . info ( 'Trying to connect to %s' , self . server_address ) try : yield from asyncio . wait_for ( self . loop . create_connection ( lambda : self . protocol , * self . server_address ) , self . reconnect_timeout , loop = self . loop ) self . tcp_check_timer = time . t...
Connect to the socket .
62,566
def run ( self ) : self . protocol = self . protocol_factory ( ) try : self . protocol . connection_made ( self ) except Exception as exc : self . alive = False self . protocol . connection_lost ( exc ) self . _connection_made . set ( ) return error = None self . _connection_made . set ( ) while self . alive : data = N...
Transport thread loop .
62,567
def register ( self , name ) : def decorator ( func ) : self [ name ] = func return func return decorator
Return decorator to register item with a specific name .
62,568
def _handle_subscription ( self , topics ) : if not isinstance ( topics , list ) : topics = [ topics ] for topic in topics : topic_levels = topic . split ( '/' ) try : qos = int ( topic_levels [ - 2 ] ) except ValueError : qos = 0 try : _LOGGER . debug ( 'Subscribing to: %s, qos: %s' , topic , qos ) self . _sub_callbac...
Handle subscription of topics .
62,569
def _init_topics ( self ) : _LOGGER . info ( 'Setting up initial MQTT topic subscription' ) init_topics = [ '{}/+/+/0/+/+' . format ( self . _in_prefix ) , '{}/+/+/3/+/+' . format ( self . _in_prefix ) , ] self . _handle_subscription ( init_topics ) if not self . persistence : return topics = [ '{}/{}/{}/{}/+/+' . form...
Set up initial subscription of mysensors topics .
62,570
def _parse_mqtt_to_message ( self , topic , payload , qos ) : topic_levels = topic . split ( '/' ) topic_levels = not_prefix = topic_levels [ - 5 : ] prefix_end_idx = topic . find ( '/' . join ( not_prefix ) ) - 1 prefix = topic [ : prefix_end_idx ] if prefix != self . _in_prefix : return None if qos and qos > 0 : ack ...
Parse a MQTT topic and payload .
62,571
def _parse_message_to_mqtt ( self , data ) : msg = Message ( data , self ) payload = str ( msg . payload ) msg . payload = '' return ( '{}/{}' . format ( self . _out_prefix , msg . encode ( '/' ) ) [ : - 2 ] , payload , msg . ack )
Parse a mysensors command string .
62,572
def _handle_presentation ( self , msg ) : ret_msg = handle_presentation ( msg ) if msg . child_id == 255 or ret_msg is None : return topics = [ '{}/{}/{}/{}/+/+' . format ( self . _in_prefix , str ( msg . node_id ) , str ( msg . child_id ) , msg_type ) for msg_type in ( int ( self . const . MessageType . set ) , int ( ...
Process a MQTT presentation message .
62,573
def recv ( self , topic , payload , qos ) : data = self . _parse_mqtt_to_message ( topic , payload , qos ) if data is None : return _LOGGER . debug ( 'Receiving %s' , data ) self . add_job ( self . logic , data )
Receive a MQTT message .
62,574
def send ( self , message ) : if not message : return topic , payload , qos = self . _parse_message_to_mqtt ( message ) try : _LOGGER . debug ( 'Publishing %s' , message . strip ( ) ) self . _pub_callback ( topic , payload , qos , self . _retain ) except Exception as exception : _LOGGER . exception ( 'Publish to %s fai...
Publish a command string to the gateway via MQTT .
62,575
def contribute_to_class ( self , cls , name , virtual_only = False ) : super ( RegexField , self ) . contribute_to_class ( cls , name , virtual_only ) setattr ( cls , name , CastOnAssignDescriptor ( self ) )
Cast to the correct value every
62,576
def run_validators ( self , value ) : value = self . to_python ( value ) value = self . value_to_string ( value ) return super ( RegexField , self ) . run_validators ( value )
Make sure value is a string so it can run through django validators
62,577
def validate_hex ( value ) : try : binascii . unhexlify ( value ) except Exception : raise vol . Invalid ( '{} is not of hex format' . format ( value ) ) return value
Validate that value has hex format .
62,578
def validate_v_rgb ( value ) : if len ( value ) != 6 : raise vol . Invalid ( '{} is not six characters long' . format ( value ) ) return validate_hex ( value )
Validate a V_RGB value .
62,579
def validate_v_rgbw ( value ) : if len ( value ) != 8 : raise vol . Invalid ( '{} is not eight characters long' . format ( value ) ) return validate_hex ( value )
Validate a V_RGBW value .
62,580
def copy ( self , ** kwargs ) : msg = Message ( self . encode ( ) , self . gateway ) for key , val in kwargs . items ( ) : setattr ( msg , key , val ) return msg
Copy a message optionally replace attributes with kwargs .
62,581
def modify ( self , ** kwargs ) : for key , val in kwargs . items ( ) : setattr ( self , key , val ) return self
Modify and return message replace attributes with kwargs .
62,582
def decode ( self , data , delimiter = ';' ) : try : list_data = data . rstrip ( ) . split ( delimiter ) self . payload = list_data . pop ( ) ( self . node_id , self . child_id , self . type , self . ack , self . sub_type ) = [ int ( f ) for f in list_data ] except ValueError : _LOGGER . warning ( 'Error decoding messa...
Decode a message from command string .
62,583
def encode ( self , delimiter = ';' ) : try : return delimiter . join ( [ str ( f ) for f in [ self . node_id , self . child_id , int ( self . type ) , self . ack , int ( self . sub_type ) , self . payload , ] ] ) + '\n' except ValueError : _LOGGER . error ( 'Error encoding message to gateway' )
Encode a command string from message .
62,584
def validate ( self , protocol_version ) : const = get_const ( protocol_version ) valid_node_ids = vol . All ( vol . Coerce ( int ) , vol . Range ( min = 0 , max = BROADCAST_ID , msg = 'Not valid node_id: {}' . format ( self . node_id ) ) ) valid_child_ids = vol . All ( vol . Coerce ( int ) , vol . Range ( min = 0 , ma...
Validate message .
62,585
def _save_pickle ( self , filename ) : with open ( filename , 'wb' ) as file_handle : pickle . dump ( self . _sensors , file_handle , pickle . HIGHEST_PROTOCOL ) file_handle . flush ( ) os . fsync ( file_handle . fileno ( ) )
Save sensors to pickle file .
62,586
def _load_pickle ( self , filename ) : with open ( filename , 'rb' ) as file_handle : self . _sensors . update ( pickle . load ( file_handle ) )
Load sensors from pickle file .
62,587
def _save_json ( self , filename ) : with open ( filename , 'w' ) as file_handle : json . dump ( self . _sensors , file_handle , cls = MySensorsJSONEncoder , indent = 4 ) file_handle . flush ( ) os . fsync ( file_handle . fileno ( ) )
Save sensors to json file .
62,588
def _load_json ( self , filename ) : with open ( filename , 'r' ) as file_handle : self . _sensors . update ( json . load ( file_handle , cls = MySensorsJSONDecoder ) )
Load sensors from json file .
62,589
def save_sensors ( self ) : if not self . need_save : return fname = os . path . realpath ( self . persistence_file ) exists = os . path . isfile ( fname ) dirname = os . path . dirname ( fname ) if ( not os . access ( dirname , os . W_OK ) or exists and not os . access ( fname , os . W_OK ) ) : _LOGGER . error ( 'Perm...
Save sensors to file .
62,590
def _load_sensors ( self , path = None ) : if path is None : path = self . persistence_file exists = os . path . isfile ( path ) if exists and os . access ( path , os . R_OK ) : if path == self . persistence_bak : os . rename ( path , self . persistence_file ) path = self . persistence_file _LOGGER . debug ( 'Loading s...
Load sensors from file .
62,591
def safe_load_sensors ( self ) : try : loaded = self . _load_sensors ( ) except ( EOFError , ValueError ) : _LOGGER . error ( 'Bad file contents: %s' , self . persistence_file ) loaded = False if not loaded : _LOGGER . warning ( 'Trying backup file: %s' , self . persistence_bak ) try : if not self . _load_sensors ( sel...
Load sensors safely from file .
62,592
def _perform_file_action ( self , filename , action ) : ext = os . path . splitext ( filename ) [ 1 ] try : func = getattr ( self , '_{}_{}' . format ( action , ext [ 1 : ] ) ) except AttributeError : raise Exception ( 'Unsupported file type {}' . format ( ext [ 1 : ] ) ) func ( filename )
Perform action on specific file types .
62,593
def default ( self , obj ) : if isinstance ( obj , Sensor ) : return { 'sensor_id' : obj . sensor_id , 'children' : obj . children , 'type' : obj . type , 'sketch_name' : obj . sketch_name , 'sketch_version' : obj . sketch_version , 'battery_level' : obj . battery_level , 'protocol_version' : obj . protocol_version , '...
Serialize obj into JSON .
62,594
def dict_to_object ( self , obj ) : if not isinstance ( obj , dict ) : return obj if 'sensor_id' in obj : sensor = Sensor ( obj [ 'sensor_id' ] ) for key , val in obj . items ( ) : setattr ( sensor , key , val ) return sensor if all ( k in obj for k in [ 'id' , 'type' , 'values' ] ) : child = ChildSensor ( obj [ 'id' ]...
Return object from dict .
62,595
def get_const ( protocol_version ) : path = next ( ( CONST_VERSIONS [ const_version ] for const_version in sorted ( CONST_VERSIONS , reverse = True ) if parse_ver ( protocol_version ) >= parse_ver ( const_version ) ) , 'mysensors.const_14' ) if path in LOADED_CONST : return LOADED_CONST [ path ] const = import_module (...
Return the const module for the protocol_version .
62,596
def fw_hex_to_int ( hex_str , words ) : return struct . unpack ( '<{}H' . format ( words ) , binascii . unhexlify ( hex_str ) )
Unpack hex string into integers .
62,597
def fw_int_to_hex ( * args ) : return binascii . hexlify ( struct . pack ( '<{}H' . format ( len ( args ) ) , * args ) ) . decode ( 'utf-8' )
Pack integers into hex string .
62,598
def compute_crc ( data ) : crc16 = crcmod . predefined . Crc ( 'modbus' ) crc16 . update ( data ) return int ( crc16 . hexdigest ( ) , 16 )
Compute CRC16 of data and return an int .
62,599
def load_fw ( path ) : fname = os . path . realpath ( path ) exists = os . path . isfile ( fname ) if not exists or not os . access ( fname , os . R_OK ) : _LOGGER . error ( 'Firmware path %s does not exist or is not readable' , path ) return None try : intel_hex = IntelHex ( ) with open ( path , 'r' ) as file_handle :...
Open firmware file and return a binary string .