idx
int64 0
63k
| question
stringlengths 53
5.28k
| target
stringlengths 5
805
|
---|---|---|
62,600 | def prepare_fw ( bin_string ) : pads = len ( bin_string ) % 128 for _ in range ( 128 - pads ) : bin_string += b'\xff' fware = { 'blocks' : int ( len ( bin_string ) / FIRMWARE_BLOCK_SIZE ) , 'crc' : compute_crc ( bin_string ) , 'data' : bin_string , } return fware | Check that firmware is valid and return dict with binary data . |
62,601 | def _get_fw ( self , msg , updates , req_fw_type = None , req_fw_ver = None ) : fw_type = None fw_ver = None if not isinstance ( updates , tuple ) : updates = ( updates , ) for store in updates : fw_id = store . pop ( msg . node_id , None ) if fw_id is not None : fw_type , fw_ver = fw_id updates [ - 1 ] [ msg . node_id ] = fw_id break if fw_type is None or fw_ver is None : _LOGGER . debug ( 'Node %s is not set for firmware update' , msg . node_id ) return None , None , None if req_fw_type is not None and req_fw_ver is not None : fw_type , fw_ver = req_fw_type , req_fw_ver fware = self . firmware . get ( ( fw_type , fw_ver ) ) if fware is None : _LOGGER . debug ( 'No firmware of type %s and version %s found' , fw_type , fw_ver ) return None , None , None return fw_type , fw_ver , fware | Get firmware type version and a dict holding binary data . |
62,602 | def respond_fw ( self , msg ) : req_fw_type , req_fw_ver , req_blk = fw_hex_to_int ( msg . payload , 3 ) _LOGGER . debug ( 'Received firmware request with firmware type %s, ' 'firmware version %s, block index %s' , req_fw_type , req_fw_ver , req_blk ) fw_type , fw_ver , fware = self . _get_fw ( msg , ( self . unstarted , self . started ) , req_fw_type , req_fw_ver ) if fware is None : return None blk_data = fware [ 'data' ] [ req_blk * FIRMWARE_BLOCK_SIZE : req_blk * FIRMWARE_BLOCK_SIZE + FIRMWARE_BLOCK_SIZE ] msg = msg . copy ( sub_type = self . _const . Stream . ST_FIRMWARE_RESPONSE ) msg . payload = fw_int_to_hex ( fw_type , fw_ver , req_blk ) msg . payload = msg . payload + binascii . hexlify ( blk_data ) . decode ( 'utf-8' ) return msg | Respond to a firmware request . |
62,603 | def respond_fw_config ( self , msg ) : ( req_fw_type , req_fw_ver , req_blocks , req_crc , bloader_ver ) = fw_hex_to_int ( msg . payload , 5 ) _LOGGER . debug ( 'Received firmware config request with firmware type %s, ' 'firmware version %s, %s blocks, CRC %s, bootloader %s' , req_fw_type , req_fw_ver , req_blocks , req_crc , bloader_ver ) fw_type , fw_ver , fware = self . _get_fw ( msg , ( self . requested , self . unstarted ) ) if fware is None : return None if fw_type != req_fw_type : _LOGGER . warning ( 'Firmware type %s of update is not identical to existing ' 'firmware type %s for node %s' , fw_type , req_fw_type , msg . node_id ) _LOGGER . info ( 'Updating node %s to firmware type %s version %s from type %s ' 'version %s' , msg . node_id , fw_type , fw_ver , req_fw_type , req_fw_ver ) msg = msg . copy ( sub_type = self . _const . Stream . ST_FIRMWARE_CONFIG_RESPONSE ) msg . payload = fw_int_to_hex ( fw_type , fw_ver , fware [ 'blocks' ] , fware [ 'crc' ] ) return msg | Respond to a firmware config request . |
62,604 | def make_update ( self , nids , fw_type , fw_ver , fw_bin = None ) : try : fw_type , fw_ver = int ( fw_type ) , int ( fw_ver ) except ValueError : _LOGGER . error ( 'Firmware type %s or version %s not valid, ' 'please enter integers' , fw_type , fw_ver ) return if fw_bin is not None : fware = prepare_fw ( fw_bin ) self . firmware [ fw_type , fw_ver ] = fware if ( fw_type , fw_ver ) not in self . firmware : _LOGGER . error ( 'No firmware of type %s and version %s found, ' 'please enter path to firmware in call' , fw_type , fw_ver ) return if not isinstance ( nids , list ) : nids = [ nids ] for node_id in nids : if node_id not in self . _sensors : continue for store in self . unstarted , self . started : store . pop ( node_id , None ) self . requested [ node_id ] = fw_type , fw_ver self . _sensors [ node_id ] . reboot = True | Start firmware update process for one or more node_id . |
62,605 | def handle_smartsleep ( msg ) : while msg . gateway . sensors [ msg . node_id ] . queue : msg . gateway . add_job ( str , msg . gateway . sensors [ msg . node_id ] . queue . popleft ( ) ) for child in msg . gateway . sensors [ msg . node_id ] . children . values ( ) : new_child = msg . gateway . sensors [ msg . node_id ] . new_state . get ( child . id , ChildSensor ( child . id , child . type , child . description ) ) msg . gateway . sensors [ msg . node_id ] . new_state [ child . id ] = new_child for value_type , value in child . values . items ( ) : new_value = new_child . values . get ( value_type ) if new_value is not None and new_value != value : msg . gateway . add_job ( msg . gateway . sensors [ msg . node_id ] . set_child_value , child . id , value_type , new_value ) | Process a message before going back to smartsleep . |
62,606 | def handle_presentation ( msg ) : if msg . child_id == SYSTEM_CHILD_ID : sensorid = msg . gateway . add_sensor ( msg . node_id ) if sensorid is None : return None msg . gateway . sensors [ msg . node_id ] . type = msg . sub_type msg . gateway . sensors [ msg . node_id ] . protocol_version = msg . payload msg . gateway . sensors [ msg . node_id ] . reboot = False msg . gateway . alert ( msg ) return msg if not msg . gateway . is_sensor ( msg . node_id ) : _LOGGER . error ( 'Node %s is unknown, will not add child %s' , msg . node_id , msg . child_id ) return None child_id = msg . gateway . sensors [ msg . node_id ] . add_child_sensor ( msg . child_id , msg . sub_type , msg . payload ) if child_id is None : return None msg . gateway . alert ( msg ) return msg | Process a presentation message . |
62,607 | def handle_set ( msg ) : if not msg . gateway . is_sensor ( msg . node_id , msg . child_id ) : return None msg . gateway . sensors [ msg . node_id ] . set_child_value ( msg . child_id , msg . sub_type , msg . payload ) if msg . gateway . sensors [ msg . node_id ] . new_state : msg . gateway . sensors [ msg . node_id ] . set_child_value ( msg . child_id , msg . sub_type , msg . payload , children = msg . gateway . sensors [ msg . node_id ] . new_state ) msg . gateway . alert ( msg ) if msg . gateway . sensors [ msg . node_id ] . reboot : return msg . copy ( child_id = SYSTEM_CHILD_ID , type = msg . gateway . const . MessageType . internal , ack = 0 , sub_type = msg . gateway . const . Internal . I_REBOOT , payload = '' ) return None | Process a set message . |
62,608 | def handle_req ( msg ) : if not msg . gateway . is_sensor ( msg . node_id , msg . child_id ) : return None value = msg . gateway . sensors [ msg . node_id ] . children [ msg . child_id ] . values . get ( msg . sub_type ) if value is not None : return msg . copy ( type = msg . gateway . const . MessageType . set , payload = value ) return None | Process a req message . |
62,609 | def handle_internal ( msg ) : internal = msg . gateway . const . Internal ( msg . sub_type ) handler = internal . get_handler ( msg . gateway . handlers ) if handler is None : return None return handler ( msg ) | Process an internal message . |
62,610 | def handle_stream ( msg ) : if not msg . gateway . is_sensor ( msg . node_id ) : return None stream = msg . gateway . const . Stream ( msg . sub_type ) handler = stream . get_handler ( msg . gateway . handlers ) if handler is None : return None return handler ( msg ) | Process a stream type message . |
62,611 | def handle_id_request ( msg ) : node_id = msg . gateway . add_sensor ( ) return msg . copy ( ack = 0 , sub_type = msg . gateway . const . Internal [ 'I_ID_RESPONSE' ] , payload = node_id ) if node_id is not None else None | Process an internal id request message . |
62,612 | def handle_time ( msg ) : return msg . copy ( ack = 0 , payload = calendar . timegm ( time . localtime ( ) ) ) | Process an internal time request message . |
62,613 | def handle_battery_level ( msg ) : if not msg . gateway . is_sensor ( msg . node_id ) : return None msg . gateway . sensors [ msg . node_id ] . battery_level = msg . payload msg . gateway . alert ( msg ) return None | Process an internal battery level message . |
62,614 | def handle_sketch_name ( msg ) : if not msg . gateway . is_sensor ( msg . node_id ) : return None msg . gateway . sensors [ msg . node_id ] . sketch_name = msg . payload msg . gateway . alert ( msg ) return None | Process an internal sketch name message . |
62,615 | def handle_sketch_version ( msg ) : if not msg . gateway . is_sensor ( msg . node_id ) : return None msg . gateway . sensors [ msg . node_id ] . sketch_version = msg . payload msg . gateway . alert ( msg ) return None | Process an internal sketch version message . |
62,616 | def handle_log_message ( msg ) : msg . gateway . can_log = True _LOGGER . debug ( 'n:%s c:%s t:%s s:%s p:%s' , msg . node_id , msg . child_id , msg . type , msg . sub_type , msg . payload ) return None | Process an internal log message . |
62,617 | def publish ( self , topic , payload , qos , retain ) : self . _mqttc . publish ( topic , payload , qos , retain ) | Publish an MQTT message . |
62,618 | def subscribe ( self , topic , callback , qos ) : if topic in self . topics : return def _message_callback ( mqttc , userdata , msg ) : callback ( msg . topic , msg . payload . decode ( 'utf-8' ) , msg . qos ) self . _mqttc . subscribe ( topic , qos ) self . _mqttc . message_callback_add ( topic , _message_callback ) self . topics [ topic ] = callback | Subscribe to an MQTT topic . |
62,619 | def _connect ( self ) : while self . protocol : _LOGGER . info ( 'Trying to connect to %s' , self . port ) try : ser = serial . serial_for_url ( self . port , self . baud , timeout = self . timeout ) except serial . SerialException : _LOGGER . error ( 'Unable to connect to %s' , self . port ) _LOGGER . info ( 'Waiting %s secs before trying to connect again' , self . reconnect_timeout ) time . sleep ( self . reconnect_timeout ) else : transport = serial . threaded . ReaderThread ( ser , lambda : self . protocol ) transport . daemon = False poll_thread = threading . Thread ( target = self . _poll_queue ) self . _stop_event . clear ( ) poll_thread . start ( ) transport . start ( ) transport . connect ( ) return | Connect to the serial port . This should be run in a new thread . |
62,620 | def _connect ( self ) : try : while True : _LOGGER . info ( 'Trying to connect to %s' , self . port ) try : yield from serial_asyncio . create_serial_connection ( self . loop , lambda : self . protocol , self . port , self . baud ) return except serial . SerialException : _LOGGER . error ( 'Unable to connect to %s' , self . port ) _LOGGER . info ( 'Waiting %s secs before trying to connect again' , self . reconnect_timeout ) yield from asyncio . sleep ( self . reconnect_timeout , loop = self . loop ) except asyncio . CancelledError : _LOGGER . debug ( 'Connect attempt to %s cancelled' , self . port ) | Connect to the serial port . |
62,621 | def is_version ( value ) : try : value = str ( value ) if not parse_ver ( '1.4' ) <= parse_ver ( value ) : raise ValueError ( ) return value except ( AttributeError , TypeError , ValueError ) : raise vol . Invalid ( '{} is not a valid version specifier' . format ( value ) ) | Validate that value is a valid version string . |
62,622 | def is_battery_level ( value ) : try : value = percent_int ( value ) return value except vol . Invalid : _LOGGER . warning ( '%s is not a valid battery level, falling back to battery level 0' , value ) return 0 | Validate that value is a valid battery level integer . |
62,623 | def is_heartbeat ( value ) : try : value = vol . Coerce ( int ) ( value ) return value except vol . Invalid : _LOGGER . warning ( '%s is not a valid heartbeat value, falling back to heartbeat 0' , value ) return 0 | Validate that value is a valid heartbeat integer . |
62,624 | def mksalt ( method = None , rounds = None ) : if method is None : method = methods [ 0 ] salt = [ '${0}$' . format ( method . ident ) if method . ident else '' ] if rounds : salt . append ( 'rounds={0:d}$' . format ( rounds ) ) salt . append ( '' . join ( _sr . choice ( _BASE64_CHARACTERS ) for char in range ( method . salt_chars ) ) ) return '' . join ( salt ) | Generate a salt for the specified method . If not specified the strongest available method will be used . |
62,625 | def double_prompt_for_plaintext_password ( ) : password = 1 password_repeat = 2 while password != password_repeat : password = getpass . getpass ( 'Enter password: ' ) password_repeat = getpass . getpass ( 'Repeat password: ' ) if password != password_repeat : sys . stderr . write ( 'Passwords do not match, try again.\n' ) return password | Get the desired password from the user through a double prompt . |
62,626 | def logic ( self , data ) : try : msg = Message ( data , self ) msg . validate ( self . protocol_version ) except ( ValueError , vol . Invalid ) as exc : _LOGGER . warning ( 'Not a valid message: %s' , exc ) return None message_type = self . const . MessageType ( msg . type ) handler = message_type . get_handler ( self . handlers ) ret = handler ( msg ) ret = self . _route_message ( ret ) ret = ret . encode ( ) if ret else None return ret | Parse the data and respond to it appropriately . |
62,627 | def alert ( self , msg ) : if self . event_callback is not None : try : self . event_callback ( msg ) except Exception as exception : _LOGGER . exception ( exception ) if self . persistence : self . persistence . need_save = True | Tell anyone who wants to know that a sensor was updated . |
62,628 | def _get_next_id ( self ) : if self . sensors : next_id = max ( self . sensors . keys ( ) ) + 1 else : next_id = 1 if next_id <= self . const . MAX_NODE_ID : return next_id return None | Return the next available sensor id . |
62,629 | def add_sensor ( self , sensorid = None ) : if sensorid is None : sensorid = self . _get_next_id ( ) if sensorid is not None and sensorid not in self . sensors : self . sensors [ sensorid ] = Sensor ( sensorid ) return sensorid if sensorid in self . sensors else None | Add a sensor to the gateway . |
62,630 | def is_sensor ( self , sensorid , child_id = None ) : ret = sensorid in self . sensors if not ret : _LOGGER . warning ( 'Node %s is unknown' , sensorid ) if ret and child_id is not None : ret = child_id in self . sensors [ sensorid ] . children if not ret : _LOGGER . warning ( 'Child %s is unknown' , child_id ) if not ret and parse_ver ( self . protocol_version ) >= parse_ver ( '2.0' ) : _LOGGER . info ( 'Requesting new presentation for node %s' , sensorid ) msg = Message ( gateway = self ) . modify ( node_id = sensorid , child_id = SYSTEM_CHILD_ID , type = self . const . MessageType . internal , sub_type = self . const . Internal . I_PRESENTATION ) if self . _route_message ( msg ) : self . add_job ( msg . encode ) return ret | Return True if a sensor and its child exist . |
62,631 | def run_job ( self , job = None ) : if job is None : if not self . queue : return None job = self . queue . popleft ( ) start = timer ( ) func , args = job reply = func ( * args ) end = timer ( ) if end - start > 0.1 : _LOGGER . debug ( 'Handle queue with call %s(%s) took %.3f seconds' , func , args , end - start ) return reply | Run a job either passed in or from the queue . |
62,632 | def set_child_value ( self , sensor_id , child_id , value_type , value , ** kwargs ) : if not self . is_sensor ( sensor_id , child_id ) : return if self . sensors [ sensor_id ] . new_state : self . sensors [ sensor_id ] . set_child_value ( child_id , value_type , value , children = self . sensors [ sensor_id ] . new_state ) else : self . add_job ( partial ( self . sensors [ sensor_id ] . set_child_value , child_id , value_type , value , ** kwargs ) ) | Add a command to set a sensor value to the queue . |
62,633 | def _poll_queue ( self ) : while not self . _stop_event . is_set ( ) : reply = self . run_job ( ) self . send ( reply ) if self . queue : continue time . sleep ( 0.02 ) | Poll the queue for work . |
62,634 | def stop ( self ) : self . _stop_event . set ( ) if not self . persistence : return if self . _cancel_save is not None : self . _cancel_save ( ) self . _cancel_save = None self . persistence . save_sensors ( ) | Stop the background thread . |
62,635 | def update_fw ( self , nids , fw_type , fw_ver , fw_path = None ) : fw_bin = None if fw_path : fw_bin = load_fw ( fw_path ) if not fw_bin : return self . ota . make_update ( nids , fw_type , fw_ver , fw_bin ) | Update firwmare of all node_ids in nids . |
62,636 | def _disconnect ( self ) : if not self . protocol or not self . protocol . transport : self . protocol = None return _LOGGER . info ( 'Disconnecting from gateway' ) self . protocol . transport . close ( ) self . protocol = None | Disconnect from the transport . |
62,637 | def send ( self , message ) : if not message or not self . protocol or not self . protocol . transport : return if not self . can_log : _LOGGER . debug ( 'Sending %s' , message . strip ( ) ) try : self . protocol . transport . write ( message . encode ( ) ) except OSError as exc : _LOGGER . error ( 'Failed writing to transport %s: %s' , self . protocol . transport , exc ) self . protocol . transport . close ( ) self . protocol . conn_lost_callback ( ) | Write a message to the gateway . |
62,638 | def stop ( self ) : _LOGGER . info ( 'Stopping gateway' ) self . _disconnect ( ) if self . connect_task and not self . connect_task . cancelled ( ) : self . connect_task . cancel ( ) self . connect_task = None if not self . persistence : return if self . _cancel_save is not None : self . _cancel_save ( ) self . _cancel_save = None yield from self . loop . run_in_executor ( None , self . persistence . save_sensors ) | Stop the gateway . |
62,639 | def add_job ( self , func , * args ) : job = func , args reply = self . run_job ( job ) self . send ( reply ) | Add a job that should return a reply to be sent . |
62,640 | def connection_made ( self , transport ) : super ( ) . connection_made ( transport ) if hasattr ( self . transport , 'serial' ) : _LOGGER . info ( 'Connected to %s' , self . transport . serial ) else : _LOGGER . info ( 'Connected to %s' , self . transport ) | Handle created connection . |
62,641 | def handle_line ( self , line ) : if not self . gateway . can_log : _LOGGER . debug ( 'Receiving %s' , line ) self . gateway . add_job ( self . gateway . logic , line ) | Handle incoming string data one line at a time . |
62,642 | def add_child_sensor ( self , child_id , child_type , description = '' ) : if child_id in self . children : _LOGGER . warning ( 'child_id %s already exists in children of node %s, ' 'cannot add child' , child_id , self . sensor_id ) return None self . children [ child_id ] = ChildSensor ( child_id , child_type , description ) return child_id | Create and add a child sensor . |
62,643 | def set_child_value ( self , child_id , value_type , value , ** kwargs ) : children = kwargs . get ( 'children' , self . children ) if not isinstance ( children , dict ) or child_id not in children : return None msg_type = kwargs . get ( 'msg_type' , 1 ) ack = kwargs . get ( 'ack' , 0 ) msg = Message ( ) . modify ( node_id = self . sensor_id , child_id = child_id , type = msg_type , ack = ack , sub_type = value_type , payload = value ) msg_string = msg . encode ( ) if msg_string is None : _LOGGER . error ( 'Not a valid message: node %s, child %s, type %s, ack %s, ' 'sub_type %s, payload %s' , self . sensor_id , child_id , msg_type , ack , value_type , value ) return None try : msg = Message ( msg_string ) msg . validate ( self . protocol_version ) except ( ValueError , AttributeError , vol . Invalid ) as exc : _LOGGER . error ( 'Not a valid message: %s' , exc ) return None child = children [ msg . child_id ] child . values [ msg . sub_type ] = msg . payload return msg_string | Set a child sensor s value . |
62,644 | def get_schema ( self , protocol_version ) : const = get_const ( protocol_version ) custom_schema = vol . Schema ( { typ . value : const . VALID_SETREQ [ typ ] for typ in const . VALID_TYPES [ const . Presentation . S_CUSTOM ] } ) return custom_schema . extend ( { typ . value : const . VALID_SETREQ [ typ ] for typ in const . VALID_TYPES [ self . type ] } ) | Return the child schema for the correct const version . |
62,645 | def validate ( self , protocol_version , values = None ) : if values is None : values = self . values return self . get_schema ( protocol_version ) ( values ) | Validate child value types and values against protocol_version . |
62,646 | def _get_shipped_from ( row ) : try : spans = row . find ( 'div' , { 'id' : 'coltextR2' } ) . find_all ( 'span' ) if len ( spans ) < 2 : return None return spans [ 1 ] . string except AttributeError : return None | Get where package was shipped from . |
62,647 | def _get_status_timestamp ( row ) : try : divs = row . find ( 'div' , { 'id' : 'coltextR3' } ) . find_all ( 'div' ) if len ( divs ) < 2 : return None timestamp_string = divs [ 1 ] . string except AttributeError : return None try : return parse ( timestamp_string ) except ValueError : return None | Get latest package timestamp . |
62,648 | def _get_driver ( driver_type ) : if driver_type == 'phantomjs' : return webdriver . PhantomJS ( service_log_path = os . path . devnull ) if driver_type == 'firefox' : return webdriver . Firefox ( firefox_options = FIREFOXOPTIONS ) elif driver_type == 'chrome' : chrome_options = webdriver . ChromeOptions ( ) for arg in CHROME_WEBDRIVER_ARGS : chrome_options . add_argument ( arg ) return webdriver . Chrome ( chrome_options = chrome_options ) else : raise USPSError ( '{} not supported' . format ( driver_type ) ) | Get webdriver . |
62,649 | def get_profile ( session ) : response = session . get ( PROFILE_URL , allow_redirects = False ) if response . status_code == 302 : raise USPSError ( 'expired session' ) parsed = BeautifulSoup ( response . text , HTML_PARSER ) profile = parsed . find ( 'div' , { 'class' : 'atg_store_myProfileInfo' } ) data = { } for row in profile . find_all ( 'tr' ) : cells = row . find_all ( 'td' ) if len ( cells ) == 2 : key = ' ' . join ( cells [ 0 ] . find_all ( text = True ) ) . strip ( ) . lower ( ) . replace ( ' ' , '_' ) value = ' ' . join ( cells [ 1 ] . find_all ( text = True ) ) . strip ( ) data [ key ] = value return data | Get profile data . |
62,650 | def get_packages ( session ) : _LOGGER . info ( "attempting to get package data" ) response = _get_dashboard ( session ) parsed = BeautifulSoup ( response . text , HTML_PARSER ) packages = [ ] for row in parsed . find_all ( 'div' , { 'class' : 'pack_row' } ) : packages . append ( { 'tracking_number' : _get_tracking_number ( row ) , 'primary_status' : _get_primary_status ( row ) , 'secondary_status' : _get_secondary_status ( row ) , 'status_timestamp' : _get_status_timestamp ( row ) , 'shipped_from' : _get_shipped_from ( row ) , 'delivery_date' : _get_delivery_date ( row ) } ) return packages | Get package data . |
62,651 | def get_mail ( session , date = None ) : _LOGGER . info ( "attempting to get mail data" ) if not date : date = datetime . datetime . now ( ) . date ( ) response = _get_dashboard ( session , date ) parsed = BeautifulSoup ( response . text , HTML_PARSER ) mail = [ ] for row in parsed . find_all ( 'div' , { 'class' : 'mailpiece' } ) : image = _get_mailpiece_image ( row ) if not image : continue mail . append ( { 'id' : _get_mailpiece_id ( image ) , 'image' : _get_mailpiece_url ( image ) , 'date' : date } ) return mail | Get mail data . |
62,652 | def get_session ( username , password , cookie_path = COOKIE_PATH , cache = True , cache_expiry = 300 , cache_path = CACHE_PATH , driver = 'phantomjs' ) : class USPSAuth ( AuthBase ) : def __init__ ( self , username , password , cookie_path , driver ) : self . username = username self . password = password self . cookie_path = cookie_path self . driver = driver def __call__ ( self , r ) : return r session = requests . Session ( ) if cache : session = requests_cache . core . CachedSession ( cache_name = cache_path , expire_after = cache_expiry ) session . auth = USPSAuth ( username , password , cookie_path , driver ) session . headers . update ( { 'User-Agent' : USER_AGENT } ) if os . path . exists ( cookie_path ) : _LOGGER . debug ( "cookie found at: %s" , cookie_path ) session . cookies = _load_cookies ( cookie_path ) else : _login ( session ) return session | Get session existing or new . |
62,653 | def rc4 ( data , key ) : S , j , out = list ( range ( 256 ) ) , 0 , [ ] for i in range ( 256 ) : j = ( j + S [ i ] + ord ( key [ i % len ( key ) ] ) ) % 256 S [ i ] , S [ j ] = S [ j ] , S [ i ] i = j = 0 for ch in data : i = ( i + 1 ) % 256 j = ( j + S [ i ] ) % 256 S [ i ] , S [ j ] = S [ j ] , S [ i ] out . append ( chr ( ord ( ch ) ^ S [ ( S [ i ] + S [ j ] ) % 256 ] ) ) return "" . join ( out ) | RC4 encryption and decryption method . |
62,654 | def verify_email_for_object ( self , email , content_object , email_field_name = 'email' ) : confirmation_key = generate_random_token ( ) try : confirmation = EmailConfirmation ( ) confirmation . content_object = content_object confirmation . email_field_name = email_field_name confirmation . email = email confirmation . confirmation_key = confirmation_key confirmation . save ( ) except IntegrityError : confirmation = EmailConfirmation . objects . get_for_object ( content_object , email_field_name ) confirmation . email = email confirmation . confirmation_key = confirmation_key confirmation . save ( update_fields = [ 'email' , 'confirmation_key' ] ) confirmation . send ( ) return confirmation | Create an email confirmation for content_object and send a confirmation mail . |
62,655 | def clean ( self ) : EmailConfirmation . objects . filter ( content_type = self . content_type , object_id = self . object_id , email_field_name = self . email_field_name ) . delete ( ) | delete all confirmations for the same content_object and the same field |
62,656 | def render_paginate ( request , template , objects , per_page , extra_context = { } ) : paginator = Paginator ( objects , per_page ) page = request . GET . get ( 'page' , 1 ) get_params = '&' . join ( [ '%s=%s' % ( k , request . GET [ k ] ) for k in request . GET if k != 'page' ] ) try : page_number = int ( page ) except ValueError : if page == 'last' : page_number = paginator . num_pages else : raise Http404 try : page_obj = paginator . page ( page_number ) except InvalidPage : raise Http404 context = { 'object_list' : page_obj . object_list , 'paginator' : paginator , 'page_obj' : page_obj , 'is_paginated' : page_obj . has_other_pages ( ) , 'get_params' : get_params } context . update ( extra_context ) return render ( request , template , context ) | Paginated list of objects . |
62,657 | def values ( self ) : report = { } for k , k_changes in self . _changes . items ( ) : if len ( k_changes ) == 1 : report [ k ] = k_changes [ 0 ] . new_value elif k_changes [ 0 ] . old_value != k_changes [ - 1 ] . new_value : report [ k ] = k_changes [ - 1 ] . new_value return report | Returns a mapping of items to their new values . The mapping includes only items whose value or raw string value has changed in the context . |
62,658 | def changes ( self ) : report = { } for k , k_changes in self . _changes . items ( ) : if len ( k_changes ) == 1 : report [ k ] = k_changes [ 0 ] else : first = k_changes [ 0 ] last = k_changes [ - 1 ] if first . old_value != last . new_value or first . old_raw_str_value != last . new_raw_str_value : report [ k ] = _Change ( first . old_value , last . new_value , first . old_raw_str_value , last . new_raw_str_value , ) return report | Returns a mapping of items to their effective change objects which include the old values and the new . The mapping includes only items whose value or raw string value has changed in the context . |
62,659 | def load ( self , source , as_defaults = False ) : if isinstance ( source , six . string_types ) : source = os . path . expanduser ( source ) with open ( source , encoding = 'utf-8' ) as f : self . _rw . load_config_from_file ( self . _config , f , as_defaults = as_defaults ) elif isinstance ( source , ( list , tuple ) ) : for s in source : with open ( s , encoding = 'utf-8' ) as f : self . _rw . load_config_from_file ( self . _config , f , as_defaults = as_defaults ) else : self . _rw . load_config_from_file ( self . _config , source , as_defaults = as_defaults ) | Load configuration values from the specified source . |
62,660 | def loads ( self , config_str , as_defaults = False ) : self . _rw . load_config_from_string ( self . _config , config_str , as_defaults = as_defaults ) | Load configuration values from the specified source string . |
62,661 | def dump ( self , destination , with_defaults = False ) : if isinstance ( destination , six . string_types ) : with open ( destination , 'w' , encoding = 'utf-8' ) as f : self . _rw . dump_config_to_file ( self . _config , f , with_defaults = with_defaults ) else : self . _rw . dump_config_to_file ( self . _config , destination , with_defaults = with_defaults ) | Write configuration values to the specified destination . |
62,662 | def dumps ( self , with_defaults = False ) : return self . _rw . dump_config_to_string ( self . _config , with_defaults = with_defaults ) | Generate a string representing all the configuration values . |
62,663 | def _default_key_setter ( self , name , subject ) : if is_config_item ( subject ) : self . add_item ( name , subject ) elif is_config_section ( subject ) : self . add_section ( name , subject ) else : raise TypeError ( 'Section items can only be replaced with items, ' 'got {type}. To set item value use ...{name}.value = <new_value>' . format ( type = type ( subject ) , name = name , ) ) | This method is used only when there is a custom key_setter set . |
62,664 | def get_section ( self , * key ) : section = self . _get_item_or_section ( key ) if not section . is_section : raise RuntimeError ( '{} is an item, not a section' . format ( key ) ) return section | The recommended way of retrieving a section by key when extending configmanager s behaviour . |
62,665 | def add_item ( self , alias , item ) : if not isinstance ( alias , six . string_types ) : raise TypeError ( 'Item name must be a string, got a {!r}' . format ( type ( alias ) ) ) item = copy . deepcopy ( item ) if item . name is not_set : item . name = alias if self . settings . str_path_separator in item . name : raise ValueError ( 'Item name must not contain str_path_separator which is configured for this Config -- {!r} -- ' 'but {!r} does.' . format ( self . settings . str_path_separator , item ) ) self . _tree [ item . name ] = item if item . name != alias : if self . settings . str_path_separator in alias : raise ValueError ( 'Item alias must not contain str_path_separator which is configured for this Config -- {!r} --' 'but {!r} used for {!r} does.' . format ( self . settings . str_path_separator , alias , item ) ) self . _tree [ alias ] = item item . _section = self self . dispatch_event ( self . hooks . item_added_to_section , alias = alias , section = self , subject = item ) | Add a config item to this section . |
62,666 | def add_section ( self , alias , section ) : if not isinstance ( alias , six . string_types ) : raise TypeError ( 'Section name must be a string, got a {!r}' . format ( type ( alias ) ) ) self . _tree [ alias ] = section if self . settings . str_path_separator in alias : raise ValueError ( 'Section alias must not contain str_path_separator which is configured for this Config -- {!r} -- ' 'but {!r} does.' . format ( self . settings . str_path_separator , alias ) ) section . _section = self section . _section_alias = alias self . dispatch_event ( self . hooks . section_added_to_section , alias = alias , section = self , subject = section ) | Add a sub - section to this section . |
62,667 | def _get_recursive_iterator ( self , recursive = False ) : names_yielded = set ( ) for obj_alias , obj in self . _tree . items ( ) : if obj . is_section : if obj . alias in names_yielded : continue names_yielded . add ( obj . alias ) yield ( obj . alias , ) , obj if not recursive : continue for sub_item_path , sub_item in obj . _get_recursive_iterator ( recursive = recursive ) : yield ( obj_alias , ) + sub_item_path , sub_item else : if obj . name in names_yielded : continue names_yielded . add ( obj . name ) yield ( obj . name , ) , obj | Basic recursive iterator whose only purpose is to yield all items and sections in order with their full paths as keys . |
62,668 | def reset ( self ) : for _ , item in self . iter_items ( recursive = True ) : item . reset ( ) | Recursively resets values of all items contained in this section and its subsections to their default values . |
62,669 | def is_default ( self ) : for _ , item in self . iter_items ( recursive = True ) : if not item . is_default : return False return True | True if values of all config items in this section and its subsections have their values equal to defaults or have no value set . |
62,670 | def dump_values ( self , with_defaults = True , dict_cls = dict , flat = False ) : values = dict_cls ( ) if flat : for str_path , item in self . iter_items ( recursive = True , key = 'str_path' ) : if item . has_value : if with_defaults or not item . is_default : values [ str_path ] = item . value else : for item_name , item in self . _tree . items ( ) : if is_config_section ( item ) : section_values = item . dump_values ( with_defaults = with_defaults , dict_cls = dict_cls ) if section_values : values [ item_name ] = section_values else : if item . has_value : if with_defaults or not item . is_default : values [ item . name ] = item . value return values | Export values of all items contained in this section to a dictionary . |
62,671 | def load_values ( self , dictionary , as_defaults = False , flat = False ) : if flat : separator = self . settings . str_path_separator flat_dictionary = dictionary dictionary = collections . OrderedDict ( ) for k , v in flat_dictionary . items ( ) : k_parts = k . split ( separator ) c = dictionary for i , kp in enumerate ( k_parts ) : if i >= len ( k_parts ) - 1 : c [ kp ] = v else : if kp not in c : c [ kp ] = collections . OrderedDict ( ) c = c [ kp ] for name , value in dictionary . items ( ) : if name not in self : if as_defaults : if isinstance ( value , dict ) : self [ name ] = self . create_section ( ) self [ name ] . load_values ( value , as_defaults = as_defaults ) else : self [ name ] = self . create_item ( name , default = value ) else : pass continue resolution = self . _get_item_or_section ( name , handle_not_found = False ) if is_config_item ( resolution ) : if as_defaults : resolution . default = value else : resolution . value = value else : resolution . load_values ( value , as_defaults = as_defaults ) | Import config values from a dictionary . |
62,672 | def create_section ( self , * args , ** kwargs ) : kwargs . setdefault ( 'section' , self ) return self . settings . section_factory ( * args , ** kwargs ) | Internal factory method used to create an instance of configuration section . |
62,673 | def item_attribute ( self , f = None , name = None ) : def decorator ( func ) : attr_name = name or func . __name__ if attr_name . startswith ( '_' ) : raise RuntimeError ( 'Invalid dynamic item attribute name -- should not start with an underscore' ) self . __item_attributes [ attr_name ] = func return func if f is None : return decorator else : return decorator ( f ) | A decorator to register a dynamic item attribute provider . |
62,674 | def get_item_attribute ( self , item , name ) : if name in self . __item_attributes : return self . __item_attributes [ name ] ( item ) elif self . section : return self . section . get_item_attribute ( item , name ) else : raise AttributeError ( name ) | Method called by item when an attribute is not found . |
62,675 | def dispatch_event ( self , event_ , ** kwargs ) : if self . settings . hooks_enabled : result = self . hooks . dispatch_event ( event_ , ** kwargs ) if result is not None : return result if self . section : return self . section . dispatch_event ( event_ , ** kwargs ) elif self . section : self . section . dispatch_event ( event_ , ** kwargs ) | Dispatch section event . |
62,676 | def load ( self ) : for section in reversed ( list ( self . iter_sections ( recursive = True , key = None ) ) ) : if section . is_config : section . load ( ) for source in self . settings . load_sources : adapter = getattr ( self , _get_persistence_adapter_for ( source ) ) if adapter . store_exists ( source ) : adapter . load ( source ) | Load user configuration based on settings . |
62,677 | def option ( self , * args , ** kwargs ) : args , kwargs = _config_parameter ( args , kwargs ) return self . _click . option ( * args , ** kwargs ) | Registers a click . option which falls back to a configmanager Item if user hasn t provided a value in the command line . |
62,678 | def argument ( self , * args , ** kwargs ) : if kwargs . get ( 'required' , True ) : raise TypeError ( 'In click framework, arguments are mandatory, unless marked required=False. ' 'Attempt to use configmanager as a fallback provider suggests that this is an optional option, ' 'not a mandatory argument.' ) args , kwargs = _config_parameter ( args , kwargs ) return self . _click . argument ( * args , ** kwargs ) | Registers a click . argument which falls back to a configmanager Item if user hasn t provided a value in the command line . |
62,679 | def _get_kwarg ( self , name , kwargs ) : at_name = '@{}' . format ( name ) if name in kwargs : if at_name in kwargs : raise ValueError ( 'Both {!r} and {!r} specified in kwargs' . format ( name , at_name ) ) return kwargs [ name ] if at_name in kwargs : return kwargs [ at_name ] return not_set | Helper to get value of a named attribute irrespective of whether it is passed with or without |
62,680 | def _get_envvar_value ( self ) : envvar_name = None if self . envvar is True : envvar_name = self . envvar_name if envvar_name is None : envvar_name = '_' . join ( self . get_path ( ) ) . upper ( ) elif self . envvar : envvar_name = self . envvar if envvar_name and envvar_name in os . environ : return self . type . deserialize ( os . environ [ envvar_name ] ) else : return not_set | Internal helper to get item value from an environment variable if item is controlled by one and if the variable is set . |
62,681 | def get ( self , fallback = not_set ) : envvar_value = self . _get_envvar_value ( ) if envvar_value is not not_set : return envvar_value if self . has_value : if self . _value is not not_set : return self . _value else : return copy . deepcopy ( self . default ) elif fallback is not not_set : return fallback elif self . required : raise RequiredValueMissing ( name = self . name , item = self ) return fallback | Returns config value . |
62,682 | def set ( self , value ) : old_value = self . _value old_raw_str_value = self . raw_str_value self . type . set_item_value ( self , value ) new_value = self . _value if old_value is not_set and new_value is not_set : return if self . section : self . section . dispatch_event ( self . section . hooks . item_value_changed , item = self , old_value = old_value , new_value = new_value , old_raw_str_value = old_raw_str_value , new_raw_str_value = self . raw_str_value ) | Sets config value . |
62,683 | def reset ( self ) : old_value = self . _value old_raw_str_value = self . raw_str_value self . _value = not_set self . raw_str_value = not_set new_value = self . _value if old_value is not_set : return if self . section : self . section . dispatch_event ( self . section . hooks . item_value_changed , item = self , old_value = old_value , new_value = new_value , old_raw_str_value = old_raw_str_value , new_raw_str_value = self . raw_str_value , ) | Resets the value of config item to its default value . |
62,684 | def is_default ( self ) : envvar_value = self . _get_envvar_value ( ) if envvar_value is not not_set : return envvar_value == self . default else : return self . _value is not_set or self . _value == self . default | True if the item s value is its default value or if no value and no default value are set . |
62,685 | def has_value ( self ) : if self . _get_envvar_value ( ) is not not_set : return True else : return self . default is not not_set or self . _value is not not_set | True if item has a default value or custom value set . |
62,686 | def validate ( self ) : if self . required and not self . has_value : raise RequiredValueMissing ( name = self . name , item = self ) | Validate item . |
62,687 | def filebrowser ( request , file_type ) : template = 'filebrowser.html' upload_form = FileUploadForm ( ) uploaded_file = None upload_tab_active = False is_images_dialog = ( file_type == 'img' ) is_documents_dialog = ( file_type == 'doc' ) files = FileBrowserFile . objects . filter ( file_type = file_type ) if request . POST : upload_form = FileUploadForm ( request . POST , request . FILES ) upload_tab_active = True if upload_form . is_valid ( ) : uploaded_file = upload_form . save ( commit = False ) uploaded_file . file_type = file_type uploaded_file . save ( ) data = { 'upload_form' : upload_form , 'uploaded_file' : uploaded_file , 'upload_tab_active' : upload_tab_active , 'is_images_dialog' : is_images_dialog , 'is_documents_dialog' : is_documents_dialog } per_page = getattr ( settings , 'FILEBROWSER_PER_PAGE' , 20 ) return render_paginate ( request , template , files , per_page , data ) | Trigger view for filebrowser |
62,688 | def available_domains ( self ) : if not hasattr ( self , '_available_domains' ) : url = 'http://{0}/request/domains/format/json/' . format ( self . api_domain ) req = requests . get ( url ) domains = req . json ( ) setattr ( self , '_available_domains' , domains ) return self . _available_domains | Return list of available domains for use in email address . |
62,689 | def generate_login ( self , min_length = 6 , max_length = 10 , digits = True ) : chars = string . ascii_lowercase if digits : chars += string . digits length = random . randint ( min_length , max_length ) return '' . join ( random . choice ( chars ) for x in range ( length ) ) | Generate string for email address login with defined length and alphabet . |
62,690 | def get_email_address ( self ) : if self . login is None : self . login = self . generate_login ( ) available_domains = self . available_domains if self . domain is None : self . domain = random . choice ( available_domains ) elif self . domain not in available_domains : raise ValueError ( 'Domain not found in available domains!' ) return u'{0}{1}' . format ( self . login , self . domain ) | Return full email address from login and domain from params in class initialization or generate new . |
62,691 | def get_mailbox ( self , email = None , email_hash = None ) : if email is None : email = self . get_email_address ( ) if email_hash is None : email_hash = self . get_hash ( email ) url = 'http://{0}/request/mail/id/{1}/format/json/' . format ( self . api_domain , email_hash ) req = requests . get ( url ) return req . json ( ) | Return list of emails in given email address or dict with error key if mail box is empty . |
62,692 | def setup_domain_socket ( location ) : clientsocket = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) clientsocket . settimeout ( timeout ) clientsocket . connect ( location ) return clientsocket | Setup Domain Socket |
62,693 | def setup_tcp_socket ( location , port ) : clientsocket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) clientsocket . settimeout ( timeout ) clientsocket . connect ( ( location , port ) ) return clientsocket | Setup TCP Socket |
62,694 | def create_primary_zone ( self , account_name , zone_name ) : zone_properties = { "name" : zone_name , "accountName" : account_name , "type" : "PRIMARY" } primary_zone_info = { "forceImport" : True , "createType" : "NEW" } zone_data = { "properties" : zone_properties , "primaryCreateInfo" : primary_zone_info } return self . rest_api_connection . post ( "/v1/zones" , json . dumps ( zone_data ) ) | Creates a new primary zone . |
62,695 | def create_primary_zone_by_upload ( self , account_name , zone_name , bind_file ) : zone_properties = { "name" : zone_name , "accountName" : account_name , "type" : "PRIMARY" } primary_zone_info = { "forceImport" : True , "createType" : "UPLOAD" } zone_data = { "properties" : zone_properties , "primaryCreateInfo" : primary_zone_info } files = { 'zone' : ( '' , json . dumps ( zone_data ) , 'application/json' ) , 'file' : ( 'file' , open ( bind_file , 'rb' ) , 'application/octet-stream' ) } return self . rest_api_connection . post_multi_part ( "/v1/zones" , files ) | Creates a new primary zone by uploading a bind file |
62,696 | def create_primary_zone_by_axfr ( self , account_name , zone_name , master , tsig_key = None , key_value = None ) : zone_properties = { "name" : zone_name , "accountName" : account_name , "type" : "PRIMARY" } if tsig_key is not None and key_value is not None : name_server_info = { "ip" : master , "tsigKey" : tsig_key , "tsigKeyValue" : key_value } else : name_server_info = { "ip" : master } primary_zone_info = { "forceImport" : True , "createType" : "TRANSFER" , "nameServer" : name_server_info } zone_data = { "properties" : zone_properties , "primaryCreateInfo" : primary_zone_info } return self . rest_api_connection . post ( "/v1/zones" , json . dumps ( zone_data ) ) | Creates a new primary zone by zone transferring off a master . |
62,697 | def create_secondary_zone ( self , account_name , zone_name , master , tsig_key = None , key_value = None ) : zone_properties = { "name" : zone_name , "accountName" : account_name , "type" : "SECONDARY" } if tsig_key is not None and key_value is not None : name_server_info = { "ip" : master , "tsigKey" : tsig_key , "tsigKeyValue" : key_value } else : name_server_info = { "ip" : master } name_server_ip_1 = { "nameServerIp1" : name_server_info } name_server_ip_list = { "nameServerIpList" : name_server_ip_1 } secondary_zone_info = { "primaryNameServers" : name_server_ip_list } zone_data = { "properties" : zone_properties , "secondaryCreateInfo" : secondary_zone_info } return self . rest_api_connection . post ( "/v1/zones" , json . dumps ( zone_data ) ) | Creates a new secondary zone . |
62,698 | def get_zones_of_account ( self , account_name , q = None , ** kwargs ) : uri = "/v1/accounts/" + account_name + "/zones" params = build_params ( q , kwargs ) return self . rest_api_connection . get ( uri , params ) | Returns a list of zones for the specified account . |
62,699 | def get_zones ( self , q = None , ** kwargs ) : uri = "/v1/zones" params = build_params ( q , kwargs ) return self . rest_api_connection . get ( uri , params ) | Returns a list of zones across all of the user s accounts . |