code stringlengths 1 18.2k |
|---|
def rewrite_links(self, func): """ Add a callback for rewriting links. The callback should take a single argument, the url, and should return a replacement url. The callback function is called everytime a ``[]()`` or ``<link>`` is processed. You can use this method as a decorator on the function you want to set as the ... |
def link_attrs(self, func): """ Add a callback for adding attributes to links. The callback should take a single argument, the url, and should return additional text to be inserted in the link tag, i.e. ``"target="_blank"``. You can use this method as a decorator on the function you want to set as the callback. """ @li... |
def isseq(obj): ''' Returns True if `obj` is a sequence-like object (but not a string or dict); i.e. a tuple, list, subclass thereof, or having an interface that supports iteration. ''' return \ not isstr(obj) \ and not isdict(obj) \ and ( isinstance(obj, (list, tuple)) \ or callable(getattr(obj, '__iter__', None))) |
def isdict(obj): ''' Returns True if `obj` is a dict-like object (but not a string or list); i.e. a dict, subclass thereof, or having an interface that supports key, value, and item iteration. ''' return \ not isstr(obj) \ and ( isinstance(obj, dict) \ or ( callable(getattr(obj, 'keys', None)) \ and callable(getattr(ob... |
def tobool(obj, default=False): ''' Returns a bool representation of `obj`: if `obj` is not a string, it is returned cast to a boolean by calling `bool()`. Otherwise, it is checked for "truthy" or "falsy" values, and that is returned. If it is not truthy or falsy, `default` is returned (which defaults to ``False``) unl... |
def tolist(obj, flat=True, split=True): ''' Returns `obj` as a list: if it is falsy, returns an empty list; if it is a string and `split` is truthy, then it is split into substrings using Unix shell semantics; if it is sequence-like, a list is returned optionally flattened if `flat` is truthy (see :func:`flatten`). '''... |
def flatten(obj): ''' TODO: add docs ''' if isseq(obj): ret = [] for item in obj: if isseq(item): ret.extend(flatten(item)) else: ret.append(item) return ret if isdict(obj): ret = dict() for key, value in obj.items(): for skey, sval in _relflatten(value): ret[key + skey] = sval return ret raise ValueError( 'only list- ... |
def unflatten(obj): ''' TODO: add docs ''' if not isdict(obj): raise ValueError( 'only dict-like objects can be unflattened, not %r' % (obj,)) ret = dict() sub = dict() for key, value in obj.items(): if '.' not in key and '[' not in key: ret[key] = value continue if '.' in key and '[' in key: idx = min(key.find('.'), k... |
def pick(source, *keys, **kws): ''' Given a `source` dict or object, returns a new dict that contains a subset of keys (each key is a separate positional argument) and/or where each key is a string and has the specified `prefix`, specified as a keyword argument. Also accepts the optional keyword argument `dict` which m... |
c='cee'), d='dee') assert morph.pick(src, 'a.b', tree=True) == dict(a=dict(b='bee')) Requests for keys not found in `source` are silently ignored. :Changes: * `tree` support added in version 0.1.3. ''' rettype = kws.pop('dict', dict) prefix = kws.pop('prefix', None) tree = kws.pop('tree', False) if kws: raise ValueErro... |
rettype() rkeys = keys if tree: rkeys = [key.split('.', 1)[0] for key in rkeys] try: ret = rettype({k: v for k, v in source.items() if k in rkeys}) except AttributeError: ret = rettype({k: getattr(source, k) for k in rkeys if hasattr(source, k)}) if tree: for key in keys: if '.' in key: key, rem = key.split('.', 1) if ... |
def xform(value, xformer): ''' Recursively transforms `value` by calling `xformer` on all keys & values in dictionaries and all values in sequences. Note that `xformer` will be passed each value to transform as the first parameter and other keyword parameters based on type. All transformers MUST support arbitrary addit... |
being transformed is a *key* in key-value dictionary pair. * `dict`: the current dictionary being transformed. * `root`: a reference to the original `value` passed to `xform`. Added in version 0.1.3. ''' def _xform(curval, **kws): if isseq(curval): return [ _xform(val, index=idx, seq=curval) for idx, val in enumerate(c... |
def load_children(self): """ Load the subelements from the xml_element in its correspondent classes. :returns: List of child objects. :rtype: list :raises CardinalityException: If there is more than one Version child. """ # Containers children = list() statuses = list() version = None titles = list() descriptions = lis... |
def _evaluate_field(self, record_dict, field_name, field_criteria): ''' a helper method for evaluating record values based upon query criteria :param record_dict: dictionary with model valid data to evaluate :param field_name: string with path to root of query field :param field_criteria: dictionary with query operator... |
'.%s' % field_name # evaluate other query criteria for key, value in field_criteria.items(): if key in ('min_size', 'min_length'): found = False if self.keyMap[field_key]['value_datatype'] == 'map': for record_value in record_values: record_size = sys.getsizeof(json.dumps(str(record_value)).replace(' ','')) - 51 if rec... |
if not found: return False elif key == 'max_value': found = False for record_value in record_values: if record_value <= value: found = True break if not found: return False elif key == 'equal_to': found = False for record_value in record_values: if record_value == value: found = True break if not found: return False el... |
in value: found = True break if not found: return False elif key == 'integer_data': found = False dummy_int = 1 for record_value in record_values: if record_value.__class__ == dummy_int.__class__: found = True break if value != found: return False elif key == 'byte_data': found = False for record_value in record_values... |
elif key == 'contains_either': found = False for regex in value: regex_pattern = re.compile(regex) for record_value in record_values: if regex_pattern.findall(record_value): found = True break if found: break if not found: return False elif key == 'unique_values': for record_value in record_values: unique_values = True... |
def _validate_dict(self, input_dict, schema_dict, path_to_root, object_title=''): ''' a helper method for recursively validating keys in dictionaries :return input_dict ''' # reconstruct key path to current dictionary in model rules_top_level_key = re.sub('\[\d+\]', '[0]', path_to_root) map_rules = self.keyMap[rules_to... |
for key in input_dict.keys(): error_dict = { 'object_title': object_title, 'model_schema': self.schema, 'input_criteria': self.keyMap[rules_top_level_key], 'failed_test': 'key_datatype', 'input_path': path_to_root, 'error_value': key, 'error_code': 4004 } error_dict['input_criteria']['key_datatype'] = 'string' if path_... |
= path_to_root + '.' + key max_keys.append(schema_key_name) max_key_list.append(key) rules_schema_key_name = re.sub('\[\d+\]', '[0]', schema_key_name) if self.keyMap[rules_schema_key_name]['required_field']: req_keys.append(schema_key_name) req_key_list.append(key) # validate existence of required fields missing_keys =... |
path_to_root + '.' + key rules_input_key_name = re.sub('\[\d+\]', '[0]', input_key_name) if input_key_name in max_keys: input_criteria = self.keyMap[rules_input_key_name] error_dict = { 'object_title': object_title, 'model_schema': self.schema, 'input_criteria': input_criteria, 'failed_test': 'value_datatype', 'input_p... |
if key not in input_key_list: indexed_key = max_keys[max_key_list.index(key)] if indexed_key in self.components.keys(): if 'default_value' in self.components[indexed_key]: input_dict[key] = self.components[indexed_key]['default_value'] return input_dict |
def _validate_list(self, input_list, schema_list, path_to_root, object_title=''): ''' a helper method for recursively validating items in a list :return: input_list ''' # construct rules for list and items rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) list_rules = self.keyMap[rules_path_to_root] initial_k... |
'error_value': None, 'error_code': 4001 } # validate datatype of items for i in range(len(input_list)): input_path = path_to_root + '[%s]' % i item = input_list[i] item_error['input_path'] = input_path try: item_index = self._datatype_classes.index(item.__class__) except: item_error['error_value'] = item.__class__.__na... |
list_error['error_value'] = input_list list_error['error_code'] = 4033 raise InputValidationError(list_error) # TODO: validate top-level item values against identical to reference # TODO: run lambda function and call validation url return input_list |
def _validate_number(self, input_number, path_to_root, object_title=''): ''' a helper method for validating properties of a number :return: input_number ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root] error_dict = { 'object_title': object_title, 'model_sc... |
in input_criteria.keys(): if input_number != input_criteria['equal_to']: error_dict['failed_test'] = 'equal_to' error_dict['error_code'] = 4026 raise InputValidationError(error_dict) if 'discrete_values' in input_criteria.keys(): if input_number not in input_criteria['discrete_values']: error_dict['failed_test'] = 'dis... |
def _validate_string(self, input_string, path_to_root, object_title=''): ''' a helper method for validating properties of a string :return: input_string ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root] error_dict = { 'object_title': object_title, 'model_sc... |
error_dict['error_code'] = 4025 raise InputValidationError(error_dict) if 'equal_to' in input_criteria.keys(): if input_string != input_criteria['equal_to']: error_dict['failed_test'] = 'equal_to' error_dict['error_code'] = 4026 raise InputValidationError(error_dict) if 'min_length' in input_criteria.keys(): if len(inp... |
in input_criteria.keys(): if input_string not in input_criteria['discrete_values']: error_dict['failed_test'] = 'discrete_values' error_dict['error_code'] = 4041 raise InputValidationError(error_dict) if 'excluded_values' in input_criteria.keys(): if input_string in input_criteria['excluded_values']: error_dict['failed... |
def _validate_boolean(self, input_boolean, path_to_root, object_title=''): ''' a helper method for validating properties of a boolean :return: input_boolean ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root] error_dict = { 'object_title': object_title, 'mode... |
def _ingest_dict(self, input_dict, schema_dict, path_to_root): ''' a helper method for ingesting keys, value pairs in a dictionary :return: valid_dict ''' valid_dict = {} # construct path to root for rules rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) # iterate over keys in schema dict for key, value in s... |
self._ingest_string(input_dict[key], key_path) elif value_type == 'map': valid_dict[key] = self._ingest_dict(input_dict[key], schema_dict[key], key_path) elif value_type == 'list': valid_dict[key] = self._ingest_list(input_dict[key], schema_dict[key], key_path) else: value_type = self.keyMap[rules_key_path]['value_data... |
def _ingest_list(self, input_list, schema_list, path_to_root): ''' a helper method for ingesting items in a list :return: valid_list ''' valid_list = [] # construct max list size max_size = None rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) if 'max_size' in self.keyMap[rules_path_to_root].keys(): if not s... |
except: pass if isinstance(max_size, int): if len(valid_list) == max_size: return valid_list return valid_list |
def _ingest_number(self, input_number, path_to_root): ''' a helper method for ingesting a number :return: valid_number ''' valid_number = 0.0 try: valid_number = self._validate_number(input_number, path_to_root) except: rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) if 'default_value' in self.keyMap[rules_... |
def _ingest_string(self, input_string, path_to_root): ''' a helper method for ingesting a string :return: valid_string ''' valid_string = '' try: valid_string = self._validate_string(input_string, path_to_root) except: rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) if 'default_value' in self.keyMap[rules_p... |
def _ingest_boolean(self, input_boolean, path_to_root): ''' a helper method for ingesting a boolean :return: valid_boolean ''' valid_boolean = False try: valid_boolean = self._validate_boolean(input_boolean, path_to_root) except: rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) if 'default_value' in self.key... |
def _reconstruct(self, path_to_root): ''' a helper method for finding the schema endpoint from a path to root :param path_to_root: string with dot path to root from :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments item_pattern = re.compile('\d+\\]') dot_pattern = re... |
def _walk(self, path_to_root, record_dict): ''' a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments item_pattern = re.compile(... |
_walk_int(shortened_segments, record_endpoint[j]) else: stop_chain = False for y in range(0, i): if item_pattern.match(path_segments[y]): stop_chain = True if not stop_chain: if len(path_segments) == i + 1: record_endpoints.append(record_endpoint[path_segments[i]]) else: record_endpoint = record_endpoint[path_segments[... |
def validate(self, input_data, path_to_root='', object_title=''): ''' a core method for validating input against the model input_data is only returned if all data is valid :param input_data: list, dict, string, number, or boolean to validate :param path_to_root: [optional] string with dot-path of model component :param... |
isinstance(object_title, str): raise ModelValidationError('%s must be a string' % _title_arg) # construct generic error dictionary error_dict = { 'object_title': object_title, 'model_schema': self.schema, 'input_criteria': self.keyMap[copy_path], 'failed_test': 'value_datatype', 'input_path': copy_path, 'error_value': ... |
def ingest(self, **kwargs): ''' a core method to ingest and validate arbitrary keyword data **NOTE: data is always returned with this method** for each key in the model, a value is returned according to the following priority: 1. value in kwargs if field passes validation test 2. default value declared for the key in t... |
will stop adding input to the list once it reaches max size :param kwargs: key, value pairs :return: dictionary with keys and value ''' __name__ = '%s.ingest' % self.__class__.__name__ schema_dict = self.schema path_to_root = '.' valid_data = self._ingest_dict(kwargs, schema_dict, path_to_root) return valid_data |
def query(self, query_criteria, valid_record=None): ''' a core method for querying model valid data with criteria **NOTE: input is only returned if all fields & qualifiers are valid for model :param query_criteria: dictionary with model field names and query qualifiers :param valid_record: dictionary with model valid r... |
convert javascript dot_path to class dot_path criteria_copy = {} equal_fields = [] dot_fields = [] for key, value in query_criteria.items(): copy_key = key if not key: copy_key = '.' else: if key[0] != '.': copy_key = '.%s' % key dot_fields.append(copy_key) criteria_copy[copy_key] = value if value.__class__ in self._da... |
raise QueryValidationError(message) # query test record if valid_record: if not isinstance(valid_record, dict): raise ModelValidationError('%s must be a dictionary.' % _record_arg) for key, value in criteria_copy.items(): eval_outcome = self._evaluate_field(valid_record, key, value) if not eval_outcome: return False re... |
def url_view(url_pattern, name=None, priority=None): """ Decorator for registering functional views. Meta decorator syntax has to be used in order to accept arguments. This decorator does not really do anything that magical: This: >>> from urljects import U, url_view >>> @url_view(U / 'my_view') ... def my_view(request... |
**kwargs): return func(*args, **kwargs) wrapper.urljects_view = True wrapper.url = url_pattern wrapper.url_name = name or func.__name__ wrapper.url_priority = priority return wrapper return meta_wrapper |
def resolve_name(view): """ Auto guesses name of the view. For function it will be ``view.__name__`` For classes it will be ``view.url_name`` """ if inspect.isfunction(view): return view.__name__ if hasattr(view, 'url_name'): return view.url_name if isinstance(view, six.string_types): return view.split('.')[-1] return ... |
def url(url_pattern, view, kwargs=None, name=None): """ This is replacement for ``django.conf.urls.url`` function. This url auto calls ``as_view`` method for Class based views and resolves URLPattern objects. If ``name`` is not specified it will try to guess it. :param url_pattern: string with regular expression or URL... |
def view_include(view_module, namespace=None, app_name=None): """ Includes view in the url, works similar to django include function. Auto imports all class based views that are subclass of ``URLView`` and all functional views that have been decorated with ``url_view``. :param view_module: object of the module or strin... |
view_dict[priority] for priority in sorted(view_dict) ]) return urls.include( arg=view_patterns, namespace=namespace, app_name=app_name) |
def cache_file(file_name): """ Cache a given file for further use (by storing them on disk) """ remote_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name) try: copyfile(file_name, remote_file_path) except Exception, e: raise e |
def copy_file(file_name): """ Copy a given file from the cache storage """ remote_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name) current_path = join(getcwd(), file_name) try: copyfile(remote_file_path, current_path) except Exception, e: raise e |
def is_cached(file_name): """ Check if a given file is available in the cache or not """ gml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name) return isfile(gml_file_path) |
def tabulate(self, format='html', syntax=''): ''' a function to create a table from the class model keyMap :param format: string with format for table output :param syntax: [optional] string with linguistic syntax :return: string with table ''' from tabulate import tabulate as _tabulate # define headers headers = ['Fie... |
'javascript': value_datatype = 'integer' elif value['value_datatype'] == 'map': if syntax == 'javascript': value_datatype = 'object' elif value['value_datatype'] == 'list': if syntax == 'javascript': value_datatype = 'array' # retrieve datatype of item in list item_key = key + '[0]' item_datatype = self.keyMap[item_key... |
v['example_values']: if example_value: example_value += ', ' if isinstance(i, str): example_value += '"%s"' % i else: example_value += value elif 'declared_value' in v.keys(): if isinstance(v['declared_value'], str): example_value = '"%s"' % v['declared_value'] elif isinstance(v['declared_value'], bool): example_value ... |
('field_description', 'field_title'): field_description = True if k == 'field_description': description = v elif not description: description = v elif k != 'extra_fields' or add_extra: additional_conditions = True if conditions: conditions += '<br>' condition_value = v if isinstance(v, str): condition_value = '"%s"' % ... |
not default_values: row.pop(3) # construct table html table_html = _tabulate(rows, headers, tablefmt='html') # add links to urls in text # markdown_url = re.compile('\[(.*?)\]\((.*)\)') table_html = _add_links(table_html) return table_html |
def register(self, app, *args, **kwargs): " Activate loginmanager and principal. " if not self._login_manager or self.app != app: self._login_manager = LoginManager() self._login_manager.user_callback = self.user_loader self._login_manager.setup_app(app) self._login_manager.login_view = 'urls.index' self._login_manager... |
def trim_start(self, string, start, end=None): """ Removes the starting substring. :param string: The entire string. :param start: The starting substring to be removed. :param end: An optional point in the string, defaults to the strings ending :return: A substring consists of the subsequent substring after the start s... |
def process_star(filename, output, *, extension, star_name, period, shift, parameters, period_label, shift_label, **kwargs): """Processes a star's lightcurve, prints its coefficients, and saves its plotted lightcurve to a file. Returns the result of get_lightcurve. """ if star_name is None: basename = path.basename(fil... |
def port_in_use(port, kill=False, logging=False): """ Checks whether a port is free or not. :param int port: The port number to check for. :param bool kill: If ``True`` the process will be killed. :returns: The process id as :class:`int` if in use, otherwise ``False`` . """ command_template = 'lsof -iTCP:{0} -sTCP:LIST... |
Check whether it was really killed. try: # If still alive kill_process(pid, logging) # call me again _log(logging, 'Process {0} is still alive! checking again...' .format(pid)) return port_in_use(port, kill) except OSError: # If killed return False else: return pid |
def _normalize_check_url(self, check_url): """ Normalizes check_url by: * Adding the `http` scheme if missing * Adding or replacing port with `self.port` """ # TODO: Write tests for this method split_url = urlsplit(check_url) host = splitport(split_url.path or split_url.netloc)[0] return '{0}://{1}:{2}'.format(self.sch... |
def check(self, check_url=None): """ Checks whether a server is running. :param str check_url: URL where to check whether the server is running. Default is ``"http://{self.host}:{self.port}"``. """ if check_url is not None: self.check_url = self._normalize_check_url(check_url) response = None sleeped = 0.0 t = datetime... |
def live(self, kill_port=False, check_url=None): """ Starts a live server in a separate process and checks whether it is running. :param bool kill_port: If ``True``, processes running on the same port as ``self.port`` will be killed. :param str check_url: URL where to check whether the server is running. Default is ``"... |
def die(self): """Stops the server if it is running.""" if self.process: _log(self.logging, 'Stopping {0} server with PID: {1} running at {2}.' .format(self.__class__.__name__, self.process.pid, self.check_url)) self._kill() |
def parse_args(cls, logging=False): """ Parses command line arguments. Looks for --liveandletdie [host] :returns: A ``(str(host), int(port))`` or ``(None, None)`` tuple. """ cls._add_args() args = cls._argument_parser.parse_args() if args.liveandletdie: _log(logging, 'Running as test live server at {0}' .format(args.li... |
def wrap(cls, app): """ Adds test live server capability to a Flask app module. :param app: A :class:`flask.Flask` app instance. """ host, port = cls.parse_args() ssl = cls._argument_parser.parse_args().ssl ssl_context = None if host: if ssl: try: import OpenSSL except ImportError: # OSX fix sys.path.append( '/System/L... |
def url(route, resource_id=None, pagination=None, **parameters): """ Generates an absolute URL to an API resource. :param route: One of the routes available (see the header of this file) :type route: string :param resource_id: The resource ID you want. If None, it will point to the endpoint. :type resource_id: string|N... |
def is_nested(values): '''Check if values is composed only by iterable elements.''' return (all(isinstance(item, Iterable) for item in values) if isinstance(values, Iterable) else False) |
def import_element(self, xml_element): """ Imports the element from an lxml element and loads its content. """ super(HTMLElement, self).import_element(xml_element) self.content = self.get_html_content() |
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ element_dict = super(HTMLElement, self).as_dict() if hasattr(self, 'content'): element_dict['content'] = self.content return element_dict |
def get_html_content(self): """ Parses the element and subelements and parses any HTML enabled text to its original HTML form for rendering. :returns: Parsed HTML enabled text content. :rtype: str """ # Extract full element node content (including subelements) html_content = '' if hasattr(self, 'xml_element'): xml = se... |
def convert_html_to_xml(self): """ Parses the HTML parsed texts and converts its tags to XML valid tags. :returns: HTML enabled text in a XML valid format. :rtype: str """ if hasattr(self, 'content') and self.content != '': regex = r'<(?!/)(?!!)' xml_content = re.sub(regex, '<xhtml:', self.content) return xml_content e... |
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) for element in self.xml_element: self.xml_element.remove(eleme... |
def submit(self, cmd_string, blocksize, job_name="parsl.auto"): """ Submit a job Args: - cmd_string :(String) - Name of the container to initiate - blocksize :(float) - Number of replicas Kwargs: - job_name (String): Name for job, must be unique Returns: - None: At capacity, cannot provision more - job_id: (string) Ide... |
def cancel(self, job_ids): """ Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. """ for job in job_ids: logger.debug("Terminating job/proc_id : {0}".format(job)) # Here we are assuming that for local, ... |
def _create_deployment_object(self, job_name, job_image, deployment_name, port=80, replicas=1, cmd_string=None, engine_json_file='~/.ipython/profile_default/security/ipcontroller-engine.json', engine_dir='.'): """ Create a kubernetes deployment for the job. Args: - job_name (string) : Name of the job and deployment - j... |
["-c", "{0}; /app/deploy.sh;".format(cmd_string)] print(launch_args) # Configureate Pod template container container = None if security_context: container = client.V1Container( name=job_name, image=job_image, ports=[client.V1ContainerPort(container_port=port)], command=['/bin/bash'], args=launch_args, env=[environment_... |
def gen_sites(path): " Seek sites by path. " for root, _, _ in walklevel(path, 2): try: yield Site(root) except AssertionError: continue |
def find_site(site, path=None): " Return inited site by name (project.bracnch) or path " try: return Site(site) except AssertionError: path = path or settings.MAKESITE_HOME if op.sep in site: raise site = site if '.' in site else "%s.master" % site project, branch = site.split('.', 1) return Site(op.join(path, project,... |
def get_info(self, full=False): " Return printable information about current site. " if full: context = self.as_dict() return "".join("{0:<25} = {1}\n".format( key, context[key]) for key in sorted(context.iterkeys())) return "%s [%s]" % (self.get_name(), self.template) |
def run_check(self, template_name=None, service_dir=None): " Run checking scripts. " print_header('Check requirements', sep='-') map(lambda cmd: call("bash %s" % cmd), self._gen_scripts( 'check', template_name=template_name, service_dir=service_dir)) return True |
def run_update(self, template_name=None, service_dir=None): " Run update scripts. " LOGGER.info('Site Update start.') print_header('Update %s' % self.get_name()) map(call, self._gen_scripts( 'update', template_name=template_name, service_dir=service_dir)) LOGGER.info('Site Update done.') return True |
def paste_template(self, template_name, template=None, deploy_dir=None): " Paste template. " LOGGER.debug("Paste template: %s" % template_name) deploy_dir = deploy_dir or self.deploy_dir template = template or self._get_template_path(template_name) self.read([op.join(template, settings.CFGNAME)], extending=True) for fn... |
def agents(self): """identify which players are agents (not observers or computers). Errors if flattened.""" ret = [] for player in self.players: if player.isComputer: continue try: if player.observer: continue except: pass ret.append(player) return ret |
def allLobbySlots(self): """the current configuration of the lobby's players, defined before the match starts""" if self.debug: p = ["Lobby Configuration detail:"] + \ [" %s:%s%s"%(p, " "*(12-len(p.type)), p.name)] #[" agent: %s"%p for p in self.agents] + \ #[" computer: %s, %s"%(r,d) for r,d in self.computers] if self... |
def connection(self): """identify the remote connection parameters""" self.getPorts() # acquire if necessary self.getIPaddresses() # acquire if necessary return (self.ipAddress, self.ports) |
def execPath(self): """the executable application's path""" vers = self.version.label if self.version else None # executables in Versions folder are stored by baseVersion (modified by game data patches) return self.installedApp.exec_path(vers) |
def installedApp(self): """identify the propery application to launch, given the configuration""" try: return self._installedApp except: # raises if not yet defined self._installedApp = runConfigs.get() # application/install/platform management return self._installedApp |
def observers(self): """the players who are actually observers""" ret = [] for player in self.players: try: if player.observer: ret.append(player) except: pass # ignore PlayerRecords which don't have an observer attribute return ret |
def participants(self): """agents + computers (i.e. all non-observers)""" ret = [] for p in self.players: try: if p.isComputer: ret.append(p) if not p.isObserver: ret.append(p) # could cause an exception if player isn't a PlayerPreGame except AttributeError: pass return ret |
def flatten(self, data=None): """reduce all objects into simplified values as a attr dictionary that could be transformed back into a full configuration via inflate()""" if data == None: data=self.attrs ret = {} for k,v in iteritems(data): if not v: continue # don't flatten if there's nothing to flatten elif k == "expo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.