code stringlengths 1 18.2k |
|---|
def to_internal_value(self, value): """Basically, each tag dict must include a full dict with id, name and slug--or else you need to pass in a dict with just a name, which indicated that the Tag doesn't exist, and should be added.""" if "id" in value: tag = Tag.objects.get(id=value["id"]) else: if "name" not in value: ... |
def to_internal_value(self, value): """Basically, each tag dict must include a full dict with id, name and slug--or else you need to pass in a dict with just a name, which indicated that the FeatureType doesn't exist, and should be added.""" if value == "": return None if isinstance(value, string_types): slug = slugify... |
def to_internal_value(self, data): """Basically, each author dict must include either a username or id.""" # model = get_user_model() model = self.Meta.model if "id" in data: author = model.objects.get(id=data["id"]) else: if "username" not in data: raise ValidationError("Authors must include an ID or a username.") use... |
def watch(directory=None, auto_clear=False, extensions=[]): """Starts a server to render the specified file or directory containing a README.""" if directory and not os.path.isdir(directory): raise ValueError('Directory not found: ' + directory) directory = os.path.abspath(directory) # Initial run event_handler = Chang... |
def run(self): """Called when a file is changed to re-run the tests with nose.""" if self.auto_clear: os.system('cls' if os.name == 'nt' else 'auto_clear') else: print print 'Running unit tests...' if self.auto_clear: print subprocess.call('nosetests', cwd=self.directory) |
def write_tex(): """ Finds all of the output data files, and writes them out to .tex """ datadir = livvkit.index_dir outdir = os.path.join(datadir, "tex") print(outdir) # functions.mkdir_p(outdir) data_files = glob.glob(datadir + "/**/*.json", recursive=True) for each in data_files: data = functions.read_json(each) tex... |
def translate_page(data): """ Translates data elements with data['Type'] = 'page'. This is the top level of translation that occurs, and delegates the translation of other element types contained on a page to their proper functions. """ if "Page" != data["Type"]: return "" tex_str = ('\\documentclass{article}\\n' + '\\... |
def translate_section(data): """ Translates data where data["Type"]=="Section" """ sect_str = "" elements = data.get("Elements", []) for elem in elements: print(" Translating " + elem["Type"]) sect_str += translate_map[elem["Type"]](elem) return sect_str |
def translate_tab(data): """ Translates data where data["Type"]=="Tab" """ tab_str = "" sections = data.get("Sections", []) for section in sections: print(" Translating " + section["Type"]) tab_str += translate_map[section["Type"]](section) return tab_str |
def translate_summary(data): """ Translates data where data["Type"]=="Summary" """ headers = sorted(data.get("Headers", [])) summary = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) summary += ' \\begin{table}[!ht] \n \\begin{center}' # Set the number of columns n_cols = len(header... |
.replace('$H_DATA_0', str(h_data[0])) .replace('$H_DATA_1', str(h_data[1])) .replace('%', '\%')) else: summary += ' $H_DATA &'.replace('$H_DATA', str(h_data)).replace('%', '\%') # This takes care of the trailing & that comes from processing the headers. summary = summary[:-1] + r' \\' summary += '\n \end{tabular} \n \e... |
def translate_table(data): """ Translates data where data["Type"]=="Table" """ headers = sorted(data.get("Headers", [])) table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) table += '\\begin{table}[!ht] \n \\begin{center}' # Set the number of columns n_cols = "c"*(len(headers)+1... |
def translate_bit_for_bit(data): """ Translates data where data["Type"]=="Bit for Bit" """ headers = sorted(data.get("Headers", [])) table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) table += '\\begin{table}[!ht] \n \\begin{center}' # Set the number of columns n_cols = "c"*(le... |
def translate_file_diff(data): """ Translates data where data["Type"]=="Diff" """ diff = '\\FloatBarrier \section{Configuration}' sections = data.get('Data') for title, config in sections.items(): title = title.replace('_', '\_') diff += ' \n \\subsection{$NAME}'.replace('$NAME', title) for opt, vals in config.items():... |
def _invoke(self, *params): """ Invoke self.exe as a subprocess """ cmd = [self.exe] + list(params) proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.location, env=self.env) stdout, stderr = proc.communicate() if not proc.returncode == 0: raise RuntimeError(stderr.strip() or stdout.... |
def allow_bare_decorator(cls): """ Wrapper for a class decorator which allows for bare decorator and argument syntax """ @wraps(cls) def wrapper(*args, **kwargs): """"Wrapper for real decorator""" # If we weren't only passed a bare class, return class instance if kwargs or len(args) != 1 or not isclass(args[0]): # pyli... |
def warp_image_by_corner_points_projection(corner_points, image): """Given corner points of a Sudoku, warps original selection to a square image. :param corner_points: :type: corner_points: list :param image: :type image: :return: :rtype: """ # Clarify by storing in named variables. top_left, top_right, bottom_left, bo... |
def cache_spec(name, spec): """ Cache the spec dict :param name: Version name :param spec: Spec dict :return: True if cached """ return cache.set(build_cache_name(name), spec, app_settings.ESI_SPEC_CACHE_DURATION) |
def get_spec(name, http_client=None, config=None): """ :param name: Name of the revision of spec, eg latest or v4 :param http_client: Requests client used for retrieving specs :param config: Spec configuration - see Spec.CONFIG_DEFAULTS :return: :class:`bravado_core.spec.Spec` """ http_client = http_client or requests_... |
def build_spec(base_version, http_client=None, **kwargs): """ Generates the Spec used to initialize a SwaggerClient, supporting mixed resource versions :param http_client: :class:`bravado.requests_client.RequestsClient` :param base_version: Version to base the spec on. Any resource without an explicit version will be t... |
def read_spec(path, http_client=None): """ Reads in a swagger spec file used to initialize a SwaggerClient :param path: String path to local swagger spec file. :param http_client: :class:`bravado.requests_client.RequestsClient` :return: :class:`bravado_core.spec.Spec` """ with open(path, 'r') as f: spec_dict = json.loa... |
def esi_client_factory(token=None, datasource=None, spec_file=None, version=None, **kwargs): """ Generates an ESI client. :param token: :class:`esi.Token` used to access authenticated endpoints. :param datasource: Name of the ESI datasource to access. :param spec_file: Absolute path to a swagger spec file to load. :par... |
= build_spec(api_version, http_client=client, **kwargs) return SwaggerClient(spec) |
def minimize_spec(spec_dict, operations=None, resources=None): """ Trims down a source spec dict to only the operations or resources indicated. :param spec_dict: The source spec dict to minimize. :type spec_dict: dict :param operations: A list of opertion IDs to retain. :type operations: list of str :param resources: A... |
not in minimized['paths']: minimized['paths'][path_name] = {} minimized['paths'][path_name][method] = data return minimized |
def _build_cache_key(request): """ Generated the key name used to cache responses :param request: request used to retrieve API response :return: formatted cache name """ str_hash = md5( (request.method + request.url + str(request.params) + str(request.data) + str(request.json)).encode( 'utf-8')).hexdigest() return 'esi... |
def _time_to_expiry(expires): """ Determines the seconds until a HTTP header "Expires" timestamp :param expires: HTTP response "Expires" header :return: seconds until "Expires" time """ try: expires_dt = datetime.strptime(str(expires), '%a, %d %b %Y %H:%M:%S %Z') delta = expires_dt - datetime.utcnow() return delta.seco... |
def dict_get_path(data, path, default=None): """ Returns the value inside nested structure of data located at period delimited path When traversing a list, as long as that list is containing objects of type dict, items in that list will have their "name" and "type" values tested against the current key in the path. Arg... |
else: return default return data |
def from_graph(cls, graph, length=0): """ Creates a hypergraph (expanded graph) from a :class:`caspo.core.graph.Graph` object instance Parameters ---------- graph : :class:`caspo.core.graph.Graph` The base interaction graph to be expanded length : int Maximum length for hyperedges source sets. If 0, use maximum possibl... |
name='name') hyper = pd.Series(hyper, name='node_idx') edges = pd.DataFrame(edges) return cls(nodes, hyper, edges) |
def to_funset(self): """ Converts the hypergraph to a set of `gringo.Fun`_ instances Returns ------- set Representation of the hypergraph as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set() for i, n in self.nodes.iteritems(): fs.add(gringo.Fun('node', [n, i... |
def _process_worker(call_queue, result_queue, shutdown): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a seperate process. Args: call_queue: A multiprocessing.Queue of _CallItems that will be read and evaluated by the worker. result_queue: A multiprocessing.Queue of _R... |
def _queue_manangement_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue, shutdown_process_event): """Manages the communication between this process and the worker processes. This function is run in a local thread. Args: executor_reference: A weakref.ref to the ProcessPo... |
when their work queue is empty. """ while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) try: result_item = result_queue.get(block=True, timeout=0.1) except queue.Empty: executor = executor_reference() # No more work items can be added if: # - The interpreter is shutting down OR # - The e... |
= pending_work_items.pop(result_item.work_id) loop = work_item.loop loop.call_from_thread(_set_work_result, work_item, result_item) del result_item, work_item, loop |
def options(f): """ Shared options, used by all bartender commands """ f = click.option('--config', envvar='VODKA_HOME', default=click.get_app_dir('vodka'), help="location of config file")(f) return f |
def check_config(config): """ Check and validate configuration attributes, to help administrators quickly spot missing required configurations and invalid configuration values in general """ cfg = vodka.config.Config(read=config) vodka.log.set_loggers(cfg.get("logging")) vodka.app.load_all(cfg) click.echo("Checking con... |
def config(config, skip_defaults): """ Generates configuration file from config specifications """ configurator = ClickConfigurator( vodka.plugin, skip_defaults=skip_defaults ) configurator.configure(vodka.config.instance, vodka.config.InstanceHandler) try: dst = munge_config.parse_url(config) except ValueError: config... |
def newapp(path): """ Generates all files for a new vodka app at the specified location. Will generate to current directory if no path is specified """ app_path = os.path.join(VODKA_INSTALL_DIR, "resources", "blank_app") if not os.path.exists(path): os.makedirs(path) elif os.path.exists(os.path.join(path, "application.... |
def serve(config): """ Serves (runs) the vodka application """ cfg = vodka.config.Config(read=config) vodka.run(cfg, cfg) |
def Email(msg=None): ''' Valida endereços de email ''' def f(v): if re.match("[\w\.\-]*@[\w\.\-]*\.\w+", str(v)): return str(v) else: raise Invalid(msg or ("Endereco de email invalido")) return f |
def is_enabled(): """Returns ``True`` if bcrypt should be used.""" enabled = getattr(settings, "BCRYPT_ENABLED", True) if not enabled: return False # Are we under a test? if hasattr(mail, 'outbox'): return getattr(settings, "BCRYPT_ENABLED_UNDER_TEST", False) return True |
def bcrypt_check_password(self, raw_password): """ Returns a boolean of whether the *raw_password* was correct. Attempts to validate with bcrypt, but falls back to Django's ``User.check_password()`` if the hash is incorrect. If ``BCRYPT_MIGRATE`` is set, attempts to convert sha1 password to bcrypt or converts between d... |
def bcrypt_set_password(self, raw_password): """ Sets the user's password to *raw_password*, hashed with bcrypt. """ if not is_enabled() or raw_password is None: _set_password(self, raw_password) else: salt = bcrypt.gensalt(get_rounds()) self.password = 'bc$' + bcrypt.hashpw(smart_str(raw_password), salt) |
def mac_app_exists(app): '''Check if 'app' is installed (OS X). Check if the given applications is installed on this OS X system. Args: app (str): The application name. Returns: bool: Is the app installed or not? ''' APP_CHECK_APPLESCRIPT = '''try tell application "Finder" set appname to name of application file id "%s... |
def open_file_with_default_program(file_path, background=False, return_cmd=False): '''Opens a file with the default program for that type. Open the file with the user's preferred application. Args: file_path (str) : Path to the file to be opened. background (bool): Run the program in the background, instead of waiting ... |
file_mime_type]) open_file_cmd = desktopfile.execute(desktopfile.locate( desktop_file)[0], files=[file_path], return_cmd=True) if return_cmd: return open_file_cmd else: def_program_proc = sp.Popen(open_file_cmd, shell=True) if not background: def_program_proc.wait() |
def terminal(exec_='', background=False, shell_after_cmd_exec=False, keep_open_after_cmd_exec=False, return_cmd=False): '''Start the default terminal emulator. Start the user's preferred terminal emulator, optionally running a command in it. **Order of starting** Windows: Powershell Mac: - iTerm2 - Terminal.app Linux/U... |
to run the terminal instead of running it. Else returns nothing. ''' desktop_env = system.get_name() if not exec_: shell_after_cmd_exec = True if desktop_env == 'windows': terminal_cmd_str = 'start powershell.exe' if desktop_env == 'mac': # Try iTerm2 first, apparently most popular Mac Terminal if mac_app_exists('iTerm... |
'gnome-terminal' elif desktop_env == 'xfce4': terminal_cmd_str = 'xfce4-terminal' elif desktop_env == 'kde' or desktop_env == 'trinity': terminal_cmd_str = 'konsole' elif desktop_env == 'mate': terminal_cmd_str = 'mate-terminal' elif desktop_env == 'i3': terminal_cmd_str = 'i3-sensible-terminal' elif desktop_env == 'pa... |
shell_after_cmd_exec: exec_ += '; ' + os.getenv('SHELL') if desktop_env == 'mac': terminal_cmd_str += ' sh -c {}'.format(shlex.quote(exec_)) else: terminal_cmd_str += ' -e {}'.format( shlex.quote('sh -c {}'.format(shlex.quote(exec_)))) if return_cmd: return terminal_cmd_str terminal_proc = sp.Popen([terminal_cmd_str], ... |
def text_editor(file='', background=False, return_cmd=False): '''Starts the default graphical text editor. Start the user's preferred graphical text editor, optionally with a file. Args: file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file). background (bool): Runs the editor in... |
text/plain editor_cmd_str = system.get_cmd_out( ['xdg-mime', 'query', 'default', 'text/plain']) if '\n' in editor_cmd_str: # Sometimes locate returns multiple results # use first one editor_cmd_str = editor_cmd_str.split('\n')[0] if editor_cmd_str.endswith('.desktop'): # We don't use desktopfile.execute() in order to h... |
def run(run_type, module, config): """ Collects the analyses cases to be run and launches processes for each of them. Args: run_type: A string representation of the run type (eg. verification) module: The module corresponding to the run. Must have a run_suite function config: The configuration for the module """ print(... |
def launch_processes(tests, run_module, group=True, **config): """ Helper method to launch processes and sync output """ manager = multiprocessing.Manager() test_summaries = manager.dict() process_handles = [multiprocessing.Process(target=run_module.run_suite, args=(test, config[test], test_summaries)) for test in test... |
def on_resize(width, height): """Setup 3D projection""" glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(30, 1.0*width/height, 0.1, 1000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() |
def Route(resource=None, methods=["get", "post", "put", "delete"], schema=None): """ route """ def _route(func): def wrapper(self, *args, **kwargs): # "test" argument means no wrap func this time, # return original func immediately. if kwargs.get("test", False): kwargs.pop("test") func(self, *args, **kwargs) _methods =... |
def _register_routes(self, methods): """ _register_routes """ # setup routes by decorator methods = [(n, v) for (n, v) in methods if v.__name__ == "wrapper"] methods = sorted(methods, key=lambda x: x[1]._order) for name, value in methods: value() # execute setting route return methods |
def _dispatch_message(self): """ _dispatch_message """ while True: message = self.req_queue.get() if message is None: _logger.debug("_dispatch_message thread is terminated") return if message._type != MessageType.EVENT: self.__dispatch_message(message) elif message._type == MessageType.EVENT: self.__dispatch_event_mess... |
def _resolve_responses(self): """ _resolve_responses """ while True: message = self.res_queue.get() if message is None: _logger.debug("_resolve_responses thread is terminated") return self.__resolve_responses(message) |
def start(self): """ start """ def main_thread(): # create resp, req thread pool self._create_thread_pool() # start connection, this will block until stop() self.conn_thread = Thread(target=self._conn.connect) self.conn_thread.daemon = True self.conn_thread.start() # register model to controller... self.is_ready.wait()... |
def stop(self, *args, **kwargs): """ exit """ _logger.debug("Bundle [%s] has been shutting down" % self.bundle.profile["name"]) if hasattr(self, 'before_stop') and \ hasattr(self.before_stop, '__call__'): _logger.debug("Invoking before_stop...") self.before_stop() self._conn.disconnect() self._session.stop() self.stop_... |
def on_sanji_message(self, client, userdata, msg): """This function will recevie all message from mqtt client the client instance for this callback userdata the private user data as set in Client() or userdata_set() message an instance of MQTTMessage. This is a class with members topic, payload, qos, retain. """ try: m... |
def on_connect(self, client, userdata, flags, rc): """ on_connect(self, client, obj, flags, rc): client the client instance for this callback userdata the private user data as set in Client() or userdata_set() flags response flags sent by the broker rc the connection result """ _logger.debug("Connection established wit... |
def register(self, reg_data, retry=True, interval=1, timeout=3): """ register function retry True, infinity retries False, no retries Number, retries times interval time period for retry return False if no success Tunnel if success """ if len(reg_data["resources"]) == 0: _logger.debug("%s no need to register due to no ... |
def deregister(self, reg_data, retry=True, interval=1, timeout=3): """ Deregister model/view of this bundle """ Retry(target=self.publish.direct.delete, args=("/controller/registration", reg_data,), kwargs={"timeout": timeout}, options={"retry": retry, "interval": interval}) _logger.debug("Deregister successfully %s tu... |
def get_context(self): """Add mails to the context """ context = super(MailListView, self).get_context() mail_list = registered_mails_names() context['mail_map'] = mail_list return context |
def url_split(s3_url): """Split S3 URL and return a tuple of (bucket, key). S3 URL is expected to be of "s3://<bucket>/<key>" format. """ assert isinstance(s3_url, str) match = re_s3_url.match(s3_url) if not match: raise UrlParseError('Error parsing S3 URL: "%s"' % s3_url) parts = match.groupdict() return (parts['bucke... |
def open(s3_url, mode='r', s3_connection=None, **kwargs): """Open S3 url, returning a File Object. S3 connection: 1. Can be specified directly by `s3_connection`. 2. `boto.connect_s3` will be used supplying all `kwargs`. - `aws_access_key_id` and `aws_secret_access_key`. - `profile_name` - recommended. See: http://boto... |
def is_decimal(self): """Determine if a data record is of the type float.""" dt = DATA_TYPES['decimal'] if type(self.data) in dt['type']: self.type = 'DECIMAL' num_split = str(self.data).split('.', 1) self.len = len(num_split[0]) self.len_decimal = len(num_split[1]) return True |
def _is_numeric_data(self, data_type): """Private method for testing text data types.""" dt = DATA_TYPES[data_type] if dt['min'] and dt['max']: if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']: self.type = data_type.upper() self.len = len(str(self.data)) return True |
def create_enrollment_term(self, account_id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None): """ Create enrollment term. Create a new enrollment term for the specified account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id ""... |
with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/terms".format(**path), data=data, params=params, single_item=True) |
def list_enrollment_terms(self, account_id, workflow_state=None): """ List enrollment terms. Return all of the terms in the account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - workflow_state """If set, only returns terms that are in the given... |
def from_model(cls, model_instance, default_value=False, **kwargs): """ wrapper for Model's get_attribute_filter """ if not isinstance(model_instance, DataCollection): raise TypeError("model_instance must be a subclass of \ prestans.types.DataCollection, %s given" % (model_instance.__class__.__name__)) elif isinstance(... |
def blueprint(self): """ :return: blueprint :rtype: dict """ blueprint = dict() for key in self.keys(): blueprint[key] = self.is_attribute_visible(key) return blueprint |
def conforms_to_template_filter(self, template_filter): """ Check AttributeFilter conforms to the rules set by the template - If self, has attributes that template_filter does not contain, throw Exception - If sub list found, perform the first check - If self has a value for an attribute, assign to final AttributeFilte... |
that we send back evaluated_attribute_filter = AttributeFilter() # 3. Evaluate the differences between the two, with template_filter as the standard for template_key in template_filter_keys: if template_key in this_filter_keys: value = getattr(self, template_key) # if sub filter and boolean provided with of true, creat... |
def keys(self): """ :returns: a list of usable keys :rtype: list """ keys = list() for attribute_name, type_instance in inspect.getmembers(self): # ignore parameters with __ and if they are methods if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue keys.append(attribute_name) return keys |
def is_filter_at_key(self, key): """ return True if attribute is a sub filter """ if key in self: attribute_status = getattr(self, key) if isinstance(attribute_status, self.__class__): return True return False |
def is_attribute_visible(self, key): """ Returns True if an attribute is visible If attribute is an instance of AttributeFilter, it returns True if all attributes of the sub filter are visible. :param key: name of attribute to check :type key: str :return: whether attribute is visible :rtype: bool """ if key in self: a... |
def are_any_attributes_visible(self): """ checks to see if any attributes are set to true """ for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue if isinstance(type_instance, bool) and type_instance is True: return True elif isin... |
def set_all_attribute_values(self, value): """ sets all the attribute values to the value and propagate to any children """ for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): # Ignore parameters with __ and if they are methods continue i... |
def as_dict(self): """ turns attribute filter object into python dictionary """ output_dictionary = dict() for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue if isinstance(type_instance, bool): output_dictionary[attribute_name] ... |
def _init_from_dictionary(self, from_dictionary, template_model=None): """ Private helper to init values from a dictionary, wraps children into AttributeFilter objects :param from_dictionary: dictionary to get attribute names and visibility from :type from_dictionary: dict :param template_model: :type template_model: D... |
check to see we can work with the value if not isinstance(value, (bool, dict)): raise TypeError("AttributeFilter input for key %s must be \ boolean or dict, %s provided" % (key, value.__class__.__name__)) # Either keep the value of wrap it up with AttributeFilter if isinstance(value, bool): setattr(self, target_key, va... |
def predict(self): """ Computes all possible weighted average predictions and their variances Example:: >>> from caspo import core, predict >>> networks = core.LogicalNetworkList.from_csv('behaviors.csv') >>> setup = core.Setup.from_json('setup.json') >>> predictor = predict.Predictor(networks, setup) >>> df = predicto... |
def get_traffic_items(self): """ :return: dictionary {name: object} of all traffic items. """ traffic = self.get_child_static('traffic') return {o.obj_name(): o for o in traffic.get_objects_or_children_by_type('trafficItem')} |
def content(self): """ Returns raw CSV content of the log file. """ raw_content = self._manager.api.session.get(self.download_link).content data = BytesIO(raw_content) archive = ZipFile(data) filename = archive.filelist[0] # Always 1 file in the archive return archive.read(filename) |
def validate(self, read_tuple_name): """Check RNF validity of a read tuple. Args: read_tuple_name (str): Read tuple name to be checked.s """ if reg_lrn.match(read_tuple_name) is None: self.report_error( read_tuple_name=read_tuple_name, error_name="wrong_read_tuple_name_structure", message="'{}' is not matched".format(r... |
def report_error(self, read_tuple_name, error_name, wrong="", message="", warning=False): """Report an error. Args: read_tuple_name (): Name of the read tuple. error_name (): Name of the error. wrong (str): What is wrong. message (str): Additional msessage to be printed. warning (bool): Warning (not an error). """ if (... |
def _is_exempt(self, environ): """ Returns True if this request's URL starts with one of the excluded paths. """ exemptions = self.exclude_paths if exemptions: path = environ.get('PATH_INFO') for excluded_p in self.exclude_paths: if path.startswith(excluded_p): return True return False |
def load_network_model(model): ''' Loads metabolic network models in metabolitics. :param str model: model name ''' if type(model) == str: if model in ['ecoli', 'textbook', 'salmonella']: return cb.test.create_test_model(model) elif model == 'recon2': return cb.io.load_json_model('%s/network_models/%s.json' % (DATASET_... |
def get_expired(self): """ Get all tokens which have expired. :return: All expired tokens. :rtype: :class:`esi.managers.TokenQueryset` """ max_age = timezone.now() - timedelta(seconds=app_settings.ESI_TOKEN_VALID_DURATION) return self.filter(created__lte=max_age) |
def bulk_refresh(self): """ Refreshes all refreshable tokens in the queryset. Deletes any tokens which fail to refresh. Deletes any tokens which are expired and cannot refresh. Excludes tokens for which the refresh was incomplete for other reasons. """ session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID) auth = requ... |
def require_valid(self): """ Ensures all tokens are still valid. If expired, attempts to refresh. Deletes those which fail to refresh or cannot be refreshed. :return: All tokens which are still valid. :rtype: :class:`esi.managers.TokenQueryset` """ expired = self.get_expired() valid = self.exclude(pk__in=expired) valid... |
def require_scopes(self, scope_string): """ :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with all requested scopes. :rtype: :class:`esi.managers.TokenQueryset` """ scopes = _process_scopes(scope_string) if not scopes: # asking for tokens with no scopes return self.f... |
def require_scopes_exact(self, scope_string): """ :param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with only the requested scopes. :rtype: :class:`esi.managers.TokenQueryset` """ num_scopes = len(_process_scopes(scope_string)) pks = [v['pk'] for v in self.annotate(model... |
def equivalent_to(self, token): """ Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset` """ return self.filter(character_id=token.character_id).require_scopes_exact(token.scopes.all()).filter( models.Q(user=token.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.