_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q229100
CumulusCI.login_url
train
def login_url(self, org=None): """ Returns the login url which will automatically log into the target Salesforce org. By default, the org_name passed to the library constructor is used but this can be overridden with the org option to log into a different org. """ ...
python
{ "resource": "" }
q229101
CumulusCI.run_task
train
def run_task(self, task_name, **options): """ Runs a named CumulusCI task for the current project with optional support for overriding task options via kwargs. Examples: | =Keyword= | =task_name= | =task_options= | =comment= | |...
python
{ "resource": "" }
q229102
CumulusCI.run_task_class
train
def run_task_class(self, class_path, **options): """ Runs a CumulusCI task class with task options via kwargs. Use this keyword to run logic from CumulusCI tasks which have not been configured in the project's cumulusci.yml file. This is most useful in cases where a test ne...
python
{ "resource": "" }
q229103
BaseTaskFlowConfig.get_task
train
def get_task(self, name): """ Returns a TaskConfig """ config = getattr(self, "tasks__{}".format(name)) if not config: raise TaskNotFoundError("Task not found: {}".format(name)) return TaskConfig(config)
python
{ "resource": "" }
q229104
BaseTaskFlowConfig.get_flow
train
def get_flow(self, name): """ Returns a FlowConfig """ config = getattr(self, "flows__{}".format(name)) if not config: raise FlowNotFoundError("Flow not found: {}".format(name)) return FlowConfig(config)
python
{ "resource": "" }
q229105
BaseReleaseNotesGenerator.render
train
def render(self): """ Returns the rendered release notes from all parsers as a string """ release_notes = [] for parser in self.parsers: parser_content = parser.render() if parser_content is not None: release_notes.append(parser_content) return u"\...
python
{ "resource": "" }
q229106
GithubReleaseNotesGenerator._update_release_content
train
def _update_release_content(self, release, content): """Merge existing and new release content.""" if release.body: new_body = [] current_parser = None is_start_line = False for parser in self.parsers: parser.replaced = False #...
python
{ "resource": "" }
q229107
BaseCumulusCI.get_flow
train
def get_flow(self, name, options=None): """ Get a primed and readytogo flow coordinator. """ config = self.project_config.get_flow(name) callbacks = self.callback_class() coordinator = FlowCoordinator( self.project_config, config, name=name, ...
python
{ "resource": "" }
q229108
EnvironmentProjectKeychain._get_env
train
def _get_env(self): """ loads the environment variables as unicode if ascii """ env = {} for k, v in os.environ.items(): k = k.decode() if isinstance(k, bytes) else k v = v.decode() if isinstance(v, bytes) else v env[k] = v return list(env.items())
python
{ "resource": "" }
q229109
import_class
train
def import_class(path): """ Import a class from a string module class path """ components = path.split(".") module = components[:-1] module = ".".join(module) mod = __import__(module, fromlist=[native_str(components[-1])]) return getattr(mod, native_str(components[-1]))
python
{ "resource": "" }
q229110
parse_datetime
train
def parse_datetime(dt_str, format): """Create a timezone-aware datetime object from a datetime string.""" t = time.strptime(dt_str, format) return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)
python
{ "resource": "" }
q229111
process_list_arg
train
def process_list_arg(arg): """ Parse a string into a list separated by commas with whitespace stripped """ if isinstance(arg, list): return arg elif isinstance(arg, basestring): args = [] for part in arg.split(","): args.append(part.strip()) return args
python
{ "resource": "" }
q229112
decode_to_unicode
train
def decode_to_unicode(content): """ decode ISO-8859-1 to unicode, when using sf api """ if content and not isinstance(content, str): try: # Try to decode ISO-8859-1 to unicode return content.decode("ISO-8859-1") except UnicodeEncodeError: # Assume content is u...
python
{ "resource": "" }
q229113
Publish._find_or_create_version
train
def _find_or_create_version(self, product): """Create a Version in MetaDeploy if it doesn't already exist """ tag = self.options["tag"] label = self.project_config.get_version_for_tag(tag) result = self._call_api( "GET", "/versions", params={"product": product["id"],...
python
{ "resource": "" }
q229114
RobotLibDoc._render_html
train
def _render_html(self, libraries): """Generate the html. `libraries` is a list of LibraryDocumentation objects""" title = self.options.get("title", "Keyword Documentation") date = time.strftime("%A %B %d, %I:%M %p") cci_version = cumulusci.__version__ stylesheet_path = os.path....
python
{ "resource": "" }
q229115
ScratchOrgConfig.generate_password
train
def generate_password(self): """Generates an org password with the sfdx utility. """ 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 =...
python
{ "resource": "" }
q229116
BaseProjectKeychain._convert_connected_app
train
def _convert_connected_app(self): """Convert Connected App to service""" 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 retur...
python
{ "resource": "" }
q229117
BaseProjectKeychain._load_scratch_orgs
train
def _load_scratch_orgs(self): """ Creates all scratch org configs for the project in the keychain if a keychain org doesn't already exist """ current_orgs = self.list_orgs() if not self.project_config.orgs__scratch: return for config_name in self.project_config.or...
python
{ "resource": "" }
q229118
BaseProjectKeychain.change_key
train
def change_key(self, key): """ re-encrypt stored services and orgs with the new 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_n...
python
{ "resource": "" }
q229119
BaseProjectKeychain.get_default_org
train
def get_default_org(self): """ retrieve the name and configuration of the default org """ for org in self.list_orgs(): org_config = self.get_org(org) if org_config.default: return org, org_config return None, None
python
{ "resource": "" }
q229120
BaseProjectKeychain.set_default_org
train
def set_default_org(self, name): """ set the default org for tasks by name key """ org = self.get_org(name) self.unset_default_org() org.config["default"] = True self.set_org(org)
python
{ "resource": "" }
q229121
BaseProjectKeychain.unset_default_org
train
def unset_default_org(self): """ unset the default orgs for tasks """ 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)
python
{ "resource": "" }
q229122
BaseProjectKeychain.get_org
train
def get_org(self, name): """ retrieve an org configuration by name key """ if name not in self.orgs: self._raise_org_not_found(name) return self._get_org(name)
python
{ "resource": "" }
q229123
BaseProjectKeychain.list_orgs
train
def list_orgs(self): """ list the orgs configured in the keychain """ orgs = list(self.orgs.keys()) orgs.sort() return orgs
python
{ "resource": "" }
q229124
BaseProjectKeychain.set_service
train
def set_service(self, name, service_config, project=False): """ Store a ServiceConfig in the keychain """ 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._se...
python
{ "resource": "" }
q229125
BaseProjectKeychain.get_service
train
def get_service(self, name): """ Retrieve a stored ServiceConfig from the keychain or exception :param name: the service name to retrieve :type name: str :rtype ServiceConfig :return the configured Service """ self._convert_connected_app() if not self.pr...
python
{ "resource": "" }
q229126
BaseProjectKeychain.list_services
train
def list_services(self): """ list the services configured in the keychain """ services = list(self.services.keys()) services.sort() return services
python
{ "resource": "" }
q229127
set_pdb_trace
train
def set_pdb_trace(pm=False): """Start the Python debugger when robotframework is running. This makes sure that pdb can use stdin/stdout even though robotframework has redirected I/O. """ import sys import pdb for attr in ("stdin", "stdout", "stderr"): setattr(sys, attr, getattr(sys...
python
{ "resource": "" }
q229128
selenium_retry
train
def selenium_retry(target=None, retry=True): """Decorator to turn on automatic retries of flaky selenium failures. Decorate a robotframework library class to turn on retries for all selenium calls from that library: @selenium_retry class MyLibrary(object): # Decorate a method ...
python
{ "resource": "" }
q229129
RetryingSeleniumLibraryMixin.selenium_execute_with_retry
train
def selenium_execute_with_retry(self, execute, command, params): """Run a single selenium command and retry once. The retry happens for certain errors that are likely to be resolved by retrying. """ try: return execute(command, params) except Exception as e: ...
python
{ "resource": "" }
q229130
GithubChangeNotesProvider._get_last_tag
train
def _get_last_tag(self): """ Gets the last release tag before self.current_tag """ 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.startswit...
python
{ "resource": "" }
q229131
GithubChangeNotesProvider._get_pull_requests
train
def _get_pull_requests(self): """ Gets all pull requests from the repo since we can't do a filtered date merged search """ for pull in self.repo.pull_requests( state="closed", base=self.github_info["master_branch"], direction="asc" ): if self._include_pull_request...
python
{ "resource": "" }
q229132
GithubChangeNotesProvider._include_pull_request
train
def _include_pull_request(self, pull_request): """ Checks if the given pull_request was merged to the default branch between self.start_date and self.end_date """ merged_date = pull_request.merged_at if not merged_date: return False if self.last_tag: last...
python
{ "resource": "" }
q229133
patch_statusreporter
train
def patch_statusreporter(): """Monkey patch robotframework to do postmortem debugging """ 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): se...
python
{ "resource": "" }
q229134
MetadataXmlElementParser.get_item_name
train
def get_item_name(self, item, parent): """ Returns the value of the first name element found inside of element """ names = self.get_name_elements(item) if not names: raise MissingNameElementError name = names[0].text prefix = self.item_name_prefix(parent) if ...
python
{ "resource": "" }
q229135
StepSpec.for_display
train
def for_display(self): """ Step details formatted for logging output. """ 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("d...
python
{ "resource": "" }
q229136
TaskRunner.run_step
train
def run_step(self): """ Run a step. :return: StepResult """ # 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(ta...
python
{ "resource": "" }
q229137
FlowCoordinator._init_steps
train
def _init_steps(self,): """ Given the flow config and everything else, create a list of steps to run, sorted by step number. :return: List[StepSpec] """ self._check_old_yaml_format() config_steps = self.flow_config.steps self._check_infinite_flows(config_steps) ...
python
{ "resource": "" }
q229138
FlowCoordinator._check_infinite_flows
train
def _check_infinite_flows(self, steps, flows=None): """ Recursively loop through the flow_config and check if there are any cycles. :param steps: Set of step definitions to loop through :param flows: Flows already visited. :return: None """ if flows is None: ...
python
{ "resource": "" }
q229139
FlowCoordinator._init_org
train
def _init_org(self): """ Test and refresh credentials to the org specified. """ self.logger.info( "Verifying and refreshing credentials for the specified org: {}.".format( self.org_config.name ) ) orig_config = self.org_config.config.copy() ...
python
{ "resource": "" }
q229140
FlowCoordinator.resolve_return_value_options
train
def resolve_return_value_options(self, options): """Handle dynamic option value lookups in the format ^^task_name.attr""" for key, value in options.items(): if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX): path, name = value[len(RETURN_VALUE_OPTION_...
python
{ "resource": "" }
q229141
init_logger
train
def init_logger(log_requests=False): """ Initialize the logger """ 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....
python
{ "resource": "" }
q229142
register_new_node
train
def register_new_node(suffix_node_id=None): """Factory method, registers new node. """ 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
python
{ "resource": "" }
q229143
register_new_edge
train
def register_new_edge(edge_id, first_char_index, last_char_index, source_node_id, dest_node_id): """Factory method, registers new edge. """ event = Edge.Created( originator_id=edge_id, first_char_index=first_char_index, last_char_index=last_char_index, source_node_id=source_n...
python
{ "resource": "" }
q229144
register_new_suffix_tree
train
def register_new_suffix_tree(case_insensitive=False): """Factory method, returns new suffix tree object. """ 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=...
python
{ "resource": "" }
q229145
find_substring
train
def find_substring(substring, suffix_tree, edge_repo): """Returns the index if substring in tree, otherwise -1. """ assert isinstance(substring, str) assert isinstance(suffix_tree, SuffixTree) assert isinstance(edge_repo, EventSourcedRepository) if not substring: return -1 if suffix_...
python
{ "resource": "" }
q229146
SuffixTree._add_prefix
train
def _add_prefix(self, last_char_index): """The core construction method. """ 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.strin...
python
{ "resource": "" }
q229147
SuffixTree._canonize_suffix
train
def _canonize_suffix(self, suffix): """This canonizes the suffix, walking along its suffix string until it is explicit or there are no more matched nodes. """ if not suffix.explicit(): edge_id = make_edge_id(suffix.source_node_id, self.string[suffix.first_char_index]) ...
python
{ "resource": "" }
q229148
entity_from_snapshot
train
def entity_from_snapshot(snapshot): """ Reconstructs domain entity from given 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...
python
{ "resource": "" }
q229149
EventSourcedSnapshotStrategy.get_snapshot
train
def get_snapshot(self, entity_id, lt=None, lte=None): """ Gets the last snapshot for entity, optionally until a particular version number. :rtype: Snapshot """ snapshots = self.snapshot_store.get_domain_events(entity_id, lt=lt, lte=lte, limit=1, is_ascending=False) if le...
python
{ "resource": "" }
q229150
EventSourcedSnapshotStrategy.take_snapshot
train
def take_snapshot(self, entity_id, entity, last_event_version): """ Creates a Snapshot from the given state, and appends it to the snapshot store. :rtype: Snapshot """ # Create the snapshot. snapshot = Snapshot( originator_id=entity_id, o...
python
{ "resource": "" }
q229151
EventSourcedRepository.get_entity
train
def get_entity(self, entity_id, at=None): """ Returns entity with given ID, optionally until position. """ # 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: ...
python
{ "resource": "" }
q229152
EventSourcedRepository.get_and_project_events
train
def get_and_project_events(self, entity_id, gt=None, gte=None, lt=None, lte=None, limit=None, initial_state=None, query_descending=False): """ Reconstitutes requested domain entity from domain events found in event store. """ # Decide if query is in ascendi...
python
{ "resource": "" }
q229153
EventSourcedRepository.take_snapshot
train
def take_snapshot(self, entity_id, lt=None, lte=None): """ 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. """ snapshot = None if self._snapshot_strategy: # Get th...
python
{ "resource": "" }
q229154
ExampleApplication.create_new_example
train
def create_new_example(self, foo='', a='', b=''): """Entity object factory.""" return create_new_example(foo=foo, a=a, b=b)
python
{ "resource": "" }
q229155
timestamp_long_from_uuid
train
def timestamp_long_from_uuid(uuid_arg): """ Returns an integer value representing a unix timestamp in tenths of microseconds. :param uuid_arg: :return: Unix timestamp integer in tenths of microseconds. :rtype: int """ if isinstance(uuid_arg, str): uuid_arg = UUID(uuid_arg) asser...
python
{ "resource": "" }
q229156
subscribe_to
train
def subscribe_to(*event_classes): """ Decorator for making a custom event handler function subscribe to a certain class of event. The decorated function will be called once for each matching event that is published, and will be given one argument, the event, when it is called. If events are published i...
python
{ "resource": "" }
q229157
mutator
train
def mutator(arg=None): """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. It works like singledisp...
python
{ "resource": "" }
q229158
AESCipher.encrypt
train
def encrypt(self, plaintext): """Return ciphertext for given 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.ne...
python
{ "resource": "" }
q229159
AESCipher.decrypt
train
def decrypt(self, ciphertext): """Return plaintext for given ciphertext.""" # String to bytes. cipherbytes = ciphertext.encode('utf8') # Decode from Base64. try: combined = base64.b64decode(cipherbytes) except (base64.binascii.Error, TypeError) as e: ...
python
{ "resource": "" }
q229160
EventStore.store
train
def store(self, domain_event_or_events): """ Appends given domain event, or list of domain events, to their sequence. :param domain_event_or_events: domain event, or list of domain events """ # Convert to sequenced item. sequenced_item_or_items = self.item_from_event(do...
python
{ "resource": "" }
q229161
EventStore.item_from_event
train
def item_from_event(self, domain_event_or_events): """ Maps domain event to sequenced item namedtuple. :param domain_event_or_events: application-level object (or list) :return: namedtuple: sequence item namedtuple (or list) """ # Convert the domain event(s) to sequenced...
python
{ "resource": "" }
q229162
EventStore.get_domain_events
train
def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Gets domain events from the sequence identified by `originator_id`. :param originator_id: ID of a sequence of events :param gt: ...
python
{ "resource": "" }
q229163
EventStore.get_domain_event
train
def get_domain_event(self, originator_id, position): """ Gets a domain event from the sequence identified by `originator_id` at position `eq`. :param originator_id: ID of a sequence of events :param position: get item at this position :return: domain event """ ...
python
{ "resource": "" }
q229164
EventStore.get_most_recent_event
train
def get_most_recent_event(self, originator_id, lt=None, lte=None): """ Gets a domain event from the sequence identified by `originator_id` at the highest position. :param originator_id: ID of a sequence of events :param lt: get highest before this position :param lte: ge...
python
{ "resource": "" }
q229165
EventStore.all_domain_events
train
def all_domain_events(self): """ Yields all domain events in the event store. """ 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
python
{ "resource": "" }
q229166
ProcessApplication.publish_prompt
train
def publish_prompt(self, event=None): """ Publishes prompt for a given event. Used to prompt downstream process application when an event is published by this application's model, which can happen when application command methods, rather than the process policy, are call...
python
{ "resource": "" }
q229167
DjangoRecordManager._prepare_insert
train
def _prepare_insert(self, tmpl, record_class, field_names, placeholder_for_id=False): """ 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 ...
python
{ "resource": "" }
q229168
DjangoRecordManager.get_notifications
train
def get_notifications(self, start=None, stop=None, *args, **kwargs): """ Returns all records in the table. """ filter_kwargs = {} # Todo: Also support sequencing by 'position' if items are sequenced by timestamp? if start is not None: filter_kwargs['%s__gte' %...
python
{ "resource": "" }
q229169
ActorModelRunner.start
train
def start(self): """ Starts all the actors to run a system of process applications. """ # Subscribe to broadcast prompts published by a process # application in the parent operating system process. subscribe(handler=self.forward_prompt, predicate=self.is_prompt) ...
python
{ "resource": "" }
q229170
ActorModelRunner.close
train
def close(self): """Stops all the actors running a system of process applications.""" super(ActorModelRunner, self).close() unsubscribe(handler=self.forward_prompt, predicate=self.is_prompt) if self.shutdown_on_close: self.shutdown()
python
{ "resource": "" }
q229171
SuffixTreeApplication.register_new_suffix_tree
train
def register_new_suffix_tree(self, case_insensitive=False): """Returns a new suffix tree entity. """ 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_collect...
python
{ "resource": "" }
q229172
SuffixTreeApplication.find_string_ids
train
def find_string_ids(self, substring, suffix_tree_id, limit=None): """Returns a set of IDs for strings that contain the given substring. """ # Find an edge for the substring. edge, ln = self.find_substring_edge(substring=substring, suffix_tree_id=suffix_tree_id) # If there isn't...
python
{ "resource": "" }
q229173
SuffixTreeApplication.find_substring_edge
train
def find_substring_edge(self, substring, suffix_tree_id): """Returns an edge that matches the given substring. """ suffix_tree = self.suffix_tree_repo[suffix_tree_id] started = datetime.datetime.now() edge, ln = find_substring_edge(substring=substring, suffix_tree=suffix_tree, ed...
python
{ "resource": "" }
q229174
SingleThreadedRunner.run_followers
train
def run_followers(self, prompt): """ First caller adds a prompt to queue and runs followers until there are no more pending prompts. Subsequent callers just add a prompt to the queue, avoiding recursion. """ assert isinstance(prompt, Prompt) # Put...
python
{ "resource": "" }
q229175
create_new_example
train
def create_new_example(foo='', a='', b=''): """ Factory method for example entities. :rtype: Example """ return Example.__create__(foo=foo, a=a, b=b)
python
{ "resource": "" }
q229176
applicationpolicy
train
def applicationpolicy(arg=None): """ Decorator for application policy method. Allows policy to be built up from methods registered for different event classes. """ def _mutator(func): wrapped = singledispatch(func) @wraps(wrapped) def wrapper(*args, **kwargs): ...
python
{ "resource": "" }
q229177
SQLAlchemyRecordManager._prepare_insert
train
def _prepare_insert(self, tmpl, record_class, field_names, placeholder_for_id=False): """ 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 ...
python
{ "resource": "" }
q229178
SQLAlchemyRecordManager.delete_record
train
def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() except Exception as e: self.session.rollback() raise ProgrammingError(e) finally: ...
python
{ "resource": "" }
q229179
TimebucketedlogRepository.get_or_create
train
def get_or_create(self, log_name, bucket_size): """ Gets or creates a log. :rtype: Timebucketedlog """ try: return self[log_name] except RepositoryKeyError: return start_new_timebucketedlog(log_name, bucket_size=bucket_size)
python
{ "resource": "" }
q229180
EventPlayer.project_events
train
def project_events(self, initial_state, domain_events): """ Evolves initial state using the sequence of domain events and a mutator function. """ return reduce(self._mutator_func or self.mutate, domain_events, initial_state)
python
{ "resource": "" }
q229181
BigArray.get_last_array
train
def get_last_array(self): """ Returns last array in compound. :rtype: CompoundSequenceReader """ # 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.ge...
python
{ "resource": "" }
q229182
BigArray.calc_parent
train
def calc_parent(self, i, j, h): """ Returns get_big_array and end of span of parent sequence that contains given child. """ 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 he...
python
{ "resource": "" }
q229183
SequencedItemMapper.item_from_event
train
def item_from_event(self, domain_event): """ Constructs a sequenced item from a domain event. """ item_args = self.construct_item_args(domain_event) return self.construct_sequenced_item(item_args)
python
{ "resource": "" }
q229184
SequencedItemMapper.construct_item_args
train
def construct_item_args(self, domain_event): """ Constructs attributes of a sequenced item from the given domain event. """ # Get the sequence ID. sequence_id = domain_event.__dict__[self.sequence_id_attr_name] # Get the position in the sequence. position = getat...
python
{ "resource": "" }
q229185
SequencedItemMapper.event_from_item
train
def event_from_item(self, sequenced_item): """ Reconstructs domain event from stored event topic and event attrs. Used in the event store when getting domain events. """ assert isinstance(sequenced_item, self.sequenced_item_class), ( self.sequenced_item_class, type(se...
python
{ "resource": "" }
q229186
AbstractSequencedItemRecordManager.get_item
train
def get_item(self, sequence_id, position): """ Gets sequenced item from the datastore. """ return self.from_record(self.get_record(sequence_id, position))
python
{ "resource": "" }
q229187
AbstractSequencedItemRecordManager.get_items
train
def get_items(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns sequenced item generator. """ records = self.get_records( sequence_id=sequence_id, gt=gt, gt...
python
{ "resource": "" }
q229188
AbstractSequencedItemRecordManager.to_record
train
def to_record(self, sequenced_item): """ Constructs a record object from given sequenced item object. """ kwargs = self.get_field_kwargs(sequenced_item) # Supply application_name, if needed. if hasattr(self.record_class, 'application_name'): kwargs['applicatio...
python
{ "resource": "" }
q229189
AbstractSequencedItemRecordManager.from_record
train
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
python
{ "resource": "" }
q229190
ACIDRecordManager.get_pipeline_and_notification_id
train
def get_pipeline_and_notification_id(self, sequence_id, position): """ Returns pipeline ID and notification ID for event at given position in given sequence. """ # Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)? record = self.get_...
python
{ "resource": "" }
q229191
SQLRecordManager.insert_select_max
train
def insert_select_max(self): """ SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records. """ if self._insert_select_max is None: if hasattr(self.record_class, 'application_name'): # Todo: Maybe make it su...
python
{ "resource": "" }
q229192
SQLRecordManager.insert_values
train
def insert_values(self): """ SQL statement that inserts records without ID. """ if self._insert_values is None: self._insert_values = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=sel...
python
{ "resource": "" }
q229193
SQLRecordManager.insert_tracking_record
train
def insert_tracking_record(self): """ SQL statement that inserts tracking records. """ if self._insert_tracking_record is None: self._insert_tracking_record = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, ...
python
{ "resource": "" }
q229194
PaxosAggregate.start
train
def start(cls, originator_id, quorum_size, network_uid): """ Factory method that returns a new Paxos aggregate. """ assert isinstance(quorum_size, int), "Not an integer: {}".format(quorum_size) return cls.__create__( event_class=cls.Started, originator_id=...
python
{ "resource": "" }
q229195
PaxosAggregate.propose_value
train
def propose_value(self, value, assume_leader=False): """ Proposes a value to the network. """ if value is None: raise ValueError("Not allowed to propose value None") paxos = self.paxos_instance paxos.leader = assume_leader msg = paxos.propose_value(val...
python
{ "resource": "" }
q229196
PaxosAggregate.receive_message
train
def receive_message(self, msg): """ Responds to messages from other participants. """ if isinstance(msg, Resolution): return paxos = self.paxos_instance while msg: if isinstance(msg, Resolution): self.print_if_verbose("{} resolved v...
python
{ "resource": "" }
q229197
PaxosAggregate.announce
train
def announce(self, msg): """ Announces a Paxos message. """ self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__)) self.__trigger_event__( event_class=self.MessageAnnounced, msg=msg, )
python
{ "resource": "" }
q229198
PaxosAggregate.setattrs_from_paxos
train
def setattrs_from_paxos(self, paxos): """ Registers changes of attribute value on Paxos instance. """ changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_...
python
{ "resource": "" }
q229199
PaxosProcess.propose_value
train
def propose_value(self, key, value, assume_leader=False): """ Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error. """ assert isinstance(key, UUID) paxos_aggregate = PaxosAggreg...
python
{ "resource": "" }