Example #1
0
        def __init__(self, backend, apidata):
                """ Create a new TVFactory instance.

                Give the name of a backend (which can be got from the 
                get_backends() method) as well as any API keys, etc, that
                the backend requests.
                """
                self.__backend = backends.get_backend(backend).get_instance(apidata)
                self.__backend_name = backends.get_backend(backend).module_name
Example #2
0
def list(request, backend, template_name=r'registration/list.html', extra_context=None):
    if extra_context is None:
        extra_context = {}
    if request.method == 'POST':
        form = RegistrationHandleForm(request.POST)
        if form.is_valid():
            backend = get_backend(backend)
            action = form.cleaned_data['action']
            registration_profiles = form.cleaned_data['registration_profiles']
            if action == 'approve' and request.user.has_perm('threestep_registration.approve_registrationprofile'):
                success_users = backend.approve(request, registration_profiles)
            elif action == 'reject' and request.user.has_perm('threestep_registration.reject_registrationprofile'):
                success_users = backend.reject(request, registration_profiles)
            else:
                return HttpResponseForbidden()
            users = [registration_profile.user for registration_profile in registration_profiles]
            success_user_ids = [user.pk for user in success_users]
            failed_users = [user for user in users if not user.pk in success_user_ids]
            verbose_action = dict(RegistrationHandleForm.ACTIONS)[action]
            message = []
            for user in success_users:
                message.append(_('You have %(action)s "%(user)s"') % {'action': verbose_action, 'user': user.username})
            messages.success(request, "\n".join(message), fail_silently=True)
            message = []
            for user in failed_users:
                message.append(_('Failed to %(action)s "%(user)s"') % {'action': verbose_action, 'user': user.username})
            messages.error(request, "\n".join(message), fail_silently=True)
    else:
        form = RegistrationHandleForm()
    extra_context['form'] = form
    extra_context['registered_profiles'] = RegistrationProfile.objects.filter(status='waiting')
    extra_context['approved_profiles'] = RegistrationProfile.objects.filter(status='approved', user__is_active=False)
    return direct_to_template(request, template_name, extra_context=extra_context)
Example #3
0
File: op2.py Project: joshcc3/PyOP2
def init(**kwargs):
    """Initialise OP2: select the backend and potentially other configuration
    options.

    :arg backend: Set the hardware-specific backend. Current choices
     are ``"sequential"``, ``"openmp"``, ``"opencl"`` and ``"cuda"``.
    :arg debug: The level of debugging output.
    :arg comm: The MPI communicator to use for parallel communication,
               defaults to `MPI_COMM_WORLD`

    .. note::
       Calling ``init`` again with a different backend raises an exception.
       Changing the backend is not possible. Calling ``init`` again with the
       same backend or not specifying a backend will update the configuration.
       Calling ``init`` after ``exit`` has been called is an error and will
       raise an exception.
    """
    backend = backends.get_backend()
    if backend == 'pyop2.finalised':
        raise RuntimeError("Calling init() after exit() is illegal.")
    if 'backend' in kwargs and backend not in ('pyop2.void', 'pyop2.' + kwargs['backend']):
        raise RuntimeError("Changing the backend is not possible once set.")
    cfg.configure(**kwargs)
    set_log_level(cfg['log_level'])
    if backend == 'pyop2.void':
        backends.set_backend(cfg.backend)
        backends._BackendSelector._backend._setup()
        if 'comm' in kwargs:
            backends._BackendSelector._backend.MPI.comm = kwargs['comm']
        global MPI
        MPI = backends._BackendSelector._backend.MPI  # noqa: backend override
Example #4
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)
Example #5
0
    def create_refs_for_file(self, filename, n_doc=1, total_docs=1):
        if filename in self._skipped:
            self.printer.print_default(
                "Skipping test '%s' (%d/%d)" %
                (os.path.join(self._docsdir, filename), n_doc, total_docs))
            return

        refs_path = os.path.join(self._refsdir, filename)
        try:
            os.makedirs(refs_path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        except:
            raise
        doc_path = os.path.join(self._docsdir, filename)

        if self.config.backends:
            backends = [get_backend(name) for name in self.config.backends]
        else:
            backends = get_all_backends()

        for backend in backends:
            if not self.config.force and backend.has_results(refs_path):
                self.printer.print_default(
                    "Results found, skipping '%s' for %s backend (%d/%d)" %
                    (doc_path, backend.get_name(), n_doc, total_docs))
                continue
            self.printer.printout_ln(
                "Creating refs for '%s' using %s backend (%d/%d)" %
                (doc_path, backend.get_name(), n_doc, total_docs))
            if backend.create_refs(doc_path, refs_path):
                backend.create_checksums(refs_path, self.config.checksums_only)
Example #6
0
    def run_test(self, filename, n_doc = 1, total_docs = 1):
        if filename in self._skip:
            doc_path = os.path.join(self._docsdir, filename)
            self._skipped.append("%s" % (doc_path))
            print("Skipping test '%s' (%d/%d)" % (doc_path, n_doc, total_docs))
            return

        out_path = os.path.join(self._outdir, filename)
        try:
            os.makedirs(out_path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        except:
            raise
        doc_path = os.path.join(self._docsdir, filename)
        refs_path = os.path.join(self._refsdir, filename)

        if not os.path.isdir(refs_path):
            self._skipped.append("%s" % (doc_path))
            print("Reference dir not found for %s, skipping (%d/%d)" % (doc_path, n_doc, total_docs))
            return

        if self.config.backends:
            backends = [get_backend(name) for name in self.config.backends]
        else:
            backends = get_all_backends()

        for backend in backends:
            self.test(refs_path, doc_path, out_path, backend, n_doc, total_docs)
Example #7
0
def register_from_csv(request, backend, file):
    # Notice:
    #    DO NOT CONTAIN words except LATIN
    reader = csv.reader(file)
    
    backend = get_backend(backend)
    
    user_profiles = []
    # Register
    for row in reader:
        if row[0].startswith("#"):
            continue
        kwargs = {
            'username': row[0].strip(),
            'email': row[1].strip(),
            'password1': mkpasswd(),
            # DO NOT CHANGE the line below. This information is used on email sent.
            'remarks': '### AUTO ###',
        }
        user = backend.register(request, **kwargs)
        profile = RegistrationProfile.objects.get(user=user)
        user_profiles.append(profile)
    # Approve
    success_users = backend.approve(request, user_profiles)
    
    return success_users
Example #8
0
    def create_refs_for_file(self, filename, n_doc = 1, total_docs = 1):
        if filename in self._skipped:
            print("Skipping test '%s' (%d/%d)" % (os.path.join(self._docsdir, filename), n_doc, total_docs))
            return

        refs_path = os.path.join(self._refsdir, filename)
        try:
            os.makedirs(refs_path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        except:
            raise
        doc_path = os.path.join(self._docsdir, filename)

        if self.config.backends:
            backends = [get_backend(name) for name in self.config.backends]
        else:
            backends = get_all_backends()

        for backend in backends:
            if not self.config.force and backend.has_results(refs_path):
                print("Results found, skipping '%s' for %s backend (%d/%d)" % (doc_path, backend.get_name(), n_doc, total_docs))
                continue
            print("Creating refs for '%s' using %s backend (%d/%d)" % (doc_path, backend.get_name(), n_doc, total_docs))
            if backend.create_refs(doc_path, refs_path):
                backend.create_checksums(refs_path, self.config.checksums_only)
Example #9
0
File: op2.py Project: POETSII/PyOP2
def exit():
    """Exit OP2 and clean up"""
    if configuration['print_cache_size'] and COMM_WORLD.rank == 0:
        from caching import report_cache, Cached, ObjectCached
        print '**** PyOP2 cache sizes at exit ****'
        report_cache(typ=ObjectCached)
        report_cache(typ=Cached)
    configuration.reset()

    if backends.get_backend() != 'pyop2.void':
        backends.unset_backend()
Example #10
0
def login_start(request, backend_name):
    backend = get_backend(backend_name)
    if backend is None:
        return HttpResponseNotFound()
    redirect_url = request.META.get('HTTP_REFERER','/')
    print redirect_url
    request.session['post_login_redirect'] = redirect_url
    return_url = "http://%s%s" % (settings.MAIN_HOST,
                                  reverse('login_return', args=[backend_name]))
    token, url = backend.get_auth_url(return_to=return_url)
    request.session['account_token'] = token
    return HttpResponseRedirect(url)
Example #11
0
def init(**kwargs):
    """Initialise PyOP2: select the backend and potentially other configuration
    options.

    :arg backend:   Set the hardware-specific backend. Current choices are
                    ``"sequential"``, ``"openmp"``, ``"opencl"``, ``"cuda"``.
    :arg debug:     The level of debugging output.
    :arg comm:      The MPI communicator to use for parallel communication,
                    defaults to `MPI_COMM_WORLD`
    :arg log_level: The log level. Options: DEBUG, INFO, WARNING, ERROR, CRITICAL

    For debugging purposes, `init` accepts all keyword arguments
    accepted by the PyOP2 :class:`Configuration` object, see
    :meth:`Configuration.__init__` for details of further accepted
    options.

    .. note::
       Calling ``init`` again with a different backend raises an exception.
       Changing the backend is not possible. Calling ``init`` again with the
       same backend or not specifying a backend will update the configuration.
       Calling ``init`` after ``exit`` has been called is an error and will
       raise an exception.
    """
    backend = backends.get_backend()
    if backend == 'pyop2.finalised':
        raise RuntimeError("Calling init() after exit() is illegal.")

    if backend != 'pyop2.void' and \
            "backend" in kwargs and \
            backend != "pyop2.%s" % kwargs["backend"]:
        raise RuntimeError("Calling init() for a different backend is illegal.")

    configuration.reconfigure(**kwargs)

    set_log_level(configuration['log_level'])
    if backend == 'pyop2.void':
        try:
            backends.set_backend(configuration["backend"])
        except:
            configuration.reset()
            raise

        backends._BackendSelector._backend._setup()
        if 'comm' in kwargs:
            backends._BackendSelector._backend.MPI.comm = kwargs['comm']
        global MPI
        MPI = backends._BackendSelector._backend.MPI  # noqa: backend override

    init_coffee(configuration['simd_isa'], configuration['compiler'],
                configuration['blas'])
Example #12
0
def exit():
    """Exit OP2 and clean up"""
    if configuration['print_cache_size'] and MPI.comm.rank == 0:
        from caching import report_cache, Cached, ObjectCached
        print '**** PyOP2 cache sizes at exit ****'
        report_cache(typ=ObjectCached)
        report_cache(typ=Cached)
    if configuration['print_summary'] and MPI.comm.rank == 0:
        from profiling import summary
        print '**** PyOP2 timings summary ****'
        summary()
    configuration.reset()

    if backends.get_backend() != 'pyop2.void':
        backends.unset_backend()
Example #13
0
def search():
    query = request.args.get('query', '')
    if query == '': return redirect(url_for('home'))

    # Normalize terms and then make sure they only contain alphanumeric characters
    simple_terms = [slugify(term, separator='') for term in query.split(' ')]
    safe_terms = [re.sub(r'[^a-zA-Z0-9]+', '', term) for term in simple_terms]

    backend = get_backend(conf.BACKEND['NAME'])
    hosts = backend.get_hosts(conf.BACKEND)
    hits = backend.search(conf.BACKEND, safe_terms, hosts, limit=100)

    for hit in hits:
        hit['size'] = sizeof_format(hit['size'])
        hit['url'] = get_url(hit['host']['name'], os.path.join(hit['path'], hit['name']))
        hit['dir_url'] = get_url(hit['host']['name'], os.path.join(hit['path']))

    return render_template('search.html', hits=hits, hit_page=True, query=query)
Example #14
0
def login_return(request, backend_name):
    backend = get_backend(backend_name)
    redirect_url = request.session.get('post_login_redirect', '/')
    return_url = "http://%s%s" % (settings.MAIN_HOST,
                                  reverse('login_return', args=[backend_name]))
    try:
        access_token = backend.get_token(request, return_url)
    except DenyException:
        return HttpResponseRedirect(redirect_url)
    except:
        return _error_page(request)

    user_data = backend.get_user_data(access_token)
    
    account = Account.objects.filter(id_from_backend=user_data['id'],
                                     backend=backend_name,
                                     )
    if account.count():
        account = account[0]
        user = account.user
        user = authenticate(username=user.username, password=2)
        login(request, user)
        return HttpResponseRedirect(redirect_url)
    if not request.user.is_authenticated():
        un = "%s - %s" % (user_data['screen_name'], user_data['id'])
        un = un[:30]
        user, created = User.objects.get_or_create(username=un)
        if created:
            temp_password = User.objects.make_random_password(length=12)
            user.set_password(temp_password)
        user.first_name = user_data['name']
        user.save()
        user = authenticate(username=user.username, password=2)
    else:
        user = request.user
    account = Account(user=user,
                      name=user.first_name,
                      img_url=user_data['picture'],
                      backend=backend_name,
                      id_from_backend=user_data['id'],
                      ) 
    account.save()
    login(request, user)
    return HttpResponseRedirect(redirect_url)
Example #15
0
def activate(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None, **kwargs):
    backend = get_backend(backend)
    account = backend.activate(request, **kwargs)

    if account:
        if success_url is None:
            to, args, kwargs = backend.post_activation_redirect(request, account)
            return redirect(to, *args, **kwargs)
        else:
            return redirect(success_url)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              kwargs,
                              context_instance=context)
Example #16
0
 def secure_backend(self):
     if self.secure_backend_settings:
         backend_cls = get_backend(self.secure_backend_settings['_backend'])
         if backend_cls:
             return backend_cls(**self.secure_backend_settings)
 def __init__(self, *args, **kwargs):
     self.backend = get_backend()
     super(ActivationView, self).__init__(*args, **kwargs)
Example #18
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).
    
    **Required arguments**
    
    None.
    
    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.
    
    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.
    
    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
Example #19
0
def activate(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None, **kwargs):
    """
    Activate a user's account.

    The actual activation of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    the backend's ``activate()`` method will be called, passing any
    keyword arguments captured from the URL, and will be assumed to
    return a ``User`` if activation was successful, or a value which
    evaluates to ``False`` in boolean context if not.

    Upon successful activation, the backend's
    ``post_activation_redirect()`` method will be called, passing the
    ``HttpRequest`` and the activated ``User`` to determine the URL to
    redirect the user to. To override this, pass the argument
    ``success_url`` (see below).

    On unsuccessful activation, will render the template
    ``registration/activate.html`` to display an error message; to
    override thise, pass the argument ``template_name`` (see below).

    **Arguments**

    ``backend``
        The dotted Python import path to the backend class to
        use. Required.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context. Optional.

    ``success_url``
        The name of a URL pattern to redirect to on successful
        acivation. This is optional; if not specified, this will be
        obtained by calling the backend's
        ``post_activation_redirect()`` method.
    
    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``registration/activate.html``.

    ``\*\*kwargs``
        Any keyword arguments captured from the URL, such as an
        activation key, which will be passed to the backend's
        ``activate()`` method.
    
    **Context:**
    
    The context will be populated from the keyword arguments captured
    in the URL, and any extra variables supplied in the
    ``extra_context`` argument (see above).
    
    **Template:**
    
    registration/activate.html or ``template_name`` keyword argument.
    
    """
    backend = get_backend(backend)
    account = backend.activate(request, **kwargs)

    if account:
        if success_url is None:
            to, args, kwargs = backend.post_activation_redirect(request, account)
            return redirect(to, *args, **kwargs)
        else:
            return redirect(success_url)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              kwargs,
                              context_instance=context)
Example #20
0
    def _get_backends(self):
        if self.config.backends:
            return [get_backend(name) for name in self.config.backends]

        return get_all_backends()
Example #21
0
File: op2.py Project: POETSII/PyOP2
def initialised():
    """Check whether PyOP2 has been yet initialised but not yet finalised."""
    return backends.get_backend() not in ['pyop2.void', 'pyop2.finalised']
Example #22
0
    def create(self, launch_browser):
        html = "<html><body><a name='top'></a>"
        if self.config.backends:
            backends = [get_backend(name) for name in self.config.backends]
        else:
            backends = get_all_backends()

        results = {}
        for root, dirs, files in os.walk(self._outdir, False):
            if not files:
                continue
            if not root.lower().endswith('.pdf'):
                continue
            if root.startswith(self._htmldir):
                continue

            results[root] = TestResult(self._docsdir, self._refsdir,
                                       self._outdir, root, files, backends)

        tests = results.keys()
        tests.sort()

        failed_anchors = []
        failed = ""
        crashed = ""
        failed_to_run = ""
        for test_name in tests:
            test = results[test_name]
            if test.is_failed():
                failed_anchors.append(test.get_test())
                failed += test.get_failed_html()
            crashed += test.get_crashed_html()
            failed_to_run += test.get_failed_to_run_html()

        if failed:
            failed = "<h1><a name='failed'>Tests Failed (differences were found)</name></h1>\n%s" % (
                failed)
        if crashed:
            crashed = "<h1><a name='crashed'>Tests Crashed</a></h1>\n%s" % (
                crashed)
        if failed_to_run:
            failed_to_run = "<h1><a name='failed_to_run'>Tests that failed to run (command returned an error status)</a></h1>\n%s" % (
                failed_to_run)

        if failed or crashed or failed_to_run:
            html += "<ul>\n"
            if failed:
                html += "<li><a href='#failed'>Tests Failed (differences were found)</a></li>\n<ul>"
                for anchor in failed_anchors:
                    html += "<li><a href='#%s'>%s</a></li>" % (anchor, anchor)
                html += "</ul>\n"
            if crashed:
                html += "<li><a href='#crashed'>Tests Crashed</a></li>\n"
            if failed_to_run:
                html += "<li><a href='#failed_to_run'>Tests that failed to run (command returned an error status)</a></li>\n"
            html += "</ul>\n"

        html += failed + crashed + failed_to_run + "</body></html>"

        report_index = os.path.join(self._htmldir, 'index.html')
        f = open(report_index, 'wb')
        f.write(html)
        f.close()

        if launch_browser:
            subprocess.Popen(['xdg-open', report_index])
Example #23
0
            if self.mlsd_support or self.mlsd_support is None:
                listing = list(ftp.mlsd(path, facts=['type', 'size']))
                self.mlsd_support = True # previous command worked
            else:
                pass # only MLSD is supported at the moment
        except ftplib.error_perm:
            # First MLSD command is used to determine whether MLSD is supported or not.
            if self.mlsd_support is None: raise MLSDNotSupported
        except ftplib.all_errors as exc:
            self.logger.warn('FTP error (%d before fatal): %r', self.errors_left, exc)
            self._error()
            return self.ls(path)
        else:
            return self._handle_mlsd(path, listing)

if __name__ == '__main__':
    import sys
    import socket
    import local_settings as conf
    from backends import get_backend

    host = sys.argv[1]

    logging.config.dictConfig(conf.LOGGING)
    backend = get_backend(conf.BACKEND['NAME'])
    ip = socket.gethostbyname(host)
    walker = Walker(host, conf.PORT, user='******', passwd='rez',
                    timeout=conf.INDEX_TIMEOUT, max_errors=conf.MAX_INDEX_ERRORS,
                    handler=backend.IndexHandler(conf.BACKEND, ip))
    walker.walk()
Example #24
0
 def public_backend(self):
     if self.public_backend_settings:
         backend_cls = get_backend(self.public_backend_settings['_backend'])
         if backend_cls:
             return backend_cls(**self.public_backend_settings)
Example #25
0
import configuration
from configuration import _branding
import backends
import storage
import utils
import sys

if sys.argv[0].endswith('%s-config' % (_branding, )):
    # Someone is calling <brandname>-config.
    # Do not try to load any configuration, as that is what they might be trying to fix!
    pass
else:
    # Load configuration
    config = configuration.load_config()
    # Get backend according to configuration
    backend = backends.get_backend(config)

    # Get functions from backend
    ls = backend.ls
    iter_ls = backend.iter_ls
    ls_se = backend.ls_se
    iter_ls_se = backend.iter_ls_se
    is_dir = backend.is_dir
    is_dir_se = backend.is_dir_se
    replicas = backend.replicas
    get_file_source = backend.get_file_source
    iter_file_sources = backend.iter_file_sources
    is_file = backend.is_file
    is_file_se = backend.is_file_se
    exists = backend.exists
    is_online = backend.is_online
Example #26
0
File: op2.py Project: jabooth/PyOP2
def initialised():
    """Check whether PyOP2 has been yet initialised but not yet finalised."""
    return backends.get_backend() not in ["pyop2.void", "pyop2.finalised"]
Example #27
0
    def create(self, launch_browser):
        html = "<html><body><a name='top'></a>"
        if self.config.backends:
            backends = [get_backend(name) for name in self.config.backends]
        else:
            backends = get_all_backends()

        results = {}
        for root, dirs, files in os.walk(self._outdir, False):
            if not files:
                continue
            if not root.lower().endswith('.pdf'):
                continue
            if root.startswith(self._htmldir):
                continue

            results[root] = TestResult(self._docsdir, self._refsdir, self._outdir, root, files, backends)

        tests = results.keys()
        tests.sort()

        failed_anchors = []
        failed = ""
        crashed = ""
        failed_to_run = ""
        for test_name in tests:
            test = results[test_name]
            if test.is_failed():
                failed_anchors.append(test.get_test())
                failed += test.get_failed_html()
            crashed += test.get_crashed_html()
            failed_to_run += test.get_failed_to_run_html()

        if failed:
            failed = "<h1><a name='failed'>Tests Failed (differences were found)</name></h1>\n%s" % (failed)
        if crashed:
            crashed = "<h1><a name='crashed'>Tests Crashed</a></h1>\n%s" % (crashed)
        if failed_to_run:
            failed_to_run = "<h1><a name='failed_to_run'>Tests that failed to run (command returned an error status)</a></h1>\n%s" % (failed_to_run)

        if failed or crashed or failed_to_run:
            html += "<ul>\n"
            if failed:
                html += "<li><a href='#failed'>Tests Failed (differences were found)</a></li>\n<ul>"
                for anchor in failed_anchors:
                    html += "<li><a href='#%s'>%s</a></li>" % (anchor, anchor)
                html += "</ul>\n"
            if crashed:
                html += "<li><a href='#crashed'>Tests Crashed(differences were found)</a></li>\n"
            if failed_to_run:
                html += "<li><a href='#failed_to_run'>Tests that failed to run (command returned an error status)</a></li>\n"
            html += "</ul>\n"

        html += failed + crashed + failed_to_run + "</body></html>"

        report_index = os.path.join(self._htmldir, 'index.html')
        f = open(report_index, 'wb')
        f.write(html)
        f.close()

        if launch_browser:
            subprocess.Popen(['xdg-open', report_index])
Example #28
0
def get_ftp():
    handler = get_backend(conf.BACKEND['NAME'])
    return [{ 'name': info['name'], 'url': get_url(info['name']) }
            for (_, info) in handler.get_hosts(conf.BACKEND).items()]
Example #29
0
File: op2.py Project: jabooth/PyOP2
def exit():
    """Exit OP2 and clean up"""
    configuration.reset()

    if backends.get_backend() != "pyop2.void":
        backends.unset_backend()
Example #30
0
 def __init__(self, uri):
     self._backend = backends.get_backend(uri)
Example #31
0
        if p.name() != 'lightningd':
            continue
        plugin.log("Killing process {name} ({pid})".format(name=p.name(),
                                                           pid=p.pid))
        p.kill()

    # Sleep forever, just in case the master doesn't die on us...
    while True:
        time.sleep(30)


plugin.add_option(
    'backup-destination', None,
    'UNUSED. Kept for backward compatibility only. Please update your configuration to remove this option.'
)

if __name__ == "__main__":
    # Did we perform the first write check?
    plugin.initialized = False
    if not os.path.exists("backup.lock"):
        kill("Could not find backup.lock in the lightning-dir")

    try:
        d = json.load(open("backup.lock", 'r'))
        destination = d['backend_url']
        plugin.backend = get_backend(destination, require_init=True)
        plugin.run()
    except Exception:
        logging.exception('Exception while initializing backup plugin')
        kill('Exception while initializing plugin, terminating lightningd')
Example #32
0
File: op2.py Project: joshcc3/PyOP2
def exit():
    """Exit OP2 and clean up"""
    cfg.reset()
    if backends.get_backend() != 'pyop2.void':
        backends.unset_backend()
Example #33
0
    def _get_backends(self):
        if self.config.backends:
            return [get_backend(name) for name in self.config.backends]

        return get_all_backends()
Example #34
0
 def __init__(self, *args, **kwargs):
     self.backend = get_backend()
     super(ActivationView, self).__init__(*args, **kwargs)