index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
34,880
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/urls.py
|
from django.conf import settings
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import RedirectView
from django.views.defaults import page_not_found
from .views import CodeList, CodeDetail, CodeSuggestRepo
from source.base.feeds import CodeFeed
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60*15)
FEED_CACHE_TIME = getattr(settings, 'FEED_CACHE_SECONDS', 60*60)
urlpatterns = [
url(
regex = '^$',
view = cache_page(STANDARD_CACHE_TIME)(CodeList.as_view()),
kwargs = {},
name = 'code_list',
),
url(
regex = '^suggest/$',
view = CodeSuggestRepo.as_view(),
kwargs = {},
name = 'code_suggest_repo',
),
url(
regex = '^rss/$',
view = cache_page(FEED_CACHE_TIME)(CodeFeed()),
kwargs = {},
name = 'code_list_feed',
),
url(
regex = '^json/$',
view = cache_page(FEED_CACHE_TIME)(CodeList.as_view()),
kwargs = {'render_json': True},
name = 'code_list_feed_json',
),
url(
regex = '^tags/(?P<tag_slugs>[-\w\+]+)/$',
view = cache_page(STANDARD_CACHE_TIME)(CodeList.as_view()),
kwargs = {},
name = 'code_list_by_tag',
),
url(
regex = '^tags/([-\w\+]+)/rss/$',
#regex = '^tags/(?P<tag_slugs>[-\w\+]+)/rss/$',
view = page_not_found,
#view = cache_page(FEED_CACHE_TIME)(CodeFeed()),
kwargs = {},
name = 'code_list_by_tag_feed',
),
url(
regex = '^tags/([-\w\+]+)/json/$',
#regex = '^tags/(?P<tag_slugs>[-\w\+]+)/json/$',
view = page_not_found,
#view = cache_page(FEED_CACHE_TIME)(CodeList.as_view()),
kwargs = {},
#kwargs = {'render_json': True},
name = 'code_list_by_tag_feed_json',
),
url(
regex = '^tags/$',
view = RedirectView.as_view(),
kwargs = {'url': '/code/'},
name = 'code_list_tags',
),
url(
regex = '^(?P<slug>[-\w]+)/$',
view = cache_page(STANDARD_CACHE_TIME)(CodeDetail.as_view()),
kwargs = {},
name = 'code_detail',
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,881
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/management/commands/migrate_org_admins.py
|
from django.core.management.base import BaseCommand
from source.people.models import Organization, OrganizationAdmin
class Command(BaseCommand):
help = "One-time command to migrate org admin emails to new OrganizationAdmin model"
def handle(self, *args, **options):
org_set = Organization.objects.all()
for org in org_set:
print("\nMigrating " + org.name)
if org.email:
obj, created = OrganizationAdmin.objects.get_or_create(organization=org, email=org.email)
else:
print("No email for this org")
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,882
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/migrations/0004_auto_20170117_1904.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-17 19:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('code', '0003_auto_20161213_1755'),
]
operations = [
migrations.AlterField(
model_name='code',
name='demo_site',
field=models.URLField(blank=True, verbose_name='Demo site URL'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,883
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/migrations/0003_organizationadmin.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-17 19:04
from __future__ import unicode_literals
import caching.base
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('people', '0002_person_photo'),
]
operations = [
migrations.CreateModel(
name='OrganizationAdmin',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('email', models.EmailField(max_length=254, unique=True, verbose_name='Email address')),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='people.Organization')),
],
options={
'ordering': ('organization', 'email'),
'verbose_name': 'Organization Admin',
},
bases=(caching.base.CachingMixin, models.Model),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,884
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/guides/forms.py
|
from django import forms
class SuggestGuideForm(forms.Form):
guide_submitter_name = forms.CharField(label='Name', max_length=128, required=True)
guide_submitter_email = forms.EmailField(label='Email', required=True)
guide_description = forms.CharField(widget=forms.Textarea(attrs={'rows': 10, 'cols': 30}), required=True)
guide_purpose = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 30}), required=False)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,885
|
OpenNews/opennews-source
|
refs/heads/master
|
/config/settings/production.py
|
# -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
'''
from __future__ import absolute_import, unicode_literals
import os
import json
from urllib.parse import urlparse
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
SECRET_KEY = env("DJANGO_SECRET_KEY")
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# django-secure
# ------------------------------------------------------------------------------
INSTALLED_APPS += ("djangosecure", )
SECURITY_MIDDLEWARE = (
'djangosecure.middleware.SecurityMiddleware',
)
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['source.opennews.org'])
INSTALLED_APPS += ("gunicorn", )
BASE_SITE_URL = 'https://source.opennews.org'
# STORAGE CONFIGURATION
# ------------------------------------------------------------------------------
# Uploaded Media Files
# ------------------------
# NOTE: AWS keys set in common.py
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
# TODO See: https://github.com/jschneier/django-storages/issues/47
# Revert the following and use str after the above-mentioned bug is fixed in
# either django-storage-redux or boto
AWS_HEADERS = {
'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY))
}
# Static Assets
# ------------------------
#STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# EMAIL
# ------------------------------------------------------------------------------
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_HOST_USER = env("MAILGUN_SMTP_LOGIN")
EMAIL_HOST_PASSWORD = env("MAILGUN_SMTP_PASSWORD")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[Source] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# SEARCH
# ------------------------------------------------------------------------------
ES_URL = urlparse(os.environ.get('BONSAI_URL') or 'http://127.0.0.1:9200/')
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': ES_URL.scheme + '://' + ES_URL.hostname + ':443',
'INDEX_NAME': 'haystack',
},
}
if ES_URL.username:
HAYSTACK_CONNECTIONS['default']['KWARGS'] = {"http_auth": ES_URL.username + ':' + ES_URL.password}
# CACHING
# ------------------------------------------------------------------------------
CACHES = {
'default': {
'BACKEND': 'django_bmemcached.memcached.BMemcached',
'LOCATION': os.environ.get('MEMCACHEDCLOUD_SERVERS').split(','),
'OPTIONS': {
'username': os.environ.get('MEMCACHEDCLOUD_USERNAME'),
'password': os.environ.get('MEMCACHEDCLOUD_PASSWORD'),
}
}
}
BASE_URL = env('BASE_URL', default='')
# LOGGING CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'mail_admins'],
'propagate': True
}
}
}
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,886
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/urls.py
|
from django.conf import settings
from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.views.decorators.cache import cache_page
from django.views.generic.base import RedirectView
from django.views.defaults import page_not_found
from .views import ArticleList, ArticleDetail, ArticleSuggestArticle
from source.base.feeds import ArticleFeed
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60*15)
FEED_CACHE_TIME = getattr(settings, 'FEED_CACHE_SECONDS', 60*60)
urlpatterns = [
url(
regex = '^$',
view = cache_page(STANDARD_CACHE_TIME)(ArticleList.as_view()),
kwargs = {},
name = 'article_list',
),
url(
regex = '^rss/$',
view = cache_page(FEED_CACHE_TIME)(ArticleFeed()),
kwargs = {},
name = 'article_list_feed',
),
url(
regex = '^tags/(?P<tag_slugs>[-\w\+]+)/$',
view = cache_page(STANDARD_CACHE_TIME)(ArticleList.as_view()),
kwargs = {},
name = 'article_list_by_tag',
),
url(
# regex = '^tags/([-\w\+]+)/rss/$',
regex = '^tags/(?P<tag_slugs>[-\w\+]+)/rss/$',
# view = page_not_found,
view = cache_page(FEED_CACHE_TIME)(ArticleFeed()),
kwargs = {},
name = 'article_list_by_tag_feed',
),
url(
regex = '^tags/$',
view = RedirectView.as_view(pattern_name='article_list'),
kwargs = {},
name = 'article_list_tags',
),
url(
regex = '^suggest/$',
view = ArticleSuggestArticle.as_view(),
kwargs = {},
name = 'article_suggest_article',
),
url(
regex = '^(?P<slug>[-\w]+)/$',
view = cache_page(STANDARD_CACHE_TIME)(ArticleDetail.as_view()),
kwargs = {},
name = 'article_detail',
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,887
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/tags/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='ConceptTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, unique=True, verbose_name='Name')),
('slug', models.SlugField(max_length=100, unique=True, verbose_name='Slug')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ConceptTaggedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.IntegerField(db_index=True, verbose_name='Object id')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags_concepttaggeditem_tagged_items', to='contenttypes.ContentType', verbose_name='Content type')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags_concepttaggeditem_concepttag_items', to='tags.ConceptTag')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='TechnologyTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, unique=True, verbose_name='Name')),
('slug', models.SlugField(max_length=100, unique=True, verbose_name='Slug')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='TechnologyTaggedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.IntegerField(db_index=True, verbose_name='Object id')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags_technologytaggeditem_tagged_items', to='contenttypes.ContentType', verbose_name='Content type')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags_technologytaggeditem_techtag_items', to='tags.TechnologyTag')),
],
options={
'abstract': False,
},
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,888
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/management/commands/export_code_data.py
|
import io
import json
from collections import OrderedDict
from django.conf import settings
from django.core.management.base import BaseCommand
from source.code.models import Code
class Command(BaseCommand):
help = 'Export Code data.'
def handle(self, *args, **options):
code_list = Code.objects.filter(is_live=True)
code_exports = []
for code in code_list:
values = OrderedDict()
values['name'] = code.name.strip()
values['description'] = code.description.strip().replace('\n', ' ').replace('\r', '')
values['url'] = code.url.strip()
values['organizations'] = ', '.join([org.name.strip() for org in code.get_live_organization_set()])
values['people'] = ', '.join([person.__str__().strip() for person in code.get_live_person_set()])
values['tags'] = ', '.join([tag.name.strip() for tag in code.merged_tag_list])
code_exports.append(values)
json_out = json.dumps(code_exports, sort_keys=False, indent=4, ensure_ascii=False)
with io.open('code_data.json', 'w', encoding='utf8') as outfile:
outfile.write(json_out)
print('Export complete')
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,889
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/utils/auth.py
|
from urllib.parse import urlunparse
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth import backends as auth_backends
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.hashers import make_password
from django.shortcuts import redirect
from sesame.backends import UrlAuthBackendMixin
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
TOKEN_NAME = getattr(settings, 'SESAME_TOKEN_NAME', 'url_auth_token')
def get_or_create_user(email):
user, created = User.objects.get_or_create(
username__iexact=email, email__iexact=email,
defaults={'username': email, 'email': email,}
)
if created:
randomize_user_password(user)
return user
def get_random_password():
password = User.objects.make_random_password(length=16)
return make_password(password)
def randomize_user_password(user):
password = get_random_password()
user.password = password
user.save()
return user
class SesameModelBackend(UrlAuthBackendMixin, auth_backends.ModelBackend):
"""
Authenticates against a token containing a signed user id.
"""
def authenticate(self, url_auth_token=None):
"""
Check the token and return the corresponding user.
Modifies sesame.backends.ModelBackend by randomizing
password after email logins.
"""
try:
user = self.parse_token(url_auth_token)
# randomize password after email login
if user and not user.is_staff:
randomize_user_password(user)
return user
except TypeError:
backend = "%s.%s" % (self.__module__, self.__class__.__name__)
logger.exception("TypeError in %s, here's the traceback before "
"Django swallows it:", backend)
raise
class SesameAuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
Log user in if if `request` contains a valid login token.
"""
token = request.GET.get(TOKEN_NAME)
if token is None:
return
user = authenticate(url_auth_token=token)
# strip the sesame auth token querystring param
# from the URL and forward user to base location
get_params = request.GET.copy()
del get_params[TOKEN_NAME]
stripped_url = urlunparse(
('', '', request.path, '', get_params.urlencode(), '',)
)
redirect_url = redirect(stripped_url)
if user is None:
return redirect_url
# If the sessions framework is enabled and the token is valid,
# persist the login in session.
if hasattr(request, 'session') and user is not None:
login(request, user)
# If the authentication middleware isn't enabled, set request.user.
# (This attribute is overwritten by the authentication middleware
# if it runs after this one.)
if not hasattr(request, 'user'):
request.user = user if user is not None else AnonymousUser()
return redirect_url
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,890
|
OpenNews/opennews-source
|
refs/heads/master
|
/config/settings/local.py
|
# -*- coding: utf-8 -*-
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .common import *
BASE_SITE_URL = 'http://127.0.0.1:8000'
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['source.opennews.org'])
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
TEMPLATES[1]['OPTIONS']['debug'] = DEBUG
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# Note: This key only used for development and testing.
SECRET_KEY = env("DJANGO_SECRET_KEY", default='!kl8xt91apv&7m*9px=j7%y*vr*8%k_q78#m010-kc8l-uqe_b')
# Mail settings
# ------------------------------------------------------------------------------
#EMAIL_HOST = 'localhost'
#EMAIL_PORT = 1025
#EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_HOST_USER = env("MAILGUN_SMTP_LOGIN")
EMAIL_HOST_PASSWORD = env("MAILGUN_SMTP_PASSWORD")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EDITORIAL_EMAIL = 'ryan@opennews.org'
# CACHING
# ------------------------------------------------------------------------------
CACHES = {
'default': {
#'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
#'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'BACKEND': 'django_bmemcached.memcached.BMemcached',
'LOCATION': '127.0.0.1:11211',
}
}
BASE_URL = 'http://127.0.0.1:8000'
# django-debug-toolbar
# ------------------------------------------------------------------------------
#MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
#INSTALLED_APPS += ('debug_toolbar', )
INTERNAL_IPS = ('127.0.0.1', '10.0.2.2',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# Your local stuff: Below this line define 3rd party library settings
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,891
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/base/helpers.py
|
import datetime
import logging
import os
import re
import types
from copy import copy
from django.conf import settings
from django.template.defaultfilters import linebreaks as django_linebreaks,\
escapejs as django_escapejs, pluralize as django_pluralize,\
date as django_date
from django.utils.encoding import force_text
from django.utils.timesince import timesince
from django_jinja import library
from jinja2 import Markup
from sorl.thumbnail.shortcuts import get_thumbnail
from typogrify.filters import typogrify as dj_typogrify,\
smartypants as dj_smartypants
from source.articles.models import Article
logger = logging.getLogger('base.helpers')
@library.filter
def typogrify(string):
return Markup(dj_typogrify(string))
@library.filter
def smartypants(string):
return Markup(dj_smartypants(string))
@library.filter
def linebreaks(string):
return django_linebreaks(string)
@library.filter
def escapejs(string):
return django_escapejs(string)
@library.global_function
def get_timestamp():
return datetime.datetime.now()
@library.filter
def dj_pluralize(string, arg='s'):
return django_pluralize(string, arg)
@library.global_function
def dj_date(value, format_string):
return django_date(value, format_string)
@library.global_function
def thumbnail(source, *args, **kwargs):
im = get_thumbnail(source, *args, **kwargs)
return im.name
@library.filter
def dj_intcomma(value):
"""
https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize.py
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
orig = force_text(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
else:
return dj_intcomma(new)
@library.filter
def simple_timesince(value):
now = datetime.datetime.now()
try:
difference = now - value
except:
return value
if difference <= datetime.timedelta(minutes=1):
return 'just now'
return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}
@library.filter
def simple_datesince(value):
today = datetime.datetime.now().date()
try:
difference = today - value
except:
return value
if difference < datetime.timedelta(days=1):
return 'today'
return '%(days)s ago' % {'days': timesince(value).split(', ')[0]}
# FORM RENDERING
# https://github.com/kmike/django-widget-tweaks/blob/master/widget_tweaks/templatetags/widget_tweaks.py
def _process_field_attributes(field, attr, process):
# split attribute name and value from 'attr:value' string
params = attr.split(':', 1)
attribute = params[0]
value = params[1] if len(params) == 2 else ''
field = copy(field)
# decorate field.as_widget method with updated attributes
old_as_widget = field.as_widget
def as_widget(self, widget=None, attrs=None, only_initial=False):
attrs = attrs or {}
process(widget or self.field.widget, attrs, attribute, value)
html = old_as_widget(widget, attrs, only_initial)
self.as_widget = old_as_widget
return html
field.as_widget = types.MethodType(as_widget, field)
return field
@library.filter
def append_attr(field, attr):
def process(widget, attrs, attribute, value):
if attrs.get(attribute):
attrs[attribute] += ' ' + value
elif widget.attrs.get(attribute):
attrs[attribute] = widget.attrs[attribute] + ' ' + value
else:
attrs[attribute] = value
return _process_field_attributes(field, attr, process)
@library.filter
def add_class(field, css_class):
return append_attr(field, 'class:' + css_class)
@library.global_function
def get_random_articles(num, recent_days=None):
random_articles = Article.live_objects.filter(show_in_lists=True)
if recent_days:
cutoff = datetime.datetime.today() - datetime.timedelta(recent_days)
if random_articles.filter(pubdate__gte=cutoff).count() > 0:
random_articles = random_articles.filter(pubdate__gte=cutoff)
random_articles = random_articles.order_by('?')
try:
if num == 1:
return random_articles[0]
else:
return random_articles[:num]
except:
return None
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,892
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/migrations/0006_auto_20170123_1809.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-23 18:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('code', '0005_code_grouping'),
]
operations = [
migrations.AlterField(
model_name='code',
name='grouping',
field=models.CharField(blank=True, help_text='The primary category where this repo will be grouped on the Code page.', max_length=64),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,893
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/urls/community.py
|
from django.conf import settings
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from source.people.views import CommunityList
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60*15)
urlpatterns = [
url(
regex = '^$',
view = cache_page(STANDARD_CACHE_TIME)(CommunityList.as_view()),
kwargs = {},
name = 'community_list',
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,894
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/migrations/0004_article_is_featured.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-13 17:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0003_auto_20160128_0100'),
]
operations = [
migrations.AddField(
model_name='article',
name='is_featured',
field=models.BooleanField(default=False, help_text='Most recent featured article appears at top of homepage', verbose_name='Featured article'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,895
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/guides/migrations/0003_auto_20170206_2215.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-02-06 22:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('guides', '0002_auto_20170123_1809'),
]
operations = [
migrations.AlterField(
model_name='guide',
name='author_name',
field=models.CharField(blank=True, help_text="This field accepts HTML, so you can wrap an author's name in a link.", max_length=128),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,896
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/migrations/0007_article_image_alt_text.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2022-02-21 15:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0006_articleblock_image_alt_text'),
]
operations = [
migrations.AddField(
model_name='article',
name='image_alt_text',
field=models.TextField(blank=True),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,897
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/jobs/migrations/0002_auto_20170206_2215.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-02-06 22:15
from __future__ import unicode_literals
from django.db import migrations, models
import source.jobs.models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='job',
options={'ordering': ('-listing_end_date', 'organization', 'slug')},
),
migrations.AlterField(
model_name='job',
name='listing_end_date',
field=models.DateField(default=source.jobs.models.get_today_plus_30, verbose_name='End date'),
),
migrations.AlterField(
model_name='job',
name='listing_start_date',
field=models.DateField(default=source.jobs.models.get_today, verbose_name='Start date'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,898
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/base/views.py
|
import requests
from django.conf import settings
from django.shortcuts import redirect
from django.views.generic import ListView, View
from haystack.views import SearchView
from source.articles.models import Article
from source.articles.views import ArticleList
from source.code.models import Code
from source.guides.models import get_random_guides
from source.jobs.models import get_recent_jobs
from source.people.models import Organization, Person
from source.utils.json import render_json_to_response
class HomepageView(ListView):
model = Article
template_name = '_v2/homepage.html'
def get_promo_article(self):
promo_article = Article.live_objects.filter(show_in_lists=True, is_featured=True).latest()
return promo_article
def get_queryset(self):
promo_article = self.get_promo_article()
queryset = Article.live_objects.filter(show_in_lists=True, is_featured=True).exclude(id=promo_article.id)[:9]
return queryset
def get_context_data(self, **kwargs):
context = super(HomepageView, self).get_context_data(**kwargs)
context['promo_article'] = self.get_promo_article()
context['recent_jobs'] = get_recent_jobs(3)
context['random_guides'] = get_random_guides(3)
return context
class SourceSearchView(SearchView):
template = "_v2/search/search.html"
def get_results(self):
'''
Limit primary search results to Article matches.
Template gets Person and Organization matches separately,
via `get_secondary_results`.
'''
results = self.form.search().models(Article).order_by('-pubdate')
return results
def get_code_results(self):
'''
Get Code matches for separate handling on template.
'''
code_results = self.form.search().models(Code).order_by('name')
return code_results
def get_person_results(self):
'''
Get Person matches for separate handling on template.
'''
person_results = self.form.search().models(Person).order_by('first_name')
return person_results
def get_organization_results(self):
'''
Get Organization matches for separate handling on template.
'''
organization_results = self.form.search().models(Organization).order_by('name')
return organization_results
def extra_context(self):
page_context = {}
if self.query:
page_context.update({
'code_results': self.get_code_results(),
'person_results': self.get_person_results(),
'organization_results': self.get_organization_results()
})
return page_context
class L10NRedirectView(View):
'''
Original Mozilla Playdoh framework forced en-US URLs. Now that we
no longer use them, this view handles redirects for old inbound links.
'''
def get(self, request, *args, **kwargs):
new_url = request.get_full_path().lower().replace('/en-us','',1)
return redirect(new_url, permanent=True)
class SlackMessageView(View):
def post(self, request, *args, **kwargs):
message = request.POST.get('message', None)
channel = request.POST.get('channel', None)
auth_token = getattr(settings, 'SLACK_TOKEN', None)
if message and auth_token:
endpoint = 'https://membot.herokuapp.com/message/inbound/'
data = {
'message': message,
'channel': channel,
'token': auth_token
}
r = requests.post(endpoint, data=data)
result = 'success'
else:
result = 'failure'
return render_json_to_response({'text': result})
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,899
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/jobs/urls.py
|
from django.conf import settings
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import JobList, JobUpdate, JobsSendLoginLink
from source.base.feeds import JobFeed
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60*15)
FEED_CACHE_TIME = getattr(settings, 'FEED_CACHE_SECONDS', 60*15)
urlpatterns = [
url(
regex = '^$',
view = cache_page(STANDARD_CACHE_TIME)(JobList.as_view()),
kwargs = {},
name = 'job_list',
),
url(
regex = '^rss/$',
view = cache_page(FEED_CACHE_TIME)(JobFeed()),
kwargs = {},
name = 'job_list_feed',
),
url(
regex = '^json/$',
view = cache_page(FEED_CACHE_TIME)(JobList.as_view()),
kwargs = {'render_json': True},
name = 'job_list_feed_json',
),
url(
regex = '^update/$',
view = JobUpdate.as_view(),
kwargs = {},
name = 'job_update',
),
url(
regex = '^login/$',
view = JobsSendLoginLink.as_view(),
kwargs = {},
name = 'job_send_login_link',
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,900
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/management/commands/export_people_data.py
|
import io
import json
from collections import OrderedDict
from django.conf import settings
from django.core.management.base import BaseCommand
from source.people.models import Person, Organization
class Command(BaseCommand):
help = 'Export Person and Organization data.'
def handle(self, *args, **options):
person_list = Person.objects.filter(is_live=True)
person_exports = []
for person in person_list:
values = OrderedDict()
values['first_name'] = person.first_name.strip()
values['last_name'] = person.last_name.strip()
values['email'] = person.email.strip()
values['twitter_username'] = person.twitter_username.strip()
values['github_username'] = person.github_username.strip()
values['organizations'] = ', '.join([org.name.strip() for org in person.get_live_organization_set()])
person_exports.append(values)
json_out = json.dumps(person_exports, sort_keys=False, indent=4, ensure_ascii=False)
with io.open('person_data.json', 'w', encoding='utf8') as outfile:
outfile.write(json_out)
org_list = Organization.objects.filter(is_live=True)
org_exports = []
for org in org_list:
values = OrderedDict()
values['name'] = org.name.strip()
values['twitter_username'] = org.twitter_username.strip()
values['github_username'] = org.github_username.strip()
values['people'] = ', '.join([person.__str__().strip() for person in org.get_live_person_set()])
org_exports.append(values)
json_out = json.dumps(org_exports, sort_keys=False, indent=4, ensure_ascii=False)
with io.open('organization_data.json', 'w', encoding='utf8') as outfile:
outfile.write(json_out)
print('Export complete')
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,901
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
import caching.base
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Organization',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('is_live', models.BooleanField(default=True, verbose_name='Display on site')),
('show_in_lists', models.BooleanField(default=True, verbose_name='Show on Organization list page')),
('name', models.CharField(max_length=255)),
('slug', models.SlugField(unique=True)),
('email', models.EmailField(blank=True, max_length=254, verbose_name='Email address')),
('twitter_username', models.CharField(blank=True, max_length=32)),
('github_username', models.CharField(blank=True, max_length=32)),
('github_repos_num', models.PositiveIntegerField(blank=True, null=True)),
('github_gists_num', models.PositiveIntegerField(blank=True, null=True)),
('homepage', models.URLField(blank=True)),
('description', models.TextField(blank=True)),
('address', models.CharField(blank=True, max_length=255)),
('city', models.CharField(blank=True, max_length=64)),
('state', models.CharField(blank=True, max_length=32)),
('country', models.CharField(blank=True, help_text='Only necessary if outside the U.S.', max_length=32)),
('logo', sorl.thumbnail.fields.ImageField(blank=True, help_text='Resized to fit 200x50 box in template', null=True, upload_to='img/uploads/org_logos')),
],
options={
'ordering': ('name',),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='OrganizationLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=128)),
('url', models.URLField()),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='people.Organization')),
],
options={
'verbose_name': 'Organization Link',
'ordering': ('organization', 'name'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='Person',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('is_live', models.BooleanField(default=True, verbose_name='Display on site')),
('show_in_lists', models.BooleanField(default=True, verbose_name='Show on People list page')),
('first_name', models.CharField(max_length=128)),
('last_name', models.CharField(max_length=128)),
('slug', models.SlugField(unique=True)),
('email', models.EmailField(blank=True, max_length=254, verbose_name='Email address')),
('twitter_username', models.CharField(blank=True, max_length=32)),
('twitter_bio', models.TextField(blank=True)),
('twitter_profile_image_url', models.URLField(blank=True)),
('github_username', models.CharField(blank=True, max_length=32)),
('github_repos_num', models.PositiveIntegerField(blank=True, null=True)),
('github_gists_num', models.PositiveIntegerField(blank=True, null=True)),
('description', models.TextField(blank=True, verbose_name='Bio')),
('organizations', models.ManyToManyField(blank=True, to='people.Organization')),
],
options={
'verbose_name_plural': 'People',
'ordering': ('last_name', 'first_name'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='PersonLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=128)),
('url', models.URLField()),
('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='people.Person')),
],
options={
'verbose_name': 'Person Link',
'ordering': ('person', 'name'),
},
bases=(caching.base.CachingMixin, models.Model),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,902
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/views.py
|
import json
import random
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.forms.models import modelformset_factory
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.views.generic import ListView, DetailView, TemplateView, View
from .forms import OrganizationUpdateForm, PersonUpdateForm
from .models import Person, Organization, OrganizationAdmin
from caching.config import NO_CACHE
from source.articles.models import Article
from source.code.models import Code, get_recent_repos
from source.jobs.models import Job, get_recent_jobs
from source.utils.json import render_json_to_response
USER_DEBUG = getattr(settings, 'USER_DEBUG', False)
class CommunityList(TemplateView):
template_name = 'people/_v2/community_index.html'
def get_context_data(self, **kwargs):
context = super(CommunityList, self).get_context_data(**kwargs)
# this page randomly selects a few Person and Organization
# records to display based on recent Article and Code posts
recent_articles = Article.live_objects.order_by('-pubdate')[:20]
recent_codes = Code.live_objects.order_by('-created')[:20]
# we only need the Person record pks here, setting NO_CACHE because
# django-cache-machine does not work with .values() or .values_list()
article_author_ids = recent_articles.values_list('authors', flat=True)
article_author_ids.timeout = NO_CACHE
#code_people_ids = recent_codes.values_list('people', flat=True)
#code_people_ids.timeout = NO_CACHE
# get 3 random unique Person records
people_ids = list(article_author_ids)# + list(code_people_ids)
people_ids = list(set([x for x in people_ids if x is not None]))
people_ids = random.sample(people_ids, 3)
people = Person.objects.filter(id__in=people_ids)
context['people'] = people
# only need the Organization pks
article_organization_ids = recent_articles.values_list('organizations', flat=True)
article_organization_ids.timeout = NO_CACHE
article_code_ids = recent_codes.values_list('organizations', flat=True)
article_code_ids.timeout = NO_CACHE
# get 3 random unique Organization records
organization_ids = list(article_organization_ids) + list(article_code_ids)
organization_ids = list(set([x for x in organization_ids if x is not None]))
organization_ids = random.sample(organization_ids, 3)
organizations = Organization.objects.filter(id__in=organization_ids)
context['organizations'] = organizations
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class PersonList(ListView):
model = Person
template_name = 'people/_v2/person_list.html'
def get_queryset(self):
queryset = Person.live_objects.exclude(show_in_lists=False).prefetch_related('organizations')
return queryset
def get_context_data(self, **kwargs):
context = super(PersonList, self).get_context_data(**kwargs)
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class PersonDetail(DetailView):
model = Person
template_name = 'people/_v2/person_detail.html'
def get_queryset(self):
queryset = Person.live_objects.prefetch_related('personlink_set', 'organizations', 'code_set', 'article_set', 'article_authors')
return queryset
def get_context_data(self, **kwargs):
context = super(PersonDetail, self).get_context_data(**kwargs)
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class PersonSearchJson(View):
def get_queryset(self):
queryset = Person.live_objects.exclude(show_in_lists=False)
return queryset
def get(self, request, *args, **kwargs):
people = self.get_queryset()
q = self.request.GET.get('q', None)
if 'q' in self.request.GET:
people = people.filter(Q(first_name__icontains = q) | Q(last_name__icontains = q))
people = people.values('first_name', 'last_name', 'email', 'twitter_username', 'github_username', 'id')
people.timeout = NO_CACHE
for person in list(people):
person['name'] = '%s %s' % (person['first_name'], person['last_name'])
return render_json_to_response(list(people))
class OrganizationList(ListView):
model = Organization
template_name = 'people/_v2/organization_list.html'
def get_queryset(self):
queryset = Organization.live_objects.exclude(show_in_lists=False).all()
return queryset
def get_context_data(self, **kwargs):
context = super(OrganizationList, self).get_context_data(**kwargs)
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class OrganizationDetail(DetailView):
model = Organization
template_name = 'people/_v2/organization_detail.html'
def get_queryset(self):
queryset = Organization.live_objects.prefetch_related('organizationlink_set')
return queryset
def get_context_data(self, **kwargs):
context = super(OrganizationDetail, self).get_context_data(**kwargs)
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class PersonUpdate(View):
template_name = "people/person_update.html"
form_message = ''
def get_success_url(self):
return reverse('person_update')
def get_organization(self):
user = self.request.user
if user.is_authenticated() and user.is_active:
organization = get_object_or_404(Organization, is_live=True, email=user.email)
return organization
elif USER_DEBUG:
organization = get_object_or_404(Organization, is_live=True, slug='spokesman-review')
return organization
return None
def get_person(self, pk=None, organization=None, task=None):
user = self.request.user
if USER_DEBUG or (user.is_authenticated() and user.is_active):
if pk and organization:
# allow for 'add' task
if task == 'add':
person = get_object_or_404(Person, is_live=True, pk=pk)
else:
# ensure that Organization admin can modify this record
person = get_object_or_404(Person, is_live=True, pk=pk, organizations=organization)
else:
# or that the authenticated user *is* this person
person = get_object_or_404(Person, is_live=True, email=user.email)
return person
return None
def create_person(self, data, organization):
name = data['name']
# make sure we actually have been given a name
if name:
try:
first_name, last_name = name.split(' ', 1)
except:
first_name, last_name = name, ''
person_kwargs = {
'first_name': first_name,
'last_name': last_name,
'slug': slugify('-'.join([first_name, last_name]))
}
i = 0
found = True
while found:
i += 1
try:
person = Person.objects.get(slug=person_kwargs['slug'])
person_kwargs['slug'] = slugify('-'.join([first_name, last_name, str(i)]))
except ObjectDoesNotExist:
person = Person(**person_kwargs)
person.save()
person.organizations.add(organization)
found = False
return person
return None
def process_form(self, person, data):
person_form = PersonUpdateForm(instance=person, data=data)
if person_form.is_valid():
person_form.save()
form_message = 'Saved!'
else:
error_message = ''
for field in person_form:
if field.errors:
add_label = field.label
add_errors = ', '.join([error for error in field.errors])
error_message += '%s: %s ' % (add_label, add_errors)
form_message = error_message
return form_message
def post(self, request, *args, **kwargs):
data = request.POST
form_message = ''
success_url = self.get_success_url()
if 'organization_task' in data:
success_url = reverse('organization_update')
self.template_name = "people/organization_update.html"
task = data['organization_task']
organization = self.get_organization()
if task == 'create':
person = self.create_person(data, organization)
form_message = 'Created'
success_url += '?new=%s' % person.pk
else:
person = self.get_person(data['person'], organization, task)
if task == 'update':
form_message = self.process_form(person, data)
elif task == 'remove':
person.organizations.remove(organization)
form_message = 'Removed'
elif task == 'add':
person.organizations.add(organization)
form_message = 'Added'
else:
person = self.get_person()
form_message = self.process_form(person, data)
if request.is_ajax():
result = {
'message': form_message,
'person': {
'name': person.name(),
'pk': person.pk,
'first_name': person.first_name,
'last_name': person.last_name,
'email': person.email,
'twitter_username': person.twitter_username,
'github_username': person.github_username
}
}
return render_json_to_response(result)
# if for some reason we're not hitting via ajax
messages.success(request, form_message)
return redirect(success_url)
class OrganizationUpdate(View):
template_name = "people/organization_update.html"
error_message = ""
def get_organization(self, user):
if user.is_authenticated() and user.is_active:
try:
org_admin = OrganizationAdmin.objects.get(email=user.email, organization__is_live=True)
return org_admin.organization
except OrganizationAdmin.DoesNotExist:
self.error_message = "Sorry, no Organization account found that matches your email address: {}".format(user.email)
except OrganizationAdmin.MultipleObjectsReturned:
self.error_message = "Uh-oh, somehow there are multiple Organization accounts attached to your email address: {}. Please contact us for cleanup.".format(user.email)
return None
def get(self, request, *args, **kwargs):
context = {}
user = request.user
if user.is_authenticated() and user.is_active:
organization = self.get_organization(user)
if organization:
organization_form = OrganizationUpdateForm(instance=organization)
context.update({
'user': request.user,
'organization': organization,
'organization_form': organization_form,
'default_job_listing_end_date': datetime.today().date() + timedelta(days=30)
})
else:
context.update({
'error_message': self.error_message
})
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
context = {}
user = request.user
organization = self.get_organization(user)
if organization:
organization_form = OrganizationUpdateForm(instance=organization, data=request.POST)
context.update({
'user': request.user,
'organization': organization,
'organization_form': organization_form,
})
if organization_form.is_valid():
organization_form.save()
if request.is_ajax():
result = {'success': 'True'}
return render_json_to_response(result)
# if for some reason we're not hitting via ajax
messages.success(request, 'Updates saved')
return render(request, self.template_name, context)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,903
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/base/utils.py
|
from functools import wraps
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404
def paginate(request, queryset, results_per_page=20):
paginator = Paginator(queryset, results_per_page)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("Sorry, that page of results does not exist.")
except ValueError:
raise PermissionDenied()
return page, paginator
def disable_for_loaddata(signal_handler):
@wraps(signal_handler)
def wrapper(*args, **kwargs):
if kwargs['raw']:
print("Skipping signal for {0} {1}".format(args, kwargs))
return
signal_handler(*args, **kwargs)
return wrapper
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,904
|
OpenNews/opennews-source
|
refs/heads/master
|
/config/urls.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
from django.views import defaults as default_views
from django.views.generic.base import RedirectView
from source.base import urls
from source.base.views import L10NRedirectView
urlpatterns = [
url(settings.ADMIN_URL, admin.site.urls),
#url(r'^en-(us|US)/rss/$', default_views.page_not_found),
url(r'^en-(us|US)/', L10NRedirectView.as_view()),
# Generate a robots.txt
url(r'^robots.txt$',
lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow') ,
content_type="text/plain"
)
),
url(r'', include(urls.BASE_URLS)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# allows error pages to be debugged during development
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permission Denied")}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}),
url(r'^500/$', default_views.server_error),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,905
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/views.py
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render, redirect
from django.template.loader import render_to_string
from django.views.generic import ListView, DetailView, View
from django.views.generic.edit import FormView
from .forms import SuggestArticleForm
from .models import Article, Section, Category
from source.code.models import get_recent_repos
from source.jobs.models import get_recent_jobs
from source.tags.utils import filter_queryset_by_tags
from source.utils.email import send_multipart_email
from source.utils.pagination import paginate
class ArticleList(ListView):
model = Article
template_name = 'articles/_v2/article_list.html'
section = None
category = None
def dispatch(self, *args, **kwargs):
self.category_kwarg = kwargs.get('category', None)
if self.category_kwarg:
self.category = get_object_or_404(Category, slug=self.category_kwarg)
self.tag_slugs = kwargs.get('tag_slugs', None)
self.tags = []
return super(ArticleList, self).dispatch(*args, **kwargs)
def get_template_names(self):
template_list = [self.template_name]
return template_list
def get_queryset(self):
queryset = Article.live_objects.filter(show_in_lists=True).prefetch_related('authors', 'people', 'organizations')
if self.category:
queryset = queryset.filter(category=self.category)
elif self.tag_slugs:
queryset, self.tags = filter_queryset_by_tags(queryset, self.tag_slugs, self.tags)
return queryset
def get_section_links(self, context):
if self.category:
context.update({
'category': self.category,
'section': self.category.section,
#'active_nav': self.category.section.slug,
'rss_link': reverse('article_list_by_category_feed', kwargs={'category': self.category.slug}),
})
elif self.tags:
context.update({
'tags': self.tags,
#'rss_link': reverse('article_list_by_tag_feed', kwargs={'tag_slugs': self.tag_slugs}),
})
else:
context.update({
'rss_link': reverse('homepage_feed'),
})
return ''
def paginate_list(self, context):
page, paginator = paginate(self.request, self.object_list, 20)
context.update({
'page': page,
'paginator': paginator
})
return ''
def get_promo_items(self, context, num_items):
_page = context.get('page', None)
# Only get promo items for the first page of a paginated section
if _page and _page.number == 1:
'''
Take the most recent three items from this section's list
of articles. Pop the first item for a `lead_promo` object.
Stash the rest in a `secondary_promos` list. Also generate
a set of pks to ignore when we iterate through the main
headline list.
'''
promo_list = self.get_queryset()[:num_items]
lead_promo = None
secondary_promos = None
if promo_list:
lead_promo = promo_list[0]
secondary_promos = promo_list[1:]
context.update({
'lead_promo': lead_promo,
'secondary_promos': secondary_promos,
'articles_to_exclude_from_list': [promo.pk for promo in promo_list]
})
def get_standard_context(self, context):
self.get_section_links(context)
self.paginate_list(context)
return ''
def get_context_data(self, **kwargs):
context = super(ArticleList, self).get_context_data(**kwargs)
self.get_standard_context(context)
context['recent_jobs'] = get_recent_jobs(2)
context['recent_repos'] = get_recent_repos(3)
return context
class ArticleDetail(DetailView):
model = Article
template_name = 'articles/_v2/article_detail.html'
def get_queryset(self):
if self.request.user.is_staff:
# simple method for allowing article preview for editors,
# bypassing `live_objects` check on detail view. List pages
# populate with public articles only, but admin user can hit
# "view on site" button to see article even if it's not live yet
queryset = Article.objects.all()
else:
queryset = Article.live_objects.all()
queryset = queryset.prefetch_related('articleblock_set', 'authors', 'people', 'organizations', 'code')
return queryset
def get_context_data(self, **kwargs):
context = super(ArticleDetail, self).get_context_data(**kwargs)
recent_articles = Article.live_objects.filter(show_in_lists=True).exclude(id=self.object.id).order_by('-pubdate')[:3]
context.update({
'section': self.object.section,
'recent_articles': recent_articles,
})
return context
class ArticleRedirectView(View):
'''
No longer splitting articles out into individual sections.
'''
def get(self, request, *args, **kwargs):
slug = kwargs['slug']
new_url = reverse('article_detail', kwargs={'slug': slug})
return redirect(new_url, permanent=True)
class ArticleSuggestArticle(FormView):
'''
Readers can submit an Article pitch, generating
an email to the editorial team.
'''
template_name = "articles/_v2/suggest_article.html"
form_class = SuggestArticleForm
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
data=form.cleaned_data
email_context = {
'data': data
}
# render text and html versions of email body
# both plain txt for now
text_content = render_to_string(
'articles/_v2/emails/suggest_article.txt',
email_context,
)
html_content = render_to_string(
'articles/_v2/emails/suggest_article.html',
email_context
)
send_multipart_email(
subject = 'Source: Article suggestion from a reader',
from_email = settings.DEFAULT_FROM_EMAIL,
to = settings.EDITORIAL_EMAIL,
text_content = text_content,
html_content = html_content
)
context.update({'success': 'True'})
return render(self.request, self.template_name, context)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,906
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/jobs/views.py
|
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render, redirect
from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.generic import ListView, DetailView, View
from django.views.generic.edit import FormView
from .forms import JobUpdateForm
from .models import Job
from source.base.helpers import dj_date
from source.people.models import Organization, OrganizationAdmin
from source.utils.caching import expire_page_cache
from source.utils.email import send_multipart_email
from source.utils.json import render_json_to_response
from sesame import utils as sesame_utils
USER_DEBUG = getattr(settings, 'USER_DEBUG', False)
class JobList(ListView):
model = Job
template_name = "jobs/_v2/job_list.html"
def dispatch(self, request, *args, **kwargs):
self.render_json = kwargs.get('render_json', False)
self.sort = request.GET.get('sort', None)
return super(JobList, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
queryset = Job.live_objects.order_by('-listing_start_date', '-created')
return queryset
def get_context_data(self, **kwargs):
context = super(JobList, self).get_context_data(**kwargs)
context['active_nav'] = 'Jobs'
context['rss_link'] = reverse('job_list_feed')
context['json_link'] = reverse('job_list_feed_json')
context['sort_value'] = self.sort or 'date'
this_week = datetime.now().date() - timedelta(days=7)
last_week = datetime.now().date() - timedelta(days=14)
if self.sort == 'organization':
context['jobs_by_organization'] = self.get_queryset().order_by('organization__name')
else:
context['jobs_this_week'] = self.get_queryset().filter(listing_start_date__gt=this_week)
context['jobs_last_week'] = self.get_queryset().filter(listing_start_date__lte=this_week, listing_start_date__gt=last_week)
context['jobs_previously'] = self.get_queryset().filter(listing_start_date__lte=last_week)
return context
def render_to_response(self, context):
if self.render_json:
jobs = []
for job in context['object_list']:
jobs.append({
'name': job.name,
'organization': job.organization.name,
'description': job.description,
'location': job.location,
'contact_name': job.contact_name,
'email': job.email,
'listed': dj_date(job.listing_start_date, 'F j, Y'),
'url': job.url,
'source_url': job.get_list_page_url,
})
return render_json_to_response(jobs)
return super(JobList, self).render_to_response(context)
class JobUpdate(FormView):
form_class = JobUpdateForm
template_name = 'jobs/_v2/job_update.html'
def get_success_url(self):
return reverse('job_update')
def get_job(self, pk=None, organization=None):
user = self.request.user
if (user.is_authenticated() and user.is_active):
if pk and organization:
# ensure that Organization admin can modify this record
job = get_object_or_404(Job, is_live=True, pk=pk, organization=organization)
return job
return None
def create_job(self, data, organization):
data.update({
'organization': organization
})
job = Job(**data)
job.save()
return job
def update_job(self, job, data, task=None):
if task == 'delete':
job.delete()
expire_page_cache(reverse('job_list'))
form_message = 'Job listing deleted. Add a new job?'
else:
job_form = JobUpdateForm(instance=job, data=data)
if job_form.is_valid():
job_form.save()
form_message = 'Saved!'
else:
error_message = ''
for field in job_form:
if field.errors:
add_label = field.label
add_errors = ', '.join([error for error in field.errors])
error_message += '%s: %s ' % (add_label, add_errors)
form_message = error_message
return form_message
def get_organization(self, user):
if user.is_authenticated() and user.is_active:
try:
org_admin = OrganizationAdmin.objects.get(email__iexact=user.username, organization__is_live=True)
return org_admin.organization
except OrganizationAdmin.DoesNotExist:
self.error_message = "Sorry, no Organization account found that matches your email address: {}".format(user.email)
except OrganizationAdmin.MultipleObjectsReturned:
self.error_message = "Uh-oh, somehow there are multiple Organization accounts attached to your email address: {}. Please contact us for cleanup.".format(user.email)
return None
def get_context_data(self, **kwargs):
context = super(JobUpdate, self).get_context_data(**kwargs)
request = self.request
user = request.user
if user.is_authenticated() and user.is_active:
organization = self.get_organization(user)
if organization:
context.update({
'user': request.user,
'organization': organization,
'default_job_listing_end_date': datetime.today().date() + timedelta(days=30),
'job': None
})
if 'job' in request.GET:
job = self.get_job(request.GET['job'], organization)
context.update({
'job': job
})
else:
context.update({
'error_message': self.error_message
})
return context
def form_valid(self, form, **kwargs):
job = form.data.get('job', None)
task = form.data.get('task', None)
data = form.cleaned_data
request = self.request
form_message = ''
user = request.user
organization = self.get_organization(user)
if not job:
job = self.create_job(data, organization)
form_message = 'New job posted to <a href="{}">Source listings</a>. Add another?'.format(reverse('job_list'))
else:
job = self.get_job(job, organization)
form_message = self.update_job(job, data, task)
messages.success(request, form_message)
return redirect(self.get_success_url())
class JobsSendLoginLink(View):
def post(self, request, *args, **kwargs):
email = request.POST.get('email')
job_update_url = reverse('job_update')
try:
user = User.objects.get(username__iexact=email)
except:
# a User record is automatically created when
# an OrganizationAdmin is added. If no User record
# is found, the address shouldn't be logging in.
msg = 'Sorry, no admin account associated with this email address.'
messages.error(request, msg)
return redirect(job_update_url)
# use django-sesame to send magic login link
site_url = '{}://{}'.format(request.scheme, get_current_site(request))
login_token = sesame_utils.get_query_string(user)
login_link = '{}{}{}'.format(site_url, job_update_url, login_token)
msg = 'We just emailed you a login link! Please check your inbox.'
email_context = {
'site_url': site_url,
'login_link': login_link,
}
text_content = render_to_string(
'jobs/_v2/emails/jobs_admin_login.txt',
email_context,
)
html_content = render_to_string(
'jobs/_v2/emails/jobs_admin_login.html',
email_context
)
send_multipart_email(
subject = 'Source Jobs: Log in to your account',
from_email = settings.DEFAULT_FROM_EMAIL,
to = email,
text_content = text_content,
html_content = html_content
)
if request.is_ajax():
result = {'message': msg}
return render_json_to_response(result)
messages.success(request, msg)
return redirect(job_update_url)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,907
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
import caching.base
import datetime
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('people', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('is_live', models.BooleanField(default=True, verbose_name='Display on site')),
('show_in_lists', models.BooleanField(default=True, verbose_name='Show in lists')),
('allow_comments', models.BooleanField(default=True, verbose_name='Allow comments')),
('title', models.CharField(max_length=128)),
('slug', models.SlugField(unique=True)),
('pubdate', models.DateTimeField(default=datetime.datetime.now)),
('subhead', models.CharField(max_length=128)),
('image', sorl.thumbnail.fields.ImageField(blank=True, help_text='Resized to fit 100% column width in template', null=True, upload_to='img/uploads/article_images')),
('image_caption', models.TextField(blank=True)),
('image_credit', models.CharField(blank=True, help_text='Optional. Will be appended to end of caption in parens. Accepts HTML.', max_length=128)),
('body', models.TextField()),
('summary', models.TextField()),
('article_type', models.CharField(blank=True, max_length=32)),
('disable_auto_linebreaks', models.BooleanField(default=False, help_text='Check this if body and article blocks already have HTML paragraph tags.')),
('article_js_header', models.TextField(blank=True)),
('article_js_footer', models.TextField(blank=True)),
('authors', models.ManyToManyField(blank=True, related_name='article_authors', to='people.Person')),
],
options={
'ordering': ('-pubdate', 'title'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='ArticleBlock',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=128)),
('slug', models.SlugField()),
('order', models.PositiveIntegerField(default=1)),
('image', sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='img/uploads/article_images')),
('image_presentation', models.CharField(blank=True, choices=[('full-width', 'Full-Width Above Text'), ('full-width-below', 'Full-Width Below Text'), ('inset-left', 'Inset Left'), ('inset-right', 'Inset Right')], max_length=24)),
('image_caption', models.TextField(blank=True)),
('image_credit', models.CharField(blank=True, help_text='Optional. Will be appended to end of caption in parens. Accepts HTML.', max_length=128)),
('body', models.TextField()),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Article')),
],
options={
'verbose_name': 'Article Block',
'ordering': ('article', 'order', 'title'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=64)),
('slug', models.SlugField()),
],
options={
'verbose_name_plural': 'Categories',
'ordering': ('section', 'name'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='Section',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=64)),
('slug', models.SlugField()),
('description', models.TextField(blank=True, help_text='Optional text to add at top of page. (Shows on promo template only.)')),
('gets_promo_items', models.BooleanField(default=False, help_text='Check this to use special template with three promo cards at top.')),
('special_template', models.CharField(blank=True, max_length=255)),
],
options={
'ordering': ('name',),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.AddField(
model_name='category',
name='section',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Section'),
),
migrations.AddField(
model_name='article',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Category'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,908
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/guides/views.py
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.views.generic import ListView, DetailView, View
from django.views.generic.edit import FormView
from .forms import SuggestGuideForm
from .models import Guide
from source.utils.email import send_multipart_email
class GuideList(ListView):
model = Guide
template_name = "guides/_v2/guide_list.html"
def dispatch(self, *args, **kwargs):
self.render_json = kwargs.get('render_json', False)
return super(GuideList, self).dispatch(*args, **kwargs)
def get_queryset(self):
queryset = Guide.live_objects.all()
return queryset
def get_context_data(self, **kwargs):
context = super(GuideList, self).get_context_data(**kwargs)
context['active_nav'] = 'Guides'
context['rss_link'] = reverse('guide_list_feed')
return context
class GuideDetail(DetailView):
model = Guide
template_name = "guides/_v2/guide_detail.html"
def get_queryset(self):
if self.request.user.is_staff:
# allow preview for logged-in editors
queryset = Guide.objects.prefetch_related('guidearticle_set')
else:
queryset = Guide.live_objects.prefetch_related('guidearticle_set')
return queryset
class GuideSuggestGuide(FormView):
'''
Readers can suggest a Guide to add to the Guide list, generating
an email to the editorial team.
'''
template_name = "guides/_v2/suggest_guide.html"
form_class = SuggestGuideForm
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
data=form.cleaned_data
email_context = {
'data': data
}
# render text and html versions of email body
# both plain txt for now
text_content = render_to_string(
'guides/_v2/emails/suggest_guide.txt',
email_context,
)
html_content = render_to_string(
'guides/_v2/emails/suggest_guide.html',
email_context
)
send_multipart_email(
subject = 'Source: Guide suggestion from a reader',
from_email = settings.DEFAULT_FROM_EMAIL,
to = settings.EDITORIAL_EMAIL,
text_content = text_content,
html_content = html_content
)
context.update({'success': 'True'})
return render(self.request, self.template_name, context)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,909
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/management/commands/migrate_code_groupings.py
|
from django.conf import settings
from django.core.management.base import BaseCommand
from source.code.models import Code
class Command(BaseCommand):
help = "One-time command to populate new `grouping` field on Code model"
def handle(self, *args, **options):
code_list = Code.objects.all()
for code in code_list:
print("\nmigrating " + code.name)
try:
tag_for_grouping = code.concept_tags.all()[0]
except:
try:
tag_for_grouping = code.technology_tags.all()[0]
except:
tag_for_grouping = None
if tag_for_grouping:
print("adding to group " + tag_for_grouping.name)
code.grouping = tag_for_grouping.name
code.save()
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,910
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
import caching.base
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Code',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('is_live', models.BooleanField(default=True, verbose_name='Display on site')),
('is_active', models.BooleanField(default=True, verbose_name='Active project')),
('seeking_contributors', models.BooleanField(default=False, verbose_name='Seeking contributors')),
('name', models.CharField(max_length=128)),
('slug', models.SlugField(unique=True)),
('url', models.URLField()),
('description', models.TextField(blank=True, verbose_name='Description')),
('summary', models.TextField(blank=True, help_text='Short, one- or two-sentence version of description, used on list pages.')),
('screenshot', sorl.thumbnail.fields.ImageField(blank=True, help_text='Resized to fit 350x250 box in template', null=True, upload_to='img/uploads/code_screenshots')),
('repo_last_push', models.DateTimeField(blank=True, null=True)),
('repo_forks', models.PositiveIntegerField(blank=True, null=True)),
('repo_watchers', models.PositiveIntegerField(blank=True, null=True)),
('repo_master_branch', models.CharField(blank=True, max_length=64)),
('repo_description', models.TextField(blank=True)),
],
options={
'ordering': ('slug',),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='CodeLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=128)),
('url', models.URLField()),
('code', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='code.Code')),
],
options={
'verbose_name': 'Code Link',
'ordering': ('code', 'name'),
},
bases=(caching.base.CachingMixin, models.Model),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,911
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/forms.py
|
from django import forms
REPO_DIFFICULTY_CHOICES = [
('1', 'Super easy'), ('2', 'Pretty easy'), ('3', 'A little tricky'), ('4', 'Kinda hard'),
]
class SuggestRepoForm(forms.Form):
repo_submitter_name = forms.CharField(label='Name', max_length=128, required=True)
repo_submitter_email = forms.EmailField(label='Email', required=True)
repo_name = forms.CharField(max_length=128, required=True)
repo_type = forms.CharField(max_length=128, required=True)
repo_purpose = forms.CharField(max_length=256, required=True)
repo_credits = forms.CharField(max_length=128, required=True)
repo_difficulty = forms.ChoiceField(choices=REPO_DIFFICULTY_CHOICES, required=False)
repo_prerequisites = forms.CharField(max_length=256, required=False)
repo_description = forms.CharField(widget=forms.Textarea(attrs={'rows': 10, 'cols': 30}), required=False)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,912
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/code/views.py
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render
from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.generic import ListView, DetailView, View
from django.views.generic.edit import FormView
from .forms import SuggestRepoForm, REPO_DIFFICULTY_CHOICES
from .models import Code
from source.tags.utils import filter_queryset_by_tags
from source.utils.email import send_multipart_email
from source.utils.pagination import paginate
class CodeList(ListView):
model = Code
template_name = 'code/_v2/code_list.html'
def dispatch(self, *args, **kwargs):
self.render_json = kwargs.get('render_json', False)
self.tag_slugs = kwargs.get('tag_slugs', None)
self.tags = []
return super(CodeList, self).dispatch(*args, **kwargs)
def get_queryset(self):
queryset = Code.live_objects.all()
if self.tag_slugs:
queryset, self.tags = filter_queryset_by_tags(queryset, self.tag_slugs, self.tags)
return queryset
def get_context_data(self, **kwargs):
context = super(CodeList, self).get_context_data(**kwargs)
context['active_nav'] = 'Code'
# FEATURED REPOS
featured_repos = Code.live_objects.filter(is_featured=True).order_by('?')
try:
featured_repos = featured_repos[:3]
except:
featured_repos = None
context['featured_repos'] = featured_repos
# RECENT REPOS
recent_repos = Code.live_objects.order_by('-created')
try:
recent_repos = recent_repos[:6]
except:
recent_repos = None
context['recent_repos'] = recent_repos
if self.tags:
context['tags'] = self.tags
#context['rss_link'] = reverse('code_list_by_tag_feed', kwargs={'tag_slugs': self.tag_slugs})
#context['json_link'] = reverse('code_list_by_tag_feed_json', kwargs={'tag_slugs': self.tag_slugs})
else:
context['rss_link'] = reverse('code_list_feed')
context['json_link'] = reverse('code_list_feed_json')
# No pagination required for current alpha list display
#page, paginator = paginate(self.request, self.object_list, 50)
#context.update({
# 'page': page,
# 'paginator': paginator
#})
return context
def render_to_response(self, context):
if self.render_json:
'''
JSON export runs through a hand-rolled template for now, so we can
attach things like related names and urls. If we start doing more
with providing JSON, we should definitly go full django-tastypie.
'''
context['HTTP_PROTOCOL'] = getattr(settings, 'HTTP_PROTOCOL', 'https')
if 'callback' in self.request.GET:
# provide jsonp support for requests
# with ?callback=foo paramater
context['jsonp_callback'] = self.request.GET['callback']
return render(
self.request,
'code/code_list.json',
context,
content_type='application/json'
)
return super(CodeList, self).render_to_response(context)
class CodeDetail(DetailView):
model = Code
template_name = 'code/_v2/code_detail.html'
def get_queryset(self):
queryset = Code.live_objects.prefetch_related('codelink_set', 'people', 'organizations', 'article_set')
return queryset
def get_context_data(self, **kwargs):
context = super(CodeDetail, self).get_context_data(**kwargs)
recent_repos = Code.live_objects.order_by('-created')
try:
recent_repos = recent_repos[:6]
except:
recent_repos = None
context['recent_repos'] = recent_repos
featured_repos = Code.live_objects.filter(is_featured=True).exclude(pk=self.object.pk).order_by('?')
try:
featured_repos = featured_repos[:3]
except:
featured_repos = None
context['featured_repos'] = featured_repos
return context
class CodeSuggestRepo(FormView):
'''
Readers can suggest a repository to add to the Code list, generating
an email to the editorial team.
'''
template_name = "code/_v2/suggest_repo.html"
form_class = SuggestRepoForm
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
data=form.cleaned_data
# human-friendly version of `repo_difficulty` form value
try:
data['repo_difficulty'] = dict(REPO_DIFFICULTY_CHOICES)[data['repo_difficulty']]
except:
pass
email_context = {
'data': data
}
# render text and html versions of email body
# both plain txt for now
text_content = render_to_string(
'code/_v2/emails/suggest_repo.txt',
email_context,
)
html_content = render_to_string(
'code/_v2/emails/suggest_repo.html',
email_context
)
send_multipart_email(
subject = 'Source: Repo submission from a reader',
from_email = settings.DEFAULT_FROM_EMAIL,
to = settings.EDITORIAL_EMAIL,
text_content = text_content,
html_content = html_content
)
context.update({'success': 'True'})
return render(self.request, self.template_name, context)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,913
|
OpenNews/opennews-source
|
refs/heads/master
|
/config/settings/common.py
|
# -*- coding: utf-8 -*-
"""
Django settings for source project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_literals
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)
APPS_DIR = ROOT_DIR.path('source')
env = environ.Env()
# APP CONFIGURATION
# ------------------------------------------------------------------------------
DJANGO_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.flatpages',
'django.contrib.humanize',
'django.contrib.messages',
'django.contrib.redirects',
'django.contrib.sessions',
'django.contrib.sites',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
)
LOCAL_APPS = (
'source.base',
'source.articles',
'source.code',
'source.guides',
'source.jobs',
'source.people',
'source.tags',
)
THIRD_PARTY_APPS = (
'caching',
'haystack',
'sorl.thumbnail',
'taggit',
'django_jinja',
'storages',
'lockdown',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS
# MIDDLEWARE CONFIGURATION
# ------------------------------------------------------------------------------
MIDDLEWARE_CLASSES = (
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'source.utils.auth.SesameAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
# MIGRATIONS CONFIGURATION
# ------------------------------------------------------------------------------
MIGRATION_MODULES = {
'sites': 'source.contrib.sites.migrations'
}
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', False)
# FIXTURE CONFIGURATION
# ------------------------------------------------------------------------------
FIXTURE_DIRS = (
str(APPS_DIR.path('fixtures')),
)
# EMAIL CONFIGURATION
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='Source <source@opennews.org>')
# MANAGER CONFIGURATION
# ------------------------------------------------------------------------------
ADMINS = [
('Ryan Pitts', 'ryan@opennews.org'),
]
MANAGERS = ADMINS
EDITORIAL_EMAIL = ['ryan@opennews.org', 'source@opennews.org']
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
'default': env.db("DATABASE_URL", default="postgres:///newsource"),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
# GENERAL CONFIGURATION
# ------------------------------------------------------------------------------
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = False
USE_TZ = False
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
from django_jinja.builtins import DEFAULT_EXTENSIONS
TEMPLATES = [
{
'BACKEND': 'django_jinja.backend.Jinja2',
'DIRS': [
str(APPS_DIR + app.split('.')[1] + 'templates') for app in LOCAL_APPS
],
'OPTIONS': {
'debug': DEBUG,
'match_extension': '.html',
'match_regex': r'^(?!admin/).*',
'auto_reload': DEBUG,
'extensions': DEFAULT_EXTENSIONS,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'source.base.context_processors.globals',
],
}
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(APPS_DIR.path('templates')),
str(APPS_DIR + 'base/templates'),
],
'OPTIONS': {
'debug': DEBUG,
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'source.base.context_processors.globals',
],
},
},
]
KEEP_DJANGO_TEMPLATES = ['admin', 'debug_toolbar',]
# STATIC FILE CONFIGURATION
# ------------------------------------------------------------------------------
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
str(APPS_DIR.path('static')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# MEDIA CONFIGURATION
# ------------------------------------------------------------------------------
MEDIA_ROOT = str(APPS_DIR('media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
#MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_S3_ACCESS_KEY_ID = env.str('AWS_S3_ACCESS_KEY_ID', None)
AWS_S3_SECRET_ACCESS_KEY = env.str('AWS_S3_SECRET_ACCESS_KEY', None)
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
AWS_STORAGE_BUCKET_NAME = 'media.opennews.org'
from boto.s3.connection import OrdinaryCallingFormat
AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()
MEDIA_URL = 'https://media.opennews.org/'
THUMBNAIL_PRESERVE_FORMAT = True
THUMBNAIL_DEBUG = DEBUG
# URL Configuration
# ------------------------------------------------------------------------------
ROOT_URLCONF = 'config.urls'
WSGI_APPLICATION = 'config.wsgi.application'
# AUTHENTICATION CONFIGURATION
# ------------------------------------------------------------------------------
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'source.utils.auth.SesameModelBackend',
)
# SLUGLIFIER
AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'
# Location of root django.contrib.admin URL, use {% url 'admin:index' %}
ADMIN_URL = r'^admin/'
# common stuff, 3rd party library settings
ENGAGE_ROBOTS = env.bool('ENGAGE_ROBOTS', False)
CACHE_MIDDLEWARE_SECONDS = 60*15
FEED_CACHE_SECONDS = 60*15
# Search with django-haystack
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
# Lockdown
LOCKDOWN_ENABLED = env.bool('LOCKDOWN_ENABLED', False)
if LOCKDOWN_ENABLED:
LOCKDOWN_PASSWORDS = env.list('LOCKDOWN_PASSWORDS',[])
LOCKDOWN_LOGOUT_KEY = 'logout'
MIDDLEWARE_CLASSES += ('lockdown.middleware.LockdownMiddleware',)
TWITTER_CONSUMER_KEY = env.str('TWITTER_CONSUMER_KEY', None)
TWITTER_CONSUMER_SECRET = env.str('TWITTER_CONSUMER_SECRET', None)
TWITTER_ACCESS_TOKEN = env.str('TWITTER_ACCESS_TOKEN', None)
TWITTER_ACCESS_TOKEN_SECRET = env.str('TWITTER_ACCESS_TOKEN_SECRET', None)
JOBS_TWITTER_CONSUMER_KEY = env.str('JOBS_TWITTER_CONSUMER_KEY', None)
JOBS_TWITTER_CONSUMER_SECRET = env.str('JOBS_TWITTER_CONSUMER_SECRET', None)
JOBS_TWITTER_ACCESS_TOKEN = env.str('JOBS_TWITTER_ACCESS_TOKEN', None)
JOBS_TWITTER_ACCESS_TOKEN_SECRET = env.str('JOBS_TWITTER_ACCESS_TOKEN_SECRET', None)
GITHUB_CLIENT_ID = env.str('GITHUB_CLIENT_ID', None)
GITHUB_CLIENT_SECRET = env.str('GITHUB_CLIENT_SECRET', None)
SLACK_TOKEN = env.str('SLACK_TOKEN', None)
# sorl-thumbnail settings
DEFAULT_IMAGE_SRC = 'img/missing.png'
TIME_ZONE='America/Chicago'
HTTP_PROTOCOL = 'https'
BASE_SITE_URL = 'https://source.opennews.org'
SESAME_MAX_AGE = 5 * 60 # 5 minutes
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,914
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/base/urls.py
|
from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from django.views.decorators.cache import cache_page
from django.views.generic.base import RedirectView
from .feeds import ArticleFeed, RecentArticleSummaryFeed
from .views import SourceSearchView, HomepageView, SlackMessageView
from haystack.forms import SearchForm
from haystack.query import SearchQuerySet
from haystack.views import search_view_factory
from source.articles.views import ArticleList, ArticleDetail, ArticleRedirectView
from source.utils.caching import ClearCache
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60*15)
FEED_CACHE_TIME = getattr(settings, 'FEED_CACHE_SECONDS', 60*60)
BASE_URLS = [
url(
regex = '^$',
view = cache_page(STANDARD_CACHE_TIME)(HomepageView.as_view()),
kwargs = {},
name = 'homepage',
),
url(r'^articles/', include('source.articles.urls')),
url(r'^code/', include('source.code.urls')),
url(r'^guides/', include('source.guides.urls')),
url(r'^jobs/', include('source.jobs.urls')),
url(r'^community/', include('source.people.urls.community')),
url(r'^organizations/', include('source.people.urls.organizations')),
url(r'^people/', include('source.people.urls.people')),
url(
regex = '^search/$',
view = search_view_factory(view_class=SourceSearchView, form_class=SearchForm),
kwargs = {},
name = 'haystack_search',
),
url(
regex = '^clear-cache/$',
view = ClearCache.as_view(),
kwargs = {},
name = 'clear_cache',
),
url(
regex = '^send-to-slack/$',
view = SlackMessageView.as_view(),
kwargs = {},
name = 'send_to_slack',
),
url(
regex = '^rss/$',
view = cache_page(FEED_CACHE_TIME)(ArticleFeed()),
kwargs = {},
name = 'homepage_feed',
),
url(
regex = '^rss/recent-summaries/$',
view = cache_page(FEED_CACHE_TIME)(RecentArticleSummaryFeed()),
kwargs = {},
name = 'recent_summaries_feed',
),
url(
regex = '^category/(?P<category>[-\w]+)/$',
view = cache_page(STANDARD_CACHE_TIME)(ArticleList.as_view()),
kwargs = {},
name = 'article_list_by_category',
),
url(
regex = '^category/(?P<category>[-\w]+)/rss/$',
view = cache_page(FEED_CACHE_TIME)(ArticleFeed()),
kwargs = {},
name = 'article_list_by_category_feed',
),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
url(r'^auth/logout/$', auth_views.logout, name='logout'),
url(r'^accounts/login/$', RedirectView.as_view(url='/admin/login/')),
# fallback for old section-based URLs
#url(
# regex = '^(?P<section>[-\w]+)/$',
# view = RedirectView.as_view(url='/articles/'),
# #view = cache_page(STANDARD_CACHE_TIME)(ArticleList.as_view()),
# kwargs = {},
# name = 'article_list_by_section',
#),
# leaving this in place for section-specific feeds
url(
regex = '^([-\w]+)/rss/$',
#regex = '^(?P<section>[-\w]+)/rss/$',
view = RedirectView.as_view(url='/rss/'),
#view = cache_page(FEED_CACHE_TIME)(ArticleFeed()),
kwargs = {},
name = 'article_list_by_section_feed',
),
url(
regex = '^(?P<section>[-\w]+)/(?P<slug>[-\w]+)/$',
view = ArticleRedirectView.as_view(),
#view = cache_page(STANDARD_CACHE_TIME)(ArticleDetail.as_view()),
kwargs = {},
name = 'article_detail_by_section',
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,915
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/migrations/0003_auto_20160128_0100.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
from django.db import migrations, models
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('articles', '0002_article_code'),
('taggit', '0002_auto_20150616_2121'),
('tags', '0001_initial'),
('people', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='concept_tags',
field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags describing relevant concepts', through='tags.ConceptTaggedItem', to='tags.ConceptTag', verbose_name='Concept Tags'),
),
migrations.AddField(
model_name='article',
name='organizations',
field=models.ManyToManyField(blank=True, to='people.Organization'),
),
migrations.AddField(
model_name='article',
name='people',
field=models.ManyToManyField(blank=True, to='people.Person'),
),
migrations.AddField(
model_name='article',
name='tags',
field=taggit.managers.TaggableManager(blank=True, help_text='Automatic combined list of Technology Tags and Concept Tags, for easy searching', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
migrations.AddField(
model_name='article',
name='technology_tags',
field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags describing relevant technologies', through='tags.TechnologyTaggedItem', to='tags.TechnologyTag', verbose_name='Technology Tags'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,916
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/guides/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
import caching.base
import datetime
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('articles', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Guide',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('is_live', models.BooleanField(default=True, verbose_name='Display on site')),
('show_in_lists', models.BooleanField(default=True, verbose_name='Show in lists')),
('title', models.CharField(max_length=128)),
('slug', models.SlugField(unique=True)),
('pubdate', models.DateTimeField(default=datetime.datetime.now)),
('image', sorl.thumbnail.fields.ImageField(blank=True, help_text='Resized to fit 100% column width in template', null=True, upload_to='img/uploads/guide_images')),
('image_caption', models.TextField(blank=True)),
('image_credit', models.CharField(blank=True, help_text='Optional. Will be appended to end of caption in parens. Accepts HTML.', max_length=128)),
('description', models.TextField(blank=True, verbose_name='Description')),
('summary', models.TextField(blank=True, help_text='The two-sentence version of description, to be used on list pages.')),
('cover_color', models.CharField(blank=True, help_text='Hex code for background color of title card, e.g. `#256188`. Probably sampled from cover image.', max_length=32)),
],
options={
'ordering': ('-pubdate', 'title'),
},
bases=(caching.base.CachingMixin, models.Model),
),
migrations.CreateModel(
name='GuideArticle',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('external_url', models.URLField(blank=True, help_text='Paste a URL here to link to an article elsewhere (overrides `Article` URL above).', null=True)),
('external_title', models.CharField(blank=True, help_text='Display title for link to article elsewhere (overrides `Article` title above).', max_length=128)),
('order', models.PositiveIntegerField(blank=True, db_index=True, default=1, help_text="A '1' will appear first, a '2' will appear second, and so on.")),
('article_notes', models.TextField(blank=True, help_text='Optional field for telling readers why this article is part of this guide.')),
('article', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='articles.Article')),
('guide', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='guides.Guide')),
],
options={
'verbose_name': 'Guide Article',
'ordering': ('guide', 'order'),
},
bases=(caching.base.CachingMixin, models.Model),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,917
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/forms.py
|
from django import forms
class SuggestArticleForm(forms.Form):
article_submitter_name = forms.CharField(label='Name', max_length=128, required=True)
article_submitter_email = forms.EmailField(label='Email', required=True)
article_description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 30}), required=True)
article_draft = forms.CharField(widget=forms.Textarea(attrs={'rows': 10, 'cols': 30}), required=False)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,918
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/guides/migrations/0002_auto_20170123_1809.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-23 18:09
from __future__ import unicode_literals
from django.db import migrations, models
import sorl.thumbnail.fields
class Migration(migrations.Migration):
dependencies = [
('guides', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='guide',
name='author_bio',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='guide',
name='author_name',
field=models.CharField(blank=True, max_length=128),
),
migrations.AddField(
model_name='guide',
name='author_photo',
field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='img/uploads/guide_author_images'),
),
migrations.AddField(
model_name='guidearticle',
name='external_author_name',
field=models.CharField(blank=True, max_length=128),
),
migrations.AddField(
model_name='guidearticle',
name='external_organization_name',
field=models.CharField(blank=True, max_length=128),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,919
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/people/admin.py
|
from django.contrib import admin
from .models import Person, PersonLink, Organization, OrganizationLink, OrganizationAdmin
#from sorl.thumbnail.admin import AdminImageMixin
from source.utils.widgets.thumbnail import AdminImageMixin
class PersonLinkInline(admin.StackedInline):
model = PersonLink
extra = 1
fieldsets = (
('', {'fields': (('name', 'url'),)}),
)
def formfield_for_dbfield(self, db_field, **kwargs):
# More usable width in admin form field for names
field = super(PersonLinkInline, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'name':
field.widget.attrs['style'] = 'width: 30em;'
return field
class PersonAdmin(admin.ModelAdmin):
save_on_top = True
prepopulated_fields = {'slug': ('first_name', 'last_name')}
list_filter = ('is_live', 'show_in_lists',)
list_display = ('name', 'is_live', 'show_in_lists', 'admin_email_tag', 'admin_twitter_tag', 'admin_github_tag', 'admin_image_tag',)
list_editable = ('is_live', 'show_in_lists',)
filter_horizontal = ('organizations',)
search_fields = ('first_name', 'last_name', 'description',)
fieldsets = (
('', {'fields': (('first_name', 'last_name', 'slug'), ('is_live', 'show_in_lists'), 'email', 'photo', 'description',)}),
('Accounts', {'fields': ('twitter_username', 'twitter_bio', 'twitter_profile_image_url', 'github_username', ('github_repos_num', 'github_gists_num'),)}),
('Related objects', {'fields': ('organizations',)}),
)
inlines = [PersonLinkInline,]
class OrganizationLinkInline(admin.StackedInline):
model = OrganizationLink
extra = 1
fieldsets = (
('', {'fields': (('name', 'url',),)}),
)
def formfield_for_dbfield(self, db_field, **kwargs):
# More usable width in admin form field for names
field = super(OrganizationLinkInline, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'name':
field.widget.attrs['style'] = 'width: 30em;'
return field
class OrganizationAdminInline(admin.StackedInline):
model = OrganizationAdmin
extra = 1
fieldsets = (
('', {'fields': ('email',),}),
)
class OrgAdmin(AdminImageMixin, admin.ModelAdmin):
save_on_top = True
prepopulated_fields = {'slug': ('name',)}
list_filter = ('is_live', 'country', 'state',)
list_display = ('name', 'is_live', 'show_in_lists', 'admin_image_tag', 'location', 'admin_twitter_tag', 'admin_github_tag', 'admin_count')
list_editable = ('is_live', 'show_in_lists',)
search_fields = ('name', 'description', 'city', 'state', 'country', 'organizationadmin__email',)
fieldsets = (
('', {'fields': (('name', 'slug'), ('is_live', 'show_in_lists'), 'email', 'twitter_username', 'github_username', ('github_repos_num', 'github_gists_num'), 'homepage', 'logo', 'description',)}),
('Location', {'fields': ('address', ('city', 'state',), 'country',)}),
)
inlines = [OrganizationAdminInline, OrganizationLinkInline,]
admin.site.register(Person, PersonAdmin)
admin.site.register(Organization, OrgAdmin)
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,920
|
OpenNews/opennews-source
|
refs/heads/master
|
/source/articles/migrations/0005_auto_20170206_2215.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-02-06 22:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0004_article_is_featured'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'get_latest_by': 'pubdate', 'ordering': ('-pubdate', 'title')},
),
migrations.AddField(
model_name='article',
name='lead_image_has_border',
field=models.BooleanField(default=False, verbose_name='Put a border on lead image'),
),
]
|
{"/source/utils/caching.py": ["/source/utils/json.py"], "/source/people/models.py": ["/source/base/utils.py", "/source/utils/auth.py", "/source/utils/caching.py"], "/source/code/urls.py": ["/source/code/views.py"], "/source/people/management/commands/migrate_org_admins.py": ["/source/people/models.py"], "/config/settings/production.py": ["/config/settings/common.py"], "/source/articles/urls.py": ["/source/articles/views.py"], "/config/settings/local.py": ["/config/settings/common.py"], "/source/people/urls/community.py": ["/source/people/views.py"], "/source/base/views.py": ["/source/articles/views.py", "/source/people/models.py", "/source/utils/json.py"], "/source/jobs/urls.py": ["/source/jobs/views.py"], "/source/people/management/commands/export_people_data.py": ["/source/people/models.py"], "/source/people/views.py": ["/source/people/models.py", "/source/utils/json.py"], "/config/urls.py": ["/source/base/views.py"], "/source/articles/views.py": ["/source/articles/forms.py"], "/source/jobs/views.py": ["/source/base/helpers.py", "/source/people/models.py", "/source/utils/caching.py", "/source/utils/json.py"], "/source/guides/views.py": ["/source/guides/forms.py"], "/source/code/views.py": ["/source/code/forms.py"], "/source/base/urls.py": ["/source/base/views.py", "/source/articles/views.py", "/source/utils/caching.py"], "/source/people/admin.py": ["/source/people/models.py"]}
|
34,949
|
jsanchezsalcedo/projectManagerForMaya
|
refs/heads/master
|
/prm_utils.py
|
import os
import maya.cmds as cmds
def getProjectFolder():
path = cmds.workspace(q=True, sn=True)
return path
def getFileInfo():
file = cmds.file(q=True, sn=True, shn=True)
name, ext = os.path.splitext(file)
try:
name, version = name.split('_v')
except ValueError:
name, version = name.split('-v')
version = int(version) + int(1)
return name, version, ext
def getNameConvention():
project = os.getenv('PRJ')
projectCode = project.split('__')[0]
directoryB = os.getenv('DIR_B')
directoryC = os.getenv('DIR_C')
department = os.getenv('DPT')
nameConvention = projectCode + '-' + directoryB + '-' + directoryC + '-' + department + '-'
return nameConvention
def createWorkspace():
path = getProjectFolder()
cmds.workspace(path, o=True)
fileRuleDict = {
'scene': 'scenes',
'sourceImages': 'images',
'images': 'render',
'iprImages': 'render/tmp',
'ASS': 'cache',
'Alembic': 'cache',
'FBX': 'cache',
'OBJ': 'cache',
'autoSave': 'tmp',
'sceneAssembly': 'scenes',
'mayaAscii': 'scenes',
'mayaBinary': 'scenes',
'offlineEdit': 'scenes',
'ASS Export': 'cache',
'FBX export': 'cache',
'OBJexport': 'cache'
}
for k, v in fileRuleDict.iteritems():
cmds.workspace(fileRule=[k, v])
cmds.workspace(s=True)
cmds.workspace(ua=True)
def createVersion():
path = getProjectFolder()
name, version, ext = getFileInfo()
name = getNameConvention()
versionName = name + 'v' + str('%03d' % version) + ext
versionPath = os.path.join(path, 'version', versionName)
cmds.file(rn=versionPath)
cmds.file(s=True, type='mayaAscii')
print ' '
print ' > You have created ' + name + 'v' + str('%03d' % version) + ext + ' successfully.'
print ' '
def createFolder():
pass
def publishAsset():
path = getProjectFolder()
name, version, ext = getFileInfo()
name = getNameConvention()
maName = name + 'main' + ext
maPath = os.path.join(path, maName)
geoName = name + 'geo.fbx'
geoPath = os.path.join(path, 'cache', geoName)
idName = name + 'id.fbx'
idPath = os.path.join(path, 'cache', idName)
versionName = name + 'v' + str('%03d' % version) + ext
versionPath = os.path.join(path, 'version', versionName)
print ' '
print ' > You have published:'
geo = []
for i in cmds.ls('ASSETS'):
for i in cmds.ls('*_geo*'):
geo.append(i)
cmds.select(geo)
try:
cmds.file(rn=maPath)
cmds.file(es=True, f=True, type='mayaAscii')
print ' > ' + maName
except RuntimeError:
pass
try:
cmds.file(rn=geoPath)
cmds.file(es=True, f=True, type='FBX export')
print ' > ' + geoName
except RuntimeError:
pass
cmds.select(d=True)
id = []
for i in cmds.ls('ASSETS'):
for i in cmds.ls('*_id*'):
id.append(i)
cmds.select(id)
try:
cmds.file(rn=idPath)
cmds.file(es=True, f=True, type='FBX export')
print ' > ' + idName
except RuntimeError:
pass
cmds.select(d=True)
cmds.file(rn=versionPath)
cmds.file(s=True, type='mayaAscii')
print ' '
print ' > You have created ' + versionName + ' successfully.'
print ' '
|
{"/prm_ui.py": ["/prm_core.py", "/prm_utils.py"]}
|
34,950
|
jsanchezsalcedo/projectManagerForMaya
|
refs/heads/master
|
/prm_ui.py
|
import os
import time
import maya.cmds as cmds
from maya import OpenMayaUI as omui
import prm_core as core
import prm_utils as util
try:
from PySide2 import QtCore, QtWidgets, QtGui
from shiboken2 import wrapInstance
except ImportError:
from PySide import QtCore, QtGui, QtWidgets
from shiboken import wrapInstance
mainWindow = None
__title__ = 'Project Manager for Maya'
__version__ = 'v3.0.0'
print('')
print(' > {} {}' . format(__title__, __version__))
print(' > Jorge Sanchez Salcedo, 2020')
print(' > www.jorgesanchez-da.com')
print('')
def getMainWindow():
ptr = omui.MQtUtil.mainWindow()
mainWindow = wrapInstance(long(ptr), QtWidgets.QMainWindow)
return mainWindow
class ProjectManagerUI(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(ProjectManagerUI, self).__init__(parent)
self.setWindowTitle('{} {}'.format(__title__, __version__))
self.setMinimumWidth(640)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
core.ProjectManager().checkedFolders()
self.buildUI()
self.setProject()
def buildUI(self):
projectManagerWidget = QtWidgets.QWidget()
mainLayout = QtWidgets.QVBoxLayout(projectManagerWidget)
mainLayout.setContentsMargins(2,2,2,2)
mainLayout.setAlignment(QtCore.Qt.AlignTop)
rootFolderWidget = QtWidgets.QWidget()
rootFolderLayout = QtWidgets.QHBoxLayout(rootFolderWidget)
rootFolderLayout.setAlignment(QtCore.Qt.AlignTop)
rootFolderLayout.setContentsMargins(2,2,2,2)
self.rootFolder = QtWidgets.QLineEdit()
self.rootFolder.setText(os.getenv('ROOT'))
self.rootFolder.setEnabled(False)
rootFolderLayout.addWidget(self.rootFolder)
mainLayout.addWidget(rootFolderWidget)
projectWidget = QtWidgets.QWidget()
projectLayout = QtWidgets.QHBoxLayout(projectWidget)
projectLayout.setAlignment(QtCore.Qt.AlignTop)
projectLayout.setContentsMargins(2,2,2,2)
projects = core.ProjectManager().getProjectFolders()
self.projectCb = QtWidgets.QComboBox()
self.projectCb.addItems(projects)
self.projectCb.setItemText(0, os.getenv('PRJ'))
projectLayout.addWidget(self.projectCb)
self.projectCb.currentTextChanged.connect(self.updateProjectFolder)
mainLayout.addWidget(projectWidget)
folderWidget = QtWidgets.QWidget()
folderLayout = QtWidgets.QHBoxLayout(folderWidget)
folderLayout.setAlignment(QtCore.Qt.AlignTop)
folderLayout.setContentsMargins(2,2,2,2)
foldersA = core.ProjectManager().getFoldersA()
self.folderACb = QtWidgets.QComboBox()
self.folderACb.addItems(foldersA)
self.folderACb.setItemText(0, os.getenv('FLDA'))
folderLayout.addWidget(self.folderACb)
self.folderACb.currentTextChanged.connect(self.updateFolderA)
foldersB = core.ProjectManager().getFoldersB()
self.folderBCb = QtWidgets.QComboBox()
self.folderBCb.addItems(foldersB)
self.folderBCb.setItemText(0, os.getenv('FLDB'))
folderLayout.addWidget(self.folderBCb)
self.folderBCb.currentTextChanged.connect(self.updateFolderB)
foldersC = core.ProjectManager().getFoldersC()
self.folderCCb = QtWidgets.QComboBox()
self.folderCCb.addItems(foldersC)
self.folderCCb.setItemText(0, os.getenv('FLDC'))
folderLayout.addWidget(self.folderCCb)
self.folderCCb.currentTextChanged.connect(self.setProject)
mainLayout.addWidget(folderWidget)
filesTableWidget = QtWidgets.QWidget()
filesTableLayout = QtWidgets.QVBoxLayout(filesTableWidget)
filesTableLayout.setAlignment(QtCore.Qt.AlignTop)
filesTableLayout.setContentsMargins(2,2,2,2)
self.filesTable = QtWidgets.QTableWidget()
self.filesTable.horizontalHeader().setVisible(True)
self.filesTable.verticalHeader().setVisible(False)
self.filesTable.setColumnCount(4)
self.filesTable.setColumnWidth(0, 375)
self.filesTable.setColumnWidth(1, 90)
self.filesTable.setColumnWidth(2, 150)
headerLabels = (['Name', 'Type', 'Date Modified'])
self.filesTable.setHorizontalHeaderLabels(headerLabels)
self.filesTable.setAlternatingRowColors(True)
self.filesTable.setSortingEnabled(True)
self.filesTable.setShowGrid(False)
self.filesTable.itemDoubleClicked.connect(self.checkFileState)
filesTableLayout.addWidget(self.filesTable)
mainLayout.addWidget(filesTableWidget)
statusBarWidget = QtWidgets.QStatusBar()
statusBarLayout = QtWidgets.QHBoxLayout(statusBarWidget)
statusBarLayout.setAlignment(QtCore.Qt.AlignTop)
statusBarLayout.setContentsMargins(2,2,2,2)
statusBarWidget.showMessage('Ready')
mainLayout.addWidget(statusBarWidget)
self.setCentralWidget(projectManagerWidget)
def updateProjectFolder(self):
os.environ['PRJ'] = self.projectCb.currentText()
self.folderACb.clear()
try:
foldersA = core.ProjectManager().getFoldersA()
except IndexError:
foldersA = ['']
self.folderACb.addItems(foldersA)
def updateFolderA(self):
os.environ['FLDA'] = self.folderACb.currentText()
self.folderBCb.clear()
try:
foldersB = core.ProjectManager().getFoldersB()
except IndexError:
foldersB = ['']
self.folderBCb.addItems(foldersB)
def updateFolderB(self):
os.environ['FLDB'] = self.folderBCb.currentText()
self.folderCCb.clear()
try:
foldersC = core.ProjectManager().getFoldersC()
except IndexError:
foldersC = ['']
self.folderCCb.addItems(foldersC)
def setProject(self):
os.environ['FLDC'] = self.folderCCb.currentText()
projectPath = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'), os.getenv('FLDA'), os.getenv('FLDB'), os.getenv('FLDC'), 'working')
try:
cmds.workspace(dir=projectPath)
cmds.workspace(projectPath, o=True)
cmds.workspace(q=True, sn=True)
cmds.workspace(ua=True)
except RuntimeError:
pass
self.populate()
def populate(self):
self.filesTable.clearContents()
filesPath = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'), os.getenv('FLDA'), os.getenv('FLDB'), os.getenv('FLDC'), 'working','scenes')
mayaFiles = sorted(core.ProjectManager().getMayaFiles())
try:
for i in mayaFiles:
filePath = os.path.join(filesPath, i)
name, ext = os.path.splitext(i)
if ext == '.ma':
ext = 'Maya ASCII'
elif ext == '.mb':
ext = 'Maya Binary'
item = QtWidgets.QTableWidgetItem(name)
item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
itemType = str(ext)
type = QtWidgets.QTableWidgetItem(itemType)
type.setFlags(QtCore.Qt.ItemIsEnabled)
itemDate = str(time.strftime('%d/%m/%Y %H:%M', time.gmtime(os.path.getmtime(filePath))))
date = QtWidgets.QTableWidgetItem(itemDate)
date.setFlags(QtCore.Qt.ItemIsEnabled)
self.filesTable.insertRow(0)
self.filesTable.setItem(0, 0, item)
self.filesTable.setItem(0, 1, type)
self.filesTable.setItem(0, 2, date)
except TypeError:
pass
def checkFileState(self):
fileState = cmds.file(q=True, mf=True)
if fileState == True:
self.warningBoxUI()
else:
self.openScene()
def warningBoxUI(self):
warningBox = QtWidgets.QMessageBox()
warningBox.setWindowTitle('Warning: Scene Not Saved')
warningBox.setText('The file has been modified. Do you want to save changes?')
warningSaveBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Save)
warningDiscardBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Discard)
warningCancelBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Cancel)
warningBox.setStandardButtons(warningSaveBtn | warningDiscardBtn | warningCancelBtn)
warningBox.setDefaultButton(warningSaveBtn)
warning = warningBox.exec_()
if warning == warningSaveBtn:
self.saveScene()
elif warning == warningDiscardBtn:
self.openScene()
elif warning == warningCancelBtn:
self.cancel()
def openScene(self):
melFiles = core.ProjectManager().getMelFiles()
try:
if 'workspace.mel' not in melFiles:
util.createWorkspace()
currentScene = self.filesTable.currentItem()
getFileName = currentScene.text()
sceneName = getFileName + '.ma'
cmds.file(sceneName, o=True, f=True, typ='mayaAscii', op='v=0')
else:
currentScene = self.filesTable.currentItem()
getFileName = currentScene.text()
sceneName = getFileName + '.ma'
cmds.file(sceneName, o=True, f=True, typ='mayaAscii', op='v=0')
except RuntimeError:
pass
print(' ')
print(' > You just opened your scene successfully.')
print(' ')
self.close()
def saveScene(self):
cmds.file(s=True, f=True)
self.openScene()
print(' ')
print(' > You just saved your scene successfully.')
print(' ')
self.close()
def cancel(self):
print(' ')
print(' > You just canceled the process successfully.')
print(' ')
self.close()
def run():
global mainWindow
if not mainWindow or not cmds.window(mainWindow,q=True,e=True):
mainWindow = ProjectManagerUI(parent=getMainWindow())
mainWindow.show()
|
{"/prm_ui.py": ["/prm_core.py", "/prm_utils.py"]}
|
34,951
|
jsanchezsalcedo/projectManagerForMaya
|
refs/heads/master
|
/backupManagerUI.py
|
import os
import time
import maya.cmds as cmds
from maya import OpenMayaUI as omui
import projectManager
reload(projectManager)
try:
from PySide2 import QtCore, QtGui, QtWidgets
from shiboken2 import wrapInstance
except ImportError:
from PySide import QtCore, QtGui, QtWidgets
from shiboken import wrapInstance
mainWindow = None
__title__ = 'Backup Manager'
__version__ = 'v1.0.0'
print ' '
print ' > {} {}'.format(__title__,__version__)
print ' > by Jorge Sanchez Salcedo (2018)'
print ' > www.jorgesanchez-da.com'
print ' > jorgesanchez.da@gmail.com'
print ' '
directories = ['PRJ', 'DPT', 'DIR_A', 'DIR_B', 'DIR_C']
for dir in directories:
try:
os.getenv(dir)
except TypeError:
os.environ[dir] = None
def getMainWindow():
ptr = omui.MQtUtil.mainWindow()
mainWindow = wrapInstance(long(ptr), QtWidgets.QMainWindow)
return mainWindow
class BackupManagerUI(QtWidgets.QDialog):
def __init__(self, parent=None):
super(BackupManagerUI, self).__init__(parent)
self.setWindowTitle('{} {}'. format(__title__,__version__))
self.setWindowFlags(QtCore.Qt.Dialog)
self.setMinimumWidth(600)
self.setMinimumHeight(425)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.directories = projectManager.ProjectManager()
self.buildUI()
def buildUI(self):
mainLayout = QtWidgets.QVBoxLayout()
filesLy = QtWidgets.QVBoxLayout()
self.filesTableWidget = QtWidgets.QTableWidget()
self.filesTableWidget.horizontalHeader().setVisible(True)
self.filesTableWidget.verticalHeader().setVisible(False)
self.filesTableWidget.setColumnCount(4)
self.filesTableWidget.setColumnWidth(0, 260)
self.filesTableWidget.setColumnWidth(1, 75)
self.filesTableWidget.setColumnWidth(2, 90)
self.filesTableWidget.setColumnWidth(3, 125)
self.filesTableWidget.setHorizontalHeaderLabels(['Name', 'Version', 'Type', 'Date Modified'])
self.filesTableWidget.setAlternatingRowColors(True)
self.filesTableWidget.setSortingEnabled(True)
self.filesTableWidget.setShowGrid(False)
self.filesTableWidget.itemDoubleClicked.connect(self.openScene)
filesLy.addWidget(self.filesTableWidget)
mainLayout.addLayout(filesLy)
self.setLayout(mainLayout)
self.populate()
def populate(self):
self.filesTableWidget.clearContents()
backupPath = self.directories.getBackups()
backupFiles = self.directories.backupFiles()
try:
for i in backupFiles:
filePath = os.path.join(backupPath, i)
name, ext = os.path.splitext(i)
name, ver = name.split('.')
item = QtWidgets.QTableWidgetItem(name)
item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
itemVersion = ver
version = QtWidgets.QTableWidgetItem(itemVersion)
version.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
itemType = str('ma File')
type = QtWidgets.QTableWidgetItem(itemType)
type.setFlags(QtCore.Qt.ItemIsEnabled)
itemDate = str(time.strftime('%d/%m/%Y %H:%M', time.gmtime(os.path.getmtime(filePath))))
date = QtWidgets.QTableWidgetItem(itemDate)
date.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
self.filesTableWidget.insertRow(0)
self.filesTableWidget.setItem(0, 0, item)
self.filesTableWidget.setItem(0, 1, version)
self.filesTableWidget.setItem(0, 2, type)
self.filesTableWidget.setItem(0, 3, date)
except TypeError:
pass
def checkFileState(self):
fileState = cmds.file(q=True, mf=True)
if fileState == True:
self.warningBoxUI()
else:
self.openScene()
def warningBoxUI(self):
warningBox = QtWidgets.QMessageBox()
warningBox.setWindowTitle('Warning: Scene Not Saved')
warningBox.setText('The file has been modified. Do you want to save changes?')
warningSaveBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Save)
warningDiscardBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Discard)
warningCancelBtn = warningBox.StandardButton(QtWidgets.QMessageBox.Cancel)
warningBox.setStandardButtons(warningSaveBtn | warningDiscardBtn | warningCancelBtn)
warningBox.setDefaultButton(warningSaveBtn)
warning = warningBox.exec_()
if warning == warningSaveBtn:
self.saveScene()
elif warning == warningDiscardBtn:
self.openScene()
elif warning == warningCancelBtn:
self.cancel()
def openScene(self):
backupPath = self.directories.getBackups()
columns = self.filesTableWidget.columnCount()
row = self.filesTableWidget.currentRow()
for col in xrange(0, columns):
name = self.filesTableWidget.item(row, 0)
version = self.filesTableWidget.item(row, 1)
sceneName = name.text() + '.' + version.text() + '.ma'
path = os.path.join(backupPath, sceneName)
cmds.file(path, o=True, f=True, typ='mayaAscii', op='v=0')
print ' '
print ' > You have opened your scene successfully.'
print ' '
self.close()
def saveScene(self):
cmds.file(s=True, f=True)
self.openScene()
print ' '
print ' > You have saved your scene successfully.'
print ' '
self.close()
def cancel(self):
print ' '
print ' > You have canceled the process successfully.'
print ' '
self.close()
def run():
global mainWindow
if not mainWindow or not cmds.window(mainWindow,q=True,e=True):
mainWindow = BackupManagerUI(parent=getMainWindow())
mainWindow.show()
|
{"/prm_ui.py": ["/prm_core.py", "/prm_utils.py"]}
|
34,952
|
jsanchezsalcedo/projectManagerForMaya
|
refs/heads/master
|
/prm_core.py
|
import os
class ProjectManager(dict):
def checkedFolders(self):
folders = ['ROOT', 'PRJ', 'FLDA', 'FLDB', 'FLDC']
for i in folders:
if os.getenv(i) == None:
os.environ['ROOT'] = self.setProjectsRoot()
os.environ['PRJ'] = self.setProjectFolder()
os.environ['FLDA'] = self.setFolderA()
os.environ['FLDB'] = self.setFolderB()
os.environ['FLDC'] = self.setFolderC()
def setProjectsRoot(self):
os.environ['ROOT'] = root = '/Users/jsanchezsalcedo/Projects'
return root
def getProjectFolders(self):
root = self.setProjectsRoot()
projects = []
for i in os.listdir(root):
path = os.path.join(root, i)
if os.path.isdir(path):
projects.append(i)
return (sorted(projects))
def setProjectFolder(self):
project = self.getProjectFolders()[0]
if os.getenv('PRJ') == None:
os.environ['PRJ'] = project
else:
project = os.environ['PRJ']
return project
def getFolders(self):
folders = []
for i in os.listdir(self.path):
folderPath = os.path.join(self.path, i)
if os.path.isdir(folderPath):
folders.append(i)
return folders
def getFoldersA(self):
self.setProjectFolder()
self.path = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'))
foldersA = self.getFolders()
return (sorted(foldersA))
def setFolderA(self):
try:
folderA = self.getFoldersA()[0]
if os.getenv('FLDA') == None:
os.environ['FLDA'] = folderA
else:
folderA = os.environ['FLDA']
return folderA
except IndexError:
pass
def getFoldersB(self):
self.setFolderA()
self.path = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'), os.getenv('FLDA'))
foldersB = self.getFolders()
return (sorted(foldersB))
def setFolderB(self):
try:
folderB = self.getFoldersB()[0]
if os.getenv('FLDB') == None:
os.environ['FLDB'] = folderB
else:
folderB = os.environ['FLDB']
return folderB
except IndexError:
pass
def getFoldersC(self):
self.setFolderB()
self.path = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'), os.getenv('FLDA'), os.getenv('FLDB'))
foldersC = self.getFolders()
return (sorted(foldersC))
def setFolderC(self):
try:
folderC = self.getFoldersC()[0]
if os.getenv('FLDC') == None:
os.environ['FLDC'] = folderC
else:
folderC = os.environ['FLDC']
return folderC
except IndexError:
pass
def getProjectPath(self):
self.setFolderC()
projectPath = os.path.join(os.getenv('ROOT'), os.getenv('PRJ'), os.getenv('FLDA'), os.getenv('FLDB'), os.getenv('FLDC'), 'working')
return projectPath
def getMayaFiles(self):
projectPath = self.getProjectPath()
filesPath = os.path.join(projectPath, 'scenes')
mayaFiles = []
try:
files = os.listdir(filesPath)
mayaFiles = [f for f in files if f.endswith('.ma') or f.endswith('.mb')]
except OSError or WindowsError:
mayaFiles = []
return mayaFiles
def getMelFiles(self):
projectPath = self.getProjectPath()
melFiles = []
try:
files = os.listdir(projectPath)
melFiles = [f for f in files if f.endswith('.mel')]
except OSError or WindowsError:
melFiles = []
return melFiles
def getBackupsFiles(self):
projectPath = self.getProjectPath()
filesPath = os.path.join(projectPath, 'tmp')
backupFiles = []
try:
files = os.listdir(filesPath)
backupFiles = [f for f in files if f.endswith('.ma')]
except OSError or WindowsError:
backupFiles = []
return backupFiles
|
{"/prm_ui.py": ["/prm_core.py", "/prm_utils.py"]}
|
34,959
|
sWallyx/Bike-Hire-Analysis
|
refs/heads/master
|
/bike.py
|
from datetime import datetime, timedelta
from defaultParams import *
from miscFunctions import checkNaNValue
class Bike:
def __init__(self, id, arrival, departure):
self.id = id
self.arrivalTime = []
self.departureTime = []
self.averageTravelTime = 0
arrival = checkNaNValue(arrival)
self.arrivalTime.append(arrival)
departure = checkNaNValue(departure)
self.departureTime.append(departure)
def setTimes(self, arrival, departure):
"""
Adds arrival and departure times to the object
Arguments:
IN -- arrival {String}, departure {String}
"""
self.arrivalTime.append(arrival)
self.departureTime.append(departure)
def getFirstArrival(self):
"""
Returns the first arrival time. It is used to reutilize temporal object, and not duplicate bikes.
Arguments:
OUT -- arrival {String}
"""
return self.arrivalTime[0]
def getFirstDeparture(self):
"""
Returns the first arrival time. It is used to reutilize temporal object, and not duplicate bikes.
Arguments:
OUT -- arrival {String}
"""
return self.departureTime[0]
def printObject(self):
"""
Prints the object for debug purpose, not used in the application
"""
print(self.id, self.arrivalTime, self.departureTime, self.averageTravelTime)
def orderTimes(self):
"""
Orders all times, arrival and departures as ASC. Then check for missing times.
"""
self.arrivalTime.sort()
self.departureTime.sort()
self.checkTimeList()
def checkTimeList(self):
"""
Checks if there are missing datetimes. If there are, it adds the default time value.
"""
# Condition of a travel: Arrival > Departure; if false, fix the missing datetime record.
if (self.arrivalTime[0] < self.departureTime[0]):
self.departureTime.insert(0, DEFAULT_TIME_VALUE)
def calculateAverageTime(self):
"""
Call the update format function. And fill an array of travelTimes with the times of each trip.
"""
travelTimes = []
self.updateTimeFormat()
for i in range(len(self.arrivalTime)):
# If departure time maches with the default time. We dont need to calculate that trip, we dont know the real departure time
if(self.departureTime[i] != datetime.strptime(DEFAULT_TIME_VALUE, TIME_FORMAT)):
travelTimes.append(self.arrivalTime[i] - self.departureTime[i])
self.averageTravelTime = sum(travelTimes, timedelta()) / len(travelTimes)
# Make the DateTime variable more user friendly
self.averageTravelTime = str(self.averageTravelTime)
def updateTimeFormat(self):
"""
Update the format of the all time variables to Datetime from String
"""
for i in range(len(self.arrivalTime)):
self.arrivalTime[i] = datetime.strptime(self.arrivalTime[i], TIME_FORMAT)
for i in range(len(self.departureTime)):
self.departureTime[i] = datetime.strptime(self.departureTime[i], TIME_FORMAT)
|
{"/bike.py": ["/defaultParams.py", "/miscFunctions.py"], "/__main__.py": ["/bike.py"], "/miscFunctions.py": ["/defaultParams.py"]}
|
34,960
|
sWallyx/Bike-Hire-Analysis
|
refs/heads/master
|
/__main__.py
|
#!/usr/bin/python3
# coding=utf-8
import os
import pandas as pd
from bike import Bike
def readCSV(name):
"""
Function name: readCVS
Description: Using pandas reads the CSV, with no headers, indicated by param and returns it
Arguments:
IN -- route to CSV file
OUT -- data object
"""
CSVdata = pd.read_csv(name, header=None, encoding='utf-8-sig')
# print(CSVdata)
return CSVdata
def createObjects(csvData):
"""
Function name: createObjects
Description: Using the CSV file data, creates all bike objects with no duplicates.
Arguments:
IN -- CSV data
OUT -- Bike Objects
"""
bikes = []
# Get the number of records in the data
for i in range(len(csvData.index)):
# Create a temporal object
temporalBikeObject = Bike(csvData[1][i], csvData[2][i], csvData[3][i])
existingBike = checkIfExist(bikes, temporalBikeObject)
if(not existingBike):
# Add new bike to list
bikes.append(temporalBikeObject)
else:
# If the bike exists add times to existing bike
existingBike.setTimes(temporalBikeObject.getFirstArrival(),temporalBikeObject.getFirstDeparture())
return bikes
def checkIfExist(bikes, bikeToCheck):
"""
Function name: checkIfExist
Description: Checks if the ID of the bike already exist in the object list.
Arguments:
IN -- Bike list, bike object to check
OUT -- Bike object if exists, False if does not exist
"""
for bike in bikes:
if bikeToCheck.id == bike.id:
return bike
return False
def orderObjectsByTime(bikeObjects):
"""
Function name: orderObjectsByTime
Description: Calls the order function of each object.
Arguments:
IN -- Bike list
"""
for bike in bikeObjects:
bike.orderTimes()
def calculateBikeAverageTimes(bikeObjects):
"""
Function name: calculateBikeAverageTimes
Description: Calls the calculate average trip time.
Arguments:
IN -- Bike list
"""
for bike in bikeObjects:
bike.calculateAverageTime()
def showAverageTimeForBike(bikeObjects):
"""
Function name: showAverageTimeForBike
Description: Shows the average trip time of each bike.
Arguments:
IN -- Bike list
"""
for bike in bikeObjects:
print("Bike: ", bike.id, " has a travel average time of: ", bike.averageTravelTime)
def main():
# Get the data from the CSV
csvData = readCSV("Bike-Hire-Analysis/data/data.csv")
# Add data to bike objects
bikeObjects = createObjects(csvData)
# Order objects time => order type, ASC and fix missing times
orderObjectsByTime(bikeObjects)
# Run the class function to calcule the travel average time
calculateBikeAverageTimes(bikeObjects)
# Run the class function to calcule the travel average time
showAverageTimeForBike(bikeObjects)
if __name__ == "__main__":
main()
print("Program ended.")
|
{"/bike.py": ["/defaultParams.py", "/miscFunctions.py"], "/__main__.py": ["/bike.py"], "/miscFunctions.py": ["/defaultParams.py"]}
|
34,961
|
sWallyx/Bike-Hire-Analysis
|
refs/heads/master
|
/defaultParams.py
|
# File containing default global values
DEFAULT_TIME_VALUE = "00010101T00:00:00"
TIME_FORMAT = '%Y%m%dT%H:%M:%S'
|
{"/bike.py": ["/defaultParams.py", "/miscFunctions.py"], "/__main__.py": ["/bike.py"], "/miscFunctions.py": ["/defaultParams.py"]}
|
34,962
|
sWallyx/Bike-Hire-Analysis
|
refs/heads/master
|
/miscFunctions.py
|
# File with generic functions
from defaultParams import DEFAULT_TIME_VALUE
def isNaN(num):
return num != num
def checkNaNValue(num):
if(isNaN(num)):
num = DEFAULT_TIME_VALUE
return num
|
{"/bike.py": ["/defaultParams.py", "/miscFunctions.py"], "/__main__.py": ["/bike.py"], "/miscFunctions.py": ["/defaultParams.py"]}
|
34,965
|
sebant/openDATA
|
refs/heads/master
|
/requestFollowers.py
|
# -*- coding: utf-8 -*-
#pip install twython
def connect():
from twython import Twython
APP_KEY = 'pIHTSqoX7QzW4HhFPJauhNglA'
APP_SECRET = 'hR4x7xDdWkGkX3NafcXCTeP8Mlk5pH0J9OODKD4T7vPT1LJoQM'
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
return twitter
def connect2():
from twython import Twython
APP_KEY = 'pIHTSqoX7QzW4HhFPJauhNglA'
APP_SECRET = 'hR4x7xDdWkGkX3NafcXCTeP8Mlk5pH0J9OODKD4T7vPT1LJoQM'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
#{u'oauth_token_secret': u'EZCPEc5x6bncqnl4z1cyDz5136UPCN9a',
#'auth_url': 'https://api.twitter.com/oauth/authenticate?oauth_token=NltG6gAAAAAAydthAAABWaMwqEg',
#u'oauth_token': u'NltG6gAAAAAAydthAAABWaMwqEg',
#u'oauth_callback_confirmed': u'true'}
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
OAUTH_URL = auth["auth_url"]
print OAUTH_URL
variable = raw_input('input PIN CODE!: ')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
final_step = twitter.get_authorized_tokens(int(variable))
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
return twitter
def load(filename,retdef):
import os
import pickle
if(not os.path.isfile(filename)):
print "File "+filename+ " does not exist"
return retdef
with open(filename, "rb") as binFile:
return pickle.load(binFile)
def scrap(twitter, listUsersIds, dict2Ret,fileout,vUsers2F):
#Query---------------------------------------------------------------
import time
import pickle
import datetime
import sys
from twython import TwythonError, TwythonRateLimitError, TwythonAuthError
for index, userId in enumerate(listUsersIds):
print str(userId) + " \t " + str(index) + "/" + str(len(listUsersIds))
i=0
fail=False
while(str(userId) not in dict2Ret and not fail and not str(userId) in vUsers2F and not userId in vUsers2F):
i+=1
print str(userId) + "\ttry: " + str(i)
try:
dict2Ret[str(userId)] = twitter.get_followers_ids(user_id = userId)
saveAndWait(fileout,dict2Ret)
except TwythonRateLimitError as e:
print "TwythonRateLimitError"
fail=True
#rate superat
if int(e.error_code) == 429:
print "Superat el ratio 1 x min, esperem 15 minuts"
print "Si cap de nos esta executant el programa des dun altre pc hem de canviar les credencials"
#lerror hauria de contindre el temps que falta
time.sleep(60*60*15)
fail = False
#el tornem a buscar
else:
print e
time.sleep(60)
except TwythonAuthError as e:
print "TwythonAuthError"
fail=True
if int(e.error_code) == 401:
pathUsers2follow = "tables/users2follow.bin"
vUsers = load(pathUsers2follow,[])
if userId not in vUsers:
vUsers.append(userId)
import pickle
with open(pathUsers2follow,"wb") as f:
pickle.dump(vUsers,f)
print "posible motiu: usuari amb perfil protegit"
print "to do: fer amb laltra conexio"
time.sleep(60)
else:
print e
time.sleep(60)
except TwythonError as e:
print "TwythonError"
fail=True
try:
if int(e.error_code) == 404:
print "Usuari eliminat, el posem a la llista amb un seguidor -1"
dict2Ret[str(userId)] = {"ids":[-1]}
saveAndWait(fileout,dict2Ret)
else:
print e
time.sleep(60)
except:
print e
time.sleep(60)
except:
fail=True
print ""
print "Error: " + str(sys.exc_info()[0])
print ""
time.sleep(60)
return [1,dict2Ret]
def saveAndWait(filename,data):
import pickle
import time
import datetime
import sys
try:
bfsave = datetime.datetime.now()
with open(filename,"wb") as f:
pickle.dump(data,f)
savingTime = datetime.datetime.now() - bfsave
dif = 60-savingTime.total_seconds()
print "waiting: " + str(dif)
if dif > 0:
time.sleep(dif+1)
except:
print "saveAndWait Error: " + str(sys.exc_info()[0])
def main():
import os
import pickle
print "start main"
fileout = "scrapFollResults/followsConexions.bin"
filein = fileout
fileListIdsIn = "tables/usersIds.bin"
#creem la carpeta scrapResults si no existeix
if(not os.path.exists("scrapFollResults")):
os.makedirs("scrapFollResults")
print "read prev res"
#carregeuem els que ja tenim
dic2res =load(filein,{})
print "prev res readed"
#llegim llista
print "read users to req"
lUsersIds = load(fileListIdsIn,[])
print "users to req readed"
print "read usrers wrong"
pathUsers2follow = "tables/users2follow.bin"
vUsers2F = load(pathUsers2follow,[])
print "users wrong readed"
print "conect to twitter"
#conectem
twitter = connect()
print "twitter conected"
print "start scrap"
dic2res = scrap(twitter,lUsersIds,dic2res,fileout,vUsers2F)
#guardem
save(fileout,dic2res)
for i in range(10):
print "!!!!!!!!!!!!!!!!FINISH!!!!!!!!!!!!!!!!!!"
if __name__ == "__main__":
main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,966
|
sebant/openDATA
|
refs/heads/master
|
/follow.py
|
def connect2():
from twython import Twython
APP_KEY = 'pIHTSqoX7QzW4HhFPJauhNglA'
APP_SECRET = 'hR4x7xDdWkGkX3NafcXCTeP8Mlk5pH0J9OODKD4T7vPT1LJoQM'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
#{u'oauth_token_secret': u'EZCPEc5x6bncqnl4z1cyDz5136UPCN9a',
#'auth_url': 'https://api.twitter.com/oauth/authenticate?oauth_token=NltG6gAAAAAAydthAAABWaMwqEg',
#u'oauth_token': u'NltG6gAAAAAAydthAAABWaMwqEg',
#u'oauth_callback_confirmed': u'true'}
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
OAUTH_URL = auth["auth_url"]
print OAUTH_URL
variable = raw_input('input PIN CODE!: ')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
final_step = twitter.get_authorized_tokens(int(variable))
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
return twitter
def load(filename,retdef):
import os
import pickle
if(not os.path.isfile(filename)):
print "File "+filename+ " does not exist"
return retdef
with open(filename, "rb") as binFile:
return pickle.load(binFile)
def main():
from twython import TwythonError, TwythonRateLimitError, TwythonAuthError
twitter= connect2()
path = "tables/users2follow.bin"
vUsers = load(path,[])
for user in vUsers:
print user
try:
twitter.create_friendship(user_id=user,follow=True)
except TwythonError as e:
print e
if __name__ == "__main__":
main()
'''{u'follow_request_sent': True
u'has_extended_profile': False
u'profile_use_background_image': True
u'default_profile_image': False
u'id': 774314204828499969
u'profile_background_image_url_https': None
u'verified': False
u'translator_type': u'none'
u'profile_text_color': u'333333'
u'muting': False
u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/819567389230698498/Z-I6SnNw_normal.jpg'
u'profile_sidebar_fill_color': u'DDEEF6'
u'entities': {u'description': {u'urls': []}}
u'followers_count': 29
u'profile_sidebar_border_color': u'C0DEED'
u'id_str': u'774314204828499969'
u'profile_background_color': u'F5F8FA'
u'listed_count': 1
u'is_translation_enabled': False
u'utc_offset': None
u'statuses_count': 6240
u'description': u'weno'
u'friends_count': 97
u'location': u' Conchinchina'
u'profile_link_color': u'1DA1F2'
u'profile_image_url': u'http://pbs.twimg.com/profile_images/819567389230698498/Z-I6SnNw_normal.jpg'
u'following': False
u'geo_enabled': False
u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/774314204828499969/1483411260'
u'profile_background_image_url': None
u'screen_name': u' '
u'lang': u'es'
u'profile_background_tile': False
u'favourites_count': 506
u'name': u'Max Power'
u'notifications': False
u'url': None
u'created_at': u'Fri Sep 09 18:31:07 +0000 2016'
u'contributors_enabled': False
u'time_zone': None
u'protected': True
u'default_profile': True
u'is_translator': False}
'''
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,967
|
sebant/openDATA
|
refs/heads/master
|
/update.py
|
#busquem nous tweets
import request
request.main()
#ajuntem totes les busquedes i generem fitxes mes manejables en "tables/"
import generateTable
generateTable.main()
#analisis del nombre de tweets en funcio del temps, i de la propagacio de tweets en funcio del temps
import timeAnalisis
timeAnalisis.main()
#busquem totes els seguidors de cada twitaire
import requestFollowers
requestFollowers.main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,968
|
sebant/openDATA
|
refs/heads/master
|
/timeAnalisis.py
|
def main():
import os
filename = "tables/all.bin"
if(not os.path.isfile(filename)):
print "File "+filename+ " does not exist"
return
import pickle
with open(filename, "rb") as binFile:
lTweets = pickle.load(binFile)
from datetime import datetime
slTweets = sorted(lTweets , key=lambda tweet: datetime.strptime(tweet["created_at"],"%a %b %d %H:%M:%S +0000 %Y"))
import time
for tweet in slTweets:
tweet["created_at"] = time.strptime(tweet["created_at"],"%a %b %d %H:%M:%S +0000 %Y")
#agrupem per dies
vTxD=[]
vTxDp=[]
vD=[]
actualDay = slTweets[0]["created_at"].tm_mday
actualMonth = slTweets[0]["created_at"].tm_mon
numToday = 0
ponToday = 0
for tweet in slTweets:
if tweet["created_at"].tm_mday == actualDay:
numToday=numToday+1
ponToday=ponToday+tweet["user"]["followers_count"]
else:
vTxD.append(numToday)
vTxDp.append(ponToday)
vD.append(str(actualMonth)+"-"+str(actualDay))
numToday=1
ponToday=tweet["user"]["followers_count"]
actualDay=tweet["created_at"].tm_mday
actualMonth = tweet["created_at"].tm_mon
vTxD.append(numToday)
vTxDp.append(ponToday)
vD.append(str(actualMonth)+"-"+str(actualDay))
#dibuixem
import numpy as np
import matplotlib.pyplot as plt
N = len(vD)
ind = np.arange(N) # the x locations for the groups
width = 1. # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, vTxD, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel('#Tweets')
ax.set_title('Day')
ax.set_xticks(ind+width/2)
ax.set_xticklabels(vD,rotation='vertical')
plt.savefig('plots/timeEvolution.png')
fig, ax = plt.subplots()
rects1 = ax.bar(ind, vTxDp, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel('#TweetsPon')
ax.set_title('Day')
ax.set_xticks(ind+width/2)
ax.set_xticklabels(vD,rotation='vertical')
plt.savefig('plots/timeEvolutionPondered.png')
if __name__ == "__main__":
main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,969
|
sebant/openDATA
|
refs/heads/master
|
/generateTable.py
|
# -*- coding: utf-8 -*-
def getAllQueryFileName():
import os
return ["scrapResults/"+f for f in os.listdir("scrapResults") if os.path.isfile(os.path.join("scrapResults", f))]
def getListOfSearch():
catalunya = ["Catalufo", "Catalunya", "Cataluña", "Catalanes", "Catalan", "Catalufos", "Indepe", "Indepes", "Independentista", "Independentistas","Catala", "Catalans", "Independentistes"]
puta = ["Puto", "Putos", "Puta", "Putas", "Mierda", "Hijoputa", "Hijos", "Hijo", "Joputa", "Joputas","Agarrados","Mierdas", "Tacaño", "muertos", "muerte", "morid", "mueran", "murais"]
return [cat+" "+p for cat in catalunya for p in puta]
def main():
import time
import os
import json
import csv
import codecs
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#creem la carpeta tables si no existeix
if(not os.path.exists("tables")):
os.makedirs("tables")
#previous searches
vfileName=getAllQueryFileName()
#no tots els twits tenen les mateixes claus
#posarem a header totes les possibles claus per poguer escriure correctament
header=[]
for fileName in vfileName:
f = open(fileName)
queryResultJson =json.load(f)
f.close()
for query in queryResultJson:
if "statuses" in queryResultJson[query]:
for tweet in queryResultJson[query]["statuses"]:
header=list(set(header+tweet.keys()))
#obrim fitxer csv
vIds =[]
lJson=[]
vIdsUsers=[]
vQueris = getListOfSearch()
with codecs.open("tables/test.csv", "w", encoding="utf-8") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
#obrim fitxer json
for fileName in vfileName:
print fileName
f = open(fileName)
queryResultJson =json.load(f)
f.close()
#per cada busqueda
for query in queryResultJson:
if query in vQueris:
#si no te statuses es pq li hem tret al request.py
#ja que tots els resultats estan en la seguent busqueda
if "statuses" in queryResultJson[query]:
for tweet in queryResultJson[query]["statuses"]:
if tweet["id"] not in vIds:
writer.writerow(tweet)
lJson.append(tweet)
vIds.append(tweet["id"])
if tweet["user"]["id"] not in vIdsUsers:
vIdsUsers.append(tweet["user"]["id"])
import pickle
with open("tables/all.bin","wb") as f:
pickle.dump(lJson,f)
with open("tables/usersIds.bin","wb") as f:
pickle.dump(vIdsUsers,f)
if __name__ == "__main__":
main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,970
|
sebant/openDATA
|
refs/heads/master
|
/test.py
|
# -*- coding: utf-8 -*-
#pip install twython
def connect():
from twython import Twython
APP_KEY = 'pIHTSqoX7QzW4HhFPJauhNglA'
APP_SECRET = 'hR4x7xDdWkGkX3NafcXCTeP8Mlk5pH0J9OODKD4T7vPT1LJoQM'
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
return twitter
def main():
twitter = connect()
res = twitter.get_followers_ids(screen_name = "ANCDones")
print res
if __name__ == "__main__":
main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,971
|
sebant/openDATA
|
refs/heads/master
|
/request.py
|
# -*- coding: utf-8 -*-
#pip install twython
def getLastQueryFileName():
import os
onlyfiles = [f for f in os.listdir("scrapResults") if os.path.isfile(os.path.join("scrapResults", f))]
if len(onlyfiles)==0:
prevResults = False
dayLast=""
hourLast=""
else:
prevResults = True
[dayLast,hourLast] = onlyfiles[0].split(".")[0].split("_")
for file in onlyfiles:
[day,hour] = file.split(".")[0].split("_")
if(int(day)>int(dayLast)):
dayLast = day
hourLast = hour
elif(int(day) == int(dayLast)):
if(int(hour)>int(hourLast)):
dayLast = day
hourLast = hour
return [prevResults,"scrapResults/"+dayLast+"_"+hourLast+".json"]
def getListOfSearch():
catalunya = ["Catalufo", "Catalunya", "Cataluña", "Catalanes", "Catalan", "Catalufos", "Polaco", "Polacos", "Indepe", "Indepes", "Independentista", "Independentistas", "Charnego", "Xarnego", "Txarnego", "Charnegos", "Xarnegos", "Txarnegos", "Catala", "Catalans", "Independentistes"]
puta = ["Puto", "Putos", "Puta", "Putas", "Mierda", "Hijoputa", "Hijos", "Hijo", "Joputa", "Joputas","Agarrados","Mierdas", "Tacaño", "muertos", "muerte", "morid", "mueran", "murais"]
return [cat+" "+p for cat in catalunya for p in puta]
def connect():
from twython import Twython
APP_KEY = 'pIHTSqoX7QzW4HhFPJauhNglA'
APP_SECRET = 'hR4x7xDdWkGkX3NafcXCTeP8Mlk5pH0J9OODKD4T7vPT1LJoQM'
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
return twitter
def scrapNTimes(twitter,n,search,lastResults):
#Query---------------------------------------------------------------
for i in range(n):
try:
results = twitter.search(count=5000, q=search)
print search, "\ttotal number of tweet found: ", len(results["statuses"])
if(len(results["statuses"])==0):
return [1,results]
if "statuses" in lastResults:
elements2Delete=[]
for result in results["statuses"]:
for lastresult in lastResults["statuses"]:
if(result["id"]==lastresult["id"]):
elements2Delete.append(lastresult)
for element in elements2Delete:
lastResults["statuses"].pop(lastResults["statuses"].index(element))
if(len(lastResults["statuses"])>=100 ):
print ""
print ""
print search, "!!!!!! HEM PERDUT TUITS !!!!!! AUGMENTAR FREQUENCIA"
print ""
print ""
import time
time.sleep(10)
return [1,results]
except:
return [0,0]
def main():
import time
import os
import json
#creem la carpeta scrapResults si no existeix
if(not os.path.exists("scrapResults")):
os.makedirs("scrapResults")
#conectem
twitter = connect()
#previous search
[lastExist, fileNameLast]=getLastQueryFileName()
if lastExist:
#print "Last query is: ", fileNameLast
fL = open(fileNameLast)
lastResult=json.load(fL)
fL.close()
for search in getListOfSearch():
#si en una busqueda no ha trobat algo ho modifiquem la llista de busqueda, q n peti
if search not in lastResult:
lastResult[search]={}
else:
lastResult={}
for search in getListOfSearch():
lastResult[search]={}
dicResults = {}
for search in getListOfSearch():
#print "Searching for: ", search
#10 nombre dintents que fer per reconectar en cada busqueda
[queryDone,results] = scrapNTimes(twitter,10,search,lastResult[search])
if queryDone:
dicResults[search]=results
else:
print "ERROR DE CONEXIO"
time.sleep(60*15)
twitter = connect()
[queryDone,results] = scrapNTimes(twitter,10,search,lastResult[search])
if queryDone:
print "ERROR DE CONEXIO ARRETGLAT"
dicResults[search]=results
else:
print "ERROR DE CONEXIO PERSISTEIX"
dicResults[search]={}
#nom del fitxer ANY MES DIA_HORA MINUT SEGON
fileName = "scrapResults/"+time.strftime("%Y%m%d_%H%M%S", time.gmtime())+".json"
f = open(fileName,"w")
json.dump(dicResults, f)
if lastExist:
fL = open(fileNameLast,"w")
json.dump(lastResult, fL)
if __name__ == "__main__":
main()
|
{"/update.py": ["/request.py", "/generateTable.py", "/timeAnalisis.py", "/requestFollowers.py"]}
|
34,988
|
math280h/PyFileMovr
|
refs/heads/main
|
/run.py
|
import argparse
from pyfilemovr.pyfilemovr import PyFileMovr
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Move all files from one destination to the other"
)
parser.add_argument(
"-i", "--input", type=str, help="Destination to move files from"
)
parser.add_argument("-o", "--output", type=str, help="Destination to move files to")
parser.add_argument(
"-e",
"--extension",
type=str,
help="Only move files with this extension (Default: *)",
)
parser.add_argument(
"-d",
"--duplicates",
type=bool,
help="If true all file hashes will be compared and only the "
"first in a series of duplicates will be moved ("
"Default: False)",
)
parser.add_argument(
"--debug", type=bool, help="Toggles debug mode (Default: False)"
)
args = parser.parse_args()
if args.input is None or args.output is None:
exit(1)
app = PyFileMovr(
args.input, args.output, args.extension, args.duplicates, args.debug
)
app.run()
|
{"/run.py": ["/pyfilemovr/pyfilemovr.py"]}
|
34,989
|
math280h/PyFileMovr
|
refs/heads/main
|
/pyfilemovr/pyfilemovr.py
|
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import hashlib
import os
import shutil
from typing import Any, Generator, List, Optional, Union
class PyFileMovr:
"""Main Application."""
def __init__(
self,
file_input: str,
output: str,
extension: Optional[str],
duplicate: Optional[bool],
debug: Optional[bool],
) -> None:
self.input = file_input
self.output = output
self.extension = extension
if duplicate is None:
self.duplicate = False
else:
self.duplicate = duplicate
if debug is None:
self.debug = False
else:
self.debug = debug
if duplicate is True:
self.hash_list: List[str] = []
@staticmethod
def walk_through_files(path: str, file_extension: Optional[str]) -> Generator:
"""Walk through all files in all sub-dirs."""
try:
for (dirpath, _, filenames) in os.walk(path):
for filename in filenames:
if file_extension is not None:
if filename.endswith(file_extension):
yield os.path.join(dirpath, filename)
else:
yield os.path.join(dirpath, filename)
except Exception as e:
print("Error:" + str(e))
@staticmethod
def get_date_time() -> str:
"""Get current date_time."""
now = datetime.now()
dt = now.strftime("%d/%m/%Y %H:%M:%S")
return dt
@staticmethod
def hash_byte_str_iter(bytes_iter: Union[Any]) -> str:
"""Get hash hex from string."""
hl = hashlib.sha256()
for block in bytes_iter:
hl.update(block)
return hl.hexdigest()
@staticmethod
def file_as_block_iter(file: Any, block_size: int = 65536) -> Generator:
"""Get hash from file in blocks."""
with file:
block = file.read(block_size)
while len(block) > 0:
yield block
block = file.read(block_size)
def move_file(self, file: str) -> None:
"""Move files to output directory."""
try:
shutil.move(file, self.output)
except shutil.Error as err:
print("Error:" + str(err))
def handle_queue(self, queue: List) -> None:
"""Handle the queue using threads."""
with ThreadPoolExecutor(max_workers=12) as worker:
worker.map(self.move_file, queue)
def run(self) -> None:
"""Run Application."""
print(
"PyFileMovr - Created by: math280h - Found at: https://github.com/math280h/PyFileMovr\n"
)
if self.debug:
print("Input path:", self.input, " Output path:", self.output, "\n")
queue: List[str] = []
for file in self.walk_through_files(self.input, file_extension=self.extension):
print("Current file: {}".format(file))
if self.debug:
print(" Hash List:", self.hash_list)
if self.duplicate is True:
fh = self.hash_byte_str_iter(self.file_as_block_iter(open(file, "rb")))
if self.debug:
print(" File hash:", fh)
if fh not in self.hash_list:
self.hash_list.append(fh)
else:
print(" Skipped: Duplicate")
continue
queue.append(file)
print(" Successfully moved file")
self.handle_queue(queue)
|
{"/run.py": ["/pyfilemovr/pyfilemovr.py"]}
|
34,990
|
math280h/PyFileMovr
|
refs/heads/main
|
/noxfile.py
|
import nox
from nox.sessions import Session
locations = "pyfilemovr", "run.py", "noxfile.py"
python_versions = ["3.9"]
nox.options.sessions = "lint", "mypy"
@nox.session(python=python_versions)
def lint(session: Session) -> None:
"""Lint code using flake8."""
args = session.posargs or locations
session.install(
"flake8",
"flake8-annotations",
"flake8-bandit",
"flake8-black",
"flake8-bugbear",
"flake8-docstrings",
"flake8-import-order",
)
session.run("flake8", *args)
@nox.session(python=python_versions)
def black(session: Session) -> None:
"""Format code using black."""
args = session.posargs or locations
session.install("black")
session.run("black", *args)
@nox.session(python=python_versions)
def mypy(session: Session) -> None:
"""Check typing with mypy."""
args = session.posargs or locations
session.install("mypy")
session.run("mypy", *args)
|
{"/run.py": ["/pyfilemovr/pyfilemovr.py"]}
|
34,999
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/middleware/__init__.py
|
# -*- coding: utf-8 -*-
from .auth import AuthHandler
from .session_manager import DatabaseSessionManager
from .translator import JSONTranslator
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,000
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/utils/auth.py
|
# -*- coding: utf-8 -*-
import bcrypt
import shortuuid
from itsdangerous import TimestampSigner
from itsdangerous import SignatureExpired, BadSignature
from cryptography.fernet import Fernet, InvalidToken
from app.config import SECRET_KEY, TOKEN_EXPIRES, UUID_LEN, UUID_ALPHABET
app_secret_key = Fernet(SECRET_KEY)
def get_common_key():
return app_secret_key
def uuid():
return shortuuid.ShortUUID(alphabet=UUID_ALPHABET).random(UUID_LEN)
def encrypt_token(data):
encryptor = get_common_key()
return encryptor.encrypt(data.encode('utf-8'))
def decrypt_token(token):
try:
decryptor = get_common_key()
return decryptor.decrypt(token.encode('utf-8'))
except InvalidToken:
return None
def hash_password(password):
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
def verify_password(password, hashed):
return bcrypt.hashpw(password.encode('utf-8'), hashed) == hashed
def generate_timed_token(user_dict, expiration=TOKEN_EXPIRES):
s = TimestampSigner(SECRET_KEY, expires_in=expiration)
return s.dumps(user_dict)
def verify_timed_token(token):
s = TimestampSigner(SECRET_KEY)
try:
data = s.loads(token)
except (SignatureExpired, BadSignature):
return None
return data
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,001
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/api/__init__.py
|
# -*- coding: utf-8 -*-
from .common import BaseResource
from .v1 import *
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,002
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/model/__init__.py
|
# -*- coding: utf-8 -*-
from .base import Base
from .user import User
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,003
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/api/v1/users.py
|
# -*- coding: utf-8 -*-
import re
import falcon
from sqlalchemy.orm.exc import NoResultFound
from cerberus import Validator, ValidationError
from app import log
from app.api.common import BaseResource
from app.utils.hooks import auth_required
from app.utils.auth import encrypt_token, hash_password, verify_password, uuid
from app.model import User
from app.errors import AppError, InvalidParameterError, UserNotExistsError, PasswordNotMatch
LOG = log.get_logger()
FIELDS = {
'username': {
'type': 'string',
'required': True,
'minlength': 4,
'maxlength': 20
},
'email': {
'type': 'string',
'regex': '[a-zA-Z0-9._-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}',
'required': True,
'maxlength': 320
},
'password': {
'type': 'string',
'regex': '[A-Za-z0-9@#$%^&+=]{8,}',
'required': True,
'minlength': 8,
'maxlength': 64
},
'info': {
'type': 'dict',
'required': False
}
}
def validate_user_create(req, res, resource, params):
schema = {
'username': FIELDS['username'],
'email': FIELDS['email'],
'password': FIELDS['password'],
'info': FIELDS['info']
}
v = Validator(schema)
try:
if not v.validate(req.context['data']):
raise InvalidParameterError(v.errors)
except ValidationError:
raise InvalidParameterError('Invalid Request %s' % req.context)
class Collection(BaseResource):
"""
Handle for endpoint: /v1/users
"""
@falcon.before(validate_user_create)
def on_post(self, req, res):
session = req.context['session']
user_req = req.context['data']
if user_req:
user = User()
user.username = user_req['username']
user.email = user_req['email']
user.password = hash_password(user_req['password']).decode('utf-8')
user.info = user_req['info'] if 'info' in user_req else None
sid = uuid()
user.sid = sid
user.token = encrypt_token(sid).decode('utf-8')
session.add(user)
self.on_success(res, None)
else:
raise InvalidParameterError(req.context['data'])
@falcon.before(auth_required)
def on_get(self, req, res):
session = req.context['session']
user_dbs = session.query(User).all()
if user_dbs:
obj = [user.to_dict() for user in user_dbs]
self.on_success(res, obj)
else:
raise AppError()
@falcon.before(auth_required)
def on_put(self, req, res):
pass
class Item(BaseResource):
"""
Handle for endpoint: /v1/users/{user_id}
"""
@falcon.before(auth_required)
def on_get(self, req, res, user_id):
session = req.context['session']
try:
user_db = User.find_one(session, user_id)
self.on_success(res, user_db.to_dict())
except NoResultFound:
raise UserNotExistsError('user id: %s' % user_id)
class Self(BaseResource):
"""
Handle for endpoint: /v1/users/self
"""
LOGIN = 'login'
RESETPW = 'resetpw'
def on_get(self, req, res):
cmd = re.split('\\W+', req.path)[-1:][0]
if cmd == Self.LOGIN:
self.process_login(req, res)
elif cmd == Self.RESETPW:
self.process_resetpw(req, res)
def process_login(self, req, res):
email = req.params['email']
password = req.params['password']
session = req.context['session']
try:
user_db = User.find_by_email(session, email)
if verify_password(password, user_db.password.encode('utf-8')):
self.on_success(res, user_db.to_dict())
else:
raise PasswordNotMatch()
except NoResultFound:
raise UserNotExistsError('User email: %s' % email)
@falcon.before(auth_required)
def process_resetpw(self, req, res):
pass
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,004
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/utils/hooks.py
|
# -*- coding: utf-8 -*-
import falcon
from app.errors import UnauthorizedError
def auth_required(req, res, resource):
if req.context['auth_user'] is None:
raise UnauthorizedError()
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,005
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/middleware/auth.py
|
# -*- coding: utf-8 -*-
from app import log
from app.utils.auth import decrypt_token
from app.errors import UnauthorizedError
LOG = log.get_logger()
class AuthHandler(object):
def process_request(self, req, res):
LOG.debug("Authorization: %s", req.auth)
if req.auth is not None:
token = decrypt_token(req.auth)
if token is None:
raise UnauthorizedError('Invalid auth token: %s' % req.auth)
else:
req.context['auth_user'] = token.decode('utf-8')
else:
req.context['auth_user'] = None
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,006
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/main.py
|
# -*- coding: utf-8 -*-
import falcon
from app import log
from app.middleware import AuthHandler, JSONTranslator, DatabaseSessionManager
from app.database import db_session, init_session
from app.api.common import base
from app.api.v1 import users
from app.errors import AppError
LOG = log.get_logger()
class App(falcon.API):
def __init__(self, *args, **kwargs):
super(App, self).__init__(*args, **kwargs)
LOG.info('API Server is starting')
# routes are added here
self.add_route('/', base.BaseResource())
# version 1
self.add_route('/v1/users', users.Collection())
self.add_route('/v1/users/{user_id}', users.Item())
self.add_route('/v1/users/self/login', users.Self())
self.add_error_handler(AppError, AppError.handle)
init_session()
middleware = [AuthHandler(), JSONTranslator(), DatabaseSessionManager(db_session)]
application = App(middleware=middleware)
if __name__ == "__main__":
from wsgiref import simple_server
httpd = simple_server.make_server('127.0.0.1', 5000, application)
httpd.serve_forever()
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,007
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/middleware/translator.py
|
# -*- coding: utf-8 -*-
import json
import falcon
from app.errors import InvalidParameterError
class JSONTranslator(object):
def process_request(self, req, res):
if req.content_type == 'application/json':
try:
raw_json = req.stream.read()
except Exception:
message = 'Read Error'
raise falcon('Bad request', message)
try:
req.context['data'] = json.loads(raw_json.decode('utf-8'))
except ValueError:
raise InvalidParameterError('No JSON object could be decoded or Malformed JSON')
except UnicodeDecodeError:
raise InvalidParameterError('Cannot be decoded by utf-8')
else:
req.context['data'] = None
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,008
|
antonizoon/falcon-rest-api
|
refs/heads/master
|
/app/model/user.py
|
# -*- coding: utf-8 -*-
from sqlalchemy import Column
from sqlalchemy import String, Integer, LargeBinary
from sqlalchemy.dialects.postgres import JSONB
from app.model import Base
from app.config import UUID_LEN
from app.utils import alchemy
class User(Base):
user_id = Column(Integer, primary_key=True)
username = Column(String(20), nullable=False)
email = Column(String(320), unique=True, nullable=False)
password = Column(String(80), nullable=False)
info = Column(JSONB, nullable=True)
token = Column(String(255), nullable=False)
# intentionally assigned for user related service such as resetting password: kind of internal user secret key
sid = Column(String(UUID_LEN), nullable=False)
def __repr__(self):
return "<User(name='%s', email='%s', token='%s', info='%s')>" % \
(self.username, self.email, self.token, self.info)
@classmethod
def get_id(cls):
return User.user_id
@classmethod
def find_by_email(cls, session, email):
return session.query(User).filter(User.email == email).one()
FIELDS = {
'username': str,
'email': str,
'info': alchemy.passby,
'token': str
}
FIELDS.update(Base.FIELDS)
|
{"/app/middleware/__init__.py": ["/app/middleware/auth.py", "/app/middleware/translator.py"], "/app/model/__init__.py": ["/app/model/user.py"], "/app/api/v1/users.py": ["/app/utils/hooks.py", "/app/utils/auth.py", "/app/model/__init__.py"], "/app/middleware/auth.py": ["/app/utils/auth.py"], "/app/main.py": ["/app/middleware/__init__.py"], "/app/model/user.py": ["/app/model/__init__.py"]}
|
35,009
|
Jian-Wuyou/Klondike
|
refs/heads/master
|
/Klondike/base.py
|
import logging
import sys
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
logger = logging.getLogger(__name__)
from . import parser
from . import game
if __name__ == '__main__':
parser_obj = parser.CommandParser(game.Game())
while True:
cmd = input(" >>> ")
parser_obj._parse_(cmd)
|
{"/Klondike/game.py": ["/Klondike/base.py"]}
|
35,010
|
Jian-Wuyou/Klondike
|
refs/heads/master
|
/Klondike/game.py
|
from . import card
from .base import logger
class TableauPile:
def __init__(self):
self._hidden_deck = card.CardDeck()
self._shown_deck = card.CardDeck()
def take(self, n: int = 1) -> card.Card or card.Iterable:
x = self._shown_deck.take(n)
if not self._shown_deck and self._hidden_deck:
self._shown_deck.put(self._hidden_deck.take(1))
return x
def peek(self):
return self._shown_deck.deck
def put(self, puts_card: card.Card or card.Iterable):
self._shown_deck.put(puts_card)
@property
def deck(self):
return self._shown_deck
def __getitem__(self, item):
return self._shown_deck[item]
def __repr__(self):
return f"<{type(self).__qualname__}: hidden={repr(self._hidden_deck)}, shown={repr(self._shown_deck)}>"
def __str__(self):
return f"TableauPile: {len(self._hidden_deck)} hidden, {self._shown_deck}"
def __len__(self):
return len(self._hidden_deck) + len(self._shown_deck)
class SuitDeck(card.CardDeck):
def __init__(self, suit: card.CardSuit, full=False):
self._suit = suit
super().__init__(full)
def __put(self, puts_card: card.Card):
if self._suit == puts_card.suit:
if (self.deck and puts_card.face.value - self.deck[-1].face.value == 1) or \
(not self.deck and puts_card.face == card.CardFace.ACE):
self._deck.append(puts_card)
else:
raise ValueError("Card face is not after deck's last card face")
else:
raise ValueError("Card does not match deck")
def take(self, n=0):
raise NotImplementedError
def __repr__(self):
return f"<{type(self).__qualname__}: " \
f"[{', '.join([repr(card) for card in self._deck]).strip()}], suit={self._suit}>"
class MoveError(Exception):
pass
class Game:
def __init__(self):
self.base_deck = card.CardDeck(full=True)
# decks are generated left to right
self.decks = [TableauPile() for __ in range(7)]
for i, v in enumerate(self.decks):
for __ in range(i + 1):
v._hidden_deck.put(self.base_deck.take())
# show one card
v._shown_deck.put(v._hidden_deck.take())
self.foundations = {k.value: SuitDeck(k) for k in card.CardSuit}
self.hand_deck = card.CardDeck()
self.debug()
def debug(self):
logger.debug(f"base deck: {self.base_deck}")
x = '\n'.join(["deck " + str(i + 1) + ": " + str(v) for i, v in enumerate(self.decks)])
logger.debug(f"TableauPile: \n{x}")
logger.debug(f"foundations: {self.foundations}")
logger.debug(f"hand: {self.hand_deck}")
def move_info(self):
print("""XX CN CN CN CN CN
CN XX XX XX XX XX XX
CN XX XX XX XX XX
CN XX XX XX XX
CN XX XX XX
CN XX XX
CN XX
CN""")
def place(self, take_number: int, take_index: int, put_index: int):
if take_index == 0:
if take_number > 1:
raise MoveError("can only take 1 card at a time from the main deck")
if self.peek_verify(put_index, self.base_deck.deck[-1]):
self.hand_deck.put(self.base_deck.take(take_number))
self.decks[put_index].put(self.hand_deck.take(card.MAX_CARDS))
return self
else:
raise MoveError("invalid move")
if not put_index:
raise MoveError("cannot place cards into main deck")
if self.peek_verify(put_index, self.decks[take_index].peek()[-1]):
self.hand_deck.put(self.decks[take_index].take(take_number))
self.decks[put_index].put(self.hand_deck.take(card.MAX_CARDS))
return self
else:
raise MoveError("invalid move")
def peek_verify(self, deck_index: int, peeked_card: card.Card) -> bool:
if len(self.decks[deck_index]):
return self.decks[deck_index][-1].face.value - peeked_card.face.value == 1 \
and not peeked_card.suit.is_same_color(self.decks[deck_index][-1].suit)
else:
return card.CardFace.KING == peeked_card.face.value
|
{"/Klondike/game.py": ["/Klondike/base.py"]}
|
35,020
|
Ezfeik/Parcial-1-IA
|
refs/heads/main
|
/main.py
|
from search import *
# Create game instance
game = Frog()
print("Game board initial state:")
print(game)
print('='*24)
# Start the tree of states
init_state = deepcopy(game)
game_tree = Tree(init_state)
solution = search_solution(game_tree, eval_heuristic=False)
solution.reverse()
for move in solution:
print(move)
print('='*24)
# Final tree
print("Tree print:")
game_tree.print_tree()
|
{"/main.py": ["/search.py"], "/search.py": ["/frog.py", "/tree.py"]}
|
35,021
|
Ezfeik/Parcial-1-IA
|
refs/heads/main
|
/search.py
|
from copy import deepcopy
from frog import Frog
from tree import Tree
BOARD = [2, 2, 2, 0, 1, 1, 1]
def heuristic(board):
"""
Returns a score based in how many values are in the right spot.
"""
score = 0
for i, j in zip(board, BOARD):
if i == j:
score += 1
return score
def search_solution(tree, eval_heuristic=False):
"""
Deep-first search python implementation search python implementation with
Best-first enhancement.
Parameters
----------
tree: Tree
Instance with a inicial root node containing the initial state of the game.
eval_heuristic: bool
If use heuristic.
Returns
-------
list[list[int]]
Board of the Frog game instance.
"""
moves = ['l', 'll', 'r', 'rr']
count = 0
history = [tree]
#state list avoid duplicated values.
state = [tree.data]
while history:
count += 1
aux_tree = history.pop(0)
if aux_tree.data.is_solve():
print("Iterations:", count)
return aux_tree.chain_to_root()
#Additional code for auto-expansion of the tree.
for move in moves:
new_game = deepcopy(aux_tree.data)
new_state = new_game.move_to(move)
if new_state and not new_game in state:
state.append(new_game)
tree.add_leaf(new_game, target=aux_tree.data)
#===============================================
if eval_heuristic:
aux_tree.leafs.sort(key=lambda x: heuristic(x.data.get_board()), reverse=True)
history = aux_tree.leafs + history
return []
|
{"/main.py": ["/search.py"], "/search.py": ["/frog.py", "/tree.py"]}
|
35,022
|
Ezfeik/Parcial-1-IA
|
refs/heads/main
|
/tree.py
|
class Tree:
"""
General Tree data structure.
A node independent implementation with basics method.
"""
def __init__(self, data, level=0):
self.data = data
self.root = None
self.leafs = []
self.level = level
def add_leaf(self, data, target=None):
"""
Insertion of an element. Change IN-PLACE
"""
if target:
if target == self.data:
leaf = Tree(data, level=self.level + 1)
leaf.root = self
self.leafs.append(leaf)
else:
for leaf in self.leafs:
leaf.add_leaf(data, target=target)
else:
leaf = Tree(data, level=self.level + 1)
leaf.root = self
self.leafs.append(leaf)
def chain_to_root(self):
"""
Return a list of the elements from the current element to the root element of
the tree.
"""
chain = [self.data]
aux_tree = self.root
while aux_tree:
chain.append(aux_tree.data)
aux_tree = aux_tree.root
return chain
def print_tree(self):
"""
Print by level. Directory tree like.
"""
print(' '*self.level + str(self.data))
if self.leafs:
for leaf in self.leafs:
leaf.print_tree()
|
{"/main.py": ["/search.py"], "/search.py": ["/frog.py", "/tree.py"]}
|
35,023
|
Ezfeik/Parcial-1-IA
|
refs/heads/main
|
/frog.py
|
RULES = {
'l': -1,
'll': -2,
'r': 1,
'rr': 2
}
class Frog:
def __init__(self, board=[1, 1, 1, 0, 2, 2, 2]):
self.board = board
self.pivot = self.board.index(0)
def get_board(self): return self.board
def get_pivot(self): return self.pivot
def _swap(self, move):
p = self.pivot
m = self.pivot + move
self.pivot = m
self.board[p], self.board[m] = self.board[m], self.board[p]
def move_to(self, move):
"""Move the pivot to a given location.
Parameters
----------
move: str
Move direction: 'l', 'll', 'r', 'rr'
Returns
-------
bool
Validation of the movement
"""
if move in RULES.keys():
if move.startswith('l'):
rule = 1
else:
rule = 2
if 0 <= self.pivot + RULES[move] < 7:
if self.board[self.pivot + RULES[move]] == rule:
self._swap(RULES[move])
return True
return False
def is_solve(self):
'''
Return True if board is solve. False otherwise.
'''
return self.board == [2, 2, 2, 0, 1, 1, 1]
def __repr__(self):
return str(self.board)
def __str__(self):
return str(self.board)
|
{"/main.py": ["/search.py"], "/search.py": ["/frog.py", "/tree.py"]}
|
35,028
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/models.py
|
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
location = models.CharField(max_length=30, blank=True)
detailed_bio = models.TextField(blank=True)
contact_info = models.TextField(blank=True)
class Education(models.Model):
university = models.CharField(max_length=100)
city = models.CharField(max_length=100, blank=True)
gpa = models.CharField(max_length=5)
courses = models.TextField()
from_date = models.DateField()
to_date = models.DateField()
class WorkExperience(models.Model):
title = models.CharField(max_length=50)
from_date = models.DateField()
to_date = models.DateField()
description = models.TextField()
organization = models.CharField(max_length=100, blank=True)
image = models.ImageField(upload_to='static/images/work_experience_images', blank=True)
class Project(models.Model):
title = models.TextField(max_length=500)
from_date = models.DateField()
to_date = models.DateField()
description = models.TextField()
organization = models.CharField(max_length=100, blank=True)
class Article(models.Model):
title = models.CharField(max_length=50)
introduction = models.TextField(blank=True)
date = models.DateField()
link = models.URLField(blank=True)
image = models.ImageField(upload_to='static/images/article_images', blank=True)
def img_url(self):
return self.image.name
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,029
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/views.py
|
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import ProfileSerializer, ProjectSerializer, ArticleSerializer, WorkExperienceSerializer, EducationSerializer
from .models import Profile, Project, Article, WorkExperience, Education
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.conf import settings
from PIL import Image
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
class ProfileView(viewsets.ModelViewSet):
serializer_class = ProfileSerializer
queryset = Profile.objects.all()
class ArticleView(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all().order_by('-date')
class WorkExperienceView(viewsets.ModelViewSet):
serializer_class = WorkExperienceSerializer
queryset = WorkExperience.objects.all()
class ProjectView(viewsets.ModelViewSet):
serializer_class = ProjectSerializer
queryset = Project.objects.all().order_by('-to_date')
class EducationView(viewsets.ModelViewSet):
serializer_class = EducationSerializer
queryset = Education.objects.all().order_by('-to_date')
def ImageView(request, id):
print("Inside view")
article = Article.objects.get(id=id)
response = HttpResponse(content_type="image/png")
img = Image.open(article.image)
img.save(response,'png')
return response
# Serve Single Page Application
index = never_cache(TemplateView.as_view(template_name='index.html'))
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,030
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/admin.py
|
from django.contrib import admin
from .models import Profile, Project, Article, WorkExperience, Education
admin.site.register(Profile)
admin.site.register(Project)
admin.site.register(Article)
admin.site.register(WorkExperience)
admin.site.register(Education)
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,031
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0010_auto_20210228_2128.py
|
# Generated by Django 3.1.7 on 2021-02-28 21:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0009_auto_20210228_2121'),
]
operations = [
migrations.RenameField(
model_name='profile',
old_name='interests',
new_name='detailed_bio',
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,032
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0009_auto_20210228_2121.py
|
# Generated by Django 3.1.7 on 2021-02-28 21:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0008_auto_20210228_0225'),
]
operations = [
migrations.CreateModel(
name='Education',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('university', models.CharField(max_length=100)),
('gpa', models.CharField(max_length=5)),
('courses', models.TextField()),
('from_date', models.DateField()),
('to_date', models.DateField()),
],
),
migrations.RemoveField(
model_name='profile',
name='birth_date',
),
migrations.AddField(
model_name='profile',
name='interests',
field=models.TextField(blank=True),
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,033
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0011_profile_contact_info.py
|
# Generated by Django 3.1.7 on 2021-02-28 21:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0010_auto_20210228_2128'),
]
operations = [
migrations.AddField(
model_name='profile',
name='contact_info',
field=models.TextField(blank=True),
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,034
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0005_auto_20210227_0343.py
|
# Generated by Django 3.1.7 on 2021-02-27 03:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0004_remove_profile_profile_picture'),
]
operations = [
migrations.CreateModel(
name='WorkExperience',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('from_date', models.DateField()),
('to_date', models.DateField()),
('description', models.TextField()),
('organization', models.CharField(blank=True, max_length=100)),
],
),
migrations.AddField(
model_name='project',
name='organization',
field=models.CharField(blank=True, max_length=100),
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,035
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0006_auto_20210227_2346.py
|
# Generated by Django 3.1.7 on 2021-02-27 23:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0005_auto_20210227_0343'),
]
operations = [
migrations.AlterField(
model_name='article',
name='image',
field=models.ImageField(blank=True, upload_to='static/images/article_images'),
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,036
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/migrations/0008_auto_20210228_0225.py
|
# Generated by Django 3.1.7 on 2021-02-28 02:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0007_article_introduction'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='content',
),
migrations.AddField(
model_name='article',
name='link',
field=models.URLField(blank=True),
),
]
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,037
|
yashm6798/portfolio
|
refs/heads/main
|
/backend/portfolio/serializers.py
|
from rest_framework import serializers
from .models import Profile, Project, Article, WorkExperience, Education
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
class EducationSerializer(serializers.ModelSerializer):
class Meta:
model = Education
fields = ['university', 'gpa', 'from_date', 'to_date', 'courses', 'city', 'id']
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Profile
fields = ['user', 'bio', 'location', 'detailed_bio', 'contact_info']
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ['id', 'title', 'from_date', 'to_date', 'description', 'organization']
class WorkExperienceSerializer(serializers.ModelSerializer):
class Meta:
model = WorkExperience
fields = ['id', 'title', 'from_date', 'to_date', 'description', 'organization', 'image']
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ['id', 'title', 'date', 'link', 'image', 'introduction']
|
{"/backend/portfolio/views.py": ["/backend/portfolio/serializers.py", "/backend/portfolio/models.py"], "/backend/portfolio/admin.py": ["/backend/portfolio/models.py"], "/backend/portfolio/serializers.py": ["/backend/portfolio/models.py"]}
|
35,115
|
uziasr/portfolio
|
refs/heads/master
|
/projects/models.py
|
from django.db import models
# Create your models here.
class Project(models.Model):
image = models.ImageField(upload_to='images/') #data can saved as an Image, like a png
summary = models.CharField(max_length=200)
def __str__(self):
message = ("{}. {}".format(str(self.id),(self.summary[:60]+"....")))
return message
|
{"/projects/views.py": ["/projects/models.py"]}
|
35,116
|
uziasr/portfolio
|
refs/heads/master
|
/projects/views.py
|
from django.shortcuts import render, get_object_or_404
from . models import Project
# Create your views here.
def uzias(request):
projects = Project.objects
return render(request, 'projects/home.html', {'projects': projects})
def detail(request, project_id):
project_detail = get_object_or_404(Project, pk=project_id)
#if (project_detail):
return render(request, 'projects/detail.html', {'project': project_detail})
|
{"/projects/views.py": ["/projects/models.py"]}
|
35,118
|
derick-droid/pythonbasics
|
refs/heads/main
|
/ifwithlist.py
|
# if statement with a list
pizzare = ["mushroom", "chocolate", "carlifornia", "newyork"]
for pizza in pizzare:
if pizza == "newyork":
print("still not available")
else:
print(f"{pizza} is being added please just wait a moment")
print()
# Checking That a List Is Not Empty
topping_list = []
if topping_list:
for requset in topping_list:
print(f"{requset} is being added please be patient")
else:
print("are sure you want plain pizza")
print()
# Using Multiple Lists
vailable_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requset_topping = ["french fry","chicken baker", "chips soda", "olives"]
for piza in requset_topping:
if piza in vailable_toppings:
print(f"{piza} is being added please be patient")
else:
print(f"{piza} is not available")
|
{"/module.py": ["/largest_number.py"]}
|
35,119
|
derick-droid/pythonbasics
|
refs/heads/main
|
/reverse.py
|
# reversing the variable
v1 = "first string"
v2 = "second string"
v3 = v1
v4 = v2
v2 = v3
v1 = v4
print(v2)
print(v1)
|
{"/module.py": ["/largest_number.py"]}
|
35,120
|
derick-droid/pythonbasics
|
refs/heads/main
|
/madlib.py
|
color = input("Enter color: ")
plural_noun = input("Enter plural of a noun: ")
celebrity = input("which celebrity do you love: ")
print("flowers are " + color )
print(plural_noun + "are noisy")
print("I love " + celebrity)
|
{"/module.py": ["/largest_number.py"]}
|
35,121
|
derick-droid/pythonbasics
|
refs/heads/main
|
/functioncorey.py
|
months_days = [0, 31, 28, 29, 30, 31, 31, 30, 32]
def is_leap_year(year):
if year % 4 == 0 and (year % 100 == 0 and year % 400 == 0):
print("this is a leap year")
def months_year(year, months):
if months < 1:
print("invalid month")
elif months > 12:
print("invalid month")
elif months == 2 and is_leap_year(year):
print(months_days[months])
elif months == 3 and not is_leap_year(year):
print(months_days[months])
else:
print(months_days[months])
pop = months_year(2020, 2)
|
{"/module.py": ["/largest_number.py"]}
|
35,122
|
derick-droid/pythonbasics
|
refs/heads/main
|
/inheritance.py
|
class Mammal:
def walk(self):
print('walking')
class Dog(Mammal):
def bark(self):
print("barking")
class Cat(Mammal):
def meaw(self):
print("meaw")
dog = Dog
dog.bark(Mammal)
dog.walk(Mammal)
cat = Cat
cat.walk(Mammal)
cat.meaw(Mammal)
|
{"/module.py": ["/largest_number.py"]}
|
35,123
|
derick-droid/pythonbasics
|
refs/heads/main
|
/dictexer.py
|
# 6-5. Rivers: Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# • Use a loop to print a sentence about each river, such as The Nile runs
# through Egypt.
# • Use a loop to print the name of each river included in the dictionary.
# • Use a loop to print the name of each country included in the dictionary.
rivers = {
"Nile": "Egypt",
"Amazon": "America",
"Tana": "Kenya"
}
for river, country in rivers.items():
print(river + " runs through " + country)
print()
for river in rivers.keys():
print(river)
print()
for country in rivers.values():
print(country)
|
{"/module.py": ["/largest_number.py"]}
|
35,124
|
derick-droid/pythonbasics
|
refs/heads/main
|
/rightangle.py
|
k= 1
for i in range(3):
# k = 1
for j in range(1, k+1):
print("*", end=" ")
k = k+2
print()
|
{"/module.py": ["/largest_number.py"]}
|
35,125
|
derick-droid/pythonbasics
|
refs/heads/main
|
/infinite.py
|
# avoiding infinite in loops
x = 1
while x <5:
# x += 1 should be implemented to avoid infinite loop
print("he ll")
# ensure the loops exits when is expected
|
{"/module.py": ["/largest_number.py"]}
|
35,126
|
derick-droid/pythonbasics
|
refs/heads/main
|
/input.py
|
name = input("Enter your name: ")
print("hello " + name )
# simple addition program
number1 = input("Enter a number: ")
number2 = input("Enter a number: ")
result = float(number1) + float(number2)
print(result)
|
{"/module.py": ["/largest_number.py"]}
|
35,127
|
derick-droid/pythonbasics
|
refs/heads/main
|
/breaks.py
|
# using breaks in while loops
prompt = "\n enter your own message , we wiil keep your message secret!"
prompt += "\n enter message:"
while True:
message = input(prompt)
if message.lower() == "quit":
break
else:
print(message)
|
{"/module.py": ["/largest_number.py"]}
|
35,128
|
derick-droid/pythonbasics
|
refs/heads/main
|
/mathsfunctions.py
|
# round off
x = 2.899
print(round(x))
y = 9000.84474
print(round(y))
m = 999999837
print(round(m))
# ABSOLUTE FUNCTION
Z = -8887489
print(abs(Z))
r = -535
print(abs(r))
# IMPORTING BUILT IN MATHS FUNCTIONS IN PYTHON
import math
print(math.floor(67))
print(math.acosh(5))
|
{"/module.py": ["/largest_number.py"]}
|
35,129
|
derick-droid/pythonbasics
|
refs/heads/main
|
/unpacking.py
|
geographical_points = (1, 2, 3)
x, y, z = geographical_points # THIS UNPACKING TO REDUCE TEDIOU WORK OF CODING
print(x)
print(y)
print(z)
|
{"/module.py": ["/largest_number.py"]}
|
35,130
|
derick-droid/pythonbasics
|
refs/heads/main
|
/exerdic.py
|
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the
# name of a pet. In each dictionary, include the kind of animal and the owner’s
# name. Store these dictionaries in a list called pets . Next, loop through your list
# and as you do print everything you know about each print it
rex = {
"name" : "rex",
"kind": "dog",
"owner's name" : "joe"
}
pop = {
"name" :"pop",
"kind" : "pig",
"owner's name": "vincent"
}
dough = {
"name": "dough",
"kind" : "cat",
"owner's name" : "pamna"
}
pets = [rex, pop, dough ]
for item in pets:
print(item)
print()
# 6-9. Favorite Places: Make a dictionary called favorite_places . Think of three
# names to use as keys in the dictionary, and store one to three favorite places
# for each person. To make this exercise a bit more interesting, ask some friends
# to name a few of their favorite places. Loop through the dictionary, and print
# each person’s name and their favorite places.
favorite_places = {
"derrick": {
"nairobi", "mombasa", "kisumu"
},
"dennis":{
"denmark", "thika", "roman"
},
"john": {
"zambia", "kajiado", "suna"
}
}
for name, places in favorite_places.items(): # looping through the dictionary and printing only the name variable
print(f"{name} 's favorite places are :")
for place in places: # looping through the places variable to come up with each value in the variable
print(f"-{place}")
print()
# 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so
# each person can have more than one favorite number. Then print each person’s
# name along with their favorite numbers.
favorite_number = {
"derrick" : [1, 2, 3],
"don" : [3, 5, 7],
"jazzy" : [7, 8, 9]
}
for name, fav_number in favorite_number.items():
print(f"{name} favorite numbers are: ")
for number in fav_number:
print(f"-{number}")
# 6-11. Cities: Make a dictionary called cities . Use the names of three cities as
# keys in your dictionary. Create a dictionary of information about each city and
# include the country that the city is in, its approximate population, and one fact
# about that city. The keys for each city’s dictionary should be something like
# country , population , and fact . Print the name of each city and all of the infor-
# mation you have stored about it.
cities = {
"Nairobi" : {
"population" : "1400000",
"country" : "kenya",
"facts" : "largest city in East Africa"
},
"Dar-es-salaam" : {
"population" : "5000000",
"country" : "tanzania",
"facts" : "largest city in Tanzania"
},
"Kampala" : {
"population" : "1000000",
"country" : "Uganda",
"facts" : "The largest city in Uganda"
}
}
for city, information in cities.items():
print(f"{city}:")
for fact,facts in information.items():
print(f"-{fact}: {facts}")
|
{"/module.py": ["/largest_number.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.