code
stringlengths
1
18.2k
if self.instantiating.count((basenote, name)) > 1: stack = ' <- '.join(repr(note) for note in self.instantiating) notes = tuple(self.instantiating) raise DependencyCycleError(stack, notes=notes) return self.handle_provider(provider_factory, note) finally: self.instantiating.pop()
def close(self): """Close injector & injected Provider instances, including generators. Providers are closed in the reverse order in which they were opened, and each provider is only closed once. Providers are closed if accessed by the injector, even if a dependency is not successfully provided. As such, providers shou...
def prepare_callable(self, fn, partial=False): """Prepare arguments required to apply function.""" notes, keyword_notes = self.get_annotations(fn) return self.prepare_notes(*notes, __partial=partial, **keyword_notes)
def prepare_notes(self, *notes, **keyword_notes): """Get injection values for all given notes.""" __partial = keyword_notes.pop('__partial', False) args = tuple(self.get(note) for note in notes) kwargs = {} for arg in keyword_notes: note = keyword_notes[arg] if isinstance(note, tuple) and len(note) == 2 and note[0] == ...
def parse_note(cls, note): """Parse string annotation into object reference with optional name.""" if isinstance(note, tuple): if len(note) != 2: raise ValueError('tuple annotations must be length 2') return note try: match = cls.re_note.match(note) except TypeError: # Note is not a string. Support any Python object as...
def handle_provider(self, provider_factory, note): """Get value from provider as requested by note.""" # Implementation in separate method to support accurate book-keeping. basenote, name = self.parse_note(note) # _handle_provider could be even shorter if # Injector.apply() worked with classes, issue #9. if basenote no...
def register(cls, note, provider): """Implementation to register provider via `provider` & `factory`.""" basenote, name = cls.parse_note(note) if 'provider_registry' not in vars(cls): cls.provider_registry = {} cls.provider_registry[basenote] = provider
def lookup(cls, basenote): """Look up note in registered annotations, walking class tree.""" # Walk method resolution order, which includes current class. for c in cls.mro(): if 'provider_registry' not in vars(c): # class is a mixin, super to base class, or never registered. continue if basenote in c.provider_registry:...
def sub(cls, *mixins_and_dicts, **values): """Create and instantiate a sub-injector. Mixins and local value dicts can be passed in as arguments. Local values can also be passed in as keyword arguments. """ class SubInjector(cls): pass mixins = [ x for x in mixins_and_dicts if isinstance(x, type) ] if mixins: SubInjecto...
def _getFuncArgs(func): r"""Gives the details on the args of the given func. Args: func (function): The function to get details on. """ code = func.func_code Defaults = func.func_defaults nargs = code.co_argcount ArgNames = code.co_varnames[:nargs] Args = OrderedDict() argCount = len(ArgNames) defCount = len(Defaults) ...
def get_form_label(self, request=None, obj=None, model=None, form=None): """Returns a customized form label, if condition is met, otherwise returns the default form label. * condition is an instance of CustomLabelCondition. """ label = form.base_fields[self.field].label condition = self.condition_cls(request=request, o...
def do_stack(self,args): """Go to the specified stack. stack -h for detailed help""" parser = CommandArgumentParser("stack") parser.add_argument(dest='stack',help='stack index or name'); parser.add_argument('-a','--asg',dest='asg',help='descend into specified asg'); args = vars(parser.parse_args(args)) try: index = int...
def do_delete_stack(self,args): """Delete specified stack. delete_stack -h for detailed help.""" parser = CommandArgumentParser("delete_stack") parser.add_argument(dest='stack',help='stack index or name'); args = vars(parser.parse_args(args)) try: index = int(args['stack']) if self.stackList == None: self.do_stacks('-s...
def do_stacks(self,args): """List available stacks. stacks -h for detailed help.""" parser = CommandArgumentParser() parser.add_argument('-s','--silent',dest='silent',action='store_true',help='Run silently') parser.add_argument('-i','--include',nargs='*',dest='includes',default=[],help='Add statuses') parser.add_argume...
= stackSummariesByIndex if not (args['silent'] or args['summary']): for index,summary in stackSummariesByIndex.items(): print '{0:3d}: {2:20} {1:40} {3}'.format(summary['Index'],summary['StackName'],summary['StackStatus'],defaultifyDict(summary,'StackStatusReason','')) if args['summary'] and not args['silent']: print '...
def do_stack_resource(self, args): """Use specified stack resource. stack_resource -h for detailed help.""" parser = CommandArgumentParser() parser.add_argument('-s','--stack-name',dest='stack-name',help='name of the stack resource'); parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the chi...
def searchTag(self,HTAG="#python"): """Set Twitter search or stream criteria for the selection of tweets""" self.t = Twython(app_key =self.app_key , app_secret =self.app_secret , oauth_token =self.oauth_token , oauth_token_secret =self.oauth_token_secret) search =self.t.search(q=HTAG,count=100,result_type="recent") ss=...
def delete_upload_id(cls, tables: I2B2Tables, upload_id: int) -> int: """ Delete all observation_fact records with the supplied upload_id :param tables: i2b2 sql connection :param upload_id: upload identifier to remove :return: number or records that were deleted """ return cls._delete_upload_id(tables.crc_connection, ...
def delete_sourcesystem_cd(cls, tables: I2B2Tables, sourcesystem_cd: str) -> int: """ Delete all records with the supplied sourcesystem_cd :param tables: i2b2 sql connection :param sourcesystem_cd: sourcesystem_cd to remove :return: number or records that were deleted """ return cls._delete_sourcesystem_cd(tables.crc_c...
def add_or_update_records(cls, tables: I2B2Tables, records: List["ObservationFact"]) -> Tuple[int, int]: """ Add or update the observation_fact table as needed to reflect the contents of records :param tables: i2b2 sql connection :param records: records to apply :return: number of records added / modified """ return cl...
def _date_val(self, dt: datetime) -> None: """ Add a date value :param dt: datetime to add """ self._tval_char = dt.strftime('%Y-%m-%d %H:%M') self._nval_num = (dt.year * 10000) + (dt.month * 100) + dt.day + \ (((dt.hour / 100.0) + (dt.minute / 10000.0)) if isinstance(dt, datetime) else 0)
def configure(self, config): """ Configure Monitor, pull list of what to monitor, initialize threads """ self.config = config self.update_monitors() # initialize thread pools for profile in ('worker', 'result'): for _ in range(config['threads'][profile]['number']): worker = threading.Thread(target=config['threads'][pro...
def feed_monitors(self): """ Pull from the cached monitors data and feed the workers queue. Run every interval (refresh:test). """ self.thread_debug("Filling worker queue...", module='feed_monitors') for mon in self.monitors: self.thread_debug(" Adding " + mon['title']) self.workers_queue.put(mon)
def start(self): """ The main loop, run forever. """ while True: self.thread_debug("Interval starting") for thr in threading.enumerate(): self.thread_debug(" " + str(thr)) self.feed_monitors() start = time.time() # wait fore queue to empty self.workers_queue.join() end = time.time() diff = self.config['interval']['test...
def update_monitors(self): """ Periodically check in with Reflex Engine and refresh the list of what to monitor """ self.thread_debug("Starting monitor refresh", module="update_monitors") # need to make a more efficient way of doing this via Reflex Engine monitors = [] self.rcs.cache_reset() svcs = self.rcs.cache_list(...
pylint: disable=protected-access self.instances = cache['instance'] self.services = cache['service'] self.pipelines = cache['pipeline'] self.thread_debug("Refresh complete", module="update_monitors")
def thread_debug(self, *args, **kwargs): """ Wrap debug to include thread information """ if 'module' not in kwargs: kwargs['module'] = "Monitor" if kwargs['module'] != 'Monitor' and self.do_DEBUG(module='Monitor'): self.debug[kwargs['module']] = True if not self.do_DEBUG(module=kwargs['module']): return thread_id = th...
def worker_thread(self): """ The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. """ self.thread_debug("Starting monitor thread") while not self.thread_stopper.is_set(): mon = self.workers_que...
def _worker_http(self, monitor): """ Process an http monitor. """ self.thread_debug("process_http", data=monitor, module='handler') query = monitor['query'] method = query['method'].lower() self.stats.http_run += 1 try: target = monitor['target'] url = 'http://{host}:{port}{path}'.format(path=query['path'], **target) r...
response['message'] = '' response['status'] = 'ok' else: # abort with failure, do not pass go return response if 'regex' in monitor['expect']: if re.search(monitor['expect']['regex'], res.text): response['message'] = '' response['status'] = 'ok' else: # abort with failure, do not pass go return response except requests...
def handler_thread(self): """ A handler thread--this pulls results from the queue and processes them accordingly. Calls a sub method based on type of monitor. """ self.thread_debug("Starting handler thread") while not self.thread_stopper.is_set(): data = self.results_queue.get() self.thread_debug("Handling Result", mod...
def _handler_http(self, result): """ Handle the result of an http monitor """ monitor = result['monitor'] self.thread_debug("process_http", data=monitor, module='handler') self.stats.http_handled += 1 # splunk will pick this up logargs = { 'type':"metric", 'endpoint': result['url'], 'pipeline': monitor['pipeline'], 'se...
def reporting(self): """ report on consumption info """ self.thread_debug("reporting") res = resource.getrusage(resource.RUSAGE_SELF) self.NOTIFY("", type='internal-usage', maxrss=round(res.ru_maxrss/1024, 2), ixrss=round(res.ru_ixrss/1024, 2), idrss=round(res.ru_idrss/1024, 2), isrss=round(res.ru_isrss/1024, 2), threa...
def heartbeat(self): """ Watch our counters--as long as things are incrementing, send a ping to statuscake sayin we are alive and okay. """ self.thread_debug("heartbeat") # check stats -- should be incrementing if self.last_stats: if self.stats.http_run <= self.last_stats.http_run: self.NOTIFY("No monitors run since la...
def start_agent(self, cfgin=True): """ CLI interface to start 12-factor service """ default_conf = { "threads": { "result": { "number": 0, "function": None }, "worker": { "number": 0, "function": None }, }, "interval": { "refresh": 900, "heartbeat": 300, "reporting": 300, "test": 60 }, "heartbeat-hook": False } indata ...
def start(): r"""Starts ec. """ processPendingModules() if not state.main_module_name in ModuleMembers: # don't start the core when main is not Ec-ed return MainModule = sys.modules[state.main_module_name] if not MainModule.__ec_member__.Members: # there was some error while loading script(s) return global BaseGroup Ba...
def execCommand(Argv, collect_missing): r"""Executes the given task with parameters. """ try: return _execCommand(Argv, collect_missing) except Exception as e: if Settings['errorHandler']: Settings['errorHandler'](e) if Settings['debug']: # #ToDo: Have an option to debug through stderr. The issue is, the way to make pd...
def getDescendant(Ancestor, RouteParts): r"""Resolves a descendant, of the given Ancestor, as pointed by the RouteParts. """ if not RouteParts: return Ancestor Resolved = Ancestor.Members.get(RouteParts.pop(0)) if isinstance(Resolved, Group): return getDescendant(Resolved, RouteParts) else: return Resolved
def setActiveModule(Module): r"""Helps with collecting the members of the imported modules. """ module_name = Module.__name__ if module_name not in ModuleMembers: ModuleMembers[module_name] = [] ModulesQ.append(module_name) Group(Module, {}) # brand the module with __ec_member__ state.ActiveModuleMemberQ = ModuleMember...
def processModule(module_name): r"""Builds a command tree out of the configured members of a module. """ Module = sys.modules[module_name] MembersTarget = [] ClassQ = [] Cls = None ClsGroup = None ClsGrpMembers = [] for Member in ModuleMembers[module_name]: Underlying = Member.Underlying member_name = Member.Config['na...
ClsGroup: ClsGroup.Members = OrderedDict(ClsGrpMembers) ModuleMembers[module_name] = [] # remove the existing members from the cache so that they won't be processed again if not hasattr(Module.__ec_member__, 'Members'): Module.__ec_member__.Members = OrderedDict(MembersTarget)
def _execCommand(Argv, collect_missing): r"""Worker of execCommand. """ if not Argv: raise HandledException('Please specify a command!') RouteParts = Argv[0].split('/') Args, KwArgs = getDigestableArgs(Argv[1:]) ResolvedMember = getDescendant(BaseGroup, RouteParts[:]) if isinstance(ResolvedMember, Group): raise Handled...
def memoize(fn): '''Cache the results of a function that only takes positional arguments.''' cache = {} @wraps(fn) def wrapped_function(*args): if args in cache: return cache[args] else: result = fn(*args) cache[args] = result return result return wrapped_function
def setup_config(epab_version: str): """ Set up elib_config package :param epab_version: installed version of EPAB as as string """ logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_...
def get_months_apart(d1, d2): """ Get amount of months between dates http://stackoverflow.com/a/4040338 """ return (d1.year - d2.year)*12 + d1.month - d2.month
def get_month_list(to_date, from_date): """ Generate a list containing year+month between two dates. Returns: [(2013, 11), (2013, 12), (2014, 1)] """ num_months = get_months_apart(to_date, from_date) month_offset = from_date.month month_list = [] for month in range(month_offset-1, month_offset+num_months): year = from_...
def find_amplitude(chunk): """ Calculate the 0-1 amplitude of an ndarray chunk of audio samples. Samples in the ndarray chunk are signed int16 values oscillating anywhere between -32768 and 32767. Find the amplitude between 0 and 1 by summing the absolute values of the minimum and maximum, and dividing by 32767. Args: ...
def step_amp(self): """ Change the amplitude according to the change rate and drift target. Returns: None """ difference = self.drift_target - self._raw_value if abs(difference) < self.change_rate: self.value = self.drift_target else: delta = self.change_rate * numpy.sign(difference) self.value = self._raw_value + delt...
def get_supported_file_loaders_2(force=False): """Returns a list of file-based module loaders. Each item is a tuple (loader, suffixes). """ if force or (2, 7) <= sys.version_info < (3, 4): # valid until which py3 version ? import imp loaders = [] for suffix, mode, type in imp.get_suffixes(): if type == imp.PY_SOURCE: l...
def _find_parent_path_names(self): """Returns a tuple of (parent-module-name, parent-path-attr-name)""" parent, dot, me = self._name.rpartition('.') if dot == '': # This is a top-level module. sys.path contains the parent path. return 'sys', 'path' # Not a top-level module. parent-module.__path__ contains the # parent ...
def is_package(self, fullname): """Concrete implementation of InspectLoader.is_package by checking if the path returned by get_filename has a filename of '__init__.py'.""" filename = os.path.split(self.get_filename(fullname))[1] filename_base = filename.rsplit('.', 1)[0] tail_name = fullname.rpartition('.')[2] return f...
def create_module(self, spec): """Creates the module, and also insert it into sys.modules, adding this onto py2 import logic.""" mod = sys.modules.setdefault(spec.name, types.ModuleType(spec.name)) # we are using setdefault to satisfy https://docs.python.org/3/reference/import.html#loaders return mod
def exec_module(self, module): """Execute the module.""" code = self.get_code(module.__name__) if code is None: raise ImportError('cannot load module {!r} when get_code() ' 'returns None'.format(module.__name__)) exec(code, module.__dict__)
def load_module(self, fullname): """Load the specified module into sys.modules and return it. This method is for python2 only, but implemented with backported py3 methods. """ if fullname in sys.modules: mod = sys.modules[fullname] self.exec_module(mod) # In this case we do not want to remove the module in case of erro...
# as per https://docs.python.org/3/reference/import.html#loaders if fullname in sys.modules: del sys.modules[fullname] raise return sys.modules[fullname]
def create_module(self, spec): """Improve python2 semantics for module creation.""" mod = super(NamespaceLoader2, self).create_module(spec) # Set a few properties required by PEP 302 # mod.__file__ = [p for p in self.path] # this will set mod.__repr__ to not builtin... shouldnt break anything in py2... # CAREFUL : get_...
def load_module(self, name): """Load a namespace module as if coming from an empty file. """ _verbose_message('namespace module loaded with path {!r}', self.path) # Adjusting code from LoaderBasics if name in sys.modules: mod = sys.modules[name] self.exec_module(mod) # In this case we do not want to remove the module i...
per https://docs.python.org/3/reference/import.html#loaders if name in sys.modules: del sys.modules[name] raise return sys.modules[name]
def get_source(self, name): """Concrete implementation of InspectLoader.get_source.""" path = self.get_filename(name) try: source_bytes = self.get_data(path) except OSError as exc: e = _ImportError('source not available through get_data()', name=name) e.__cause__ = exc raise e return decode_source(source_bytes)
def exec_module(self, module): """Execute the module using the old imp.""" path = [os.path.dirname(module.__file__)] # file should have been resolved before (module creation) file = None try: file, pathname, description = imp.find_module(module.__name__.rpartition('.')[-1], path) module = imp.load_module(module.__name_...
def load_module(self, name): """Load a module from a file. """ # Implementation inspired from pytest.rewrite and importlib # If there is an existing module object named 'name' in # sys.modules, the loader must use that existing module. (Otherwise, # the reload() builtin will not work correctly.) if name in sys.modules:...
not in sys.modules: if '.' in pkgname: # parent has to be in sys.modules. make sure it is a package, else fails if '__path__' in vars(sys.modules[pkgname.rpartition('.')[0]]): path = sys.modules[pkgname.rpartition('.')[0]].__path__ else: raise ImportError("{0} is not a package (no __path__ detected)".format(pkgname.rpa...
def analyze_xml(xml): """Analyzes `file` against packtools' XMLValidator. """ f = StringIO(xml) try: xml = packtools.XMLValidator.parse(f, sps_version='sps-1.4') except packtools.exceptions.PacktoolsError as e: logger.exception(e) summary = {} summary['dtd_is_valid'] = False summary['sps_is_valid'] = False summary['is_...
def init_host(self): """ Initial host """ env.host_string = self.host_string env.user = self.host_user env.password = self.host_passwd env.key_filename = self.host_keyfile
def install(self): """ install the server """ try: if self.args.server is not None: server = ServerLists(self.server_type) DynamicImporter( 'ezhost', server.name, args=self.args, configure=self.configure ) else: ServerCommand(self.args) except Exception as e: raise e
def filehandles(path, openers_list=openers, pattern='', verbose=False): """Main function that iterates over list of openers and decides which opener to use. :param str path: Path. :param list openers_list: List of openers. :param str pattern: Regular expression pattern. :param verbose: Print additional information. :ty...
def directory_opener(path, pattern='', verbose=False): """Directory opener. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ if not os.path.isdir(path): raise NotADirectoryError else: openers_list = [opener for opener in openers if not opener.__name__.startswith('direct...
def ziparchive_opener(path, pattern='', verbose=False): """Opener that opens files from zip archive.. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ with zipfile.ZipFile(io.BytesIO(urlopen(path).read()), 'r') if is_url(path) else zipfile.ZipFile(path, 'r') as ziparchi...
def tararchive_opener(path, pattern='', verbose=False): """Opener that opens files from tar archive. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ with tarfile.open(fileobj=io.BytesIO(urlopen(path).read())) if is_url(path) else tarfile.open(path) as tararchive: for t...
def gzip_opener(path, pattern='', verbose=False): """Opener that opens single gzip compressed file. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ source = path if is_url(path) else os.path.abspath(path) filename = os.path.basename(path) if pattern and not re.match(pa...
def bz2_opener(path, pattern='', verbose=False): """Opener that opens single bz2 compressed file. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ source = path if is_url(path) else os.path.abspath(path) filename = os.path.basename(path) if pattern and not re.match(patt...
def text_opener(path, pattern='', verbose=False): """Opener that opens single text file. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ source = path if is_url(path) else os.path.abspath(path) filename = os.path.basename(path) if pattern and not re.match(pattern, file...
def random_string(length, charset): """ Return a random string of the given length from the given character set. :param int length: The length of string to return :param str charset: A string of characters to choose from :returns: A random string :rtype: str """ n = len(charset) return ''.join(charset[random.randrange(...
def random_alphanum(length): """ Return a random string of ASCII letters and digits. :param int length: The length of string to return :returns: A random string :rtype: str """ charset = string.ascii_letters + string.digits return random_string(length, charset)
def random_hex(length): """ Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str """ charset = ''.join(set(string.hexdigits.lower())) return random_string(length, charset)
def format_obj_keys(obj, formatter): """ Take a dictionary with string keys and recursively convert all keys from one form to another using the formatting function. The dictionary may contain lists as values, and any nested dictionaries within those lists will also be converted. :param object obj: The object to convert...
in obj] elif type(obj) == dict: return {formatter(k): format_obj_keys(v, formatter) for k, v in obj.items()} else: return obj
def merge_nodes(self, keep_node, kill_node): """ Merge two nodes in the graph. Takes two nodes and merges them together, merging their links by combining the two link lists and summing the weights of links which point to the same node. All links in the graph pointing to ``kill_node`` will be merged into ``keep_node``. ...
'Three'] >>> graph.merge_nodes(node_2, node_3) >>> print([node.value for node in graph.node_list]) ['One', 'Two'] >>> for link in graph.node_list[1].link_list: ... print('{} {}'.format(link.target.value, link.weight)) One 1 Two 8 """ # Merge links from kill_node to keep_node for kill_link in kill_node.link_list: if kil...
def add_nodes(self, nodes): """ Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: >>> from blur.markov.node import Node >>> graph = Graph() >>> node_1 = Node('One') >>> graph.add_nodes(node_1) >...
def feather_links(self, factor=0.01, include_self=False): """ Feather the links of connected nodes. Go through every node in the network and make it inherit the links of the other nodes it is connected to. Because the link weight sum for any given node can be very different within a graph, the weights of inherited link...
{}'.format(link.target.value, link.weight)) Two 1 One 0.01 """ def feather_node(node): node_weight_sum = sum(l.weight for l in node.link_list) # Iterate over a copy of the original link list since we will # need to refer to this while modifying node.link_list for original_link in node.link_list[:]: neighbor_node = orig...
def apply_noise(self, noise_weights=None, uniform_amount=0.1): """ Add noise to every link in the network. Can use either a ``uniform_amount`` or a ``noise_weight`` weight profile. If ``noise_weight`` is set, ``uniform_amount`` will be ignored. Args: noise_weights (list): a list of weight tuples of form ``(float, float...
... link.target.value, link.weight)) # doctest: +SKIP One 3.154 Two 5.321 """ # Main node loop for node in self.node_list: for link in node.link_list: if noise_weights is not None: noise_amount = round(weighted_rand(noise_weights), 3) else: noise_amount = round(random.uniform( 0, link.weight * uniform_amount), 3) link....
def find_node_by_value(self, value): """ Find and return a node in self.node_list with the value ``value``. If multiple nodes exist with the value ``value``, return the first one found. If no such node exists, this returns ``None``. Args: value (Any): The value of the node to find Returns: Node: A node with value ``val...
def remove_node(self, node): """ Remove a node from ``self.node_list`` and links pointing to it. If ``node`` is not in the graph, do nothing. Args: node (Node): The node to be removed Returns: None Example: >>> from blur.markov.node import Node >>> node_1 = Node('One') >>> graph = Graph([node_1]) >>> graph.remove_node(...
def remove_node_by_value(self, value): """ Delete all nodes in ``self.node_list`` with the value ``value``. Args: value (Any): The value to find and delete owners of. Returns: None Example: >>> from blur.markov.node import Node >>> node_1 = Node('One') >>> graph = Graph([node_1]) >>> graph.remove_node_by_value('One') >...
def has_node_with_value(self, value): """ Whether any node in ``self.node_list`` has the value ``value``. Args: value (Any): The value to find in ``self.node_list`` Returns: bool Example: >>> from blur.markov.node import Node >>> node_1 = Node('One') >>> graph = Graph([node_1]) >>> graph.has_node_with_value('One') True...
def pick(self, starting_node=None): """ Pick a node on the graph based on the links in a starting node. Additionally, set ``self.current_node`` to the newly picked node. * if ``starting_node`` is specified, start from there * if ``starting_node`` is ``None``, start from ``self.current_node`` * if ``starting_node`` is `...
= self.current_node # Use weighted_choice on start_node.link_list self.current_node = weighted_choice( [(link.target, link.weight) for link in starting_node.link_list]) return self.current_node
def from_string(cls, source, distance_weights=None, merge_same_words=False, group_marker_opening='<<', group_marker_closing='>>'): """ Read a string and derive of ``Graph`` from it. Words and punctuation marks are made into nodes. Punctuation marks are split into separate nodes unless they fall between other non-punctu...
= r'{0}(.+){1}|([^\w\s]+)\B|([\S]+\b)'.format( ''.join('\\' + c for c in group_marker_opening), ''.join('\\' + c for c in group_marker_closing) ) Args: source (str): the string to derive the graph from distance_weights (dict): dict of relative indices corresponding with word weights. For example, if a dict entry is ``1...
whatever word follows it. Consequently, if this default value is used and ``merge_same_words`` is ``False``, the resulting graph behavior will simply move linearly through the source, wrapping at the end to the beginning. merge_same_words (bool): if nodes which have the same value should be merged or not. group_marker_...
blur' """ if distance_weights is None: distance_weights = {1: 1} # Convert distance_weights to a sorted list of tuples # To make output node list order more predictable sorted_weights_list = sorted(distance_weights.items(), key=lambda i: i[0]) # regex that matches: # * Anything surrounded by # group_marker_opening and ...
a 1:1 correspondence between words and nodes, # and that all links point to these nodes as well # Create nodes for every unique word temp_node_list = [] for word in words: if word not in (n.value for n in temp_node_list): temp_node_list.append(Node(word)) # Loop through words, attaching links to nodes which correspond ...
for every (not necessarily unique) word. temp_node_list = [Node(word) for word in words] for i, node in enumerate(temp_node_list): for key, weight in sorted_weights_list: # Wrap the index of edge items wrapped_index = (key + i) % len(temp_node_list) node.add_link(temp_node_list[wrapped_index], weight) graph = cls() gra...
def from_file(cls, source, distance_weights=None, merge_same_words=False, group_marker_opening='<<', group_marker_closing='>>'): """ Read a string from a file and derive a ``Graph`` from it. This is a convenience function for opening a file and passing its contents to ``Graph.from_string()`` (see that for more detail) ...
nothing to say and i' """ source_string = open(source, 'r').read() return cls.from_string(source_string, distance_weights, merge_same_words, group_marker_opening=group_marker_opening, group_marker_closing=group_marker_closing)
def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs): """Overridden to only call `notify` if model matches. """ notified = False instance = kwargs.get("instance") if instance._meta.label_lower == self.model: notified = super().notify( force_notify=force_notify, use_email=use_email, use_sms=use_sm...
def getclient(): ''' return settings dictionnary ''' if not Configuration.client_initialized: Configuration._initconf() Configuration.client_settings = Configuration.settings['client'] Configuration.client_initialized = True return Configuration.client_settings