コード例 #1
0
ファイル: utils.py プロジェクト: artursmet/saleor
def sorting_header(context, field, label, is_wide=False):
    """Render a table sorting header."""
    request = context['request']
    request_get = request.GET.copy()
    sort_by = request_get.get('sort_by')

    # path to icon indicating applied sorting
    sorting_icon = ''

    # flag which determines if active sorting is on field
    is_active = False

    if sort_by:
        if field == sort_by:
            is_active = True
            # enable ascending sort
            # new_sort_by is used to construct a link with already toggled
            # sort_by value
            new_sort_by = '-%s' % field
            sorting_icon = static('/images/arrow-up-icon.svg')
        else:
            # enable descending sort
            new_sort_by = field
            if field == sort_by.strip('-'):
                is_active = True
                sorting_icon = static('/images/arrow-down-icon.svg')
    else:
        new_sort_by = field

    request_get['sort_by'] = new_sort_by
    return {
        'url': '%s?%s' % (request.path, request_get.urlencode()),
        'is_active': is_active, 'sorting_icon': sorting_icon, 'label': label,
        'is_wide': is_wide}
コード例 #2
0
ファイル: views.py プロジェクト: gazoon/icemad
def update_logo(request, project):
    user = request.user
    if 'remove_logo' in request.POST:
        project.logo.delete()
        data = {
            'logo': static(DEFAULT_LOGO)
        }
    elif 'remove_logo_youtube' in request.POST:
        if project.is_youtube_logo:
            project.logo.delete()
            logo_url = static(DEFAULT_LOGO)
        else:
            logo_url = project.logo.url
        data = {
            'logo': logo_url
        }
    else:
        form = UpdateLogoForm(request.POST, request.FILES)
        if not form.is_valid():
            return form.errors_dict, http.BAD_REQUEST
        with form.cleaned_data['logo'] as uploaded_image:
            img_name = uploaded_image.name
            img_content = uploaded_image.read()
        project.set_logo(img_name, img_content)
        project.is_youtube_logo = False
        project.save(update_fields=['logo', 'is_youtube_logo'])
        data = {
            'logo': project.logo.url
        }
    return data, http.OK
コード例 #3
0
ファイル: views.py プロジェクト: HelloLily/hellolily
    def create(self, request, *args, **kwargs):
        """
        Sends a websocket message to the user with the corresponding internal number
        """
        response = super(CallViewSet, self).create(request, *args, **kwargs)
        called_user = LilyUser.objects.filter(
            internal_number=request.data['internal_number'],
            tenant_id=request.user.tenant_id
        ).first()

        if not called_user:
            return response

        caller_number = parse_phone_number(request.data['caller_number'])
        account, contact = search_number(called_user.tenant_id, caller_number)

        # If a account with this number has been found, show information about and link to this account.
        if account:
            data = {
                'destination': 'account',
                'icon': static('app/images/notification_icons/account.png'),
                'params': {
                    'name': account.name,
                    'number': caller_number,
                    'id': account.id,
                },
            }

        # There is no account for the number, but if there is a contact, show information about and link to it.
        elif contact:
            data = {
                'destination': 'contact',
                'icon': static('app/images/notification_icons/contact.png'),
                'params': {
                    'name': contact.full_name,
                    'number': caller_number,
                    'id': contact.id,
                },
            }

        # If no account or contact has been found, use the name provided by VoIPGRID.
        else:
            data = {
                'destination': 'create',
                'icon': static('app/images/notification_icons/add-account.png'),
                'params': {
                    'name': request.data.get('caller_name'),
                    'number': caller_number,
                },
            }

        # Sends the data as a notification event to the user who picked up the phone.
        Group('user-%s' % called_user.id).send({
            'text': json.dumps({
                'event': 'notification',
                'data': data,
            }),
        })

        return response
コード例 #4
0
ファイル: modeladmins.py プロジェクト: finid/feincms
    def _actions_column(self, page):
        addable = getattr(page, 'feincms_addable', True)

        preview_url = "../../r/%s/%s/" % (
                ContentType.objects.get_for_model(self.model).id,
                page.id)
        actions = super(PageAdmin, self)._actions_column(page)

        if addable:
            if not page.template.enforce_leaf:
                actions.insert(
                    0,
                    u'<a href="add/?parent=%s" title="%s">'
                    u'<img src="%s" alt="%s" />'
                    u'</a>' % (
                        page.pk,
                        _('Add child page'),
                        static('feincms/img/icon_addlink.gif'),
                        _('Add child page'),
                    )
                )
        actions.insert(
            0,
            u'<a href="%s" title="%s">'
            u'<img src="%s" alt="%s" />'
            u'</a>' % (
                preview_url,
                _('View on site'),
                static('feincms/img/selector-search.gif'),
                _('View on site'),
            )
        )
        return actions
コード例 #5
0
ファイル: models.py プロジェクト: drwelby/mapstory
    def render(self, width=None, height=None, css_class=None):
        '''width and height are just hints - ignored for images'''

        ctx = dict(href=self.href, link_content=self.name, css_class=css_class, width='', height='')
        if self.is_image():
            return '<img class="%(css_class)s" src="%(href)s" title="%(link_content)s"></img>' % ctx

        video = self.get_youtube_video()
        if video:
            ctx['video'] = video
            ctx['width'] = 'width="%s"' % width
            ctx['height'] = 'height="%s"' % height
            return ('<iframe class="youtube-player" type="text/html"'
                    ' %(width)s %(height)s frameborder="0"'
                    ' src="http://www.youtube.com/embed/%(video)s">'
                    '</iframe>') % ctx

        known_links = [
            (self.get_twitter_link, static('img/twitter.png')),
            (self.get_facebook_link, static('img/facebook.png')),
        ]
        for fun, icon in known_links:
            if fun():
                ctx['link_content'] = '<img src="%s" border=0>' % icon
                break

        return '<a target="_" href="%(href)s">%(link_content)s</a>' % ctx
コード例 #6
0
ファイル: mixins.py プロジェクト: TalentoUnicamp/my
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     sidebar_context = {
         'active_tab': self.active_tab,
         'event_name': dj_settings.EVENT_NAME,
         'event_logo': static('project/img/logo.svg'),
         'event_logo_png': static('project/img/logo.png'),
         'redirect_urls': {
             'dashboard': reverse('dashboard:index'),
             'application': reverse('application:form'),
             'company': reverse('company:index'),
             'team': reverse('dashboard:index'),
             'admin': reverse('godmode:index'),
             'staff': reverse('staff:index'),
             'stats': reverse('stats:index'),
             'schedule': reverse('schedule:index'),
             'helper': reverse('helper:index'),
             'logout': reverse('profile:logout'),
         },
         'api': {
             'get_announcement': reverse('announcement:api:announcement-list'),
         }
     }
     context['sidebar_context'] = json.dumps(sidebar_context)
     return context
コード例 #7
0
    def render_data(self, review_request):
        user = self.datagrid.request.user

        if user.is_anonymous() or review_request.mycomments_my_reviews == 0:
            return ""

        image_url = None
        image_alt = None

        # Priority is ranked in the following order:
        #
        # 1) Non-public (draft) reviews
        # 2) Public reviews marked "Ship It"
        # 3) Public reviews not marked "Ship It"
        if review_request.mycomments_private_reviews > 0:
            image_url = self.image_url
            image_alt = _("Comments drafted")
        else:
            if review_request.mycomments_shipit_reviews > 0:
                image_url = static("rb/images/comment-shipit-small.png")
                image_alt = _("Comments published. Ship it!")
            else:
                image_url = static("rb/images/comment-small.png")
                image_alt = _("Comments published")

        return '<img src="%s" width="%s" height="%s" alt="%s" ' \
               'title="%s" />' % \
                (image_url, self.image_width, self.image_height,
                 image_alt, image_alt)
コード例 #8
0
ファイル: tethys_gizmos.py プロジェクト: astraiophos/tethys
    def render(self, context):
        # Get the gizmos rendered from the context
        gizmos_rendered = context['gizmos_rendered']

        # Compile list of unique gizmo dependencies
        dependencies = []

        # Add gizmo dependencies
        for rendered_gizmo in gizmos_rendered:
            try:
                # Retrieve the "gizmo_dependencies" module and find the appropriate function
                dependencies_module = __import__('tethys_gizmos.gizmo_dependencies', fromlist=[rendered_gizmo])
                dependencies_function = getattr(dependencies_module, rendered_gizmo)

                # Retrieve a list of dependencies for the gizmo
                gizmo_deps = dependencies_function(context)

                # Only append dependencies if they do not already exist
                for dependency in gizmo_deps:
                    if EXTERNAL_INDICATOR in dependency:
                        static_url = dependency
                    else:
                        static_url = static(dependency)

                    if static_url not in dependencies:
                        # Lookup the static url given the path
                        dependencies.append(static_url)

            except AttributeError:
                # Skip those that do not have dependencies
                pass

        # Add the global dependencies last
        for dependency in global_dependencies(context):
            if EXTERNAL_INDICATOR in dependency:
                static_url = dependency
            else:
                static_url = static(dependency)

            if static_url not in dependencies:
                # Lookup the static url given the path
                dependencies.append(static_url)

        # Create markup tags
        script_tags = []
        style_tags = []
        for dependency in dependencies:
            # Only process Script tags if the dependency has a ".js" extension and the output type is JS or not specified
            if JS_EXTENSION in dependency and (self.output_type == JS_OUTPUT_TYPE or self.output_type is None):
                script_tags.append('<script src="{0}" type="text/javascript"></script>'.format(dependency))

            # Only process Style tags if the dependency has a ".css" extension and the output type is CSS or not specified
            elif CSS_EXTENSION in dependency and (self.output_type == CSS_OUTPUT_TYPE or self.output_type is None):
                style_tags.append('<link href="{0}" rel="stylesheet" />'.format(dependency))

        # Combine all tags
        tags = style_tags + script_tags
        tags_string = '\n'.join(tags)
        return tags_string
コード例 #9
0
ファイル: views.py プロジェクト: bysreg/m_play
def get_char_image(name, point):
	point = int(point)
	if point > 0:
		return static('gnovel/res/result/'+name+'_happy.png')
	elif point == 0:
		return static('gnovel/res/result/' +name+'_silhouette.png');
	else:
		return static('gnovel/res/result/'+name+'_sad.png')
コード例 #10
0
 def media(self):
     return forms.Media(
         js=[
             static('wagtailadmin/js/blocks/sequence.js'),
             static('wagtailadmin/js/blocks/list.js'),
             static('common/js/blocks/tabs.js')
         ]
     )
コード例 #11
0
ファイル: common.py プロジェクト: admin-pro/patchman
def yes_no_img(boolean, alt_yes='Active', alt_no='Not Active'):
    yes_icon = static('img/icon-yes.gif')
    no_icon = static('img/icon-no.gif')
    if boolean:
        html = '<img src="{0!s}" alt="{1!s}" />'.format(yes_icon, alt_yes)
    else:
        html = '<img src="{0!s}" alt="{1!s}" />'.format(no_icon, alt_no)
    return format_html(html)
コード例 #12
0
ファイル: common.py プロジェクト: admin-pro/patchman
def no_yes_img(boolean, alt_yes='Not Required', alt_no='Required'):
    yes_icon = static('img/icon-yes.gif')
    no_icon = static('img/icon-no.gif')
    if not boolean:
        html = '<img src="{0!s}" alt="{1!s}" />'.format(yes_icon, alt_yes)
    else:
        html = '<img src="{0!s}" alt="{1!s}" />'.format(no_icon, alt_no)
    return format_html(html)
コード例 #13
0
ファイル: rich_text.py プロジェクト: chrxr/wagtail
 def media(self):
     return Media(js=[
         static('wagtailadmin/js/vendor/hallo.js'),
         static('wagtailadmin/js/hallo-bootstrap.js'),
         static('wagtailadmin/js/hallo-plugins/hallo-wagtaillink.js'),
         static('wagtailadmin/js/hallo-plugins/hallo-hr.js'),
         static('wagtailadmin/js/hallo-plugins/hallo-requireparagraphs.js'),
     ])
コード例 #14
0
ファイル: wagtail_hooks.py プロジェクト: kapito/wagtail
def register_blockquote_feature(features):
    features.register_editor_plugin(
        'hallo', 'blockquote', HalloPlugin(
            name='halloblockquote',
            js=[static('testapp/js/hallo-blockquote.js')],
            css={'all': [static('testapp/css/hallo-blockquote.css')]},
        )
    )
コード例 #15
0
ファイル: views.py プロジェクト: borisshou/speaknow
def find_js_recorderWorker(request):
    if settings.DEBUG:  # local
        url = "http://" + request.get_host() + static("js/recorder/recorderWorker.js")
    else:  # deployed
        url = static("js/recorder/recorderWorker.js")  # will obtain an Amazon S3 storage address such as follows
        # url = 'https://speaknowapp.s3.amazonaws.com/static/js/recorder/recorderWorker.js?Signature=P%2Fz%2BpLnETvlyyf%2FJ9HtYRz0ljZA%3D&Expires=1448860345&AWSAccessKeyId=AKIAJVNNABYOMGHAVMJA'
    r = requests.get(url)
    return HttpResponse(r.text, content_type="application/javascript")
コード例 #16
0
def jquery_min():
    "Return the path to jquery.min.js"
    if VERSION >= (1, 9):
        url = static('admin/js/vendor/jquery/jquery.min.js')
    else:
        url = static('admin/js/jquery.min.js')

    return url
コード例 #17
0
ファイル: views.py プロジェクト: gazoon/python_labs
def vk_api(request):
    if request.method != 'POST' or not request.is_ajax():
        raise Http404()
    form = UserForm(request.POST)
    if form.is_valid():
        user_id = str(form.cleaned_data['id'])
        fields = ','.join(FIELDS_REQUEST)
        try:
            url = "https://api.vk.com/method/users.get?user_ids=%s&fields=%s" % (user_id, fields)
            content = requests.get(url).json()['response'][0]
            url = "https://api.vk.com/method/friends.get?uid=%s&fields=first_name,last_name&count=20" % \
                  user_id
            friends = requests.get(url).json()['response']
        except (AttributeError, KeyError):
            form.add_error('id', "User not found.")
            return JsonResponse(form.errors, status=409)

        sex = content.get('sex', 0)
        if sex == 1:
            content['sex'] = "Женский"
        elif sex == 2:
            content['sex'] = "Мужской"
        else:
            content['sex'] = "Неизвестно"
        counters = content.get('counters')

        def func(pair):
            key, name = pair
            value = content.get(key)
            if counters and not value:
                value = counters.get(key)
            value = value or "Неизвестно"
            return name, value

        info = list(map(func, visible_name.items()))

        context = {
            'info': info,
            'avatar': static('vk_api/img/default.jpeg'),
            'friends': friends,
        }
        try:
            photo_id = content['photo_id']
            url = "https://api.vk.com/method/photos.getById?photos=%s" % photo_id
            content = requests.get(url).json()['response'][0]
            photo_src = content['src_big']
        except (AttributeError, KeyError):
            return render(request, 'vk_api/profile.html', context)
        photo = requests.get(photo_src).content
        relative_path = 'vk_api/img/%s.jpeg' % photo_id
        path = os.path.join(settings.STATICFILES_DIRS[0], relative_path)
        with open(path, 'wb') as f:
            f.write(photo)
        context['avatar'] = static(relative_path)
        return render(request, 'vk_api/profile.html', context)

    return JsonResponse(form.errors, status=409)
コード例 #18
0
 def test_RedactorWidget_media(self):
     widget = RedactorWidget()
     js_url = static(widget.Media.js[0])
     css_url = static(widget.Media.css['all'][0])
     self.assertHTMLEqual(str(widget.media),
                          '<link href="%s" media="all" rel="stylesheet" '
                          'type="text/css" /><script src="%s" '
                          'type="text/javascript" />'
                          % (css_url, js_url))
コード例 #19
0
ファイル: blocks.py プロジェクト: praekelt/molo.surveys
 def media(self):
     media = super(SkipLogicStreamBlock, self).media
     media.add_js(
         [static('js/blocks/skiplogic_stream.js')]
     )
     media.add_css(
         {'all': [static('css/blocks/skiplogic.css')]}
     )
     return media
コード例 #20
0
ファイル: topology.py プロジェクト: mssumanth/Temp
def _create_ext_network_node(name):
    node = _create_empty_node()
    node.update({'id': name,
                 'image': static('muranodashboard/images/ext-net.png'),
                 'link_type': 'relation',
                 'info_box': _network_info(name, static(
                     'dashboard/img/lb-green.svg'))}
                )
    return node
コード例 #21
0
ファイル: neutron_tags.py プロジェクト: jgsogo/neutron
def flag_icon(language_code, size=24):
    try:
        id = language_code.split('-', 1)[1]
        return static('flags/flags_iso/{}/{}.png'.format(size, id.lower()))
    except IndexError as e:
        return static('flags/flags_iso/{}/{}.png'.format(size, language_code.lower()))
    except Exception as e:
        log.error("Flag for language_code {!r} not found.".format(language_code))
    return ""
コード例 #22
0
def avatar_url(user, size='thumbnail'):
    if not isinstance(user, User):
        return static('img/letsmeet_icon.png')

    up, created = UserProfile.objects.get_or_create(user=user)
    if not up.avatar:
        return static('img/letsmeet_icon.png')

    return static(getattr(up.avatar, size).url)
コード例 #23
0
ファイル: seqdisplay.py プロジェクト: graik/rotmic
def seqdisplay_libs():
    """benchling javascript import statement"""
    f1 = ST.static('d3.v3.min.js')
    f2 = ST.static('d3sequence.js')

    r = "<script src='%s' type='text/javascript' charset='utf-8'></script>\n"\
        % f1 
##    r = "<script src='http://d3js.org/d3.v3.min.js' charset='utf-8'></script>\n"
    r += "<script src='%s' type='text/javascript'></script>" % f2
    return r
コード例 #24
0
ファイル: rich_text.py プロジェクト: kapito/wagtail
    def media(self):
        media = Media(js=[
            static('wagtailadmin/js/vendor/hallo.js'),
            static('wagtailadmin/js/hallo-bootstrap.js'),
        ])

        for plugin in self.plugins:
            media += plugin.media

        return media
コード例 #25
0
    def test_application_logo_white(self):
        site = Site.objects.all()[0]

        site.domain = "example.com"
        site.save()
        assert ts.application_logo_white() == static('img/westlife-logo.png')

        site.domain = "pypeapp.com"
        site.save()
        assert ts.application_logo_white() == static("img/pype-white.png")
コード例 #26
0
ファイル: test_tags.py プロジェクト: larssos/django.js
 def test_jquery_js_migrate_unminified(self):
     '''Should include jQuery unminified library with migrate when DEBUG=True'''
     template = Template('''
         {% load js %}
         {% jquery_js migrate="true" %}
         ''')
     rendered = template.render(Context())
     jquery = static('js/libs/jquery-%s.js' % JQUERY_DEFAULT_VERSION)
     migrate = static('js/libs/jquery-migrate-%s.js' % JQUERY_MIGRATE_VERSION)
     self.assertIn('<script type="text/javascript" src="%s">' % jquery, rendered)
     self.assertIn('<script type="text/javascript" src="%s">' % migrate, rendered)
コード例 #27
0
ファイル: test_tags.py プロジェクト: cpdean/django.js
 def test_django_js(self):
     '''Should include and initialize django.js'''
     template = Template('''
         {% load js %}
         {% django_js %}
         ''')
     rendered = template.render(Context())
     jquery = static('js/libs/jquery-%s.min.js' % JQUERY_DEFAULT_VERSION)
     django_js = static('js/djangojs/django.js')
     self.failUnless('<script type="text/javascript" src="%s">' % jquery in rendered)
     self.failUnless('<script type="text/javascript" src="%s">' % django_js in rendered)
コード例 #28
0
ファイル: test_tags.py プロジェクト: cpdean/django.js
 def test_jquery_js_migrate(self):
     '''Should include jQuery library with migrate'''
     template = Template('''
         {% load js %}
         {% jquery_js migrate="true" %}
         ''')
     rendered = template.render(Context())
     jquery = static('js/libs/jquery-%s.min.js' % JQUERY_DEFAULT_VERSION)
     migrate = static('js/libs/jquery-migrate-%s.min.js' % JQUERY_MIGRATE_VERSION)
     self.failUnless('<script type="text/javascript" src="%s">' % jquery in rendered)
     self.failUnless('<script type="text/javascript" src="%s">' % migrate in rendered)
コード例 #29
0
ファイル: helppages.py プロジェクト: astrobin/astrobin
    def get_context_data(self, **kwargs):
        context = super(Help, self).get_context_data(**kwargs)

        prefix = 'rawdata/images/tour/%s' % (self.request.LANGUAGE_CODE\
            if 'LANGUAGE_CODE' in self.request\
            else 'en')
        context['screenshot_urls'] = [{
            'thumb': static('%s/thumbs/rawdata-tour-%02d.png' % (prefix, i)),
            'href': static('%s/rawdata-tour-%02d.png' % (prefix, i))
        } for i in range(1, 16)]

        return context
コード例 #30
0
ファイル: models.py プロジェクト: quantm/custom_django_oscar
    def get_avatar_src_full_url(self):
        ts = time.time()
        avatar_url = static('images/no_avatar.png')
        img_avatar = AVATAR_DIR + str(self.id) + '_avatar.png'
        avatar = static(AVATAR_URL + str(self.id) + '_avatar.png') + "?ts=" + str(ts)

        if isfile(img_avatar):
            avatar_url = avatar
        elif self.fb_id:
            avatar_url = 'https://graph.facebook.com/' + str(self.fb_id) + '/picture?width=200&height=200'

        return avatar_url
コード例 #31
0
ファイル: views.py プロジェクト: matthewlilley/web
def bounty_details(request,
                   ghuser='',
                   ghrepo='',
                   ghissue=0,
                   stdbounties_id=None):
    """Display the bounty details.

    Args:
        ghuser (str): The Github user. Defaults to an empty string.
        ghrepo (str): The Github repository. Defaults to an empty string.
        ghissue (int): The Github issue number. Defaults to: 0.

    Raises:
        Exception: The exception is raised for any exceptions in the main query block.

    Returns:
        django.template.response.TemplateResponse: The Bounty details template response.

    """
    is_user_authenticated = request.user.is_authenticated
    if is_user_authenticated and hasattr(request.user, 'profile'):
        _access_token = request.user.profile.get_access_token()
    else:
        _access_token = request.session.get('access_token')
    issue_url = 'https://github.com/' + ghuser + '/' + ghrepo + '/issues/' + ghissue if ghissue else request.GET.get(
        'url')

    # try the /pulls url if it doesnt exist in /issues
    try:
        assert Bounty.objects.current().filter(github_url=issue_url).exists()
    except Exception:
        issue_url = 'https://github.com/' + ghuser + '/' + ghrepo + '/pull/' + ghissue if ghissue else request.GET.get(
            'url')
        print(issue_url)

    params = {
        'issueURL': issue_url,
        'title': _('Issue Details'),
        'card_title': _('Funded Issue Details | Gitcoin'),
        'avatar_url': static('v2/images/helmet.png'),
        'active': 'bounty_details',
        'is_github_token_valid': is_github_token_valid(_access_token),
        'github_auth_url': get_auth_url(request.path),
        "newsletter_headline":
        _("Be the first to know about new funded issues."),
    }

    if issue_url:
        try:
            bounties = Bounty.objects.current().filter(github_url=issue_url)
            if stdbounties_id:
                bounties.filter(standard_bounties_id=stdbounties_id)
            if bounties:
                bounty = bounties.order_by('-pk').first()
                if bounties.count() > 1 and bounties.filter(
                        network='mainnet').count() > 1:
                    bounty = bounties.filter(
                        network='mainnet').order_by('-pk').first()
                # Currently its not finding anyting in the database
                if bounty.title and bounty.org_name:
                    params[
                        'card_title'] = f'{bounty.title} | {bounty.org_name} Funded Issue Detail | Gitcoin'
                    params['title'] = params['card_title']
                    params['card_desc'] = ellipses(
                        bounty.issue_description_text, 255)

                params['bounty_pk'] = bounty.pk
                params['network'] = bounty.network
                params['stdbounties_id'] = bounty.standard_bounties_id
                params[
                    'interested_profiles'] = bounty.interested.select_related(
                        'profile').all()
                params['avatar_url'] = bounty.get_avatar_url(True)
        except Bounty.DoesNotExist:
            pass
        except Exception as e:
            print(e)
            logging.error(e)

    return TemplateResponse(request, 'bounty_details.html', params)
コード例 #32
0
 def media(self):
     return forms.Media(js=[static('wagtailadmin/js/explorer-menu.js')])
コード例 #33
0
def global_admin_css():
    """
    Add some custom CSS for our patched/replaced forms.
    """
    return format_html('<link rel="stylesheet" href="{}">',
                       static('wagtail_patches/css/admin.css'))
コード例 #34
0
ファイル: forum_tags.py プロジェクト: tawanda/django-musette
def get_item_notification(notification):
    '''
        This filter return info about
        one notification of one user
    '''
    idobject = notification.idobject
    is_comment = notification.is_comment

    html = ""
    if is_comment:

        try:
            comment = Comment.objects.get(idcomment=idobject)
            forum = comment.topic.forum.name
            slug = comment.topic.slug
            idtopic = comment.topic.idtopic
            description = Truncator(comment.description).chars(100)
            username = comment.user.username

            url_topic = "/topic/" + forum + "/" + \
                slug + "/" + str(idtopic) + "/"

            title = "<h5><a href='"+url_topic+"'><u>" + \
                comment.topic.title+"</u></h5></a>"

            description = "<p>" + description + "</p>"

            # Get params for url profile
            try:
                params = ""
                params = get_params_url_profile(comment.user)
            except Exception:
                params = ""

            # Data profile
            profile = get_id_profile(comment.user.id)
            photo = get_photo_profile(profile)
            if photo:
                path_img = settings.MEDIA_URL + str(photo)
            else:
                path_img = static("img/profile.png")

            url_profile = URL_PROFILE

            if params:
                user = "******"+url_profile+params + \
                    "'><p>" + username + "</p></a>"
            else:
                user = "******" + username + "</a>"

            date = get_datetime_topic(notification.date)

            # Notificacion
            html += '<div class="list-group">'
            html += '   <div class="list-group-item">'
            html += '      <div class="row-action-primary">'
            html += '           <img src="'+path_img + \
                '" width=30 height=30 class="img-circle" />'
            html += '       </div>'
            html += '       <div class="row-content">'
            html += '           <div class="least-content">' + date + '</div>'
            html += '           <h4 class="list-group-item-heading">' + \
                title.encode('utf8')+'</h4>'
            html += '           <p class="list-group-item-text">' + \
                description.encode('utf8')+'</p>'
            html += '           <p>' + user.encode('utf8') + '</p>'
            html += '        </div>'
            html += '   </div>'
            html += '   <div class="list-group-separator"></div>'
            html += '</div>'

        except Comment.DoesNotExist:
            html = ""
    else:
        html = ""

    return html
コード例 #35
0
    def _issue_licence(self, request, application, issue_licence_form):
        # do credit card payment if required
        payment_status = payment_utils.PAYMENT_STATUSES.get(
            payment_utils.get_application_payment_status(application))

        if payment_status == payment_utils.PAYMENT_STATUS_AWAITING:
            raise PaymentException(
                'Payment is required before licence can be issued')
        elif payment_status == payment_utils.PAYMENT_STATUSES.get(
                payment_utils.PAYMENT_STATUS_CC_READY):
            payment_utils.invoke_credit_card_payment(application)

        licence = application.licence

        licence.issuer = request.user

        previous_licence = None
        if application.previous_application is not None:
            previous_licence = application.previous_application.licence
            licence.licence_number = previous_licence.licence_number

            # if licence is renewal, start with previous licence's sequence number
            if licence.licence_sequence == 0:
                licence.licence_sequence = previous_licence.licence_sequence

        if not licence.licence_number:
            licence.save(no_revision=True)
            licence.licence_number = '%s-%s' % (
                str(licence.licence_type.pk).zfill(LICENCE_TYPE_NUM_CHARS),
                str(licence.id).zfill(LICENCE_NUMBER_NUM_CHARS))

        # for re-issuing
        original_issue_date = application.licence.issue_date if application.licence.is_issued else None

        licence.licence_sequence += 1

        # reset renewal_sent flag in case of reissue
        licence.renewal_sent = False

        licence_filename = 'licence-%s-%d.pdf' % (licence.licence_number,
                                                  licence.licence_sequence)

        licence.licence_document = create_licence_pdf_document(
            licence_filename, licence, application, settings.WL_PDF_URL,
            original_issue_date)

        cover_letter_filename = 'cover-letter-%s-%d.pdf' % (
            licence.licence_number, licence.licence_sequence)

        licence.cover_letter_document = create_cover_letter_pdf_document(
            cover_letter_filename, licence,
            request.build_absolute_uri(reverse('home')))

        licence.save()

        if previous_licence is not None:
            previous_licence.replaced_by = licence
            previous_licence.save()

        licence_issued.send(sender=self.__class__, wildlife_licence=licence)

        # update statuses
        application.customer_status = 'approved'
        application.processing_status = 'issued'
        Assessment.objects.filter(application=application, status='awaiting_assessment').\
            update(status='assessment_expired')

        application.save()

        # The licence should be emailed to the customer if they applied for it online. If an officer entered
        # the application on their behalf, the licence needs to be posted to the user.

        # CC's and attachments
        # Rules for emails:
        #  If application lodged by proxy officer and there's a CC list: send email to CCs (to recipients = CCs)
        #  else send the email to customer and if there are CCs put them into the bccs of the email
        ccs = None
        if 'ccs' in issue_licence_form.cleaned_data and issue_licence_form.cleaned_data[
                'ccs']:
            ccs = re.split('[,;]', issue_licence_form.cleaned_data['ccs'])
        attachments = []
        if request.FILES and 'attachments' in request.FILES:
            for _file in request.FILES.getlist('attachments'):
                doc = Document.objects.create(file=_file, name=_file.name)
                attachments.append(doc)

        # check we have an email address to send to
        if licence.profile.email and not licence.profile.user.is_dummy_user:
            to = [licence.profile.email]
            messages.success(
                request,
                'The licence has now been issued and sent as an email attachment to the '
                'licencee: {}.'.format(licence.profile.email))
            send_licence_issued_email(licence,
                                      application,
                                      request,
                                      to=to,
                                      bcc=ccs,
                                      additional_attachments=attachments)
        else:
            # no email
            messages.success(
                request,
                'The licence has now been issued and must be posted to the licencee. Click '
                'this link to show the licence <a href="{0}" target="_blank">Licence PDF'
                '</a><img height="20px" src="{1}"></img> and this link to show the cover letter '
                '<a href="{2}" target="_blank">Cover Letter PDF</a><img height="20px" src="{3}">'
                '</img>'.format(licence.licence_document.file.url,
                                static('wl/img/pdf.png'),
                                licence.cover_letter_document.file.url,
                                static('wl/img/pdf.png')))
            if ccs:
                send_licence_issued_email(licence,
                                          application,
                                          request,
                                          to=ccs,
                                          additional_attachments=attachments)

        application.log_user_action(
            ApplicationUserAction.ACTION_ISSUE_LICENCE_.format(licence),
            request)
コード例 #36
0
ファイル: views.py プロジェクト: tompollard/physionet-build
def wfdbcal(request):
    return redirect(static('wfdbcal'))
コード例 #37
0
 def img_profile_url(self):
     if self.img_profile:
         return self.img_profile.url
     return static('images/blank_user.png')
コード例 #38
0
 def avatar_url(self):
     if self.avatar and hasattr(self.avatar, 'url'):
         return self.avatar.url
     else:
         return static('images/no-avatar.png')
コード例 #39
0
 def get_redirect_url(self, *args, **kwargs):
     return static('favicon/favicon.ico')
コード例 #40
0
ファイル: models.py プロジェクト: devunt/pyconkr-2018
    def get_image_url(self):
        if self.image:
            return self.image.url

        return static('image/anonymous.png')
コード例 #41
0
 def cover_url(self):
     if self.cover and hasattr(self.cover, 'url'):
         return self.cover.url
     else:
         return static('images/no-img.png')
コード例 #42
0
ファイル: models.py プロジェクト: joshua1988/cartmango-1
 def avatar_url(self):
     if self.avatar and hasattr(self.avatar, 'url'):
         return self.avatar.url
     else:
         return static('img/default-avatar.jpg')
コード例 #43
0
 def a_inner_html(link):
     return '<img class="link-icon" aria-hidden="true" src="{icon_url}" height="16" width="16"><span id="{link_id}_text">{link_name}</span>'.format(
         icon_url=static(link.icon),
         link_name=link.display_name,
         link_id=link.html_id)
コード例 #44
0
ファイル: views.py プロジェクト: matthewlilley/web
def toolbox(request):
    access_token = request.GET.get('token')
    if access_token and is_github_token_valid(access_token):
        helper_handle_access_token(request, access_token)

    tools = Tool.objects.prefetch_related('votes').all()

    actors = [{
        "title":
        _("Basics"),
        "description":
        _("Accelerate your dev workflow with Gitcoin\'s incentivization tools."
          ),
        "tools":
        tools.filter(category=Tool.CAT_BASIC)
    }, {
        "title": _("Advanced"),
        "description": _("Take your OSS game to the next level!"),
        "tools": tools.filter(category=Tool.CAT_ADVANCED)
    }, {
        "title":
        _("Community"),
        "description":
        _("Friendship, mentorship, and community are all part of the process."
          ),
        "tools":
        tools.filter(category=Tool.CAT_COMMUNITY)
    }, {
        "title":
        _("Tools to BUIDL Gitcoin"),
        "description":
        _("Gitcoin is built using Gitcoin.  Purdy cool, huh? "),
        "tools":
        tools.filter(category=Tool.CAT_BUILD)
    }, {
        "title":
        _("Tools in Alpha"),
        "description":
        _("These fresh new tools are looking for someone to test ride them!"),
        "tools":
        tools.filter(category=Tool.CAT_ALPHA)
    }, {
        "title":
        _("Tools Coming Soon"),
        "description":
        _("These tools will be ready soon.  They'll get here sooner if you help BUIDL them :)"
          ),
        "tools":
        tools.filter(category=Tool.CAT_COMING_SOON)
    }, {
        "title":
        _("Just for Fun"),
        "description":
        _("Some tools that the community built *just because* they should exist."
          ),
        "tools":
        tools.filter(category=Tool.CAT_FOR_FUN)
    }]

    # setup slug
    for key in range(0, len(actors)):
        actors[key]['slug'] = slugify(actors[key]['title'])

    profile_up_votes_tool_ids = ''
    profile_down_votes_tool_ids = ''
    profile_id = request.user.profile.pk if request.user.is_authenticated and hasattr(
        request.user, 'profile') else None

    if profile_id:
        ups = list(
            request.user.profile.votes.filter(value=1).values_list('tool',
                                                                   flat=True))
        profile_up_votes_tool_ids = ','.join(str(x) for x in ups)
        downs = list(
            request.user.profile.votes.filter(value=-1).values_list('tool',
                                                                    flat=True))
        profile_down_votes_tool_ids = ','.join(str(x) for x in downs)

    context = {
        "active":
        "tools",
        'title':
        _("Toolbox"),
        'card_title':
        _("Gitcoin Toolbox"),
        'avatar_url':
        static('v2/images/tools/api.jpg'),
        "card_desc":
        _("Accelerate your dev workflow with Gitcoin\'s incentivization tools."
          ),
        'actors':
        actors,
        'newsletter_headline':
        _("Don't Miss New Tools!"),
        'profile_up_votes_tool_ids':
        profile_up_votes_tool_ids,
        'profile_down_votes_tool_ids':
        profile_down_votes_tool_ids
    }
    return TemplateResponse(request, 'toolbox.html', context)
コード例 #45
0
def help(request):
    faq = {
        'Product': [
            {
                'q':
                _('I am a developer, I want build more Open Source Software. Where can I start?'
                  ),
                'a':
                _("The <a href=https://gitcoin.co/explorer>Funded Issue Explorer</a> contains a handful of issues that are ready to be paid out as soon as they are turned around. Check out the developer guide at <a href=https://gitcoin.co/help/dev>https://gitcoin.co/help/dev</a>."
                  )
            },
            {
                'q':
                _('I am a repo maintainer.  How do I get started?'),
                'a':
                _("The best way to get started is to post a funded issue on a task you need done.  Check out the repo maintainers guide at <a href=https://gitcoin.co/help/repo>https://gitcoin.co/help/repo</a>."
                  )
            },
            {
                'q':
                _('What tokens does Gitcoin support?'),
                'a':
                _("Gitcoin supports Ether and all ERC20 tokens.  If the token you'd like to use is Ethereum based, then Gitcoin supports it."
                  )
            },
            {
                'q':
                _('What kind of issues are fundable?'),
                'a':
                _("""

    <p class="c5"><span class="c4 c0">Gitcoin supports bug, feature, and security funded issues. &nbsp;Any issue that you need done is a good candidate for a funded issue, provided that:</span></p><ul class="c13 lst-kix_twl0y342ii52-0 start"><li class="c5 c11"><span class="c4 c0">It&rsquo;s open today.</span></li><li class="c5 c11"><span class="c4 c0">The repo README clearly enumerates how a new developer should get set up to contribute.</span></li><li class="c5 c11"><span class="c4 c0">The task is well defined.</span></li><li class="c5 c11"><span class="c4 c0">The end-state of the task is well defined.</span></li><li class="c5 c11"><span class="c4 c0">The pricing of the task reflects (market rate * complexity) of the task.</span></li><li class="c5 c11"><span class="c4 c0">The issue is on the roadmap, but does not block other work.</span></li></ul><p class="c5 c6"><span class="c4 c0"></span></p><p class="c5"><span class="c4 c0">To get started with funded issues today, it might be good to start small. &nbsp;Is there a small bug that needs fixed? &nbsp;An issue that&rsquo;s been open for a while that no one is tackling? &nbsp;An administrative task?</span></p>


            """)
            },
            {
                'q':
                _('Whats the difference between tips & funded issues?'),
                'a':
                _("""

<p>
<strong>A tip</strong> is a tool to send ether or any ethereum token to any github account.  The flow for tips looks like this:
</p><p>
> Send (party 1) => receive (party 2)
</p><p>

<strong>Funded Issues</strong> are a way to fund open source features, bugs, or security bounties.  The flow for funded issues looks like this:
</p><p>

>  Fund Issue (party 1) => claim funds  (party 2) => accept (party 1)
</p>


            """)
            },
            {
                'q':
                _('What kind of contributors are successful on the Gitcoin network?'
                  ),
                'a':
                _("""

<p>
If you have an issues board that needs triaged, read on..
</p>
<p>
If you would like to recruit engineers to help work on your repo, read on..
</p>
<p>
If you want to create value, and receive Ether tokens in return, read on..
</p>
<p>
If you are looking for a quick win, an easy buck, or to promote something, please turn around.
</p>

<p>
We value communication that is:
</p>

<ul>
<li>
    Collaborative
</li>
<li>
    Intellectual & Intellectually Honest
</li>
<li>
    Humble
</li>
<li>
    Empathetic
</li>
<li>
    Pragmatic
</li>
<li>
    Stress reducing
</li>
</ul>

<p>
Here are some of our values
</p>
<ul>
<li>
    Show, don't tell
</li>
<li>
    Give first
</li>
<li>
     Be thoughtful & direct
</li>
<li>
     Be credible
</li>
<li>
     Challenge the status quo and be willing to be challenged
</li>
<li>
     Create delightful experiences
</li>
</ul>


            """)
            },
            {
                'q':
                _('I received a notification about tip / funded issue, but I can\'t process it.  Help!'
                  ),
                'a':
                _("We'd love to help!  Please email <a href='mailto:[email protected]'>[email protected]</a> or join <a href=/slack>Gitcoin Community Slack</a>."
                  )
            },
            {
                'q':
                _('Am I allowed to place bounties on projects I don\'t contribute to or own?'
                  ),
                'a':
                _("TLDR: Yes you are.  But as OSS devs ourselves, our experience has been that if you want to get the product you work on merged into the upstream, you will need to work with the contributors or owners of that repo.  If not, you can always fork a repo and run your own roadmap."
                  )
            },
            {
                'q':
                _('I started work on a bounty but someone else has too.  Who gets it?'
                  ),
                'a':
                _("As a general rule, we tend to treat the person who 'started work' first as having precedence over the issue.  The parties involved are all welcome to work together to split the bounty or come to some other agreement, but if an agreement is uanble to be made, then the first person to start work will have first shot at the bounty."
                  )
            },
        ],
        'General': [
            {
                'q':
                _('Is Gitcoin open source?'),
                'a':
                _("Yes, all of Gitcoin's core software systems are open source and available at <a href=https://github.com/gitcoinco/>https://github.com/gitcoinco/</a>.  Please see the liscense.txt file in each repo for more details."
                  )
            },
            {
                'q':
                _('Is a token distribution event planned for Gitcoin?'),
                'a':
                _("""
<p>Gitcoin Core is considering doing a token distribution event (TDI), but at the time is focused first and foremost on providing value in Open Source Software&nbsp;in a lean way.</p>
<p>To find out more about a possible upcoming token distribution event,&nbsp;check out&nbsp;<a href="https://gitcoin.co/whitepaper">https://gitcoin.co/whitepaper</a></p>
<p>&nbsp;</p>            """)
            },
            {
                'q':
                _('What is the difference between Gitcoin and Gitcoin Core?'),
                'a':
                _("""
Gitcoin Core LLC is the legal entity that manages the software development of the Gitcoin Network (Gitcoin).

The Gitcoin Network is a series of smart contracts that helps Grow Open Source, but enabling developers to easily post and manage funded issues.            """
                  )
            },
            {
                'q':
                _('Who is the team at Gitcoin Core?'),
                'a':
                _("""
<p>The founder is <a href="https://linkedin.com/in/owocki">Kevin Owocki</a>, a technologist from the Boulder Colorado tech scene. &nbsp; &nbsp;Kevin&nbsp;has a BS in Computer Science, 15 years experience in Open Source Software and Technology Startups. He is a volunteer in the Boulder Community for several community organizations, and an avid open source developer. His work has been featured in&nbsp;<a href="http://techcrunch.com/2011/02/10/group-dating-startup-ignighter-raises-3-million/">TechCrunch</a>,&nbsp;<a href="http://www.cnn.com/2011/BUSINESS/03/29/india.online.matchmaking/">CNN</a>,&nbsp;<a href="http://www.inc.com/30under30/2011/profile-adam-sachs-kevin-owocki-and-dan-osit-founders-ignighter.html">Inc Magazine</a>,&nbsp;<a href="http://www.nytimes.com/2011/02/20/business/20ignite.html?_r=4&amp;amp;pagewanted=1&amp;amp;ref=business">The New York Times</a>,&nbsp;<a href="http://boingboing.net/2011/09/24/tosamend-turn-all-online-i-agree-buttons-into-negotiations.html">BoingBoing</a>,&nbsp;<a href="http://www.wired.com/2015/12/kevin-owocki-adblock-to-bitcoin/">WIRED</a>,&nbsp;<a href="https://www.forbes.com/sites/amycastor/2017/08/31/toothpick-takes-top-prize-in-silicon-beach-ethereum-hackathon/#6bf23b7452ad">Forbes</a>, and&nbsp;<a href="http://www.techdigest.tv/2007/08/super_mario_get_1.html">TechDigest</a>.</p>
<p><strong>Gitcoin</strong>&nbsp;was borne of the community in Boulder Colorado's thriving tech scene. One of the most amazing things about the Boulder community is the #givefirst mantra. The founding team has built their careers off of advice, mentorship, and relationships in the local tech community. &nbsp;</p>

<p>We are hiring.  If you want to join the team, <a href=mailto:[email protected]>email us</a>.

            """)
            },
            {
                'q':
                _('What is the mission of Gitcoin Core?'),
                'a':
                _("""
The mission of Gitcoin is "Grow Open Source".

            """)
            },
            {
                'q':
                _('How can I stay in touch with project updates?'),
                'a':
                _("""
The best way to stay in touch is to

<ul>
<li>
    <a href="/#mailchimp">Subscribe to the mailing list</a>
</li>
<li>
    <a href="/twitter">Follow the project on twitter</a>
</li>
<li>
    <a href="/slack">Join the slack channel</a>
</li>

</ul>

            """)
            },
        ],
        'Web3': [
            {
                'category':
                "Web3",
                'q':
                _('What is the difference between Gitcoin and centralized hiring websites?'
                  ),
                'a':
                gettext("""
<p>There are many successful centralized hiring resources available on the web. &nbsp;Because these platforms were an&nbsp;efficient way to source, select, and manage a global workforce , millions of dollars was&nbsp;processed through these systems every day.</p>
<p>Gitcoin takes the value that flows through these system, and makes it more efficient and fair. &nbsp;Gitcoin is a distributed network of smart contracts, based upon Ethereum, that aims to solve problems with centralized hiring resources, namely by</p>
<ul>
<li>being more open,</li>
<li>being more fair,</li>
<li>being more efficient,</li>
<li>being easier to use.</li>
<li>leveraging a global workforce,</li>
<li>cutting out the middlemen,</li>
</ul>
<p>When Sir Tim Berners-Lee first invented the World Wide Web in the late 1980s&nbsp;to make information sharing on the Internet easier, he did something very important. He specified an open protocol, the Hypertext Transfer Protocol or HTTP, that anyone could use to make information available and to access such information. &nbsp;</p>
<p>Gitcoin is similarly built on an open protocol of smart contracts.</p>
<p>By specifying a&nbsp;protocol, Tim Berners-Lee opened the way for anyone to build software, so-called web servers and browsers that would be compatible with this protocol. &nbsp; By specifying an open source protocol for Funding Issues and software development scoping &amp; payment, the Gitcoin Core team hopes to similarly inspire a generation of inventions in 21st century software.</p>
<p>
To learn more about blockchain, please checkout <a href="{}">this video about web3</a> or the <a href="https://github.com/gitcoinco/gitcoinco/issues?q=is%3Aissue+is%3Aopen+label%3Ahelp">Github Issues board</a>
</p>
            """).format(reverse('web3'))
            },
            {
                'q':
                _('Why do I need metamask?'),
                'a':
                gettext("""
<p>
You need <a href="https://metamask.io/">Metamask</a> in order to use Gitcoin.
</p>
<p>

Metamask turns google chrome into a Web3 Browser.   Web3 is powerful because it lets websites retrieve data from the blockchain, and lets users securely manage identity.
</p>
<p>

In contrast to web2 where third parties own your data, in web3 you own your data and you are always in control.  On web3, your data is secured on the blockchain, which means that no one can ever freeze your assets or censor you.
</p>
<p>

Download Metamask <a href="https://metamask.io/">here</a> today.
</p>
<p>
To learn more about Metamask, please checkout <a href="{}">this video about web3</a> or the <a href="https://github.com/gitcoinco/gitcoinco/issues?q=is%3Aissue+is%3Aopen+label%3Ahelp">Github Issues board</a>
</p>

           """).format(reverse('web3'))
            },
            {
                'q':
                _('Why do I need to pay gas?'),
                'a':
                _("""
<p>
"Gas" is the name for a special unit used in Ethereum. It measures how much "work" an action or set of actions takes to perform (for example, storing data in a smart contract).
</p>
<p>
The reason gas is important is that it helps to ensure an appropriate fee is being paid by transactions submitted to the network. By requiring that a transaction pay for each operation it performs (or causes a contract to perform), we ensure that network doesn't become bogged down with performing a lot of intensive work that isn't valuable to anyone.
</p>
<p>
Gas fees are paid to the maintainers of the Ethereum network, in return for securing all of the Ether and Ethereum-based transactions in the world.  Gas fees are not paid to Gitcoin Core directly or indirectly.
</p>
<p>
To learn more about gas, pleaes checkout the <a href="https://github.com/gitcoinco/gitcoinco/issues?q=is%3Aissue+is%3Aopen+label%3Ahelp">Github Issues board</a>
</p>
           """)
            },
            {
                'q':
                _('What are the advanages of Ethereum based applications?'),
                'a':
                gettext("""
Here are some of the advantages of Ethereum based applications:
<ul>
<li>
    Lower (or no) fees
</li>
<li>
    No middlemen
</li>
<li>
    No third party owns or can sell your data
</li>
<li>
    No international conversion fees
</li>
<li>
    Get paid in protocol, utility, or application tokens; not just cash.
</li>
</ul>
<p>
To learn more about Ethereum based apps, please checkout <a href="{}">this video about web3</a> or the <a href="https://github.com/gitcoinco/gitcoinco/issues?q=is%3Aissue+is%3Aopen+label%3Ahelp">Github Issues board</a>
</p>


           """).format(reverse('web3'))
            },
            {
                'q':
                _('I still dont get it.  Help!'),
                'a':
                _("""
We want to nerd out with you a little bit more.  <a href="/slack">Join the Gitcoin Slack Community</a> and let's talk.


""")
            },
        ],
    }

    tutorials = [{
        'img':
        static('v2/images/help/firehose.jpg'),
        'url':
        'https://medium.com/gitcoin/tutorial-leverage-gitcoins-firehose-of-talent-to-do-more-faster-dcd39650fc5',
        'title':
        _('Leverage Gitcoin’s Firehose of Talent to Do More Faster'),
    }, {
        'img': static('v2/images/help/tools.png'),
        'url':
        'https://medium.com/gitcoin/tutorial-post-a-bounty-in-90-seconds-a7d1a8353f75',
        'title': _('Post a Bounty in 90 Seconds'),
    }]

    context = {
        'active': 'help',
        'title': _('Help'),
        'faq': faq,
        'tutorials': tutorials,
    }
    return TemplateResponse(request, 'help.html', context)
コード例 #46
0
 def thumbnail_url(self):
     if self.thumbnail and hasattr(self.thumbnail, 'url'):
         return self.thumbnail.url
     else:
         return static('img/no-product-image.png')
コード例 #47
0
def render_d3_data(request, environment):
    if not (environment and environment.services):
        return None

    ext_net_name = None
    d3_data = {"nodes": [], "environment": {}}

    in_progress, status_message = _get_environment_status_message(environment)
    environment_node = _create_empty_node()
    environment_node.update({
        'id':
        environment.id,
        'name':
        environment.name,
        'status':
        status_message,
        'image':
        static('dashboard/img/stack-green.svg'),
        'in_progress':
        in_progress,
        'info_box':
        _environment_info(environment, status_message)
    })
    d3_data['environment'] = environment_node

    unit_image_active = static('dashboard/img/server-green.svg')
    unit_image_non_active = static('dashboard/img/server-gray.svg')

    node_refs = {}

    def get_image(fqdn, node_data):
        if fqdn.startswith('io.murano.resources'):
            if len(node_data.get('ipAddresses', [])) > 0:
                image = unit_image_active
            else:
                image = unit_image_non_active
        else:
            image = get_app_image(request, fqdn)
        return image

    def rec(node_data, node_key, parent_node=None):
        if not isinstance(node_data, dict):
            return
        node_type = node_data.get('?', {}).get('type')
        node_id = node_data.get('?', {}).get('id')
        atomics, containers = _split_seq_by_predicate(node_data.iteritems(),
                                                      _is_atomic)
        if node_type and node_data is not parent_node:
            node = _create_empty_node()
            node_refs[node_id] = node
            atomics.extend([('id', node_data['?']['id']), ('type', node_type),
                            ('name', node_data.get('name', node_key))])

            image = get_image(node_type, node_data)
            node.update({
                'id': node_id,
                'info_box': _unit_info(atomics, image),
                'image': image,
                'link_type': 'unit',
                'in_progress': in_progress
            })
            d3_data['nodes'].append(node)

        for key, value in containers:
            if key == '?':
                continue
            if isinstance(value, dict):
                rec(value, key, node_data)
            elif isinstance(value, list):
                for index, val in enumerate(value):
                    rec(val, '{0}[{1}]'.format(key, index), node_data)

    def build_links_rec(node_data, parent_node=None):
        if not isinstance(node_data, dict):
            return
        node_id = node_data.get('?', {}).get('id')
        if not node_id:
            return
        node = node_refs[node_id]

        atomics, containers = _split_seq_by_predicate(node_data.iteritems(),
                                                      _is_atomic)

        # the actual second pass of node linking
        if parent_node is not None:
            node['required_by'].append(parent_node['?']['id'])
            node['link_type'] = 'aggregation'

        for key, value in atomics:
            if value in node_refs:
                remote_node = node_refs[value]
                if node_id not in remote_node['required_by']:
                    remote_node['required_by'].append(node_id)
                    remote_node['link_type'] = 'reference'

        for key, value in containers:
            if key == '?':
                continue
            if isinstance(value, dict):
                build_links_rec(value, node_data)
            elif isinstance(value, list):
                for val in value:
                    build_links_rec(val, node_data)

    for service in environment.services:
        in_progress, status_message = _get_environment_status_message(service)
        required_by = None
        if 'instance' in service and service['instance'] is not None:
            if service['instance'].get('assignFloatingIp', False):
                if ext_net_name:
                    required_by = ext_net_name
                else:
                    ext_net_name = 'External_Network'
                    ext_network_node = _create_ext_network_node(ext_net_name)
                    d3_data['nodes'].append(ext_network_node)
                    required_by = ext_net_name

        service_node = _create_empty_node()
        service_image = get_app_image(request, service['?']['type'],
                                      service['?']['status'])
        node_id = service['?']['id']
        node_refs[node_id] = service_node
        service_node.update({
            'name':
            service.get('name', ''),
            'status':
            status_message,
            'image':
            service_image,
            'id':
            node_id,
            'link_type':
            'relation',
            'in_progress':
            in_progress,
            'info_box':
            _application_info(service, service_image, status_message)
        })
        if required_by:
            service_node['required_by'].append(required_by)
        d3_data['nodes'].append(service_node)
        rec(service, None, service)

    for service in environment.services:
        build_links_rec(service)

    return json.dumps(d3_data)
コード例 #48
0
ファイル: user_profile.py プロジェクト: joyfulflyer/playacamp
 def profile_pic_url(self) -> str:
     if self.profile_picture:
         assert settings.AWS_STORAGE_BUCKET_NAME
         return self.profile_picture.url
     return static('default-profile-pic.png')
コード例 #49
0
import random
import string
from django.utils.text import slugify
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.conf import settings
from django.conf.urls.static import static

no_property_img_url = static("static/images/no_image.png")


def random_string_generator(size=10,
                            chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def unique_slug_generator(instance, new_slug=None):
    """
    random_string_generator is located here:
    http://joincfe.com/blog/random-string-generator-in-python/

    This is for a Django project and it assumes your instance 
    has a model with a slug field and a title character (char) field.
    """
    if new_slug is not None:
        slug = new_slug
    else:
        slug = slugify(instance.title)

    target_class = instance.__class__
    qs_exists = target_class.objects.filter(slug=slug).exists()
    if qs_exists:
コード例 #50
0
 def media(self):
     return forms.Media(js=[static('wagtailadmin/js/blocks/struct.js')])
コード例 #51
0
ファイル: views.py プロジェクト: YoussefRamadan98/Tailored
def user_profile(request):
	"""This view shows the profile of the authenticated user."""
	user = User.objects.get(username = request.user)
	user_profile = get_object_or_404(UserProfile, user = user)

	context_dict = {}
	search_form = Search_bar()
	context_dict['search_bar'] = search_form
	context_dict['user_profile'] = user_profile
	context_dict['user_rating'] = range(int(round(user_profile.rating, 0)))
	
	reviews_user = Review.objects.filter(Q(item__in = Item.objects.filter(seller = user_profile)))
	context_dict['reviews_user'] = reviews_user.order_by('-datePosted')

	user_items = Item.objects.filter(seller = user_profile, sold_to = None)
	context_dict['user_items'] = user_items
	
	item_form = ItemForm()
	user_form = EditUserProfileForm()

	if request.method == "POST":
		item_form = ItemForm(request.POST, request.FILES)
		user_form = EditUserProfileForm(request.POST, request.FILES)
		
		if item_form.is_valid():
			item = item_form.save(commit = False)

			if not item_form.cleaned_data['picture']:
				# Handle when the user does not upload an image for the item
				image = Image.open(path.dirname(path.dirname(path.abspath(__file__))) + static('images/item.png'))
				output = BytesIO()
				image.save(output, 'PNG', quality = 100)
				output.seek(0)
				
				file_system = FileSystemStorage(settings.MEDIA_ROOT + '/item_images/')
				filename = file_system.save('item.png', output)
				file_url = file_system.url(filename)

				item.picture = file_url.replace('/media', 'item_images', 1)
			else:
				item.picture = item_form.cleaned_data['picture']

			item.seller = user_profile
			item.save()

			context_dict['user_form'] = user_form
			return HttpResponseRedirect(reverse('tailored:index'))

		elif user_form.is_valid():
			if user_form.has_changed():
				user_form_keys = list(user_form.cleaned_data.keys())
				
				for key in user_form_keys[:2]:
					if user_form.cleaned_data[key] and user.__dict__[key] != user_form.cleaned_data[key]:
						user.__dict__[key] = user_form.cleaned_data[key]
				user.save()

				for key in user_form_keys[2:]:
					if user_form.cleaned_data[key] and user_profile.__dict__[key] != user_form.cleaned_data[key]:
						user_profile.__dict__[key] = user_form.cleaned_data[key]
				user_profile.save()

				context_dict['item_form'] = item_form
				return HttpResponseRedirect(reverse('tailored:index'))
			else:
				keys = list(user_form.cleaned_data.keys())
				
				for key in keys:
					user_form.add_error(key, forms.ValidationError("You need to fill at least one field."))
				
				context_dict['item_form'] = item_form
				context_dict['user_form'] = user_form
				return render(request, 'tailored/user_profile.html', context_dict)

	context_dict['item_form'] = item_form
	context_dict['user_form'] = user_form
	return render(request, "tailored/user_profile.html", context_dict)
コード例 #52
0
from django import template
from django.template.defaultfilters import stringfilter
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import format_html, format_html_join

from os.path import join as pjoin

from django.utils.safestring import mark_safe

from ..settings import Settings
from ..widgets import FontAwesomeIcon, Label

register = template.Library()

_bootstrap_url_base = Settings.get('STATIC.BOOTSTRAP_URL_BASE', None)
bootstrap_url_base = _bootstrap_url_base if _bootstrap_url_base else static(
    'bootstrap')
_fontawesome_url_base = Settings.get('STATIC.FONTAWESOME_URL_BASE', None)
fontawesome_url_base = _fontawesome_url_base if _fontawesome_url_base else static(
    'Font-Awesome')
_ionicons_url_base = Settings.get('STATIC.IONICONS_URL_BASE', None)
ionicons_url_base = _ionicons_url_base if _ionicons_url_base else static(
    'ionicons')
_adminlte_url_base = Settings.get('STATIC.ADMINLTE_URL_BASE', None)
adminlte_url_base = _adminlte_url_base if _adminlte_url_base else static(
    'AdminLTE')
_jquery_url = Settings.get('STATIC.JQUERY_URL', None)
jquery_url = _jquery_url if _jquery_url else static(
    'AdminLTE/plugins/jQuery/jQuery-2.1.4.min.js')


@register.simple_tag
コード例 #53
0
 def icon_src(self, instance):
     return static("images/icons/bookmark_32x32.png")
コード例 #54
0
ファイル: aert_base_tags.py プロジェクト: aert/aert-farmerp
 def render(self, context):
     path = "themes/" + current_theme() + "/" + self.static_url
     return static(path)
コード例 #55
0
def contributor_landing(request):
    slides = [
        ("Daniel", static("v2/images/testimonials/gitcoiners/daniel.jpeg"),
         _("When I found Gitcoin I was gladly surprised that it took one thing and did it well. \
         It took the Ethereum tech and used it as a bridge to technology with open source Jobs.  \
         Even though Gitcoin is still in it’s early stages, I think it’s filled with potential to grow."
           ), 'https://github.com/dmerrill6'),
        ("CryptoMental",
         static("v2/images/testimonials/gitcoiners/cryptomental.png"),
         _(" think the great thing about GitCoin is how easy it is for projects to reach out to worldwide talent. \
         GitCoin helps to find people who have time to contribute and increase speed of project development. \
         Thanks to GitCoin a bunch of interesting OpenSource projects got my attention!"
           ), 'https://github.com/cryptomental'),
        ("Elan", static("v2/images/testimonials/gitcoiners/elan.jpeg"),
         _("The bounty process with Gitcoin is pretty amazing.  Just go on the website, find an issue you can \
         work on, you claim it.  All you do then is submit your code to Github, get the code merged.  \
         Once it’s merged, the smart contract kicks in and sends the money to your Ethereum account.  \
         The whole process is pretty smooth.  There’s a giant slack community.  It puts the freelance \
         market back in the hands of the community!"),
         "https://github.com/elaniobro"),
        ("Jack", static("v2/images/testimonials/gitcoiners/jack.jpeg"),
         _("I really like Gitcoin because it’s allowed me to get involved in some really interesting \
         Open Source Projects.  I’ve written code for MyEtherWallet and Gitcoin itself.  \
         I think Gitcoin is becoming a great asset for the Ethereum ecosystem."
           ), 'https://github.com/jclancy93'),
        ("Miguel Angel Rodriguez Bermudez",
         static("v2/images/testimonials/gitcoiners/miguel.jpeg"),
         _("I came across Gitcoin 3 months ago.  I was hearing lots of ideas about projects involving \
         cryptocurrencies, and I kept thinking \"what about open source projects?\".  I see Gitcoin as \
         the next level of freelance, where you can not only help repos on Github, but get money out of \
         it.  It is that simple and it works."), 'https://github.com/marbrb'),
        ("Octavio Amuchástegui",
         static("v2/images/testimonials/gitcoiners/octavioamu.jpeg"),
         _("I'm in love with Gitcoin. It isn't only a platform, it's a community that gives me the \
         opportunity to open my network and work with amazing top technology projects and earn some \
         money in a way I'm visible to the dev community and work opportunities. Open source is amazing, \
         and is even better to make a living from it, I think is the future of development."
           ), 'https://github.com/octavioamu')
    ]

    gitcoin_description = _(
        "A community for developers to collaborate and monetize their skills while working \
        on Open Source projects through bounties.")

    projects = [{
        'name': 'Augur Logo',
        'source': 'v2/images/project_logos/augur.png'
    }, {
        'name': 'Bounties Logo',
        'source': 'v2/images/project_logos/bounties.png'
    }, {
        'name': 'Balance Logo',
        'source': 'v2/images/project_logos/balance.png'
    }, {
        'name': 'Metamask Logo',
        'source': 'v2/images/project_logos/metamask.png'
    }, {
        'name': 'uPort Logo',
        'source': 'v2/images/project_logos/uport.png'
    }, {
        'name': 'Market Protocol Logo',
        'source': 'v2/images/project_logos/market.png'
    }, {
        'name': 'Trust Wallet Logo',
        'source': 'v2/images/project_logos/trust.png'
    }, {
        'name': 'MCrypto Logo',
        'source': 'v2/images/project_logos/mycrypto.png'
    }, {
        'name': 'Truffle Logo',
        'source': 'v2/images/project_logos/truffle.png'
    }, {
        'name': 'Solidity Logo',
        'source': 'v2/images/project_logos/solidity.png'
    }, {
        'name': 'Casper Logo',
        'source': 'v2/images/project_logos/casper.png'
    }, {
        'name': 'Wyvern Logo',
        'source': 'v2/images/project_logos/wyvern.png'
    }, {
        'name': 'Ethereum Logo',
        'source': 'v2/images/project_logos/eth.png'
    }, {
        'name': 'Livepeer Logo',
        'source': 'v2/images/project_logos/livepeer.png'
    }, {
        'name': 'Raiden Logo',
        'source': 'v2/images/project_logos/raiden.png'
    }, {
        'name': 'Databroker Logo',
        'source': 'v2/images/project_logos/databroker.png'
    }]

    available_bounties_count = open_bounties().count()
    available_bounties_worth = amount_usdt_open_work()

    context = {
        'slides': slides,
        'slideDurationInMs': 6000,
        'active': 'home',
        'projects': projects,
        'gitcoin_description': gitcoin_description,
        'available_bounties_count': available_bounties_count,
        'available_bounties_worth': available_bounties_worth
    }

    return TemplateResponse(request, 'contributor_landing.html', context)
コード例 #56
0
def canonical_static(path):
    return canonical_link(static(path))
コード例 #57
0
ファイル: models.py プロジェクト: jacqui/squarelet
class User(AvatarMixin, AbstractBaseUser, PermissionsMixin):
    """User model for squarelet

    This is a general user model which should only store information applicable
    to all of the different services which will be authenticating against
    squarelet

    Attributes:
        # AbstractBaseUser
        password (CharField): the hashed password
        last_login (DateTimeField): date time of last login

        # PermissionsMixin
        is_superuser (BooleanField): designates this user as having all permissions
        groups (ManyToManyField): groups the user are in - they will receive
            permissions from their groups
        user_permissions (ManyToManyField): permissions for this user
    """

    individual_organization = models.OneToOneField(
        verbose_name=_("individual organization"),
        to="organizations.Organization",
        on_delete=models.PROTECT,
        editable=False,
        to_field="uuid",
        help_text=_(
            "This is both the UUID for the user, as well as a foreign key to the "
            "corresponding individual organization, which has the same UUID. "
            "This is used to uniquely identify the user across services."),
    )
    name = models.CharField(_("name of user"),
                            max_length=255,
                            help_text=_("The user's full name"))
    email = CIEmailField(_("email"),
                         unique=True,
                         null=True,
                         help_text=_("The user's email address"))
    username = CICharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, digits and ./-/_ only.  "
            "May only be changed once."),
        validators=[UsernameValidator()],
        error_messages={
            "unqiue": _("A user with that username already exists.")
        },
    )
    avatar = ImageField(
        _("avatar"),
        upload_to=user_file_path,
        blank=True,
        max_length=255,
        help_text=_("An image to represent the user"),
    )
    can_change_username = models.BooleanField(
        _("can change username"),
        default=True,
        help_text=_(
            "Keeps track of whether or not the user has used their one "
            "username change"),
    )
    is_staff = models.BooleanField(
        _("staff status"),
        default=False,
        help_text=_(
            "Designates whether the user can log into this admin site."),
    )
    is_active = models.BooleanField(
        _("active"),
        default=True,
        help_text=_(
            "Designates whether this user should be treated as active. "
            "Unselect this instead of deleting accounts."),
    )
    is_agency = models.BooleanField(
        _("agency user"),
        default=False,
        help_text=
        _("This is an account used for allowing agencies to log in to the site"
          ),
    )
    source = models.CharField(
        _("source"),
        max_length=11,
        choices=(
            ("muckrock", _("MuckRock")),
            ("documentcloud", _("DocumentCloud")),
            ("foiamachine", _("FOIA Machine")),
            ("quackbot", _("QuackBot")),
            ("squarelet", _("Squarelet")),
        ),
        default="squarelet",
        help_text=_("Which service did this user originally sign up for?"),
    )
    email_failed = models.BooleanField(
        _("email failed"),
        default=False,
        help_text=_(
            "Has an email we sent to this user's email address failed?"),
    )

    created_at = AutoCreatedField(_("created at"),
                                  help_text=_("When this user was created"))
    updated_at = AutoLastModifiedField(
        _("updated at"), help_text=_("When this user was last updated"))

    # preferences
    use_autologin = models.BooleanField(
        _("use autologin"),
        default=True,
        help_text=("Links you receive in emails from us will contain"
                   " a token to automatically log you in"),
    )

    USERNAME_FIELD = "username"
    EMAIL_FIELD = "email"
    REQUIRED_FIELDS = ["email"]

    default_avatar = static("images/avatars/profile.png")

    objects = UserManager()

    def __str__(self):
        return self.username

    @property
    def uuid(self):
        """The UUID is the value of the foreign key to the individual organization"""
        return self.individual_organization_id

    @property
    def date_joined(self):
        """Alias date joined to create_at for third party apps"""
        return self.created_at

    def save(self, *args, **kwargs):
        with transaction.atomic():
            super().save(*args, **kwargs)
            transaction.on_commit(
                lambda: send_cache_invalidations("user", self.uuid))

    def get_absolute_url(self):
        return reverse("users:detail", kwargs={"username": self.username})

    def get_full_name(self):
        return self.name

    def safe_name(self):
        if self.name:
            return self.name
        return self.username

    @mproperty
    def primary_email(self):
        """A user's primary email object"""
        return self.emailaddress_set.filter(primary=True).first()

    def wrap_url(self, url, **extra):
        """Wrap a URL for autologin"""
        if self.use_autologin:
            extra.update(sesame.utils.get_parameters(self))

        return "{}?{}".format(url, urlencode(extra))
コード例 #58
0
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.urls import reverse
from django.utils.translation import get_language

from .gateway import settings as misago_settings  # noqa
from .gateway import db_settings

BLANK_AVATAR_URL = static(misago_settings.MISAGO_BLANK_AVATAR)


def settings(request):
    return {
        'DEBUG': misago_settings.DEBUG,
        'LANGUAGE_CODE_SHORT': get_language()[:2],
        'misago_settings': db_settings,
        'BLANK_AVATAR_URL': BLANK_AVATAR_URL,
        'THREADS_ON_INDEX': misago_settings.MISAGO_THREADS_ON_INDEX,
        'USERS_ON_INDEX': misago_settings.MISAGO_USERS_ON_INDEX,
        'LOGIN_REDIRECT_URL': misago_settings.LOGIN_REDIRECT_URL,
        'LOGIN_URL': misago_settings.LOGIN_URL,
        'LOGOUT_URL': misago_settings.LOGOUT_URL,
    }


def preload_settings_json(request):
    preloaded_settings = db_settings.get_public_settings()

    preloaded_settings.update({
        'LOGIN_API_URL':
        misago_settings.MISAGO_LOGIN_API_URL,
        'LOGIN_REDIRECT_URL':
コード例 #59
0
 def get_image(self):
     if self.image and self.image.url and len(self.image.url) > 0:
         return self.image.url
     else:
         return static('uploads/robot.png')
コード例 #60
0
ファイル: wagtail_hooks.py プロジェクト: zed2015/wagtail
 def media(self):
     return forms.Media(js=[static('testapp/js/kittens.js')])