Exemplo n.º 1
0
    def get_form_list(self):
        if not hasattr(self, '_form_list'):
            init_form_list = SortedDict()

            assert len(
                self.wizard_form_list) > 0, 'at least one form is needed'

            for i, form in enumerate(self.wizard_form_list):
                init_form_list[unicode(form[0])] = form[1]

            self._form_list = init_form_list

        return self._form_list
Exemplo n.º 2
0
    def __init__(self, apps=None, *args, **kwargs):
        # List of locations with static files
        self.locations = get_directories_in_tethys_apps(('static', 'public'), with_app_name=True)

        # Maps dir paths to an appropriate storage instance
        self.storages = SortedDict()

        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage

        super(TethysAppsStaticFinder, self).__init__(*args, **kwargs)
Exemplo n.º 3
0
    def __init__(self, name=None, model=None, template_dir=None, exclude=None):

        self.links = {self.default_global_link: []}
        self.instance_links = {self.default_instance_link: []}

        if exclude:
            self.exclude = exclude

        if model:
            self.model = model

        if self.model:
            self.opts = self.model._meta

        if name:
            self.name = name
        elif not self.name:
            self.name = self.model._meta.verbose_name_plural.lower()

        self.name = slugify(self.name)

        base_url = self.get_base_url()

        self.views = SortedDict()

        for ordering, (name, view) in enumerate(
            (("list", ViewSetListView), ("create", ViewSetCreateView),
             ("detail", ViewSetDetailView), ("update", ViewSetUpdateView),
             ("delete", ViewSetDeleteView))):
            if name not in self.exclude:
                if name in (
                        "update",
                        "delete",
                ):
                    self.instance_view(name, ordering=ordering)(view)
                elif name in ("list", ):
                    self.register(name, url=r'^$', ordering=ordering,
                                  links=[])(view)
                elif name in ("detail", ):
                    self.register(name,
                                  url=r'^%s$' % self.object_url,
                                  links=[])(view)
                else:
                    self.register(name, ordering=ordering)(view)

        if template_dir:
            self.template_dir = template_dir
        elif not self.template_dir:
            self.template_dir = self.name

        ViewSet._managers.append(self)
Exemplo n.º 4
0
 def get_features(self):
     """Returns this site's features organised into nested
     SortedDicts by feature set."""
     features = SortedDict()
     features['features'] = []
     # Iterate over Features, which are in the desired final order,
     # and group them according to the FeatureSet hierarchy. This
     # grouping removes duplication (ie, each FeatureSet will occur
     # only once), which may change the specified order. The first
     # occurrence of a FeatureSet determines its placement in the
     # order.
     for feature in self.features.all():
         fs_rank = features
         feature_sets = feature.get_feature_set_hierarchy()
         i = 1
         for feature_set in feature_sets:
             container = SortedDict()
             fs_rank = fs_rank.setdefault(feature_set, container)
             if 'features' not in fs_rank:
                 fs_rank['features'] = []
             i += 1
         fs_rank['features'].append(feature)
     return features
Exemplo n.º 5
0
    def get_checking_fields(self, special_exclude=['id']):
        """
        Returns the set of fields on which we perform checkings
        """
        ret = SortedDict()
        for f in self._meta.fields:
            # avoid special_exclude fields
            if f.attname in special_exclude:
                continue
            ret[f.attname] = f

        # Deal with reverse relationships
        reverse_rels = self._meta.get_all_related_objects()
        # reverse_rels += self._meta.get_all_related_many_to_many_objects()
        for relation in reverse_rels:
            accessor_name = relation.get_accessor_name()
            to_many = relation.field.rel.multiple
            if not self.opts.fields or accessor_name not in self.opts.fields:
                continue
            if not to_many:
                raise NotImplementedError
            ret[accessor_name] = PrimaryKeyRelatedField()

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Exemplo n.º 6
0
def view(request, variant_id):
    variant = get_object_or_404(Variant, pk=variant_id)

    variant.info = json.loads(variant.info)

    new_dict = SortedDict()
    key_list = list(variant.info.keys())
    key_list.sort()
    for key in key_list:
        new_dict[key] = variant.info[key]

    variant.info = new_dict
    print(type(variant.info))

    return render(request, 'variants/view.html', {'variant': variant})
Exemplo n.º 7
0
    def get_response(self, __):
        if self.request.GET.get('_format') == 'html':
            self.admin_view.detail_template = 'xadmin/views/quick_detail.html'
            return __()

        form = self.admin_view.form_obj
        layout = form.helper.layout

        results = []

        for p, f in layout.get_field_names():
            result = self.admin_view.get_field_result(f)
            results.append((result.label, result.val))

        return self.render_response(SortedDict(results))
Exemplo n.º 8
0
 def __init__(self, meta, help_text=None):
     self.use_sites = meta.pop('use_sites', False)
     self.use_i18n = meta.pop('use_i18n', False)
     self.use_redirect = meta.pop('use_redirect', False)
     self.use_cache = meta.pop('use_cache', False)
     self.groups = meta.pop('groups', {})
     self.seo_views = meta.pop('seo_views', [])
     self.verbose_name = meta.pop('verbose_name', None)
     self.verbose_name_plural = meta.pop('verbose_name_plural', None)
     self.backends = list(
         meta.pop('backends', ('path', 'modelinstance', 'model', 'view')))
     self._set_seo_models(meta.pop('seo_models', []))
     self.bulk_help_text = help_text
     self.original_meta = meta
     self.models = SortedDict()
     self.name = None
     self.elements = None
     self.metadata = None
Exemplo n.º 9
0
    def prepare_actions(self):
        self.action_list = SortedDict()
        for action in self.get_actions():
            try:
                slug, func = self.get_action(action)
            except NoActionFound:
                continue
            if hasattr(func, "short_description"):
                title = func.short_description % {
                    "verbose_name":
                    force_text(self.model._meta.verbose_name),
                    "verbose_name_plural":
                    force_text(self.model._meta.verbose_name_plural)
                }
            else:
                title = slug.title().replace("_", " ")

            self.action_list[slug] = (title, func)

        return self.action_list
Exemplo n.º 10
0
    def __init__(self, apps=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = SortedDict()

        for theme_name in os.listdir('{}/themes/'.format(
                settings.BOOKTYPE_ROOT)):
            theme_dir = '{}/themes/{}'.format(settings.BOOKTYPE_ROOT,
                                              theme_name)
            static_dir = '{}/static/'.format(theme_dir)

            if os.path.isdir(static_dir):
                theme_prefix = 'themes/{}'.format(theme_name)
                self.locations.append((theme_prefix, static_dir))

                filesystem_storage = FileSystemStorage(location=static_dir)
                filesystem_storage.prefix = theme_prefix
                self.storages[static_dir] = filesystem_storage

        super(ThemeFinder, self).__init__(*args, **kwargs)
Exemplo n.º 11
0
def admin_reorder(context, token):
    """
    Called in admin/base_site.html template override and applies custom ordering 
    of apps/models defined by settings.ADMIN_REORDER
    """
    # sort key function - use index of item in order if exists, otherwise item
    sort = lambda order, item: (order.index(item), "") if item in order else (
        len(order), item)
    if "app_list" in context:
        # sort the app list
        order = SortedDict(settings.ADMIN_REORDER)
        context["app_list"].sort(
            key=lambda app: sort(order.keys(), app["app_url"][:-1]))
        for i, app in enumerate(context["app_list"]):
            # sort the model list for each app
            app_name = app["app_url"][:-1]
            if not app_name:
                app_name = context["request"].path.strip("/").split("/")[-1]
            model_order = [m.lower() for m in order.get(app_name, [])]
            context["app_list"][i]["models"].sort(key=lambda model: sort(
                model_order, model["admin_url"].strip("/").split("/")[-1]))
    return ""
Exemplo n.º 12
0
    def export(self, queryset=None):
        """
        Exports a resource.
        """

        #TODO quickly patched.. this whole code needs to be rewritten to for performance (streaming)



        if queryset is None:
            queryset = self.get_queryset()

        if getattr(self, 'up_queryset', None):
            queryset = self.up_queryset(queryset)


        fields = SortedDict()
        data = tablib.Dataset(headers=fields.keys())

        for model in queryset.iterator():
            # first pass creates table shape
            self.fill_row(model, fields)
            data.append(fields.keys())
            # run only once for the headers
            break

        self.headers = fields

        # Iterate without the queryset cache, to avoid wasting memory when
        # exporting large datasets.

        for model in queryset.all():
            # second pass creates rows from the known table shape
            row = fields.copy()
            self.fill_row(model, row)
            data.append(row.values())

        return data
Exemplo n.º 13
0
 def get(self, field_class, d=None):
     return self._dict.get(field_class, SortedDict(self.COMMON))
Exemplo n.º 14
0
    def get_data(self):
	authUrl = "http://*****:*****@127.0.0.1:61209"
        #server = xmlrpclib.ServerProxy(authUrl)
	clusters = server.list_cluster()["data"]
        instances = []
	for cluster in clusters:
	    name = cluster["cluster_name"]
	    _cluster_instances = server.list_instance(name)
	    _cluster_instances = Response(code=_cluster_instances["code"], message=_cluster_instances["message"], data=_cluster_instances["data"])
	    result = _cluster_instances.code
	    cluster_instances = _cluster_instances.data.get("instanceList")
	    if result == 'succeed':
		if cluster_instances != "":
		    #cluster_instances = cluster_instances.split(",")
		    for _instance in cluster_instances:
			instance_id = _instance["id"]
			try:
			    instance = api.nova.server_get(self.request, instance_id)
			    instance.cluster_name = name
			    # instance.cluster_id = uuid
			    instances.append(instance)
			except Exception:
			    msg = _('Unable to retrieve instance list.')
			    exceptions.handle(self.request, msg)
		
        marker = self.request.GET.get(
            project_tables.InstancesTable._meta.pagination_param, None)
        search_opts = self.get_filters({'marker': marker, 'paginate': True})
        # Gather our tenants to correlate against IDs
        try:
            tenants, has_more = api.keystone.tenant_list(self.request)
        except Exception:
            tenants = []
            msg = _('Unable to retrieve instance project information.')
            exceptions.handle(self.request, msg)

        if 'project' in search_opts:
            ten_filter_ids = [t.id for t in tenants
                              if t.name == search_opts['project']]
            del search_opts['project']
            if len(ten_filter_ids) > 0:
                search_opts['tenant_id'] = ten_filter_ids[0]
            else:
                self._more = False
                return []
	"""
        try:
            instances, self._more = api.nova.server_list(
                self.request,
                search_opts=search_opts,
                all_tenants=True)
        except Exception:
            self._more = False
            exceptions.handle(self.request,
                              _('Unable to retrieve instance list.'))
        """
	if instances:
            try:
                api.network.servers_update_addresses(self.request, instances,
                                                     all_tenants=True)
            except Exception:
                exceptions.handle(
                    self.request,
                    message=_('Unable to retrieve IP addresses from Neutron.'),
                    ignore=True)

            # Gather our flavors to correlate against IDs
            try:
                flavors = api.nova.flavor_list(self.request)
            except Exception:
                # If fails to retrieve flavor list, creates an empty list.
                flavors = []

            full_flavors = SortedDict([(f.id, f) for f in flavors])
            tenant_dict = SortedDict([(t.id, t) for t in tenants])
            count = 1 # to count instances number
            # Loop through instances to get flavor and tenant info.
            for inst in instances:
                flavor_id = inst.flavor["id"]
                try:
                    if flavor_id in full_flavors:
                        inst.full_flavor = full_flavors[flavor_id]
                    else:
                        # If the flavor_id is not in full_flavors list,
                        # gets it via nova api.
                        inst.full_flavor = api.nova.flavor_get(
                            self.request, flavor_id)
                except Exception:
                    msg = _('Unable to retrieve instance size information.')
                    exceptions.handle(self.request, msg)
                tenant = tenant_dict.get(inst.tenant_id, None)
		inst.number = count
                inst.tenant_name = getattr(tenant, "name", None)

		cluster_name = inst.cluster_name
	        #result, node_list = server.listNode(cluster_id).split(";")
		cluster_node = server.list_node(cluster_name)
                cluster_node = Response(code=cluster_node["code"], message=cluster_node["message"], data=cluster_node["data"])
		result = cluster_node.code
		node_list = cluster_node.data.get("nodeList")
		cluster_nodes = []
		for node in node_list:
			cluster_nodes.append(node["node_name"])
	        if len(cluster_nodes) == 1:
		    inst.protection = "Incomplete Protected"
	        else:
		    inst.protection = "Protected"
		count = count +1
        return instances
Exemplo n.º 15
0
 def __init__(self, _dict):
     self._dict = dict()
     for field_class, args in list(_dict.items()):
         self._dict[field_class] = SortedDict(self.COMMON + args)
Exemplo n.º 16
0
def simple_query(context, separator, **kwargs):
    query = SortedDict(kwargs.iteritems())
    return build_query(context['params'], query, separator=separator)
Exemplo n.º 17
0
    except ImportError:
        from django.utils.datastructures import SortedDict

    UseExceptions()
    AllRegister()

    GCI_TO_NAME = SortedDict((
        (GCI_Undefined, "Undefined"),
        (GCI_GrayIndex, "GrayIndex"),
        (GCI_PaletteIndex, "PaletteIndex"),
        (GCI_RedBand, "RedBand"),
        (GCI_GreenBand, "GreenBand"),
        (GCI_BlueBand, "BlueBand"),
        (GCI_AlphaBand, "AlphaBand"),
        (GCI_HueBand, "HueBand"),
        (GCI_SaturationBand, "SaturationBand"),
        (GCI_LightnessBand, "LightnessBand"),
        (GCI_CyanBand, "CyanBand"),
        (GCI_MagentaBand, "MagentaBand"),
        (GCI_YellowBand, "YellowBand"),
        (GCI_BlackBand, "BlackBand"),
        (GCI_YCbCr_YBand, "YBand"),
        (GCI_YCbCr_CbBand, "CbBand"),
        (GCI_YCbCr_CrBand, "CrBand"),
    ))

    NAME_TO_GCI = dict((j.lower(), i) for (i, j) in GCI_TO_NAME.items())

    GDT_TO_NAME = SortedDict((
        (GDT_Byte, "Byte"),
        (GDT_UInt16, "UInt16"),
Exemplo n.º 18
0
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    # 'debug_toolbar.panels.cache.CachePanel',
    # 'debug_toolbar.panels.signals.SignalsPanel',
    # 'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
)

LOCALE_PATHS = (os.path.join(ROOT_DIR, 'locale/'), )

# We are using lazy translation, so these strings will be translated in the
# template not here.
AVAILABLE_UNITS = SortedDict([
    ("aya", _("Ayahs")),
    #( "sura", "Surahs" ),
    ("translation", _("Translations")),
    # ( "word", _("Words") ),
    #  tafsir, hadith, dream, poem
])

HTML_MINIFY = True

EXCLUDE_FROM_MINIFYING = ('^', )

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = False
COMPRESS_STORAGE = 'compressor.storage.GzipCompressorFileStorage'
GZIP_CONTENT_TYPES = ('text/css', 'application/javascript',
                      'application/x-javascript', 'text/javascript')

################################
Exemplo n.º 19
0
 def safe_summary (self, encoded):
     return SortedDict ([
         (_ ('algorithm'), self.algorithm),
         (_ ('hash'),mask_hash (encoded, show = 3)),
     ])
Exemplo n.º 20
0
def check_split_by_blast(transcript, cds_boundaries):
    """
    This method verifies if a transcript with multiple ORFs has support by BLAST to
    NOT split it into its different components.

    The minimal overlap between ORF and HSP is defined inside the JSON at the key
        ["chimera_split"]["blast_params"]["minimal_hsp_overlap"]
    basically, we consider a HSP a hit only if the overlap is over a certain threshold
    and the HSP evalue under a certain threshold.

    The split by CDS can be executed in three different ways - PERMISSIVE, LENIENT, STRINGENT:

    - PERMISSIVE: split if two CDSs do not have hits in common,
    even when one or both do not have a hit at all.
    - STRINGENT: split only if two CDSs have hits and none
    of those is in common between them.
    - LENIENT: split if *both* lack hits, OR *both* have hits and none
    of those is in common.

    :param transcript: the transcript instance
    :type transcript: Mikado.loci_objects.transcript.Transcript
    :param cds_boundaries:
    :return: cds_boundaries
    :rtype: dict
    """

    # Establish the minimum overlap between an ORF and a BLAST hit to consider it
    # to establish belongingness

    assert isinstance(transcript.configuration,
                      (MikadoConfiguration, DaijinConfiguration))

    minimal_overlap = transcript.configuration.pick.chimera_split.blast_params.minimal_hsp_overlap
    transcript.logger.debug("Minimal overlap when checking for %s: %s",
                            transcript.id, minimal_overlap)

    cds_hit_dict = SortedDict().fromkeys(cds_boundaries.keys())
    for key in cds_hit_dict:
        cds_hit_dict[key] = collections.defaultdict(list)

    # BUG, this is a hacky fix
    if not hasattr(transcript, "blast_hits"):
        transcript.logger.warning(
            "BLAST hits store lost for %s! Creating a mock one to avoid a crash",
            transcript.id)
        transcript.blast_hits = []

    transcript.logger.debug("%s has %d possible hits", transcript.id,
                            len(transcript.blast_hits))

    # Determine for each CDS which are the hits available
    min_eval = transcript.configuration.pick.chimera_split.blast_params.hsp_evalue
    for hit in transcript.blast_hits:
        for hsp in iter(_hsp for _hsp in hit["hsps"]
                        if _hsp["hsp_evalue"] <= min_eval):
            for cds_run in cds_boundaries:
                # If I have a valid hit b/w the CDS region and the hit,
                # add the name to the set
                overlap_threshold = minimal_overlap * (cds_run[1] + 1 -
                                                       cds_run[0])
                overl = overlap(cds_run,
                                (hsp['query_hsp_start'], hsp['query_hsp_end']))

                if overl >= overlap_threshold:
                    cds_hit_dict[cds_run][(hit["target"],
                                           hit["target_length"])].append(hsp)
                    transcript.logger.debug(
                        "Overlap %s passed for %s between %s CDS and %s HSP (threshold %s)",
                        overlap, transcript.id, cds_run,
                        (hsp['query_hsp_start'], hsp['query_hsp_end']),
                        overlap_threshold)
                else:
                    transcript.logger.debug(
                        "Overlap %s rejected for %s between %s CDS and %s HSP (threshold %s)",
                        overlap, transcript.id, cds_run,
                        (hsp['query_hsp_start'], hsp['query_hsp_end']),
                        overlap_threshold)

    transcript.logger.debug("Final cds_hit_dict for %s (length %s): %s",
                            transcript.id, len(cds_hit_dict), cds_hit_dict)

    final_boundaries = SortedDict()
    for boundary in __get_boundaries_from_blast(transcript, cds_boundaries,
                                                cds_hit_dict):
        if len(boundary) == 1:
            assert len(boundary[0]) == 2
            boundary = boundary[0]
            final_boundaries[boundary] = cds_boundaries[boundary]
        else:
            nboun = (boundary[0][0], boundary[-1][1])
            final_boundaries[nboun] = []
            for boun in boundary:
                final_boundaries[nboun].extend(cds_boundaries[boun])
    transcript.logger.debug("Final boundaries for %s: %s", transcript.id,
                            final_boundaries)

    cds_boundaries = final_boundaries.copy()
    return cds_boundaries
Exemplo n.º 21
0
def results(request, unit="aya"):

    if unit not in settings.AVAILABLE_UNITS:
        raise Http404()
    mutable_request = dict(request.GET.items())
    show_params = {"action": "show", "query": "all"}

    if 'query' in mutable_request and mutable_request.get(
            'action', 'search') == 'search':
        search_params = mutable_request
        suggest_params = {
            "action": "suggest",
            "query": mutable_request["query"]
        }
    elif 'search' in mutable_request:
        ## back-compatibility of links:
        # if it's a classic API style, wrap it to the new API style
        search_params = {
            "action": "search",
            "query": mutable_request["search"],
            "page": mutable_request.get('page', 1),
            "sortedby": mutable_request.get('sortedby', 'relevance'),
        }
        suggest_params = {
            "action": "suggest",
            "query": mutable_request["search"],
        }
    else:
        search_params = {}
        suggest_params = {}
        # override the unit flag

    mutable_request["unit"] = unit
    # use search as first action
    raw_search = RAWoutput.do(search_params) if search_params else None
    # use suggest as second action
    raw_suggest = RAWoutput.do(suggest_params) if suggest_params else None
    # use show as third action
    raw_show = RAWoutput.do(show_params) if show_params else None

    # TODO: We shouldn't get the language info here. We have to get the bidi info in the
    # template, same as we do with the other language stuff.

    # language direction  properties
    bidi_val = my_get_language_info(request.LANGUAGE_CODE)['bidi']
    fields_mapping_en_ar = raw_show["show"]["fields_reverse"]
    fields_mapping_en_en = dict([(k, k) for k in fields_mapping_en_ar])

    # a sorted list of translations
    translations = raw_show["show"]["translations"]
    sorted_translations = SortedDict(
        sorted(translations.iteritems(), key=itemgetter(0)))

    bidi_properties = {
        False: {
            "val": bidi_val,
            "direction": "ltr",
            "align": "left",
            "align_inverse": "right",
            "image_extension": "_en",
            "fields": fields_mapping_en_en
        },
        True: {
            "val": bidi_val,
            "direction": "rtl",
            "align": "right",
            "align_inverse": "left",
            "image_extension": "_ar",
            "fields": fields_mapping_en_ar
        }
    }
    mytemplate = unit + '_search.html'

    context = {
        'current': {
            'path': request.path,
            'request': request.GET.urlencode(),
            'unit': unit,
        },
        "bidi": bidi_properties[bidi_val],
        "available": {
            "units": settings.AVAILABLE_UNITS,
            "translations": sorted_translations
        },
        "params": search_params,
        "results": raw_search,
        "suggestions": raw_suggest,
        "info": raw_show
    }

    response = render_to_response(mytemplate, context)
    if raw_search and (raw_search["error"]["code"]
                       or not raw_search["search"]["interval"]["total"]):
        response.status_code = 404

    return response
Exemplo n.º 22
0
def split_by_cds(transcript):
    """This method is used for transcripts that have multiple ORFs.
    It will split them according to the CDS information into multiple transcripts.
    UTR information will be retained only if no ORF is down/upstream.

    :param transcript: the transcript instance
    :type transcript: Mikado.loci_objects.transcript.Transcript
    """

    transcript.finalize()

    # List of the transcript that will be retained

    if transcript.number_internal_orfs < 2:
        new_transcripts = [transcript]  # If we only have one ORF this is easy
    elif transcript.source in transcript.configuration.pick.chimera_split.skip:
        # Disable splitting for transcripts with certain tags
        transcript.logger.debug("%s (label %s) to be skipped for splitting",
                                transcript.id,
                                transcript.id.split("_")[0])
        new_transcripts = [transcript]
    else:
        cds_boundaries = SortedDict()
        for orf in sorted(transcript.loaded_bed12,
                          key=operator.attrgetter("thick_start", "thick_end")):
            cds_boundaries[(orf.thick_start, orf.thick_end)] = [orf]

        # Check whether we have to split or not based on BLAST data
        if transcript.configuration.pick.chimera_split.blast_check is True:
            cds_boundaries = check_split_by_blast(transcript, cds_boundaries)

        if len(cds_boundaries) == 1:
            # Recheck how many boundaries we have - after the BLAST check
            # we might have determined that the transcript has not to be split
            transcript.logger.debug("Not splitting %s", transcript.id)
            new_transcripts = [transcript]
        else:
            try:
                new_transcripts = __create_splitted_transcripts(
                    transcript, cds_boundaries)
            except InvalidTranscript as err:
                exc = InvalidTranscript(err)
                transcript.logger.error("Error in splitting %s by ORF",
                                        transcript.id)
                transcript.logger.exception(exc)
                transcript.logger.error(
                    "ORFs: %s",
                    "\n".join([str(_) for _ in transcript.internal_orfs]))
                transcript.logger.error(
                    "BED12: %s",
                    "\n".join([str(_) for _ in transcript.loaded_bed12]))
                transcript.logger.error("Stripping %s of its CDS.",
                                        transcript.id)
                transcript.strip_cds()
                new_transcripts = [transcript]

    assert len(new_transcripts) > 0, str(transcript)
    __original = set()
    for internal in transcript.internal_orfs:
        __original.add(tuple([_[1] for _ in internal if _[0] == "CDS"]))

    for new_transc in new_transcripts:
        for internal in new_transc.internal_orfs:
            internal = tuple([_[1] for _ in internal if _[0] == "CDS"])
            assert internal in __original, (transcript.id, __original,
                                            internal)

        new_transc.verified_introns = set.intersection(
            set(new_transc.introns), transcript.verified_introns)
        new_transc.attributes["split"] = True
        yield new_transc

    return
Exemplo n.º 23
0
                        if distance < settings.PASSWORD_DIFFERENCE_DISTANCE:
                            raise forms.ValidationError(self.error_messages['password_similar'])
        return cleaned_data

    def save(self, commit=True):
        user = super(PasswordPoliciesChangeForm, self).save(commit=commit)
        try:
            # Checking the object id to prevent AssertionError id is None when deleting.
            if user.password_change_required and user.password_change_required.id:
                user.password_change_required.delete()
        except ObjectDoesNotExist:
            pass
        return user

PasswordPoliciesChangeForm.base_fields = SortedDict([
    (k, PasswordPoliciesChangeForm.base_fields[k])
    for k in ['old_password', 'new_password1', 'new_password2']
])


class PasswordResetForm(forms.Form):
    """
A form to let a user reset his/her password.

Has the following fields and methods:
"""
    #: This forms error messages.
    error_messages = {
        'unknown': _("That e-mail address doesn't have an associated "
                     "user account. Are you sure you've registered?"),
        'unusable': _("The user account associated with this e-mail "
                      "address cannot reset the password."),
Exemplo n.º 24
0
 def __init__(self):
     self._supported_languages = SortedDict(settings.LANGUAGES)
     self._language_domains = SortedDict(settings.MULTILANG_LANGUAGE_DOMAINS)
Exemplo n.º 25
0
    def __init__(self, base_dir, name):
        self._base_dir = os.path.abspath(base_dir)
        self._indexers = SortedDict()
        self._name = name

        self.__class__.instances.append(self)
Exemplo n.º 26
0
def task_list(request):
    # get the signed in volunteer
    if request.user.is_authenticated():
        volunteer = Volunteer.objects.get(user=request.user)
    else:
        volunteer = None
        is_dr_manhattan = False
    current_tasks = Task.objects.filter(edition=Edition.get_current())
    if volunteer:
        is_dr_manhattan, dr_manhattan_task_sets = volunteer.detect_dr_manhattan()
        dr_manhattan_task_ids = [x.id for x in set.union(*dr_manhattan_task_sets)] if dr_manhattan_task_sets else []
        ok_tasks = current_tasks.exclude(id__in=dr_manhattan_task_ids)
    else:
        ok_tasks = current_tasks
    days = sorted(list(set([x.date for x in current_tasks])))

    # when the user submitted the form
    if request.method == 'POST' and volunteer:
        # get the checked tasks
        task_ids = request.POST.getlist('task')

        # unchecked boxes, delete him/her from the task
        for task in current_tasks.exclude(id__in=task_ids):
            VolunteerTask.objects.filter(task=task, volunteer=volunteer).delete()

        # checked boxes, add the volunteer to the tasks when he/she is not added
        for task in current_tasks.filter(id__in=task_ids):
            VolunteerTask.objects.get_or_create(task=task, volunteer=volunteer)

        # show success message when enabled
        if userena_settings.USERENA_USE_MESSAGES:
            messages.success(request, _('Your tasks have been updated.'), fail_silently=True)

        # redirect to prevent repost
        return redirect('task_list')

    # get the preferred and other tasks, preserve key order with srteddict for view
    context = {
        'tasks': SortedDict({}),
        'checked': {},
        'attending': {},
        'is_dr_manhattan': is_dr_manhattan,
        'setup_for_current_year_complete': getattr(settings, 'SETUP_FOR_CURRENT_YEAR_COMPLETE', False),
    }
    # get the categories the volunteer is interested in
    if volunteer:
        categories_by_task_pref = {
            'preferred tasks': TaskCategory.objects.filter(volunteer=volunteer, active=True),
            'other tasks': TaskCategory.objects.filter(active=True).exclude(volunteer=volunteer),
        }
        context['volunteer'] = volunteer
        context['dr_manhattan_task_sets'] = dr_manhattan_task_sets
        context['tasks']['preferred tasks'] = SortedDict.fromkeys(days, {})
        context['tasks']['other tasks'] = SortedDict.fromkeys(days, {})
    else:
        categories_by_task_pref = {
            # 'preferred tasks': [],
            'tasks': TaskCategory.objects.filter(active=True),
        }
        context['tasks']['tasks'] = SortedDict.fromkeys(days, {})
    context['user'] = request.user
    for category_group in context['tasks']:
        for day in context['tasks'][category_group]:
            context['tasks'][category_group][day] = SortedDict.fromkeys(categories_by_task_pref[category_group], [])
            for category in context['tasks'][category_group][day]:
                dct = ok_tasks.filter(template__category=category, date=day)
                context['tasks'][category_group][day][category] = dct

    # mark checked, attending tasks
    if volunteer:
        for task in current_tasks:
            context['checked'][task.id] = 'checked' if volunteer in task.volunteers.all() else ''
            context['attending'][task.id] = False

        # take the moderation tasks to talks the volunteer is attending
        for task in current_tasks.filter(talk__volunteers=volunteer):
            context['attending'][task.id] = True
        check_profile_completeness(request, volunteer)
    else:
        for task in current_tasks:
            context['attending'][task.id] = False

    return render(request, 'volunteers/tasks.html', context)
 def __init__(self, *args, **kwargs):
     super(SortedDotDict, self).__init__(*args, **kwargs)
     self._dict = SortedDict()
Exemplo n.º 28
0
class Company(models.Model):
    AVATAR_ROOT = 'company/avatars'

    COMPANY_SIZE_0_1 = "0"
    COMPANY_SIZE_2_10 = "2"
    COMPANY_SIZE_11_15 = "11"
    COMPANY_SIZE_51_200 = "51"
    COMPANY_SIZE_201_500 = "201"
    COMPANY_SIZE_501_1000 = "501"
    COMPANY_SIZE_1001_5000 = "501"
    COMPANY_SIZE_5001_10000 = "50001"
    COMPANY_SIZE_100001_PLUS = "10001"

    COMPANY_SIZE_CHOICES = SortedDict([
        (COMPANY_SIZE_0_1, _("0-1 employees")),
        (COMPANY_SIZE_2_10, _("2-10 employees")),
        (COMPANY_SIZE_11_15, _("11-50 employees")),
        (COMPANY_SIZE_51_200, _("51-200 employees")),
        (COMPANY_SIZE_201_500, _("201-500 employees")),
        (COMPANY_SIZE_501_1000, _("501-1,000 employees")),
        (COMPANY_SIZE_1001_5000, _("1,001-5,000 employees")),
        (COMPANY_SIZE_5001_10000, _("5,001-10,000 employees")),
        (COMPANY_SIZE_100001_PLUS, _("10,001+ employees")),
    ])

    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=255,
                            null=True,
                            blank=True,
                            verbose_name=_("slug"))
    description = models.TextField(
        help_text="company description",
        null=True,
        blank=True,
    )
    description_extra = models.TextField(
        help_text="company description extra",
        null=True,
        blank=True,
    )

    size = models.CharField(max_length=5,
                            choices=list(COMPANY_SIZE_CHOICES.items()),
                            help_text=_("company size"),
                            default=COMPANY_SIZE_2_10,
                            blank=True)

    founded = models.DateField(max_length=255, null=True, blank=True)
    avatar = models.ImageField(upload_to=unique_company_avatar_filename,
                               blank=True,
                               null=True)
    website = models.URLField(verbose_name="website", blank=True, null=True)

    facebook = models.CharField(max_length=256,
                                blank=True,
                                null=True,
                                help_text="Please leave empty if none")
    twitter = models.CharField(max_length=256,
                               blank=True,
                               null=True,
                               help_text="Please leave empty if none")
    linkedin = models.CharField(max_length=256,
                                blank=True,
                                null=True,
                                help_text="Please leave empty if none")
    city = models.ForeignKey(City,
                             blank=True,
                             null=True,
                             related_name='companies',
                             help_text="city where the company is located in")
    latitude = models.CharField(max_length=255,
                                null=True,
                                blank=True,
                                verbose_name=_("Location's latitude"))
    longitude = models.CharField(max_length=255,
                                 null=True,
                                 blank=True,
                                 verbose_name=_("Location's longitude"))
    the_geom = models.PointField(null=True,
                                 blank=True,
                                 editable=False,
                                 srid=4326,
                                 verbose_name=_("point"))
    verified = models.BooleanField(default=False, verbose_name=_("Verified"))
    owner = models.ForeignKey(AUTH_USER_MODEL,
                              related_name="owned_companies",
                              verbose_name=_("owner"),
                              null=True,
                              blank=True)
    members = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                     related_name="companies",
                                     through="Membership",
                                     verbose_name=_("members"),
                                     through_fields=("company", "user"))
    creator = models.ForeignKey(AUTH_USER_MODEL,
                                related_name="+",
                                verbose_name=_("creator"))

    _importing = None

    class Meta:
        app_label = 'company'
        verbose_name_plural = "companies"
        ordering = ['name']
        permissions = (
            ('view_section', 'view company details'),
            ('edit_company', 'edit company details'),
            ('add_member', 'add team member to company'),
        )

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.longitude and self.latitude:
            the_geom = 'POINT(%s %s)' % (self.longitude, self.latitude)
            self.the_geom = GEOSGeometry(the_geom, srid=4326)
        super(Company, self).save(*args, **kwargs)

        if not self.slug:  # @todo find a better solution
            self.slug = "%s--%s" % (self.pk, slugify(self.name))
            self.save()

    @property
    def full_name(self):
        return self.name

    def gen_company_name(self):
        return "%s HR Team - %s" % (slugify(self.name), self.owner_id)

    def get_absolute_url(self):
        return reverse('company', args=(
            self.id,
            self.slug,
        ))

    def geo_es_format(self):
        if self.latitude and self.longitude:
            return {
                "lat": self.latitude if self.latitude else None,
                "lon": self.latitude if self.latitude else None,
            }

    @cached_property
    def cached_memberships(self):
        return {
            m.user.id: m
            for m in self.memberships.exclude(
                user__isnull=True).select_related("user", "company", "role")
        }

    def cached_memberships_for_user(self, user):
        return self.cached_memberships.get(user.id, None)

    @cached_property
    def cached_notify_policies(self):
        return {
            np.user.id: np
            for np in self.notify_policies.select_related("user", "company")
        }

    def cached_notify_policy_for_user(self, user):
        """
        Get notification level for specified company and user.
        """
        policy = self.cached_notify_policies.get(user.id, None)
        if policy is None:
            model_cls = get_model("notifications", "NotifyPolicy")
            policy = model_cls.objects.create(
                company=self, user=user, notify_level=NotifyLevel.involved)

            del self.cached_notify_policies

        return policy

    def _get_q_watchers(self):
        return Q(notify_policies__company_id=self.id) & ~Q(
            notify_policies__notify_level=NotifyLevel.none)

    def get_watchers(self):
        return get_user_model().objects.filter(self._get_q_watchers())

    def get_related_people(self):
        related_people_q = Q()

        ## - Owner
        if self.owner_id:
            related_people_q.add(Q(id=self.owner_id), Q.OR)

        ## - Watchers
        related_people_q.add(self._get_q_watchers(), Q.OR)

        ## - Apply filters
        related_people = get_user_model().objects.filter(related_people_q)

        ## - Exclude inactive and system users and remove duplicate
        related_people = related_people.exclude(is_active=False)
        related_people = related_people.exclude(is_system=True)
        related_people = related_people.distinct()
        return related_people
Exemplo n.º 29
0
        else:
            count += 1
    return count


def index_decorator(func):
    def inner(*args, **kwargs):
        template_response = func(*args, **kwargs)
        for app in template_response.context_data['available_apps']:
            app['models'].sort(key=lambda x: find_model_index(x['name']))
        return template_response

    return inner


registry = SortedDict()
registry.update(admin.site._registry)
admin.site._registry = registry
admin.site.index = index_decorator(admin.site.index)
admin.site.app_index = index_decorator(admin.site.app_index)
admin.site.site_header = '成都软件测试'
admin.site.siteTitle = '成都软件测试'

display = ()


class BlackListForm(admin.ModelAdmin):
    search_fields = ('CompanyName', )
    list_display = ('id', 'CompanyName', 'CompanyAddress', 'ComplainData',
                    'status')
    list_display_links = ('id', 'CompanyName', 'CompanyAddress', 'status')
Exemplo n.º 30
0
    def autocompletion_search(query, **kwargs):
        limit = kwargs.get('limit')
        exact = kwargs.get('exact', False)
        groups_only = kwargs.get('groups_only', False)
        sceners_only = kwargs.get('sceners_only', False)

        group_ids = kwargs.get('group_ids', [])
        group_names = [name.lower() for name in kwargs.get('group_names', [])]
        member_names = [
            name.lower() for name in kwargs.get('member_names', [])
        ]

        if query:
            if exact:
                nick_variants = NickVariant.objects.filter(name__iexact=query)
            else:
                nick_variants = NickVariant.objects.filter(
                    name__istartswith=query)

            if groups_only:
                nick_variants = nick_variants.filter(
                    nick__releaser__is_group=True)
            elif sceners_only:
                nick_variants = nick_variants.filter(
                    nick__releaser__is_group=False)
            else:
                # nasty hack to ensure that we're joining on releaser, for the 'group_names' subquery
                nick_variants = nick_variants.filter(
                    nick__releaser__is_group__in=[True, False])

            if group_ids:
                # Add a 'score' field that prioritises releasers that are members of any of the specified groups
                select = SortedDict([
                    ('score', '''
                        SELECT COUNT(*) FROM demoscene_membership
                        WHERE demoscene_membership.member_id = demoscene_releaser.id
                        AND demoscene_membership.group_id IN %s
                    '''),
                ])
                select_params = [tuple(group_ids)]
            elif group_names:
                # Add a 'score' field that prioritises releasers that are members of a group with one of the given names
                select = SortedDict([
                    ('score', '''
                        SELECT COUNT(*) FROM demoscene_membership
                        INNER JOIN demoscene_releaser AS demogroup ON (demoscene_membership.group_id = demogroup.id)
                        INNER JOIN demoscene_nick AS group_nick ON (demogroup.id = group_nick.releaser_id)
                        INNER JOIN demoscene_nickvariant AS group_nickvariant ON (
                            group_nick.id = group_nickvariant.nick_id
                        )
                        WHERE demoscene_membership.member_id = demoscene_releaser.id
                        AND LOWER(group_nickvariant.name) IN %s
                    '''),
                ])
                select_params = [tuple(group_names)]
            elif member_names:
                # Add a 'score' field that prioritises groups that have members with one of the given names
                select = SortedDict([
                    ('score', '''
                        SELECT COUNT(*) FROM demoscene_membership
                        INNER JOIN demoscene_releaser AS member ON (demoscene_membership.member_id = member.id)
                        INNER JOIN demoscene_nick AS member_nick ON (member.id = member_nick.releaser_id)
                        INNER JOIN demoscene_nickvariant AS member_nickvariant ON (
                            member_nick.id = member_nickvariant.nick_id
                        )
                        WHERE demoscene_membership.group_id = demoscene_releaser.id
                        AND LOWER(member_nickvariant.name) IN %s
                    '''),
                ])
                select_params = [tuple(member_names)]
            else:
                select = SortedDict([
                    ('score', '0'),
                ])
                select_params = []

            # Add an 'is_exact_match' column to the results - true if the query matches the result exactly
            select['is_exact_match'] = '''
                CASE WHEN LOWER(demoscene_nickvariant.name) = LOWER(%s) THEN 1 ELSE 0 END
            '''
            select_params.append(query)

            # Add an 'is_primary_nickvariant' column to the results -
            # true if the matched nick variant is the nick's primary one
            select['is_primary_nickvariant'] = '''
                CASE WHEN demoscene_nick.name = demoscene_nickvariant.name THEN 1 ELSE 0 END
            '''

            nick_variants = nick_variants.extra(
                select=select,
                select_params=select_params,
                order_by=('-score', '-is_exact_match',
                          '-is_primary_nickvariant', 'name'))

            if limit:
                nick_variants = nick_variants[:limit]

            nick_variants = nick_variants.select_related(
                'nick', 'nick__releaser')
        else:
            nick_variants = NickVariant.objects.none()

        return nick_variants