idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
227,700 | def _render_html ( self , libraries ) : title = self . options . get ( "title" , "Keyword Documentation" ) date = time . strftime ( "%A %B %d, %I:%M %p" ) cci_version = cumulusci . __version__ stylesheet_path = os . path . join ( os . path . dirname ( __file__ ) , "stylesheet.css" ) with open ( stylesheet_path ) as f : stylesheet = f . read ( ) jinjaenv = jinja2 . Environment ( loader = jinja2 . FileSystemLoader ( os . path . dirname ( __file__ ) ) , autoescape = False ) jinjaenv . filters [ "robot_html" ] = robot . utils . html_format template = jinjaenv . get_template ( "template.html" ) return template . render ( libraries = libraries , title = title , cci_version = cci_version , stylesheet = stylesheet , date = date , ) | Generate the html . libraries is a list of LibraryDocumentation objects | 229 | 14 |
227,701 | def generate_password ( self ) : if self . password_failed : self . logger . warning ( "Skipping resetting password since last attempt failed" ) return # Set a random password so it's available via cci org info command = sarge . shell_format ( "sfdx force:user:password:generate -u {0}" , self . username ) self . logger . info ( "Generating scratch org user password with command {}" . format ( command ) ) p = sarge . Command ( command , stdout = sarge . Capture ( buffer_size = - 1 ) , stderr = sarge . Capture ( buffer_size = - 1 ) , shell = True , ) p . run ( ) stderr = io . TextIOWrapper ( p . stderr ) . readlines ( ) stdout = io . TextIOWrapper ( p . stdout ) . readlines ( ) if p . returncode : self . config [ "password_failed" ] = True # Don't throw an exception because of failure creating the # password, just notify in a log message self . logger . warning ( "Failed to set password: \n{}\n{}" . format ( "\n" . join ( stdout ) , "\n" . join ( stderr ) ) ) | Generates an org password with the sfdx utility . | 282 | 12 |
227,702 | def _convert_connected_app ( self ) : if self . services and "connected_app" in self . services : # already a service return connected_app = self . get_connected_app ( ) if not connected_app : # not configured return self . logger . warning ( "Reading Connected App info from deprecated config." " Connected App should be changed to a service." " If using environment keychain, update the environment variable." " Otherwise, it has been handled automatically and you should not" " see this message again." ) ca_config = ServiceConfig ( { "callback_url" : connected_app . callback_url , "client_id" : connected_app . client_id , "client_secret" : connected_app . client_secret , } ) self . set_service ( "connected_app" , ca_config ) | Convert Connected App to service | 182 | 7 |
227,703 | def _load_scratch_orgs ( self ) : current_orgs = self . list_orgs ( ) if not self . project_config . orgs__scratch : return for config_name in self . project_config . orgs__scratch . keys ( ) : if config_name in current_orgs : # Don't overwrite an existing keychain org continue self . create_scratch_org ( config_name , config_name ) | Creates all scratch org configs for the project in the keychain if a keychain org doesn t already exist | 99 | 23 |
227,704 | def change_key ( self , key ) : services = { } for service_name in self . list_services ( ) : services [ service_name ] = self . get_service ( service_name ) orgs = { } for org_name in self . list_orgs ( ) : orgs [ org_name ] = self . get_org ( org_name ) self . key = key if orgs : for org_name , org_config in list ( orgs . items ( ) ) : self . set_org ( org_config ) if services : for service_name , service_config in list ( services . items ( ) ) : self . set_service ( service_name , service_config ) self . _convert_connected_app ( ) | re - encrypt stored services and orgs with the new key | 165 | 12 |
227,705 | def get_default_org ( self ) : for org in self . list_orgs ( ) : org_config = self . get_org ( org ) if org_config . default : return org , org_config return None , None | retrieve the name and configuration of the default org | 51 | 10 |
227,706 | def set_default_org ( self , name ) : org = self . get_org ( name ) self . unset_default_org ( ) org . config [ "default" ] = True self . set_org ( org ) | set the default org for tasks by name key | 50 | 9 |
227,707 | def unset_default_org ( self ) : for org in self . list_orgs ( ) : org_config = self . get_org ( org ) if org_config . default : del org_config . config [ "default" ] self . set_org ( org_config ) | unset the default orgs for tasks | 63 | 8 |
227,708 | def get_org ( self , name ) : if name not in self . orgs : self . _raise_org_not_found ( name ) return self . _get_org ( name ) | retrieve an org configuration by name key | 42 | 8 |
227,709 | def list_orgs ( self ) : orgs = list ( self . orgs . keys ( ) ) orgs . sort ( ) return orgs | list the orgs configured in the keychain | 32 | 9 |
227,710 | def set_service ( self , name , service_config , project = False ) : if not self . project_config . services or name not in self . project_config . services : self . _raise_service_not_valid ( name ) self . _validate_service ( name , service_config ) self . _set_service ( name , service_config , project ) self . _load_services ( ) | Store a ServiceConfig in the keychain | 89 | 8 |
227,711 | def get_service ( self , name ) : self . _convert_connected_app ( ) if not self . project_config . services or name not in self . project_config . services : self . _raise_service_not_valid ( name ) if name not in self . services : self . _raise_service_not_configured ( name ) return self . _get_service ( name ) | Retrieve a stored ServiceConfig from the keychain or exception | 87 | 12 |
227,712 | def list_services ( self ) : services = list ( self . services . keys ( ) ) services . sort ( ) return services | list the services configured in the keychain | 27 | 8 |
227,713 | def set_pdb_trace ( pm = False ) : import sys import pdb for attr in ( "stdin" , "stdout" , "stderr" ) : setattr ( sys , attr , getattr ( sys , "__%s__" % attr ) ) if pm : # Post-mortem debugging of an exception pdb . post_mortem ( ) else : pdb . set_trace ( ) | Start the Python debugger when robotframework is running . | 93 | 10 |
227,714 | def selenium_retry ( target = None , retry = True ) : if isinstance ( target , bool ) : # Decorator was called with a single boolean argument retry = target target = None def decorate ( target ) : if isinstance ( target , type ) : cls = target # Metaclass time. # We're going to generate a new subclass that: # a) mixes in RetryingSeleniumLibraryMixin # b) sets the initial value of `retry_selenium` return type ( cls . __name__ , ( cls , RetryingSeleniumLibraryMixin ) , { "retry_selenium" : retry , "__doc__" : cls . __doc__ } , ) func = target @ functools . wraps ( func ) def run_with_retry ( self , * args , * * kwargs ) : # Set the retry setting and run the original function. old_retry = self . retry_selenium self . retry = retry try : return func ( self , * args , * * kwargs ) finally : # Restore the previous value self . retry_selenium = old_retry set_pdb_trace ( ) run_with_retry . is_selenium_retry_decorator = True return run_with_retry if target is None : # Decorator is being used with arguments return decorate else : # Decorator was used without arguments return decorate ( target ) | Decorator to turn on automatic retries of flaky selenium failures . | 325 | 17 |
227,715 | def selenium_execute_with_retry ( self , execute , command , params ) : try : return execute ( command , params ) except Exception as e : if isinstance ( e , ALWAYS_RETRY_EXCEPTIONS ) or ( isinstance ( e , WebDriverException ) and "Other element would receive the click" in str ( e ) ) : # Retry self . builtin . log ( "Retrying {} command" . format ( command ) , level = "WARN" ) time . sleep ( 2 ) return execute ( command , params ) else : raise | Run a single selenium command and retry once . | 121 | 12 |
227,716 | def _get_last_tag ( self ) : current_version = LooseVersion ( self . _get_version_from_tag ( self . release_notes_generator . current_tag ) ) versions = [ ] for tag in self . repo . tags ( ) : if not tag . name . startswith ( self . github_info [ "prefix_prod" ] ) : continue version = LooseVersion ( self . _get_version_from_tag ( tag . name ) ) if version >= current_version : continue versions . append ( version ) if versions : versions . sort ( ) return "{}{}" . format ( self . github_info [ "prefix_prod" ] , versions [ - 1 ] ) | Gets the last release tag before self . current_tag | 156 | 12 |
227,717 | def _get_pull_requests ( self ) : for pull in self . repo . pull_requests ( state = "closed" , base = self . github_info [ "master_branch" ] , direction = "asc" ) : if self . _include_pull_request ( pull ) : yield pull | Gets all pull requests from the repo since we can t do a filtered date merged search | 68 | 18 |
227,718 | def _include_pull_request ( self , pull_request ) : merged_date = pull_request . merged_at if not merged_date : return False if self . last_tag : last_tag_sha = self . last_tag_info [ "commit" ] . sha if pull_request . merge_commit_sha == last_tag_sha : # Github commit dates can be different from the merged_at date return False current_tag_sha = self . current_tag_info [ "commit" ] . sha if pull_request . merge_commit_sha == current_tag_sha : return True # include PRs before current tag if merged_date <= self . start_date : if self . end_date : # include PRs after last tag if ( merged_date > self . end_date and pull_request . merge_commit_sha != last_tag_sha ) : return True else : # no last tag, include all PRs before current tag return True return False | Checks if the given pull_request was merged to the default branch between self . start_date and self . end_date | 215 | 26 |
227,719 | def patch_statusreporter ( ) : from robot . running . statusreporter import StatusReporter orig_exit = StatusReporter . __exit__ def __exit__ ( self , exc_type , exc_val , exc_tb ) : if exc_val and isinstance ( exc_val , Exception ) : set_pdb_trace ( pm = True ) return orig_exit ( self , exc_type , exc_val , exc_tb ) StatusReporter . __exit__ = __exit__ | Monkey patch robotframework to do postmortem debugging | 110 | 10 |
227,720 | def get_item_name ( self , item , parent ) : names = self . get_name_elements ( item ) if not names : raise MissingNameElementError name = names [ 0 ] . text prefix = self . item_name_prefix ( parent ) if prefix : name = prefix + name return name | Returns the value of the first name element found inside of element | 66 | 12 |
227,721 | def for_display ( self ) : skip = "" if self . skip : skip = " [SKIP]" result = "{step_num}: {path}{skip}" . format ( step_num = self . step_num , path = self . path , skip = skip ) description = self . task_config . get ( "description" ) if description : result += ": {}" . format ( description ) return result | Step details formatted for logging output . | 88 | 7 |
227,722 | def run_step ( self ) : # Resolve ^^task_name.return_value style option syntax task_config = self . step . task_config . copy ( ) task_config [ "options" ] = task_config [ "options" ] . copy ( ) self . flow . resolve_return_value_options ( task_config [ "options" ] ) exc = None try : task = self . step . task_class ( self . project_config , TaskConfig ( task_config ) , org_config = self . org_config , name = self . step . task_name , stepnum = self . step . step_num , flow = self . flow , ) self . _log_options ( task ) task ( ) except Exception as e : self . flow . logger . exception ( "Exception in task {}" . format ( self . step . task_name ) ) exc = e return StepResult ( self . step . step_num , self . step . task_name , self . step . path , task . result , task . return_values , exc , ) | Run a step . | 232 | 4 |
227,723 | def _init_steps ( self , ) : self . _check_old_yaml_format ( ) config_steps = self . flow_config . steps self . _check_infinite_flows ( config_steps ) steps = [ ] for number , step_config in config_steps . items ( ) : specs = self . _visit_step ( number , step_config ) steps . extend ( specs ) return sorted ( steps , key = attrgetter ( "step_num" ) ) | Given the flow config and everything else create a list of steps to run sorted by step number . | 108 | 19 |
227,724 | def _check_infinite_flows ( self , steps , flows = None ) : if flows is None : flows = [ ] for step in steps . values ( ) : if "flow" in step : flow = step [ "flow" ] if flow == "None" : continue if flow in flows : raise FlowInfiniteLoopError ( "Infinite flows detected with flow {}" . format ( flow ) ) flows . append ( flow ) flow_config = self . project_config . get_flow ( flow ) self . _check_infinite_flows ( flow_config . steps , flows ) | Recursively loop through the flow_config and check if there are any cycles . | 126 | 17 |
227,725 | def _init_org ( self ) : self . logger . info ( "Verifying and refreshing credentials for the specified org: {}." . format ( self . org_config . name ) ) orig_config = self . org_config . config . copy ( ) # attempt to refresh the token, this can throw... self . org_config . refresh_oauth_token ( self . project_config . keychain ) if self . org_config . config != orig_config : self . logger . info ( "Org info has changed, updating org in keychain" ) self . project_config . keychain . set_org ( self . org_config ) | Test and refresh credentials to the org specified . | 139 | 9 |
227,726 | def resolve_return_value_options ( self , options ) : for key , value in options . items ( ) : if isinstance ( value , str ) and value . startswith ( RETURN_VALUE_OPTION_PREFIX ) : path , name = value [ len ( RETURN_VALUE_OPTION_PREFIX ) : ] . rsplit ( "." , 1 ) result = self . _find_result_by_path ( path ) options [ key ] = result . return_values . get ( name ) | Handle dynamic option value lookups in the format ^^task_name . attr | 114 | 17 |
227,727 | def init_logger ( log_requests = False ) : logger = logging . getLogger ( __name__ . split ( "." ) [ 0 ] ) for handler in logger . handlers : # pragma: nocover logger . removeHandler ( handler ) formatter = coloredlogs . ColoredFormatter ( fmt = "%(asctime)s: %(message)s" ) handler = logging . StreamHandler ( ) handler . setLevel ( logging . DEBUG ) handler . setFormatter ( formatter ) logger . addHandler ( handler ) logger . setLevel ( logging . DEBUG ) logger . propagate = False if log_requests : requests . packages . urllib3 . add_stderr_logger ( ) | Initialize the logger | 157 | 4 |
227,728 | def register_new_node ( suffix_node_id = None ) : node_id = uuid4 ( ) event = Node . Created ( originator_id = node_id , suffix_node_id = suffix_node_id ) entity = Node . mutate ( event = event ) publish ( event ) return entity | Factory method registers new node . | 69 | 6 |
227,729 | def register_new_edge ( edge_id , first_char_index , last_char_index , source_node_id , dest_node_id ) : event = Edge . Created ( originator_id = edge_id , first_char_index = first_char_index , last_char_index = last_char_index , source_node_id = source_node_id , dest_node_id = dest_node_id , ) entity = Edge . mutate ( event = event ) publish ( event ) return entity | Factory method registers new edge . | 117 | 6 |
227,730 | def register_new_suffix_tree ( case_insensitive = False ) : assert isinstance ( case_insensitive , bool ) root_node = register_new_node ( ) suffix_tree_id = uuid4 ( ) event = SuffixTree . Created ( originator_id = suffix_tree_id , root_node_id = root_node . id , case_insensitive = case_insensitive , ) entity = SuffixTree . mutate ( event = event ) assert isinstance ( entity , SuffixTree ) entity . nodes [ root_node . id ] = root_node publish ( event ) return entity | Factory method returns new suffix tree object . | 136 | 8 |
227,731 | def find_substring ( substring , suffix_tree , edge_repo ) : assert isinstance ( substring , str ) assert isinstance ( suffix_tree , SuffixTree ) assert isinstance ( edge_repo , EventSourcedRepository ) if not substring : return - 1 if suffix_tree . case_insensitive : substring = substring . lower ( ) curr_node_id = suffix_tree . root_node_id i = 0 while i < len ( substring ) : edge_id = make_edge_id ( curr_node_id , substring [ i ] ) try : edge = edge_repo [ edge_id ] except RepositoryKeyError : return - 1 ln = min ( edge . length + 1 , len ( substring ) - i ) if substring [ i : i + ln ] != suffix_tree . string [ edge . first_char_index : edge . first_char_index + ln ] : return - 1 i += edge . length + 1 curr_node_id = edge . dest_node_id return edge . first_char_index - len ( substring ) + ln | Returns the index if substring in tree otherwise - 1 . | 253 | 12 |
227,732 | def _add_prefix ( self , last_char_index ) : last_parent_node_id = None while True : parent_node_id = self . active . source_node_id if self . active . explicit ( ) : edge_id = make_edge_id ( self . active . source_node_id , self . string [ last_char_index ] ) if edge_id in self . edges : # prefix is already in tree break else : edge_id = make_edge_id ( self . active . source_node_id , self . string [ self . active . first_char_index ] ) e = self . edges [ edge_id ] if self . string [ e . first_char_index + self . active . length + 1 ] == self . string [ last_char_index ] : # prefix is already in tree break parent_node_id = self . _split_edge ( e , self . active ) node = register_new_node ( ) self . nodes [ node . id ] = node edge_id = make_edge_id ( parent_node_id , self . string [ last_char_index ] ) e = register_new_edge ( edge_id = edge_id , first_char_index = last_char_index , last_char_index = self . N , source_node_id = parent_node_id , dest_node_id = node . id , ) self . _insert_edge ( e ) if last_parent_node_id is not None : self . nodes [ last_parent_node_id ] . suffix_node_id = parent_node_id last_parent_node_id = parent_node_id if self . active . source_node_id == self . root_node_id : self . active . first_char_index += 1 else : self . active . source_node_id = self . nodes [ self . active . source_node_id ] . suffix_node_id self . _canonize_suffix ( self . active ) if last_parent_node_id is not None : self . nodes [ last_parent_node_id ] . suffix_node_id = parent_node_id self . active . last_char_index += 1 self . _canonize_suffix ( self . active ) | The core construction method . | 504 | 5 |
227,733 | def _canonize_suffix ( self , suffix ) : if not suffix . explicit ( ) : edge_id = make_edge_id ( suffix . source_node_id , self . string [ suffix . first_char_index ] ) e = self . edges [ edge_id ] if e . length <= suffix . length : suffix . first_char_index += e . length + 1 suffix . source_node_id = e . dest_node_id self . _canonize_suffix ( suffix ) | This canonizes the suffix walking along its suffix string until it is explicit or there are no more matched nodes . | 110 | 22 |
227,734 | def entity_from_snapshot ( snapshot ) : assert isinstance ( snapshot , AbstractSnapshop ) , type ( snapshot ) if snapshot . state is not None : entity_class = resolve_topic ( snapshot . topic ) return reconstruct_object ( entity_class , snapshot . state ) | Reconstructs domain entity from given snapshot . | 59 | 10 |
227,735 | def get_snapshot ( self , entity_id , lt = None , lte = None ) : snapshots = self . snapshot_store . get_domain_events ( entity_id , lt = lt , lte = lte , limit = 1 , is_ascending = False ) if len ( snapshots ) == 1 : return snapshots [ 0 ] | Gets the last snapshot for entity optionally until a particular version number . | 77 | 14 |
227,736 | def take_snapshot ( self , entity_id , entity , last_event_version ) : # Create the snapshot. snapshot = Snapshot ( originator_id = entity_id , originator_version = last_event_version , topic = get_topic ( entity . __class__ ) , state = None if entity is None else deepcopy ( entity . __dict__ ) ) self . snapshot_store . store ( snapshot ) # Return the snapshot. return snapshot | Creates a Snapshot from the given state and appends it to the snapshot store . | 99 | 18 |
227,737 | def get_entity ( self , entity_id , at = None ) : # Get a snapshot (None if none exist). if self . _snapshot_strategy is not None : snapshot = self . _snapshot_strategy . get_snapshot ( entity_id , lte = at ) else : snapshot = None # Decide the initial state of the entity, and the # version of the last item applied to the entity. if snapshot is None : initial_state = None gt = None else : initial_state = entity_from_snapshot ( snapshot ) gt = snapshot . originator_version # Obtain and return current state. return self . get_and_project_events ( entity_id , gt = gt , lte = at , initial_state = initial_state ) | Returns entity with given ID optionally until position . | 172 | 9 |
227,738 | def get_and_project_events ( self , entity_id , gt = None , gte = None , lt = None , lte = None , limit = None , initial_state = None , query_descending = False ) : # Decide if query is in ascending order. # - A "speed up" for when events are stored in descending order (e.g. # in Cassandra) and it is faster to get them in that order. # - This isn't useful when 'until' or 'after' or 'limit' are set, # because the inclusiveness or exclusiveness of until and after # and the end of the stream that is truncated by limit both depend on # the direction of the query. Also paging backwards isn't useful, because # all the events are needed eventually, so it would probably slow things # down. Paging is intended to support replaying longer event streams, and # only makes sense to work in ascending order. if gt is None and gte is None and lt is None and lte is None and self . __page_size__ is None : is_ascending = False else : is_ascending = not query_descending # Get entity's domain events from the event store. domain_events = self . event_store . get_domain_events ( originator_id = entity_id , gt = gt , gte = gte , lt = lt , lte = lte , limit = limit , is_ascending = is_ascending , page_size = self . __page_size__ ) # The events will be replayed in ascending order. if not is_ascending : domain_events = list ( reversed ( list ( domain_events ) ) ) # Project the domain events onto the initial state. return self . project_events ( initial_state , domain_events ) | Reconstitutes requested domain entity from domain events found in event store . | 398 | 15 |
227,739 | def take_snapshot ( self , entity_id , lt = None , lte = None ) : snapshot = None if self . _snapshot_strategy : # Get the latest event (optionally until a particular position). latest_event = self . event_store . get_most_recent_event ( entity_id , lt = lt , lte = lte ) # If there is something to snapshot, then look for a snapshot # taken before or at the entity version of the latest event. Please # note, the snapshot might have a smaller version number than # the latest event if events occurred since the latest snapshot was taken. if latest_event is not None : latest_snapshot = self . _snapshot_strategy . get_snapshot ( entity_id , lt = lt , lte = lte ) latest_version = latest_event . originator_version if latest_snapshot and latest_snapshot . originator_version == latest_version : # If up-to-date snapshot exists, there's nothing to do. snapshot = latest_snapshot else : # Otherwise recover entity state from latest snapshot. if latest_snapshot : initial_state = entity_from_snapshot ( latest_snapshot ) gt = latest_snapshot . originator_version else : initial_state = None gt = None # Fast-forward entity state to latest version. entity = self . get_and_project_events ( entity_id = entity_id , gt = gt , lte = latest_version , initial_state = initial_state , ) # Take snapshot from entity. snapshot = self . _snapshot_strategy . take_snapshot ( entity_id , entity , latest_version ) return snapshot | Takes a snapshot of the entity as it existed after the most recent event optionally less than or less than or equal to a particular position . | 375 | 28 |
227,740 | def create_new_example ( self , foo = '' , a = '' , b = '' ) : return create_new_example ( foo = foo , a = a , b = b ) | Entity object factory . | 41 | 4 |
227,741 | def timestamp_long_from_uuid ( uuid_arg ) : if isinstance ( uuid_arg , str ) : uuid_arg = UUID ( uuid_arg ) assert isinstance ( uuid_arg , UUID ) , uuid_arg uuid_time = uuid_arg . time return uuid_time - 0x01B21DD213814000 | Returns an integer value representing a unix timestamp in tenths of microseconds . | 85 | 16 |
227,742 | def subscribe_to ( * event_classes ) : event_classes = list ( event_classes ) def wrap ( func ) : def handler ( event ) : if isinstance ( event , ( list , tuple ) ) : for e in event : handler ( e ) elif not event_classes or isinstance ( event , tuple ( event_classes ) ) : func ( event ) subscribe ( handler = handler , predicate = lambda _ : True ) return func if len ( event_classes ) == 1 and isfunction ( event_classes [ 0 ] ) : func = event_classes . pop ( ) return wrap ( func ) else : return wrap | Decorator for making a custom event handler function subscribe to a certain class of event . | 133 | 18 |
227,743 | def mutator ( arg = None ) : domain_class = None def _mutator ( func ) : wrapped = singledispatch ( func ) @ wraps ( wrapped ) def wrapper ( initial , event ) : initial = initial or domain_class return wrapped . dispatch ( type ( event ) ) ( initial , event ) wrapper . register = wrapped . register return wrapper if isfunction ( arg ) : return _mutator ( arg ) else : domain_class = arg return _mutator | Structures mutator functions by allowing handlers to be registered for different types of event . When the decorated function is called with an initial value and an event it will call the handler that has been registered for that type of event . | 99 | 45 |
227,744 | def encrypt ( self , plaintext ) : # String to bytes. plainbytes = plaintext . encode ( 'utf8' ) # Compress plaintext bytes. compressed = zlib . compress ( plainbytes ) # Construct AES-GCM cipher, with 96-bit nonce. cipher = AES . new ( self . cipher_key , AES . MODE_GCM , nonce = random_bytes ( 12 ) ) # Encrypt and digest. encrypted , tag = cipher . encrypt_and_digest ( compressed ) # Combine with nonce. combined = cipher . nonce + tag + encrypted # Encode as Base64. cipherbytes = base64 . b64encode ( combined ) # Bytes to string. ciphertext = cipherbytes . decode ( 'utf8' ) # Return ciphertext. return ciphertext | Return ciphertext for given plaintext . | 173 | 8 |
227,745 | def decrypt ( self , ciphertext ) : # String to bytes. cipherbytes = ciphertext . encode ( 'utf8' ) # Decode from Base64. try : combined = base64 . b64decode ( cipherbytes ) except ( base64 . binascii . Error , TypeError ) as e : # base64.binascii.Error for Python 3. # TypeError for Python 2. raise DataIntegrityError ( "Cipher text is damaged: {}" . format ( e ) ) # Split out the nonce, tag, and encrypted data. nonce = combined [ : 12 ] if len ( nonce ) != 12 : raise DataIntegrityError ( "Cipher text is damaged: invalid nonce length" ) tag = combined [ 12 : 28 ] if len ( tag ) != 16 : raise DataIntegrityError ( "Cipher text is damaged: invalid tag length" ) encrypted = combined [ 28 : ] # Construct AES cipher, with old nonce. cipher = AES . new ( self . cipher_key , AES . MODE_GCM , nonce ) # Decrypt and verify. try : compressed = cipher . decrypt_and_verify ( encrypted , tag ) except ValueError as e : raise DataIntegrityError ( "Cipher text is damaged: {}" . format ( e ) ) # Decompress plaintext bytes. plainbytes = zlib . decompress ( compressed ) # Bytes to string. plaintext = plainbytes . decode ( 'utf8' ) # Return plaintext. return plaintext | Return plaintext for given ciphertext . | 328 | 8 |
227,746 | def store ( self , domain_event_or_events ) : # Convert to sequenced item. sequenced_item_or_items = self . item_from_event ( domain_event_or_events ) # Append to the sequenced item(s) to the sequence. try : self . record_manager . record_sequenced_items ( sequenced_item_or_items ) except RecordConflictError as e : raise ConcurrencyError ( e ) | Appends given domain event or list of domain events to their sequence . | 100 | 14 |
227,747 | def item_from_event ( self , domain_event_or_events ) : # Convert the domain event(s) to sequenced item(s). if isinstance ( domain_event_or_events , ( list , tuple ) ) : return [ self . item_from_event ( e ) for e in domain_event_or_events ] else : return self . mapper . item_from_event ( domain_event_or_events ) | Maps domain event to sequenced item namedtuple . | 97 | 11 |
227,748 | def get_domain_events ( self , originator_id , gt = None , gte = None , lt = None , lte = None , limit = None , is_ascending = True , page_size = None ) : if page_size : sequenced_items = self . iterator_class ( record_manager = self . record_manager , sequence_id = originator_id , page_size = page_size , gt = gt , gte = gte , lt = lt , lte = lte , limit = limit , is_ascending = is_ascending , ) else : sequenced_items = self . record_manager . get_items ( sequence_id = originator_id , gt = gt , gte = gte , lt = lt , lte = lte , limit = limit , query_ascending = is_ascending , results_ascending = is_ascending , ) # Deserialize to domain events. domain_events = map ( self . mapper . event_from_item , sequenced_items ) return list ( domain_events ) | Gets domain events from the sequence identified by originator_id . | 246 | 14 |
227,749 | def get_domain_event ( self , originator_id , position ) : sequenced_item = self . record_manager . get_item ( sequence_id = originator_id , position = position , ) return self . mapper . event_from_item ( sequenced_item ) | Gets a domain event from the sequence identified by originator_id at position eq . | 63 | 18 |
227,750 | def get_most_recent_event ( self , originator_id , lt = None , lte = None ) : events = self . get_domain_events ( originator_id = originator_id , lt = lt , lte = lte , limit = 1 , is_ascending = False ) events = list ( events ) try : return events [ 0 ] except IndexError : pass | Gets a domain event from the sequence identified by originator_id at the highest position . | 88 | 19 |
227,751 | def all_domain_events ( self ) : for originator_id in self . record_manager . all_sequence_ids ( ) : for domain_event in self . get_domain_events ( originator_id = originator_id , page_size = 100 ) : yield domain_event | Yields all domain events in the event store . | 64 | 11 |
227,752 | def publish_prompt ( self , event = None ) : prompt = Prompt ( self . name , self . pipeline_id ) try : publish ( prompt ) except PromptFailed : raise except Exception as e : raise PromptFailed ( "{}: {}" . format ( type ( e ) , str ( e ) ) ) | Publishes prompt for a given event . | 67 | 8 |
227,753 | def _prepare_insert ( self , tmpl , record_class , field_names , placeholder_for_id = False ) : field_names = list ( field_names ) if hasattr ( record_class , 'application_name' ) and 'application_name' not in field_names : field_names . append ( 'application_name' ) if hasattr ( record_class , 'pipeline_id' ) and 'pipeline_id' not in field_names : field_names . append ( 'pipeline_id' ) if hasattr ( record_class , 'causal_dependencies' ) and 'causal_dependencies' not in field_names : field_names . append ( 'causal_dependencies' ) if placeholder_for_id : if self . notification_id_name : if self . notification_id_name not in field_names : field_names . append ( 'id' ) statement = tmpl . format ( tablename = self . get_record_table_name ( record_class ) , columns = ", " . join ( field_names ) , placeholders = ", " . join ( [ '%s' for _ in field_names ] ) , notification_id = self . notification_id_name ) return statement | With transaction isolation level of read committed this should generate records with a contiguous sequence of integer IDs using an indexed ID column the database - side SQL max function the insert - select - from form and optimistic concurrency control . | 281 | 43 |
227,754 | def get_notifications ( self , start = None , stop = None , * args , * * kwargs ) : filter_kwargs = { } # Todo: Also support sequencing by 'position' if items are sequenced by timestamp? if start is not None : filter_kwargs [ '%s__gte' % self . notification_id_name ] = start + 1 if stop is not None : filter_kwargs [ '%s__lt' % self . notification_id_name ] = stop + 1 objects = self . record_class . objects . filter ( * * filter_kwargs ) if hasattr ( self . record_class , 'application_name' ) : objects = objects . filter ( application_name = self . application_name ) if hasattr ( self . record_class , 'pipeline_id' ) : objects = objects . filter ( pipeline_id = self . pipeline_id ) objects = objects . order_by ( '%s' % self . notification_id_name ) return objects . all ( ) | Returns all records in the table . | 227 | 7 |
227,755 | def start ( self ) : # Subscribe to broadcast prompts published by a process # application in the parent operating system process. subscribe ( handler = self . forward_prompt , predicate = self . is_prompt ) # Initialise the system actor. msg = SystemInitRequest ( self . system . process_classes , self . infrastructure_class , self . system . followings , self . pipeline_ids ) response = self . actor_system . ask ( self . system_actor , msg ) # Keep the pipeline actor addresses, to send prompts directly. assert isinstance ( response , SystemInitResponse ) , type ( response ) assert list ( response . pipeline_actors . keys ( ) ) == self . pipeline_ids , ( "Configured pipeline IDs mismatch initialised system {} {}" ) . format ( list ( self . pipeline_actors . keys ( ) ) , self . pipeline_ids ) self . pipeline_actors = response . pipeline_actors | Starts all the actors to run a system of process applications . | 200 | 13 |
227,756 | def close ( self ) : super ( ActorModelRunner , self ) . close ( ) unsubscribe ( handler = self . forward_prompt , predicate = self . is_prompt ) if self . shutdown_on_close : self . shutdown ( ) | Stops all the actors running a system of process applications . | 53 | 12 |
227,757 | def register_new_suffix_tree ( self , case_insensitive = False ) : suffix_tree = register_new_suffix_tree ( case_insensitive = case_insensitive ) suffix_tree . _node_repo = self . node_repo suffix_tree . _node_child_collection_repo = self . node_child_collection_repo suffix_tree . _edge_repo = self . edge_repo suffix_tree . _stringid_collection_repo = self . stringid_collection_repo return suffix_tree | Returns a new suffix tree entity . | 125 | 7 |
227,758 | def find_string_ids ( self , substring , suffix_tree_id , limit = None ) : # Find an edge for the substring. edge , ln = self . find_substring_edge ( substring = substring , suffix_tree_id = suffix_tree_id ) # If there isn't an edge, return an empty set. if edge is None : return set ( ) # Get all the string IDs beneath the edge's destination node. string_ids = get_string_ids ( node_id = edge . dest_node_id , node_repo = self . node_repo , node_child_collection_repo = self . node_child_collection_repo , stringid_collection_repo = self . stringid_collection_repo , length_until_end = edge . length + 1 - ln , limit = limit ) # Return a set of string IDs. return set ( string_ids ) | Returns a set of IDs for strings that contain the given substring . | 205 | 14 |
227,759 | def find_substring_edge ( self , substring , suffix_tree_id ) : suffix_tree = self . suffix_tree_repo [ suffix_tree_id ] started = datetime . datetime . now ( ) edge , ln = find_substring_edge ( substring = substring , suffix_tree = suffix_tree , edge_repo = self . edge_repo ) # if edge is not None: # print("Got edge for substring '{}': {}".format(substring, edge)) # else: # print("No edge for substring '{}'".format(substring)) print ( " - searched for edge in {} for substring: '{}'" . format ( datetime . datetime . now ( ) - started , substring ) ) return edge , ln | Returns an edge that matches the given substring . | 178 | 10 |
227,760 | def run_followers ( self , prompt ) : assert isinstance ( prompt , Prompt ) # Put the prompt on the queue. self . pending_prompts . put ( prompt ) if self . iteration_lock . acquire ( False ) : start_time = time . time ( ) i = 0 try : while True : try : prompt = self . pending_prompts . get ( False ) except Empty : break else : followers = self . system . followers [ prompt . process_name ] for follower_name in followers : follower = self . system . processes [ follower_name ] follower . run ( prompt ) i += 1 self . pending_prompts . task_done ( ) finally : run_frequency = i / ( time . time ( ) - start_time ) # print(f"Run frequency: {run_frequency}") self . iteration_lock . release ( ) | First caller adds a prompt to queue and runs followers until there are no more pending prompts . | 187 | 18 |
227,761 | def create_new_example ( foo = '' , a = '' , b = '' ) : return Example . __create__ ( foo = foo , a = a , b = b ) | Factory method for example entities . | 39 | 6 |
227,762 | def applicationpolicy ( arg = None ) : def _mutator ( func ) : wrapped = singledispatch ( func ) @ wraps ( wrapped ) def wrapper ( * args , * * kwargs ) : event = kwargs . get ( 'event' ) or args [ - 1 ] return wrapped . dispatch ( type ( event ) ) ( * args , * * kwargs ) wrapper . register = wrapped . register return wrapper assert isfunction ( arg ) , arg return _mutator ( arg ) | Decorator for application policy method . | 105 | 8 |
227,763 | def _prepare_insert ( self , tmpl , record_class , field_names , placeholder_for_id = False ) : field_names = list ( field_names ) if hasattr ( record_class , 'application_name' ) and 'application_name' not in field_names : field_names . append ( 'application_name' ) if hasattr ( record_class , 'pipeline_id' ) and 'pipeline_id' not in field_names : field_names . append ( 'pipeline_id' ) if hasattr ( record_class , 'causal_dependencies' ) and 'causal_dependencies' not in field_names : field_names . append ( 'causal_dependencies' ) if self . notification_id_name : if placeholder_for_id : if self . notification_id_name not in field_names : field_names . append ( self . notification_id_name ) statement = text ( tmpl . format ( tablename = self . get_record_table_name ( record_class ) , columns = ", " . join ( field_names ) , placeholders = ", " . join ( [ ":{}" . format ( f ) for f in field_names ] ) , notification_id = self . notification_id_name ) ) # Define bind parameters with explicit types taken from record column types. bindparams = [ ] for col_name in field_names : column_type = getattr ( record_class , col_name ) . type bindparams . append ( bindparam ( col_name , type_ = column_type ) ) # Redefine statement with explicitly typed bind parameters. statement = statement . bindparams ( * bindparams ) # Compile the statement with the session dialect. compiled = statement . compile ( dialect = self . session . bind . dialect ) return compiled | With transaction isolation level of read committed this should generate records with a contiguous sequence of integer IDs assumes an indexed ID column the database - side SQL max function the insert - select - from form and optimistic concurrency control . | 405 | 43 |
227,764 | def delete_record ( self , record ) : try : self . session . delete ( record ) self . session . commit ( ) except Exception as e : self . session . rollback ( ) raise ProgrammingError ( e ) finally : self . session . close ( ) | Permanently removes record from table . | 55 | 8 |
227,765 | def get_or_create ( self , log_name , bucket_size ) : try : return self [ log_name ] except RepositoryKeyError : return start_new_timebucketedlog ( log_name , bucket_size = bucket_size ) | Gets or creates a log . | 56 | 7 |
227,766 | def project_events ( self , initial_state , domain_events ) : return reduce ( self . _mutator_func or self . mutate , domain_events , initial_state ) | Evolves initial state using the sequence of domain events and a mutator function . | 40 | 16 |
227,767 | def get_last_array ( self ) : # Get the root array (might not have been registered). root = self . repo [ self . id ] # Get length and last item in the root array. apex_id , apex_height = root . get_last_item_and_next_position ( ) # Bail if there isn't anything yet. if apex_id is None : return None , None # Get the current apex array. apex = self . repo [ apex_id ] assert isinstance ( apex , Array ) # Descend until hitting the bottom. array = apex array_i = 0 height = apex_height while height > 1 : height -= 1 array_id , width = array . get_last_item_and_next_position ( ) assert width > 0 offset = width - 1 array_i += offset * self . repo . array_size ** height array = self . repo [ array_id ] return array , array_i | Returns last array in compound . | 202 | 6 |
227,768 | def calc_parent ( self , i , j , h ) : N = self . repo . array_size c_i = i c_j = j c_h = h # Calculate the number of the sequence in its row (sequences # with same height), from left to right, starting from 0. c_n = c_i // ( N ** c_h ) p_n = c_n // N # Position of the child ID in the parent array. p_p = c_n % N # Parent height is child height plus one. p_h = c_h + 1 # Span of sequences in parent row is max size N, to the power of the height. span = N ** p_h # Calculate parent i and j. p_i = p_n * span p_j = p_i + span # Check the parent i,j bounds the child i,j, ie child span is contained by parent span. assert p_i <= c_i , 'i greater on parent than child: {}' . format ( p_i , p_j ) assert p_j >= c_j , 'j less on parent than child: {}' . format ( p_i , p_j ) # Return parent i, j, h, p. return p_i , p_j , p_h , p_p | Returns get_big_array and end of span of parent sequence that contains given child . | 290 | 18 |
227,769 | def item_from_event ( self , domain_event ) : item_args = self . construct_item_args ( domain_event ) return self . construct_sequenced_item ( item_args ) | Constructs a sequenced item from a domain event . | 44 | 11 |
227,770 | def construct_item_args ( self , domain_event ) : # Get the sequence ID. sequence_id = domain_event . __dict__ [ self . sequence_id_attr_name ] # Get the position in the sequence. position = getattr ( domain_event , self . position_attr_name , None ) # Get topic and data. topic , state = self . get_item_topic_and_state ( domain_event . __class__ , domain_event . __dict__ ) # Get the 'other' args. # - these are meant to be derivative of the other attributes, # to populate database fields, and shouldn't affect the hash. other_args = tuple ( ( getattr ( domain_event , name ) for name in self . other_attr_names ) ) return ( sequence_id , position , topic , state ) + other_args | Constructs attributes of a sequenced item from the given domain event . | 185 | 14 |
227,771 | def event_from_item ( self , sequenced_item ) : assert isinstance ( sequenced_item , self . sequenced_item_class ) , ( self . sequenced_item_class , type ( sequenced_item ) ) # Get the topic and state. topic = getattr ( sequenced_item , self . field_names . topic ) state = getattr ( sequenced_item , self . field_names . state ) return self . event_from_topic_and_state ( topic , state ) | Reconstructs domain event from stored event topic and event attrs . Used in the event store when getting domain events . | 112 | 25 |
227,772 | def get_item ( self , sequence_id , position ) : return self . from_record ( self . get_record ( sequence_id , position ) ) | Gets sequenced item from the datastore . | 34 | 11 |
227,773 | def get_items ( self , sequence_id , gt = None , gte = None , lt = None , lte = None , limit = None , query_ascending = True , results_ascending = True ) : records = self . get_records ( sequence_id = sequence_id , gt = gt , gte = gte , lt = lt , lte = lte , limit = limit , query_ascending = query_ascending , results_ascending = results_ascending , ) for item in map ( self . from_record , records ) : yield item | Returns sequenced item generator . | 132 | 6 |
227,774 | def to_record ( self , sequenced_item ) : kwargs = self . get_field_kwargs ( sequenced_item ) # Supply application_name, if needed. if hasattr ( self . record_class , 'application_name' ) : kwargs [ 'application_name' ] = self . application_name # Supply pipeline_id, if needed. if hasattr ( self . record_class , 'pipeline_id' ) : kwargs [ 'pipeline_id' ] = self . pipeline_id return self . record_class ( * * kwargs ) | Constructs a record object from given sequenced item object . | 132 | 12 |
227,775 | def from_record ( self , record ) : kwargs = self . get_field_kwargs ( record ) return self . sequenced_item_class ( * * kwargs ) | Constructs and returns a sequenced item object from given ORM object . | 41 | 15 |
227,776 | def get_pipeline_and_notification_id ( self , sequence_id , position ) : # Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)? record = self . get_record ( sequence_id , position ) notification_id = getattr ( record , self . notification_id_name ) return record . pipeline_id , notification_id | Returns pipeline ID and notification ID for event at given position in given sequence . | 87 | 15 |
227,777 | def insert_select_max ( self ) : if self . _insert_select_max is None : if hasattr ( self . record_class , 'application_name' ) : # Todo: Maybe make it support application_name without pipeline_id? assert hasattr ( self . record_class , 'pipeline_id' ) , self . record_class tmpl = self . _insert_select_max_tmpl + self . _where_application_name_tmpl else : tmpl = self . _insert_select_max_tmpl self . _insert_select_max = self . _prepare_insert ( tmpl = tmpl , record_class = self . record_class , field_names = list ( self . field_names ) , ) return self . _insert_select_max | SQL statement that inserts records with contiguous IDs by selecting max ID from indexed table records . | 181 | 17 |
227,778 | def insert_values ( self ) : if self . _insert_values is None : self . _insert_values = self . _prepare_insert ( tmpl = self . _insert_values_tmpl , placeholder_for_id = True , record_class = self . record_class , field_names = self . field_names , ) return self . _insert_values | SQL statement that inserts records without ID . | 83 | 8 |
227,779 | def insert_tracking_record ( self ) : if self . _insert_tracking_record is None : self . _insert_tracking_record = self . _prepare_insert ( tmpl = self . _insert_values_tmpl , placeholder_for_id = True , record_class = self . tracking_record_class , field_names = self . tracking_record_field_names , ) return self . _insert_tracking_record | SQL statement that inserts tracking records . | 97 | 7 |
227,780 | def start ( cls , originator_id , quorum_size , network_uid ) : assert isinstance ( quorum_size , int ) , "Not an integer: {}" . format ( quorum_size ) return cls . __create__ ( event_class = cls . Started , originator_id = originator_id , quorum_size = quorum_size , network_uid = network_uid ) | Factory method that returns a new Paxos aggregate . | 93 | 10 |
227,781 | def propose_value ( self , value , assume_leader = False ) : if value is None : raise ValueError ( "Not allowed to propose value None" ) paxos = self . paxos_instance paxos . leader = assume_leader msg = paxos . propose_value ( value ) if msg is None : msg = paxos . prepare ( ) self . setattrs_from_paxos ( paxos ) self . announce ( msg ) return msg | Proposes a value to the network . | 104 | 8 |
227,782 | def receive_message ( self , msg ) : if isinstance ( msg , Resolution ) : return paxos = self . paxos_instance while msg : if isinstance ( msg , Resolution ) : self . print_if_verbose ( "{} resolved value {}" . format ( self . network_uid , msg . value ) ) break else : self . print_if_verbose ( "{} <- {} <- {}" . format ( self . network_uid , msg . __class__ . __name__ , msg . from_uid ) ) msg = paxos . receive ( msg ) # Todo: Make it optional not to announce resolution (without which it's hard to see final value). do_announce_resolution = True if msg and ( do_announce_resolution or not isinstance ( msg , Resolution ) ) : self . announce ( msg ) self . setattrs_from_paxos ( paxos ) | Responds to messages from other participants . | 200 | 8 |
227,783 | def announce ( self , msg ) : self . print_if_verbose ( "{} -> {}" . format ( self . network_uid , msg . __class__ . __name__ ) ) self . __trigger_event__ ( event_class = self . MessageAnnounced , msg = msg , ) | Announces a Paxos message . | 65 | 7 |
227,784 | def setattrs_from_paxos ( self , paxos ) : changes = { } for name in self . paxos_variables : paxos_value = getattr ( paxos , name ) if paxos_value != getattr ( self , name , None ) : self . print_if_verbose ( "{} {}: {}" . format ( self . network_uid , name , paxos_value ) ) changes [ name ] = paxos_value setattr ( self , name , paxos_value ) if changes : self . __trigger_event__ ( event_class = self . AttributesChanged , changes = changes ) | Registers changes of attribute value on Paxos instance . | 146 | 11 |
227,785 | def propose_value ( self , key , value , assume_leader = False ) : assert isinstance ( key , UUID ) paxos_aggregate = PaxosAggregate . start ( originator_id = key , quorum_size = self . quorum_size , network_uid = self . name ) msg = paxos_aggregate . propose_value ( value , assume_leader = assume_leader ) while msg : msg = paxos_aggregate . receive_message ( msg ) new_events = paxos_aggregate . __batch_pending_events__ ( ) self . record_process_event ( ProcessEvent ( new_events ) ) self . repository . take_snapshot ( paxos_aggregate . id ) self . publish_prompt ( ) return paxos_aggregate | Starts new Paxos aggregate and proposes a value for a key . | 179 | 14 |
227,786 | def receive ( self , msg ) : handler = getattr ( self , 'receive_' + msg . __class__ . __name__ . lower ( ) , None ) if handler is None : raise InvalidMessageError ( 'Receiving class does not support messages of type: ' + msg . __class__ . __name__ ) return handler ( msg ) | Message dispatching function . This function accepts any PaxosMessage subclass and calls the appropriate handler function | 76 | 19 |
227,787 | def propose_value ( self , value ) : if self . proposed_value is None : self . proposed_value = value if self . leader : self . current_accept_msg = Accept ( self . network_uid , self . proposal_id , value ) return self . current_accept_msg | Sets the proposal value for this node iff this node is not already aware of a previous proposal value . If the node additionally believes itself to be the current leader an Accept message will be returned | 63 | 39 |
227,788 | def prepare ( self ) : self . leader = False self . promises_received = set ( ) self . nacks_received = set ( ) self . proposal_id = ProposalID ( self . highest_proposal_id . number + 1 , self . network_uid ) self . highest_proposal_id = self . proposal_id self . current_prepare_msg = Prepare ( self . network_uid , self . proposal_id ) return self . current_prepare_msg | Returns a new Prepare message with a proposal id higher than that of any observed proposals . A side effect of this method is to clear the leader flag if it is currently set . | 105 | 35 |
227,789 | def receive_nack ( self , msg ) : self . observe_proposal ( msg . promised_proposal_id ) if msg . proposal_id == self . proposal_id and self . nacks_received is not None : self . nacks_received . add ( msg . from_uid ) if len ( self . nacks_received ) == self . quorum_size : return self . prepare ( ) | Returns a new Prepare message if the number of Nacks received reaches a quorum . | 89 | 17 |
227,790 | def receive_promise ( self , msg ) : self . observe_proposal ( msg . proposal_id ) if not self . leader and msg . proposal_id == self . proposal_id and msg . from_uid not in self . promises_received : self . promises_received . add ( msg . from_uid ) if self . highest_accepted_id is None or msg . last_accepted_id > self . highest_accepted_id : self . highest_accepted_id = msg . last_accepted_id if msg . last_accepted_value is not None : self . proposed_value = msg . last_accepted_value if len ( self . promises_received ) == self . quorum_size : self . leader = True if self . proposed_value is not None : self . current_accept_msg = Accept ( self . network_uid , self . proposal_id , self . proposed_value ) return self . current_accept_msg | Returns an Accept messages if a quorum of Promise messages is achieved | 211 | 13 |
227,791 | def receive_prepare ( self , msg ) : if self . promised_id is None or msg . proposal_id >= self . promised_id : self . promised_id = msg . proposal_id return Promise ( self . network_uid , msg . from_uid , self . promised_id , self . accepted_id , self . accepted_value ) else : return Nack ( self . network_uid , msg . from_uid , msg . proposal_id , self . promised_id ) | Returns either a Promise or a Nack in response . The Acceptor s state must be persisted to disk prior to transmitting the Promise message . | 106 | 28 |
227,792 | def receive_accept ( self , msg ) : if self . promised_id is None or msg . proposal_id >= self . promised_id : self . promised_id = msg . proposal_id self . accepted_id = msg . proposal_id self . accepted_value = msg . proposal_value return Accepted ( self . network_uid , msg . proposal_id , msg . proposal_value ) else : return Nack ( self . network_uid , msg . from_uid , msg . proposal_id , self . promised_id ) | Returns either an Accepted or Nack message in response . The Acceptor s state must be persisted to disk prior to transmitting the Accepted message . | 116 | 30 |
227,793 | def receive_accepted ( self , msg ) : if self . final_value is not None : if msg . proposal_id >= self . final_proposal_id and msg . proposal_value == self . final_value : self . final_acceptors . add ( msg . from_uid ) return Resolution ( self . network_uid , self . final_value ) last_pn = self . acceptors . get ( msg . from_uid ) if last_pn is not None and msg . proposal_id <= last_pn : return # Old message self . acceptors [ msg . from_uid ] = msg . proposal_id if last_pn is not None : # String proposal_key, need string keys for JSON. proposal_key = str ( last_pn ) ps = self . proposals [ proposal_key ] ps . retain_count -= 1 ps . acceptors . remove ( msg . from_uid ) if ps . retain_count == 0 : del self . proposals [ proposal_key ] # String proposal_key, need string keys for JSON. proposal_key = str ( msg . proposal_id ) if not proposal_key in self . proposals : self . proposals [ proposal_key ] = ProposalStatus ( msg . proposal_value ) ps = self . proposals [ proposal_key ] assert msg . proposal_value == ps . value , 'Value mismatch for single proposal!' ps . accept_count += 1 ps . retain_count += 1 ps . acceptors . add ( msg . from_uid ) if ps . accept_count == self . quorum_size : self . final_proposal_id = msg . proposal_id self . final_value = msg . proposal_value self . final_acceptors = ps . acceptors self . proposals = None self . acceptors = None return Resolution ( self . network_uid , self . final_value ) | Called when an Accepted message is received from an acceptor . Once the final value is determined the return value of this method will be a Resolution message containing the consentual value . Subsequent calls after the resolution is chosen will continue to add new Acceptors to the final_acceptors set and return Resolution messages . | 397 | 64 |
227,794 | def resolve_topic ( topic ) : try : module_name , _ , class_name = topic . partition ( '#' ) module = importlib . import_module ( module_name ) except ImportError as e : raise TopicResolutionError ( "{}: {}" . format ( topic , e ) ) try : cls = resolve_attr ( module , class_name ) except AttributeError as e : raise TopicResolutionError ( "{}: {}" . format ( topic , e ) ) return cls | Return class described by given topic . | 108 | 7 |
227,795 | def resolve_attr ( obj , path ) : if not path : return obj head , _ , tail = path . partition ( '.' ) head_obj = getattr ( obj , head ) return resolve_attr ( head_obj , tail ) | A recursive version of getattr for navigating dotted paths . | 51 | 11 |
227,796 | def make_skip_list ( cts ) : # maybe make these non-country searches but don't discard, at least for # some (esp. bodies of water) special_terms = [ "Europe" , "West" , "the West" , "South Pacific" , "Gulf of Mexico" , "Atlantic" , "the Black Sea" , "Black Sea" , "North America" , "Mideast" , "Middle East" , "the Middle East" , "Asia" , "the Caucasus" , "Africa" , "Central Asia" , "Balkans" , "Eastern Europe" , "Arctic" , "Ottoman Empire" , "Asia-Pacific" , "East Asia" , "Horn of Africa" , "Americas" , "North Africa" , "the Strait of Hormuz" , "Mediterranean" , "East" , "North" , "South" , "Latin America" , "Southeast Asia" , "Western Pacific" , "South Asia" , "Persian Gulf" , "Central Europe" , "Western Hemisphere" , "Western Europe" , "European Union (E.U.)" , "EU" , "European Union" , "E.U." , "Asia-Pacific" , "Europe" , "Caribbean" , "US" , "U.S." , "Persian Gulf" , "West Africa" , "North" , "East" , "South" , "West" , "Western Countries" ] # Some words are recurring spacy problems... spacy_problems = [ "Kurd" , "Qur'an" ] #skip_list = list(cts.keys()) + special_terms skip_list = special_terms + spacy_problems skip_list = set ( skip_list ) return skip_list | Return hand - defined list of place names to skip and not attempt to geolocate . If users would like to exclude country names this would be the function to do it with . | 394 | 36 |
227,797 | def country_list_nlp ( cts ) : ct_nlp = [ ] for i in cts . keys ( ) : nlped = nlp ( i ) ct_nlp . append ( nlped ) return ct_nlp | NLP countries so we can use for vector comparisons | 57 | 10 |
227,798 | def make_country_nationality_list ( cts , ct_file ) : countries = pd . read_csv ( ct_file ) nationality = dict ( zip ( countries . nationality , countries . alpha_3_code ) ) both_codes = { * * nationality , * * cts } return both_codes | Combine list of countries and list of nationalities | 70 | 10 |
227,799 | def structure_results ( res ) : out = { 'hits' : { 'hits' : [ ] } } keys = [ u'admin1_code' , u'admin2_code' , u'admin3_code' , u'admin4_code' , u'alternativenames' , u'asciiname' , u'cc2' , u'coordinates' , u'country_code2' , u'country_code3' , u'dem' , u'elevation' , u'feature_class' , u'feature_code' , u'geonameid' , u'modification_date' , u'name' , u'population' , u'timezone' ] for i in res : i_out = { } for k in keys : i_out [ k ] = i [ k ] out [ 'hits' ] [ 'hits' ] . append ( i_out ) return out | Format Elasticsearch result as Python dictionary | 211 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.