code stringlengths 1 18.2k |
|---|
def collectstatic(force=False): """ collect static files for production httpd If run with ``settings.DEBUG==True``, this is a no-op unless ``force`` is set to ``True`` """ # noise reduction: only collectstatic if not in debug mode from django.conf import settings if force or not settings.DEBUG: tasks.manage('collectsta... |
def load_manifests(self): """ Loads all plugin manifests on the plugin path """ for path in self.plugin_paths: for item in os.listdir(path): item_path = os.path.join(path, item) if os.path.isdir(item_path): self.load_manifest(item_path) |
def load_manifest(self, path): """ Loads a plugin manifest from a given path :param path: The folder to load the plugin manifest from """ manifest_path = os.path.join(path, "plugin.json") self._logger.debug("Attempting to load plugin manifest from {}.".format(manifest_path)) try: with open(manifest_path) as f: manifest... |
def load_plugin(self, manifest, *args): """ Loads a plugin from the given manifest :param manifest: The manifest to use to load the plugin :param args: Arguments to pass to the plugin """ if self.get_plugin_loaded(manifest["name"]): self._logger.debug("Plugin {} is already loaded.".format(manifest["name"])) return try:... |
manifest.get("main_path", "__init__.py")) ) module_class = manifest.get("main_class", "Plugin") plugin_class = getattr(module, module_class) if issubclass(plugin_class, self._plugin_class): plugin = plugin_class(manifest, *args) else: self._logger.error("Failed to load {} due to invalid baseclass.".format(manifest["nam... |
def load_plugins(self, *args): """ Loads all plugins :param args: Arguments to pass to the plugins """ for manifest in self._manifests: self.load_plugin(manifest, *args) |
def get_all_plugins(self): """ Gets all loaded plugins :return: List of all plugins """ return [{ "manifest": i, "plugin": self.get_plugin(i["name"]), "module": self.get_module(i["name"]) } for i in self._manifests] |
def reload_manifest(self, manifest): """ Reloads a manifest from the disk :param manifest: The manifest to reload """ self._logger.debug("Reloading manifest for {}.".format(manifest.get("name", "Unnamed Plugin"))) self._manifests.remove(manifest) self.load_manifest(manifest["path"]) self._logger.debug("Manifest reloade... |
def reload_all_manifests(self): """ Reloads all loaded manifests, and loads any new manifests """ self._logger.debug("Reloading all manifests.") self._manifests = [] self.load_manifests() self._logger.debug("All manifests reloaded.") |
def reload_plugin(self, name, *args): """ Reloads a given plugin :param name: The name of the plugin :param args: The args to pass to the plugin """ self._logger.debug("Reloading {}.".format(name)) self._logger.debug("Disabling {}.".format(name)) self.get_plugin(name).disable() self._logger.debug("Removing plugin insta... |
def reload_all_plugins(self, *args): """ Reloads all initialized plugins """ for manifest in self._manifests[:]: if self.get_plugin(manifest["name"]) is not None: self.reload_plugin(manifest["name"], *args) |
def unload_plugin(self, name): """ Unloads a specified plugin :param name: The name of the plugin """ self._logger.debug("Unloading {}.".format(name)) self._logger.debug("Removing plugin instance.") del self._plugins[name] self._logger.debug("Unloading module.") del self._modules[name] self._logger.debug("Unloading man... |
def quickload(self, *args): """ Loads all manifests, loads all plugins, and then enables all plugins :param args: The args to pass to the plugin """ self.load_manifests() self.load_plugins(args) self.enable_all_plugins() |
def next(self): """ Yields the next row from the source files. """ for self._filename in self._filenames: self._open() for row in self._csv_reader: self._row_number += 1 if self._fields: yield dict(zip_longest(self._fields, row, fillvalue='')) else: yield row self._close() self._row_number = -1 self._filename = None ra... |
def _open_file(self, mode, encoding=None): """ Opens the next current file. :param str mode: The mode for opening the file. :param str encoding: The encoding of the file. """ if self._filename[-4:] == '.bz2': self._file = bz2.open(self._filename, mode=mode, encoding=encoding) else: self._file = open(self._filename, mod... |
def _get_sample(self, mode, encoding): """ Get a sample from the next current input file. :param str mode: The mode for opening the file. :param str|None encoding: The encoding of the file. None for open the file in binary mode. """ self._open_file(mode, encoding) self._sample = self._file.read(UniversalCsvReader.sampl... |
def _detect_delimiter(self): """ Detects the field delimiter in the sample data. """ candidate_value = ',' candidate_count = 0 for delimiter in UniversalCsvReader.delimiters: count = self._sample.count(delimiter) if count > candidate_count: candidate_value = delimiter candidate_count = count self._formatting_parameters... |
def _detect_line_ending(self): """ Detects the line ending in the sample data. """ candidate_value = '\n' candidate_count = 0 for line_ending in UniversalCsvReader.line_endings: count = self._sample.count(line_ending) if count > candidate_count: candidate_value = line_ending candidate_count = count self._formatting_par... |
def _open(self): """ Opens the next current file with proper settings for encoding and delimiter. """ self._sample = None formatting_parameters0 = {'encoding': 'auto', 'delimiter': 'auto', 'line_terminator': 'auto', 'escape_char': '\\', 'quote_char': '"'} formatting_parameters1 = self._helper.pass1(self._filename, form... |
def list_syntax(self): ''' Prints a list of available syntax for the current paste service ''' syntax_list = ['Available syntax for %s:' %(self)] logging.info(syntax_list[0]) for key in self.SYNTAX_DICT.keys(): syntax = '\t%-20s%-30s' %(key, self.SYNTAX_DICT[key]) logging.info(syntax) syntax_list.append(syntax) return ... |
def process_commmon(self): ''' Some data processing common for all services. No need to override this. ''' data = self.data data_content = data['content'][0] ## Paste the output of a command # This is deprecated after piping support if data['command']: try: call = subprocess.Popen(data_content.split(), stderr=subproces... |
not useful in paste information for key in ['func', 'verbose', 'service', 'extra', 'command', 'file']: del self.data[key] |
def get_response(self): ''' Returns response according submitted the data and method. ''' self.process_commmon() self.process_data() urlencoded_data = urllib.urlencode(self.data) if self.METHOD == POST: req = urllib2.Request(self.URL, urlencoded_data) else: req = urllib2.Request('%s?%s' %(self.URL, urlencoded_data)) if... |
def url(self): ''' Executes the methods to send request, process the response and then publishes the url. ''' self.get_response() url = self.process_response() if url: logging.info('Your paste has been published at %s' %(url)) return url else: logging.error('Did not get a URL back for the paste') raise PasteException("... |
def get_api_user_key(self, api_dev_key, username=None, password=None): ''' Get api user key to enable posts from user accounts if username and password available. Not getting an api_user_key means that the posts will be "guest" posts ''' username = username or get_config('pastebin', 'api_user_name') password = password... |
def has_any(): "Returns the best available proactor implementation for the current platform." return get_first(has_ctypes_iocp, has_iocp, has_stdlib_kqueue, has_kqueue, has_stdlib_epoll, has_epoll, has_poll, has_select) |
def copy(self, name=None, description=None, meta=None): """ Create a copy of the current object (may alter the container's name, description, and update the metadata if needed). """ cls = self.__class__ kwargs = self._rel(copy=True) kwargs.update(self._data(copy=True)) if name is not None: kwargs['name'] = name if desc... |
def slice_naive(self, key): """ Naively slice each data object in the container by the object's index. Args: key: Int, slice, or list by which to extra "sub"-container Returns: sub: Sub container of the same format with a view of the data Warning: To ensure that a new container is created, use the copy method. .. code-... |
def slice_cardinal(self, key): """ Slice the container according to its (primary) cardinal axis. The "cardinal" axis can have any name so long as the name matches a data object attached to the container. The index name for this object should also match the value of the cardinal axis. The algorithm builds a network grap... |
Also: For data network generation, see :func:`~exa.core.container.Container.network`. For information about relationships between data objects see :mod:`~exa.core.numerical`. """ if self._cardinal: cls = self.__class__ key = check_key(self[self._cardinal], key, cardinal=True) g = self.network(fig=False) kwargs = {self.... |
cdf[cdf[parent].isin(kwargs[parent].index.values)] elif typ == 'column-index': # Select from the child where the child's index is in the # column of the parent. Note that this relationship cdf = self[child] cin = cdf.index.name cols = [col for col in kwargs[parent] if cin == col or (cin == col[:-1] and col[-1].isdigit(... |
def cardinal_groupby(self): """ Create an instance of this class for every step in the cardinal dimension. """ if self._cardinal: g = self.network(fig=False) cardinal_indexes = self[self._cardinal].index.values selfs = {} cls = self.__class__ for cardinal_index in cardinal_indexes: kwargs = {self._cardinal: self[self._... |
where the child's index is in the # column of the parent. Note that this relationship cdf = self[child] cin = cdf.index.name cols = [col for col in kwargs[parent] if cin == col or (cin == col[:-1] and col[-1].isdigit())] index = kwargs[parent][cols].stack().astype(np.int64).values kwargs[child] = cdf[cdf.index.isin(ind... |
def info(self): """ Display information about the container's data objects (note that info on metadata and visualization objects is also provided). Note: Sizes are reported in bytes. """ names = [] types = [] sizes = [] names.append('WIDGET') types.append('-') s = 0 sizes.append(s) names.append('METADATA') types.append... |
def memory_usage(self, string=False): """ Get the memory usage estimate of the container. Args: string (bool): Human readable string (default false) See Also: :func:`~exa.core.container.Container.info` """ if string: n = getsizeof(self) return ' '.join((str(s) for s in convert_bytes(n))) return self.info()['size'] |
def network(self, figsize=(14, 9), fig=True): """ Display information about the container's object relationships. Nodes correspond to data objects. The size of the node corresponds to the size of the table in memory. The color of the node corresponds to its fundamental data type. Nodes are labeled by their container na... |
node based on the node's (sub)type.""" cols = mpl.sns.color_palette('viridis', len(conn_types)) for col in cols: if isinstance(obj, (pd.DataFrame, pd.Series, pd.SparseSeries, pd.SparseDataFrame)): typ = type(obj) return '.'.join((typ.__module__, typ.__name__)), col return 'other', 'gray' def legend(items, name, loc, ax... |
and color node_conn_dict = {} # Values are tuple of connection type and color items = self._data().items() for k0, v0 in items: n0 = k0[1:] if k0.startswith('_') else k0 node_type_dict[n0] = get_node_type_color(v0) for k1, v1 in items: if v0 is v1: continue n1 = k1[1:] if k1.startswith('_') else k1 for name in v0.index... |
('column-index', conn[contyp]) g = nx.Graph() g.add_nodes_from(node_size_dict.keys()) g.add_edges_from(node_conn_dict.keys()) node_sizes = [node_size_dict[node] for node in g.nodes()] node_labels = {node: ' {}\n({})'.format(node, node_class_name_dict[node]) for node in g.nodes()} node_colors = [node_type_dict[node][1] ... |
def save(self, path=None, complevel=1, complib='zlib'): """ Save the container as an HDF5 archive. Args: path (str): Path where to save the container """ if path is None: path = self.hexuid + '.hdf5' elif os.path.isdir(path): path += os.sep + self.hexuid + '.hdf5' elif not (path.endswith('.hdf5') or path.endswith('.hdf... |
str(i) if isinstance(field, pd.Series): store[ffname] = pd.Series(field) else: store[ffname] = pd.DataFrame(field) fc += 1 elif isinstance(data, Series): s = pd.Series(data) if isinstance(data.dtype, pd.types.dtypes.CategoricalDtype): s = s.astype('O') store[name] = s elif isinstance(data, DataFrame): store[name] = pd.... |
def load(cls, pkid_or_path=None): """ Load a container object from a persistent location or file path. Args: pkid_or_path: Integer pkid corresponding to the container table or file path Returns: container: The saved container object """ path = pkid_or_path if isinstance(path, (int, np.int32, np.int64)): raise NotImplem... |
def _rel(self, copy=False): """ Get descriptive kwargs of the container (e.g. name, description, meta). """ rel = {} for key, obj in vars(self).items(): if not isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)) and not key.startswith('_'): if copy and 'id' not in key: rel[key] = deepcopy(ob... |
def _data(self, copy=False): """ Get data kwargs of the container (i.e. dataframe and series objects). """ data = {} for key, obj in vars(self).items(): if isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)): if copy: data[key] = obj.copy(deep=True) else: data[key] = obj return data |
def create_property(name, ptype): """ Creates a custom property with a getter that performs computing functionality (if available) and raise a type error if setting with the wrong type. Note: By default, the setter attempts to convert the object to the correct type; a type error is raised if this fails. """ pname = '_'... |
set {} first.'.format(name)) return getattr(self, pname) def setter(self, obj): # This is the default property "setter" for container data objects. # Prior to setting a property value, this function checks that the # object's type is correct. if not isinstance(obj, ptype): try: obj = ptype(obj) except Exception: raise ... |
def _polar_to_cartesian(cx, cy, r, theta): """ :param cx: X coord of circle :param cy: Y coord of circle :param r: Radius of circle :param theta: Degrees from vertical, clockwise, in radians :return: (x, y) """ return cx - r * math.sin(theta), cy - r * math.cos(theta) |
def circle(self, cx, cy, r, stroke=None, fill=None, stroke_width=1): """ :param cx: Center X :param cy: Center Y :param r: Radius """ self.put(' <circle cx="') self.put(str(cx)) self.put('" cy="') self.put(str(cy)) self.put('" r="') self.put(str(r)) self.put('" stroke-width="') self.put(str(stroke_width)) self.put('"')... |
def polygon(self, points, stroke=None, fill=None, stroke_width=1, disable_anti_aliasing=False): """ :param points: List of points """ self.put(' <polygon points="') self.put(' '.join(['%s,%s' % p for p in points])) self.put('" stroke-width="') self.put(str(stroke_width)) self.put('"') if fill: self.put(' fill="') self.... |
def arc(self, cx, cy, r, start_radians, end_radians, fill=None): """ NOTE: This will leave gaps between adjacent segments. You can fix this by disabling anti-aliasing using shape-rendering="crispEdges" on the path tag If you want to add a stroke to this, it's advisable to create a second path that just strokes the outs... |
total_radians = start_radians - end_radians if total_radians < 0: total_radians *= -1 large_arc_flag = 1 if total_radians > math.pi else 0 path = SvgPathGenerator() path.move_to(end[0], end[1]) path.line_to(cx, cy) path.line_to(start[0], start[1]) path.arc_to(r, r, 0, large_arc_flag, 0, end[0], end[1]) self.put(' <path... |
def name_targets(func): """ Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms the value into ``dict(a=1, b=2, c=3)``. This is useful in the case where the last parameter is an SCons command. """ def wrap(*a, **kw): ret = func(*a, **kw) return dict(zip(ret[:-1], ret[-1])) return wrap |
def add(self, name, nestable, **kw): """ Adds a level to the nesting and creates a checkpoint that can be reverted to later for aggregation by calling :meth:`SConsWrap.pop`. :param name: Identifier for the nest level :param nestable: A nestable object - see :meth:`Nest.add() <nestly.core.Nest.add>`. :param kw: Addition... |
def pop(self, name=None): """ Reverts to the nest stage just before the corresponding call of :meth:`SConsWrap.add_aggregate`. However, any aggregate collections which have been worked on will still be accessible, and can be called operated on together after calling this method. If no name is passed, will revert to the... |
def add_nest(self, name=None, **kw): """A simple decorator which wraps :meth:`nestly.core.Nest.add`.""" def deco(func): self.add(name or func.__name__, func, **kw) return func return deco |
def add_target(self, name=None): """ Add an SCons target to this nest. The function decorated will be immediately called with each of the output directories and current control dictionaries. Each result will be added to the respective control dictionary for later nests to access. :param name: Name for the target in the... |
def add_target_with_env(self, environment, name=None): """Add an SCons target to this nest, with an SCons Environment The function decorated will be immediately called with three arguments: * ``environment``: A clone of the SCons environment, with variables populated for all values in the control dictionary, plus a var... |
create_dir=False) self._register_alias(key) return func return deco |
def add_aggregate(self, name, data_fac): """ Add an aggregate target to this nest. Since nests added after the aggregate can access the construct returned by the factory function value, it can be mutated to provide additional values for use when the decorated function is called. To do something with the aggregates, you... |
def add_controls(self, env, target_name='control', file_name='control.json', encoder_cls=SConsEncoder): """ Adds a target to build a control file at each of the current leaves. :param env: SCons Environment object :param target_name: Name for target in nest :param file_name: Name for output file. """ if not HAS_SCONS: ... |
def clean(amount): """ Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str """ # Return empty input immediately. if not amount: return amount if re.search(r'[\. ][0-9]{3},[0-9]{1,2}$', amount): # Assume amount is in 1.123,12 or 1 123,12 format (Dutch). return amount.replac... |
def get_id(self, natural_key, date, enhancement=None): """ Returns the technical ID for a natural key at a date or None if the given natural key is not valid. :param T natural_key: The natural key. :param str date: The date in ISO 8601 (YYYY-MM-DD) format. :param T enhancement: Enhancement data of the dimension row. :r... |
strings in ISO 8601 format. if isinstance(row[self._key_date_start], datetime.date): row[self._key_date_start] = row[self._key_date_start].isoformat() if isinstance(row[self._key_date_end], datetime.date): row[self._key_date_end] = row[self._key_date_end].isoformat() success = True finally: self.post_call_stored_proced... |
def factory(coords, dependent_variables, helper_functions): """Fields factory generating specialized container build around a triflow Model and xarray. Parameters ---------- coords: iterable of str: coordinates name. First coordinate have to be shared with all variables dependent_variables : iterable tuple (name, coord... |
def factory1D(dependent_variables, helper_functions): """Fields factory generating specialized container build around a triflow Model and xarray. Wrapper for 1D data. Parameters ---------- dependent_variables : iterable for str name of the dependent variables helper_functions : iterable of str name of the helpers funct... |
def uflat(self): """return a flatten **copy** of the main numpy array with only the dependant variables. Be carefull, modification of these data will not be reflected on the main array! """ # noqa aligned_arrays = [self[key].values[[(slice(None) if c in coords else None) for c in self._coords]].T for key, coords in sel... |
def file_follow_durable( path, min_dump_interval=10, xattr_name='user.collectd.logtail.pos', xattr_update=True, **follow_kwz ): '''Records log position into xattrs after reading line every min_dump_interval seconds. Checksum of the last line at the position is also recorded (so line itself don't have to fit into xattr)... |
(OSError, IOError) as err: collectd.info('Failed to restore log position: {}'.format(err)) src.seek(0) tailer = file_follow(src, yield_file=True, **follow_kwz) # ...and keep it updated pos_dump_ts_get = lambda ts=None: (ts or time()) + min_dump_interval pos_dump_ts = pos_dump_ts_get() while True: line, src_chk = next(t... |
def complete(self, request, response): """ Complete net auth. """ extra = self.get_extra_data(response) data = {} for form_field, backend_field in self.PROFILE_MAPPING.items(): data[form_field] = self.extract_data(extra, backend_field) request.session['extra'] = data if settings.ACCEPT_EXTRA_FORM: self.fill_extra_field... |
def merge_accounts(self, request): """ Attach NetID account to regular django account and then redirect user. In this situation user dont have to fill extra fields because he filled them when first account (request.user) was created. Note that self.indentity must be already set in this stage by validate_response functi... |
def login_user(self, request): """ Try to login user by net identity. Do nothing in case of failure. """ # only actavted users can login if activation required. user = auth.authenticate(identity=self.identity, provider=self.provider) if user and settings.ACTIVATION_REQUIRED and not user.is_active: messages.add_message(... |
def fill_extra_fields(self, request, data): """ Try to fetch extra data from provider, if this data is enough to validate settings.EXTRA_FORM then call save method of form class and login the user. The extra parameter can be some complex object this is why we use method function 'extra_data' to extract data from this o... |
def match(self, row): """ Returns True if the field matches the glob expression of this simple condition. Returns False otherwise. :param dict row: The row. :rtype: bool """ return fnmatch.fnmatchcase(row[self._field], self._expression) |
def clean(date, ignore_time=False): """ Converts a date in miscellaneous format to ISO-8601 (YYYY-MM-DD) format. :param str date: The input date. :param bool ignore_time: If true any trailing time prt is ignore. :rtype: str """ # Return empty input immediately. if not date: return date parts = re.split(r'[\-/. ]', date... |
date is in DD-MM-YYYY or D-M-YYYY format. return parts[2] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:] if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 2: # Assume date is in DD-MM-YY or D-M-YY format. year = '19' + parts[2] if parts[2] >= '20' else '20' + parts[2] return year + '-' + ... |
Try YYYYMMDD format. pattern = r'^\d{8}' + ('.*$' if ignore_time else '$') match = re.match(pattern, date) if match: # Assume date is YYYYMMDD format return date[0:4] + '-' + date[4:6] + '-' + date[6:8] # Format not recognized. Just return the original string. return date |
def template_string(context, template): 'Return the rendered template content with the current context' if not isinstance(context, Context): context = Context(context) return Template(template).render(context) |
def raster_to_shape(raster): """Take a raster and return a polygon representing the outer edge.""" left = raster.bounds.left right = raster.bounds.right top = raster.bounds.top bottom = raster.bounds.bottom top_left = (left, top) top_right = (right, top) bottom_left = (left, bottom) bottom_right = (right, bottom) retur... |
def apply_markup(value, arg=None): """ Applies text-to-HTML conversion. Takes an optional argument to specify the name of a filter to use. """ if arg is not None: return formatter(value, filter_name=arg) return formatter(value) |
def smartypants(value): """ Applies SmartyPants to a piece of text, applying typographic niceties. Requires the Python SmartyPants library to be installed; see http://web.chad.org/projects/smartypants.py/ """ try: from smartypants import smartyPants except ImportError: if settings.DEBUG: raise TemplateSyntaxError("Erro... |
def refine_MIDDLEWARE_CLASSES(original): """ Django docs say that the LocaleMiddleware should come after the SessionMiddleware. Here, we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position. Be careful with the order when refining the MiddlewareClasses with followi... |
def list(cls, params=None): """ Retrieves a list of the model :param params: params as dictionary :type params: dict :return: the list of the parsed xml objects :rtype: list """ return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode( cls.element_from_string(cls._get_request(params=params).text) ) |
def setup_config(command, filename, section, vars): """Place any commands to setup chatapp here""" confuri = "config:" + filename if ":" in section: confuri += "#" + section.rsplit(":", 1)[-1] conf = appconfig(confuri) load_environment(conf.global_conf, conf.local_conf) |
def watch(self): """This is a coroutine that runs permanently for each participant to the chat. If the participant has more than 10 unpulled messages this coroutine will die. `pubsub` is a queue that hosts the messages from all the participants. * subscribe registers this coro to the queue * fetch pulls the recent mess... |
def push(self): """This action puts a message in the global queue that all the clients will get via the 'pull' action.""" print `request.body` yield request.environ['cogen.call'](pubsub.publish)( "%s: %s" % (session['client'].name, request.body) ) # the request.environ['cogen.*'] objects are the the asynchronous # make... |
def pull(self): """This action does some state checking (adds a object in the session that will identify this chat participant and adds a coroutine to manage it's state) and gets new messages or bail out in 10 seconds if there are no messages.""" if not 'client' in session or session['client'].dead: client = Client(str... |
def main(): """ main """ args = MainArguments() if args.tool.lower() == "tool1": args = Tool1Arguments() elif args.tool.lower() == "tool2": args = Tool2Arguments() else: print("Unknown tool", args.tool) print(args) |
def get_or_create_home_repo(reset=False): """ Check to make sure we never operate with a non-existing local repo """ dosetup = True if os.path.exists(ONTOSPY_LOCAL): dosetup = False if reset: import shutil var = input("Delete the local library and all of its contents? (y/n) ") if var == "y": shutil.rmtree(ONTOSPY_LOCAL... |
SystemExit(1) if dosetup: print(Fore.GREEN + "Setup successfull: local library created at <%s>" % LIBRARY_HOME + Style.RESET_ALL) # else: # print(Style.DIM + "Local library: <%s>" % LIBRARY_HOME + Style.RESET_ALL) return True |
def get_pickled_ontology(filename): """ try to retrieve a cached ontology """ pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if GLOBAL_DISABLE_CACHE: printDebug("WARNING: DEMO MODE cache has been disabled in __init__.py ==============", "red") if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:... |
def del_pickled_ontology(filename): """ try to remove a cached ontology """ pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE: os.remove(pickledfile) return True else: return None |
def rename_pickled_ontology(filename, newname): """ try to rename a cached ontology """ pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" newpickledfile = ONTOSPY_LOCAL_CACHE + "/" + newname + ".pickle" if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE: os.rename(pickledfile, newpickledfile) retu... |
def do_pickle_ontology(filename, g=None): """ from a valid filename, generate the graph instance and pickle it too note: option to pass a pre-generated graph instance too 2015-09-17: added code to increase recursion limit if cPickle fails see http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-us... |
aborting..." % filename ) print(str(e)) sys.setrecursionlimit(int(sys.getrecursionlimit()/10)) return g |
def update(self): """ Updates the object :return: :rtype: response """ return self._put_request( data=self.element_to_string( self.encode() ), endpoint=self.ENDPOINT + '/' + str(self.id) ) |
def mixing_phases(U): """Return the angles and CP phases of the CKM or PMNS matrix in standard parametrization, starting from a matrix with arbitrary phase convention.""" f = {} # angles f['t13'] = asin(abs(U[0,2])) if U[0,0] == 0: f['t12'] = pi/2 else: f['t12'] = atan(abs(U[0,1])/abs(U[0,0])) if U[2,2] == 0: f['t23'] ... |
def rephase_standard(UuL, UdL, UuR, UdR): """Function to rephase the quark rotation matrices in order to obtain the CKM matrix in standard parametrization. The input matrices are assumed to diagonalize the up-type and down-type quark matrices like ``` UuL.conj().T @ Mu @ UuR = Mu_diag UdL.conj().T @ Md @ UdR = Md_diag ... |
def rephase_pmns_standard(Unu, UeL, UeR): """Function to rephase the lepton rotation matrices in order to obtain the PMNS matrix in standard parametrization. The input matrices are assumed to diagonalize the charged lepton and neutrino mass matrices like ``` UeL.conj().T @ Me @ UeR = Me_diag Unu.T @ Mnu @ Unu = Mnu_dia... |
def check_outdated(package, version): """ Given the name of a package on PyPI and a version (both strings), checks if the given version is the latest version of the package available. Returns a 2-tuple (is_outdated, latest_version) where is_outdated is a boolean which is True if the given version is earlier than the la... |
latest = None def get_latest(): url = 'https://pypi.python.org/pypi/%s/json' % package response = utils.get_url(url) return json.loads(response)['info']['version'] if latest is None: latest = get_latest() parsed_latest = parse_version(latest) if parsed_version > parsed_latest: # Probably a stale cached value latest = g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.