commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
eb994bad8556c750f2c27f83117e7d32899d9427
tests.py
tests.py
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?username=') assert 'Invalid username' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid username' in rv.data if __name__ == '__main__': unittest.main()
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest try: import cPickle as pickle except ImportError: import pickle DATA_SOURCES = [ 'lib/noslang.p' ] class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?username=') assert 'Invalid username' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid username' in rv.data def test_data_sources(self): """Test to make sure data sources exist and can be loaded""" for filename in DATA_SOURCES: with open(filename, 'r') as f: data = pickle.load(f) assert data if __name__ == '__main__': unittest.main()
Add validate data sources test
Add validate data sources test
Python
mit
jayelm/twittersa,jayelm/twittersa
--- +++ @@ -9,6 +9,15 @@ import TwitterSA import unittest +try: + import cPickle as pickle +except ImportError: + import pickle + + +DATA_SOURCES = [ + 'lib/noslang.p' +] class TwitterSATestCase(unittest.TestCase): @@ -38,6 +47,12 @@ rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid username' in rv.data + def test_data_sources(self): + """Test to make sure data sources exist and can be loaded""" + for filename in DATA_SOURCES: + with open(filename, 'r') as f: + data = pickle.load(f) + assert data if __name__ == '__main__': unittest.main()
3cf7ca56ac156154dc08433955fff4b15e7eb331
mpd_mypy.py
mpd_mypy.py
#!/usr/bin/python import mpd SERVER = "localhost" PORT = 6600 def connect(mpdclient): """ Handle connection to the mpd server """ mpdclient.connect(SERVER, PORT) mpdclient = mpd.MPDClient() connect(mpdclient) bands = set(mpdclient.list("artist"))
#!/usr/bin/python import mpd SERVER = "localhost" PORT = 6600 def connect(mpdclient): """ Handle connection to the mpd server """ mpdclient.connect(SERVER, PORT) mpdclient = mpd.MPDClient() connect(mpdclient) bands = set(str(artist).lower() for artist in mpdclient.list("artist") if artist != "") print(bands)
Apply filters on artists to clean duplicates
Apply filters on artists to clean duplicates
Python
bsd-2-clause
Anthony25/mpd_muspy
--- +++ @@ -15,4 +15,6 @@ mpdclient = mpd.MPDClient() connect(mpdclient) -bands = set(mpdclient.list("artist")) +bands = set(str(artist).lower() for artist in mpdclient.list("artist") + if artist != "") +print(bands)
d837a194e29b867443a3758bb4c159afe193e798
enumfields/fields.py
enumfields/fields.py
from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: choices = enum.choices() except AttributeError: choices = [(m.value, getattr(m, 'label', m.name)) for m in enum] super(EnumFieldMixin, self).__init__( choices=choices, max_length=max_length, **options) def to_python(self, value): if value is None: return None for m in self.enum: if value == m: return value if value == m.value: return m raise ValidationError('%s is not a valid value for enum %s' % (value, self.enum)) def get_prep_value(self, value): return None if value is None else value.value class EnumField(EnumFieldMixin, models.CharField): pass class EnumIntegerField(EnumFieldMixin, models.IntegerField): pass try: from south.modelsinspector import add_introspection_rules except: pass else: add_introspection_rules([], ['^enumfields\.fields\.EnumField$']) add_introspection_rules([], ['^enumfields\.fields\.EnumIntegerField$'])
from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: choices = enum.choices() except AttributeError: choices = [(m.value, getattr(m, 'label', m.name)) for m in enum] super(EnumFieldMixin, self).__init__( choices=choices, max_length=max_length, **options) def to_python(self, value): if value is None: return None for m in self.enum: if value == m: return value if value == m.value: return m raise ValidationError('%s is not a valid value for enum %s' % (value, self.enum)) def get_prep_value(self, value): return None if value is None else value.value class EnumField(EnumFieldMixin, models.CharField): pass class EnumIntegerField(EnumFieldMixin, models.IntegerField): pass
Revert "Add South introspection rules"
Revert "Add South introspection rules" They weren't correct. This reverts commit b7235e2fc4b28271e0dce8d812faa4a46ed84aea.
Python
mit
suutari-ai/django-enumfields,jessamynsmith/django-enumfields,bxm156/django-enumfields,jackyyf/django-enumfields
--- +++ @@ -34,12 +34,3 @@ class EnumIntegerField(EnumFieldMixin, models.IntegerField): pass - - -try: - from south.modelsinspector import add_introspection_rules -except: - pass -else: - add_introspection_rules([], ['^enumfields\.fields\.EnumField$']) - add_introspection_rules([], ['^enumfields\.fields\.EnumIntegerField$'])
5e12fbf432331f1cc6f16c85e9535c12e5584ecc
neuroimaging/setup.py
neuroimaging/setup.py
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('data_io') config.add_subpackage('externals') config.add_subpackage('fixes') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils') config.add_subpackage('testing') config.add_data_dir('testing') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('externals') config.add_subpackage('fixes') config.add_subpackage('io') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils') config.add_subpackage('testing') config.add_data_dir('testing') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Change neuroimaging package list data_io to io.
Change neuroimaging package list data_io to io.
Python
bsd-3-clause
alexis-roche/nipy,alexis-roche/register,arokem/nipy,alexis-roche/register,alexis-roche/niseg,nipy/nireg,nipy/nipy-labs,nipy/nireg,arokem/nipy,alexis-roche/nipy,alexis-roche/register,arokem/nipy,alexis-roche/nireg,bthirion/nipy,nipy/nipy-labs,alexis-roche/nireg,bthirion/nipy,bthirion/nipy,alexis-roche/nipy,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,bthirion/nipy
--- +++ @@ -6,9 +6,9 @@ config.add_subpackage('algorithms') config.add_subpackage('core') - config.add_subpackage('data_io') config.add_subpackage('externals') config.add_subpackage('fixes') + config.add_subpackage('io') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils')
e8454180e4ec612e5c76ab0ec5f149adcaadf026
runtests.py
runtests.py
#!/usr/bin/env python from django.conf import settings from django.core.management import call_command INSTALLED_APPS = ( # Required contrib apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', # Our app and it's test app. 'dbsettings', ) SETTINGS = { 'INSTALLED_APPS': INSTALLED_APPS, 'SITE_ID': 1, 'ROOT_URLCONF': 'dbsettings.tests.test_urls', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, } if not settings.configured: settings.configure(**SETTINGS) call_command('test', 'dbsettings')
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command INSTALLED_APPS = ( # Required contrib apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', # Our app and it's test app. 'dbsettings', ) SETTINGS = { 'INSTALLED_APPS': INSTALLED_APPS, 'SITE_ID': 1, 'ROOT_URLCONF': 'dbsettings.tests.test_urls', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, } if not settings.configured: settings.configure(**SETTINGS) if django.VERSION >= (1, 7): django.setup() call_command('test', 'dbsettings')
Make testrunner work with Django 1.7).
Make testrunner work with Django 1.7).
Python
bsd-3-clause
helber/django-dbsettings,helber/django-dbsettings,zlorf/django-dbsettings,sciyoshi/django-dbsettings,johnpaulett/django-dbsettings,nwaxiomatic/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,winfieldco/django-dbsettings,DjangoAdminHackers/django-dbsettings,johnpaulett/django-dbsettings,winfieldco/django-dbsettings,sciyoshi/django-dbsettings,nwaxiomatic/django-dbsettings
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python +import django from django.conf import settings from django.core.management import call_command @@ -29,4 +30,7 @@ if not settings.configured: settings.configure(**SETTINGS) +if django.VERSION >= (1, 7): + django.setup() + call_command('test', 'dbsettings')
6b7f3ac5bc8c753eb77e975003eb3ee626491774
SLClearOldLists.py
SLClearOldLists.py
# -*- coding: utf-8 -*- import os import re from collections import defaultdict html_files = set() html_file_groups = defaultdict(list) newest_files = set() def get_all_files(): for n in os.listdir('output'): r = re.findall(r'SoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html', n) if r: html_files.add(n) html_file_groups[r[0]].append(n) for k in html_file_groups: html_file_groups[k].sort() newest_files.add(html_file_groups[k][-1]) def delete_old_files(): for f in html_files - newest_files: os.remove(os.path.join('output', f)) def main(): get_all_files() delete_old_files() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import os import re from collections import defaultdict html_files = set() html_file_groups = defaultdict(list) newest_files = set() def get_all_files(): for n in os.listdir('output'): r = re.findall(r'\ASoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html\Z', n) if r: html_files.add(n) html_file_groups[r[0]].append(n) for k in html_file_groups: html_file_groups[k].sort() newest_files.add(html_file_groups[k][-1]) def delete_old_files(): for f in html_files - newest_files: os.remove(os.path.join('output', f)) def main(): get_all_files() delete_old_files() if __name__ == '__main__': main()
Fix file name matching when clearing old lists
Fix file name matching when clearing old lists
Python
mit
gousaiyang/SoftwareList,gousaiyang/SoftwareList
--- +++ @@ -11,7 +11,7 @@ def get_all_files(): for n in os.listdir('output'): - r = re.findall(r'SoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html', n) + r = re.findall(r'\ASoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html\Z', n) if r: html_files.add(n) html_file_groups[r[0]].append(n)
f9b079b7956419ec324234dbad11d073bed70dd8
users/views.py
users/views.py
from django.shortcuts import redirect from rest_framework import viewsets from .models import User from .permissions import IsUserOrReadOnly from .serializers import AuthenticatedUserSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint for viewing and editing users.""" queryset = User.objects.all() permission_classes = (IsUserOrReadOnly,) def get_serializer_class(self): return (AuthenticatedUserSerializer if self.request.user == self.get_object() else UserSerializer) def retrieve(self, request, pk=None): """Retrieve given user or current user if ``pk`` is "me".""" if pk == 'me' and request.user.is_authenticated(): return redirect('user-detail', request.user.pk) else: return super(UserViewSet, self).retrieve(request, pk)
from django.shortcuts import redirect from rest_framework import viewsets from .models import User from .permissions import IsUserOrReadOnly from .serializers import AuthenticatedUserSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint for viewing and editing users.""" queryset = User.objects.all() permission_classes = (IsUserOrReadOnly,) def get_serializer_class(self): return (AuthenticatedUserSerializer if self.request.user == self.get_object() else UserSerializer) def retrieve(self, request, pk=None): """Retrieve given user or current user if ``pk`` is "me".""" if pk == 'me' and request.user.is_authenticated(): return redirect('user-detail', request.user.pk) else: return super().retrieve(request, pk)
Use Python 3 style for super
Use Python 3 style for super
Python
bsd-3-clause
FreeMusicNinja/api.freemusic.ninja
--- +++ @@ -23,4 +23,4 @@ if pk == 'me' and request.user.is_authenticated(): return redirect('user-detail', request.user.pk) else: - return super(UserViewSet, self).retrieve(request, pk) + return super().retrieve(request, pk)
2dc6c076c1d5dce2623ba49eb42a239f31c37547
roc/roc_curve.py
roc/roc_curve.py
import argparse import numpy def load_default(): print "TODO: load default scores" return None, None def get_data(): """ Get scores data. If there are no arguments in command line load default """ parser = argparse.ArgumentParser(description="Solve the ROC curve") parser.add_argument("-c", "--clients", type=argparse.FileType('r'), help="Clients filename", metavar="C", dest="clients_file") parser.add_argument("-i", "--impersonators", type=argparse.FileType('r'), help="Impersonators filename", metavar="I", dest="impersonators_file") try: args = parser.parse_args() if args.impersonators_file is None or args.clients_file is None: load_default() else: c_id, c_score = numpy.loadtxt(args.clients_file, unpack=True) i_id, i_score = numpy.loadtxt(args.impersonators_file, unpack=True) return c_score, i_score except SystemExit: #TODO: load default scores filenames print "Default" load_default() def solve_roc(): c_score, i_score = get_data() print c_score if __name__ == "__main__": solve_roc()
import argparse import numpy def load_default(): print "TODO: load default scores" return None, None def get_data(): """ Get scores data. If there are no arguments in command line load default """ parser = argparse.ArgumentParser(description="Solve the ROC curve") parser.add_argument("-c", "--clients", type=argparse.FileType('r'), help="Clients filename", metavar="C", dest="clients_file") parser.add_argument("-i", "--impersonators", type=argparse.FileType('r'), help="Impersonators filename", metavar="I", dest="impersonators_file") try: args = parser.parse_args() if args.impersonators_file is None or args.clients_file is None: load_default() else: c_id, c_score = numpy.loadtxt(args.clients_file, unpack=True) i_id, i_score = numpy.loadtxt(args.impersonators_file, unpack=True) return c_score, i_score except SystemExit: #TODO: load default scores filenames print "Default" load_default() def solve_roc(): scores = [] c_score, i_score = get_data() scores = zip(['c']*len(c_score),c_score) print len(scores) scores.extend(zip(['i']*len(i_score),i_score)) print len(scores) if __name__ == "__main__": solve_roc()
Load clients and impostors data
Load clients and impostors data
Python
mit
maigimenez/bio,maigimenez/bio,maigimenez/bio
--- +++ @@ -35,8 +35,12 @@ def solve_roc(): + scores = [] c_score, i_score = get_data() - print c_score + scores = zip(['c']*len(c_score),c_score) + print len(scores) + scores.extend(zip(['i']*len(i_score),i_score)) + print len(scores) if __name__ == "__main__":
8a452925f4d630c5f29d2aab9e565798b4a6284c
sardine/const.py
sardine/const.py
# v = 108 * sqrt(k/m) cm^-1 CM_CONVERSION_FACTOR = 108.
# v = 108 * sqrt(k/m) cm^-1 CM_CONVERSION_FACTOR = 108.46435
Expand wavenumber conversion factor out to a few decimal places.
Expand wavenumber conversion factor out to a few decimal places.
Python
bsd-2-clause
grollins/sardine,grollins/sardine
--- +++ @@ -1,2 +1,2 @@ # v = 108 * sqrt(k/m) cm^-1 -CM_CONVERSION_FACTOR = 108. +CM_CONVERSION_FACTOR = 108.46435
f9791b4b19b2cf304e322db0a40c95ad4632d5a8
screenshooter.py
screenshooter.py
import time from selenium import webdriver starttime=time.time() url = 'http://applemusic.tumblr.com/beats1' while True: driver = webdriver.PhantomJS() driver.set_window_size(1920, 1080) driver.get(url) driver.save_screenshot('page.jpg') print('Screenie taken @ ' + str(time.time()) ) time.sleep(60.0 - ((time.time() - starttime) % 60.0))
import time import os import logging as logger from selenium import webdriver starttime=time.time() logger.basicConfig(filename='screenshooter.log',level=logger.DEBUG) url = 'http://applemusic.tumblr.com/beats1' while True: #driver = webdriver.PhantomJS() #driver.set_window_size(1920, 1080) #driver.get(url) #driver.save_screenshot('page.jpg') try: print('hey') except Exception: logger.info('No File exsits') logger.info('screenie init') os.system("./webshots --width 1080 --height 1920 https://twitter.com/radio_scrobble") #print('Screenie taken @ ' + str(time.time()) ) logger.info('Screenie taken') time.sleep(5.0 - ((time.time() - starttime) % 5.0))
Update service for covers and music
Update service for covers and music
Python
mit
duramato/Beats-Metadata
--- +++ @@ -1,11 +1,21 @@ import time +import os +import logging as logger from selenium import webdriver starttime=time.time() +logger.basicConfig(filename='screenshooter.log',level=logger.DEBUG) url = 'http://applemusic.tumblr.com/beats1' while True: - driver = webdriver.PhantomJS() - driver.set_window_size(1920, 1080) - driver.get(url) - driver.save_screenshot('page.jpg') - print('Screenie taken @ ' + str(time.time()) ) - time.sleep(60.0 - ((time.time() - starttime) % 60.0)) + #driver = webdriver.PhantomJS() + #driver.set_window_size(1920, 1080) + #driver.get(url) + #driver.save_screenshot('page.jpg') + try: + print('hey') + except Exception: + logger.info('No File exsits') + logger.info('screenie init') + os.system("./webshots --width 1080 --height 1920 https://twitter.com/radio_scrobble") + #print('Screenie taken @ ' + str(time.time()) ) + logger.info('Screenie taken') + time.sleep(5.0 - ((time.time() - starttime) % 5.0))
78854858ebeb3fe92df82e203880e177a205051a
apps/mommy/management/commands/mommy-task-run.py
apps/mommy/management/commands/mommy-task-run.py
from django.core.management.base import BaseCommand from apps import mommy class Command(BaseCommand): args = 'name of job' help = 'run a job' @staticmethod def print_job_names(): possible_jobs = [] for task, _ in mommy.schedule.tasks.items(): possible_jobs.append(task.__name__) print("possible jobs:" + str(possible_jobs)) def handle(self, *args, **options): mommy.autodiscover() if len(args) == 0: self.print_job_names() return # run shit do_name = args[0] for task, _ in mommy.schedule.tasks.items(): if task.__name__ == do_name: task.run() return print("could not find job:" + do_name)
from django.core.management.base import BaseCommand from apps import mommy class Command(BaseCommand): help = 'run a job' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) mommy.autodiscover() def add_arguments(self, parser): parser.add_argument('job', help='name of job', choices=Command.job_names()) @staticmethod def job_names(): possible_jobs = [] for task, _ in mommy.schedule.tasks.items(): possible_jobs.append(task.__name__) return possible_jobs def handle(self, *args, **options): mommy.autodiscover() # run shit do_name = options['job'] for task, _ in mommy.schedule.tasks.items(): if task.__name__ == do_name: task.run() return print("could not find job:" + do_name)
Use add_arguments instead of deprecated .args
Use add_arguments instead of deprecated .args
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -4,25 +4,27 @@ class Command(BaseCommand): - args = 'name of job' help = 'run a job' + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + mommy.autodiscover() + + def add_arguments(self, parser): + parser.add_argument('job', help='name of job', choices=Command.job_names()) + @staticmethod - def print_job_names(): + def job_names(): possible_jobs = [] for task, _ in mommy.schedule.tasks.items(): possible_jobs.append(task.__name__) - print("possible jobs:" + str(possible_jobs)) + return possible_jobs def handle(self, *args, **options): mommy.autodiscover() - if len(args) == 0: - self.print_job_names() - return - # run shit - do_name = args[0] + do_name = options['job'] for task, _ in mommy.schedule.tasks.items(): if task.__name__ == do_name: task.run()
7e1a490aa4ab490ef2d53c0f73593ed5bd405920
ftp.py
ftp.py
#!/usr/bin/env python # Designed for use with boofuzz v0.0.1-dev3 from boofuzz import * def main(): session = sessions.Session( target=sessions.Target( connection=SocketConnection("192.168.56.101", 8021, proto='tcp'))) s_initialize("user") s_string("USER") s_delim(" ") s_string("anonymous") s_static("\r\n") s_initialize("pass") s_string("PASS") s_delim(" ") s_string("james") s_static("\r\n") s_initialize("stor") s_string("STOR") s_delim(" ") s_string("AAAA") s_static("\r\n") s_initialize("retr") s_string("RETR") s_delim(" ") s_string("AAAA") s_static("\r\n") session.connect(s_get("user")) session.connect(s_get("user"), s_get("pass")) session.connect(s_get("pass"), s_get("stor")) session.connect(s_get("pass"), s_get("retr")) session.fuzz() if __name__ == "__main__": main()
#!/usr/bin/env python # Designed for use with boofuzz v0.0.1-dev3 from boofuzz import * def main(): session = sessions.Session( target=sessions.Target( connection=SocketConnection("127.0.0.1", 8021, proto='tcp'))) s_initialize("user") s_string("USER") s_delim(" ") s_string("anonymous") s_static("\r\n") s_initialize("pass") s_string("PASS") s_delim(" ") s_string("james") s_static("\r\n") s_initialize("stor") s_string("STOR") s_delim(" ") s_string("AAAA") s_static("\r\n") s_initialize("retr") s_string("RETR") s_delim(" ") s_string("AAAA") s_static("\r\n") session.connect(s_get("user")) session.connect(s_get("user"), s_get("pass")) session.connect(s_get("pass"), s_get("stor")) session.connect(s_get("pass"), s_get("retr")) session.fuzz() if __name__ == "__main__": main()
Use more predictable demo IP address
Use more predictable demo IP address
Python
mit
jtpereyda/boofuzz-ftp
--- +++ @@ -6,7 +6,7 @@ def main(): session = sessions.Session( target=sessions.Target( - connection=SocketConnection("192.168.56.101", 8021, proto='tcp'))) + connection=SocketConnection("127.0.0.1", 8021, proto='tcp'))) s_initialize("user") s_string("USER")
14557e20e2e813a83c05d5733fb2998857527460
Differ.py
Differ.py
file1 = raw_input('[file1:] ') modified = open(file1,"r").readlines()[0] file2 = raw_input('[file2:] ') pi = open(file2, "r").readlines()[0] # [:len(modified)] resultado = "".join( x for x,y in zip(modified, pi) if x != y) resultado2 = "".join( x for x,y in zip(pi, modified) if x != y) print "[Differ:] print '\n-------------------------------------' print "[file1] -> [file2]", resultado print '-------------------------------------' print "[file2] -> [file1]", resultado2
#!/usr/bin/python # Script to Check the difference in 2 files # 1 fevereiro de 2015 # https://github.com/thezakman file1 = raw_input('[file1:] ') modified = open(file1,"r").readlines()[0] file2 = raw_input('[file2:] ') pi = open(file2, "r").readlines()[0] # [:len(modified)] resultado = "".join( x for x,y in zip(modified, pi) if x != y) resultado2 = "".join( x for x,y in zip(pi, modified) if x != y) print "[Differ:] print '\n-------------------------------------' print "[file1] -> [file2]", resultado print '-------------------------------------' print "[file2] -> [file1]", resultado2
Check Diff of 2 files
Check Diff of 2 files
Python
artistic-2.0
thezakman/CTF-Scripts,thezakman/CTF-Scripts
--- +++ @@ -1,3 +1,9 @@ + +#!/usr/bin/python + +# Script to Check the difference in 2 files +# 1 fevereiro de 2015 +# https://github.com/thezakman file1 = raw_input('[file1:] ') modified = open(file1,"r").readlines()[0] @@ -8,6 +14,7 @@ resultado = "".join( x for x,y in zip(modified, pi) if x != y) resultado2 = "".join( x for x,y in zip(pi, modified) if x != y) + print "[Differ:] print '\n-------------------------------------' print "[file1] -> [file2]", resultado
234dd098ccca89c0a547f6d6cf5175a39b3b429b
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages import versioneer setup(name='pycompmusic', version=versioneer.get_version(), description='Tools for playing with the compmusic collection', author='CompMusic / MTG UPF', url='http://compmusic.upf.edu', install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'], packages=find_packages(exclude=["test"]), cmdclass=versioneer.get_cmdclass() )
#!/usr/bin/env python from setuptools import setup, find_packages import versioneer setup(name='pycompmusic', version=versioneer.get_version(), description='Tools for playing with the compmusic collection', author='CompMusic / MTG UPF', author_email='compmusic@upf.edu', url='http://compmusic.upf.edu', install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'], packages=find_packages(exclude=["test"]), cmdclass=versioneer.get_cmdclass() )
Add author info to package config
Add author info to package config
Python
agpl-3.0
MTG/pycompmusic
--- +++ @@ -8,6 +8,7 @@ version=versioneer.get_version(), description='Tools for playing with the compmusic collection', author='CompMusic / MTG UPF', + author_email='compmusic@upf.edu', url='http://compmusic.upf.edu', install_requires=['musicbrainzngs', 'requests', 'six', 'eyed3'], packages=find_packages(exclude=["test"]),
ba8615cb7d895ce883d5126b557c29a69e2f93e0
setup.py
setup.py
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-api', version='0.1.2', packages=['django_api'], include_package_data=True, license='BSD License', description='Specify and validate your Django APIs', long_description=README, author='Bipin Suresh', author_email='bipins@alumni.stanford.edu', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-api', version='0.1.2', packages=['django_api'], url='https://github.com/bipsandbytes/django-api', include_package_data=True, license='BSD License', description='Specify and validate your Django APIs', long_description=README, author='Bipin Suresh', author_email='bipins@alumni.stanford.edu', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Add URL in package info
Add URL in package info
Python
bsd-3-clause
bipsandbytes/django-api
--- +++ @@ -12,6 +12,7 @@ name='django-api', version='0.1.2', packages=['django_api'], + url='https://github.com/bipsandbytes/django-api', include_package_data=True, license='BSD License', description='Specify and validate your Django APIs',
79c0568b600443e0b86097a6e60ee0526a2b8db3
setup.py
setup.py
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-basic-podcast', version='0.3', description='Blanc Basic Podcast for Django', long_description=readme, url='https://github.com/blancltd/blanc-basic-podcast', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], extras_require={ ':python_version == "2.7"': [ 'hsaudiotag>=1.1.1', ], ':python_version >= "3.3"': [ 'hsaudiotag3k>=1.1.3', ], }, packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-basic-podcast', version='0.3', description='Blanc Basic Podcast for Django', long_description=readme, url='https://github.com/developersociety/blanc-basic-podcast', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], extras_require={ ':python_version == "2.7"': [ 'hsaudiotag>=1.1.1', ], ':python_version >= "3.3"': [ 'hsaudiotag3k>=1.1.3', ], }, packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
Update GitHub repos from blancltd to developersociety
Update GitHub repos from blancltd to developersociety
Python
bsd-2-clause
blancltd/blanc-basic-podcast
--- +++ @@ -13,7 +13,7 @@ version='0.3', description='Blanc Basic Podcast for Django', long_description=readme, - url='https://github.com/blancltd/blanc-basic-podcast', + url='https://github.com/developersociety/blanc-basic-podcast', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'],
afe3cd41e5224e5de5aa37ee8ef2b0fa485cb1b0
setup.py
setup.py
from distutils.core import setup setup( name = 'athletic_pandas', packages = ['athletic_pandas'], version = '0.3', description = 'Workout analysis', author='Aart Goossens', author_email='aart@goossens.me', url='https://github.com/AartGoossens/athletic_pandas', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', ] )
from distutils.core import setup setup( name = 'athletic_pandas', packages = ['athletic_pandas'], version = '0.4.0', description = 'Workout analysis', author='Aart Goossens', author_email='aart@goossens.me', url='https://github.com/AartGoossens/athletic_pandas', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', ] )
CHANGE - Updates version to 0.4.0
CHANGE - Updates version to 0.4.0
Python
mit
AartGoossens/athletic_pandas
--- +++ @@ -3,7 +3,7 @@ setup( name = 'athletic_pandas', packages = ['athletic_pandas'], - version = '0.3', + version = '0.4.0', description = 'Workout analysis', author='Aart Goossens', author_email='aart@goossens.me',
800b9faf318bd5fd403ae9beef8bddb35e82802a
setup.py
setup.py
#!/usr/bin/env python3 try: from setuptools import setup except ImportError: from distutils.core import setup with open('fcmcmp/__meta__.py') as file: exec(file.read()) with open('README.rst') as file: readme = file.read() setup( name='fcmcmp', version=__version__, author=__author__, author_email=__email__, description="A lightweight, flexible, and modern framework for annotating flow cytometry data.", long_description=readme, url='https://github.com/kalekundert/fcmcmp', packages=[ 'fcmcmp', ], include_package_data=True, install_requires=[ 'fcsparser', 'pyyaml', ], license='MIT', zip_safe=False, keywords=[ 'fcmcmp', ], )
#!/usr/bin/env python3 try: from setuptools import setup except ImportError: from distutils.core import setup with open('fcmcmp/__meta__.py') as file: exec(file.read()) with open('README.rst') as file: readme = file.read() setup( name='fcmcmp', version=__version__, author=__author__, author_email=__email__, description="A lightweight, flexible, and modern framework for annotating flow cytometry data.", long_description=readme, url='https://github.com/kalekundert/fcmcmp', packages=[ 'fcmcmp', ], include_package_data=True, install_requires=[ 'fcsparser', 'pyyaml', 'pathlib', ], license='MIT', zip_safe=False, keywords=[ 'fcmcmp', ], )
Add pathlib as a dependency.
Add pathlib as a dependency. This is only required for python<=3.2, after which pathlib is included in the standard library.
Python
mit
kalekundert/fcmcmp
--- +++ @@ -25,6 +25,7 @@ install_requires=[ 'fcsparser', 'pyyaml', + 'pathlib', ], license='MIT', zip_safe=False,
c9278c030620a0b56e88130a745ee21315b904bf
setup.py
setup.py
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='consultants@pdx.edu', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=0.9.9.2', ], 'dev': [ 'django>=1.7', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='consultants@pdx.edu', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.2', ], 'dev': [ 'django>=1.7', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Upgrade ldap3 0.9.9.2 => 1.0.2
Upgrade ldap3 0.9.9.2 => 1.0.2
Python
mit
wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils
--- +++ @@ -32,7 +32,7 @@ ], 'ldap': [ 'certifi>=2015.11.20.1', - 'ldap3>=0.9.9.2', + 'ldap3>=1.0.2', ], 'dev': [ 'django>=1.7',
c90a76dd2f8b7ccfd081267b3d246d47a18df2e2
setup.py
setup.py
from distutils.core import setup setup(name='lattice', version='0.8', description='Java Build tool in Python', author='Zhenlei Cai', author_email='jpenguin@gmail.com', url='http://www.python.org/sigs/distutils-sig/', include_package_data = True, packages=['lattice'] )
from setuptools import setup, find_packages setup(name='lattice', version='0.9', description='Java Build tool in Python', author='Zhenlei Cai', author_email='jpenguin@gmail.com', url='http://www.python.org/sigs/distutils-sig/', include_package_data = True, packages=['lattice'], package_data = { '': ['*.jar'], } )
Include junit.jar in the final EGG package installation
Include junit.jar in the final EGG package installation
Python
apache-2.0
jerryzhenleicai/lattice,jerryzhenleicai/lattice,jerryzhenleicai/lattice
--- +++ @@ -1,13 +1,15 @@ - -from distutils.core import setup +from setuptools import setup, find_packages setup(name='lattice', - version='0.8', + version='0.9', description='Java Build tool in Python', author='Zhenlei Cai', author_email='jpenguin@gmail.com', url='http://www.python.org/sigs/distutils-sig/', include_package_data = True, - packages=['lattice'] + packages=['lattice'], + package_data = { + '': ['*.jar'], + } )
055b939e8e906c5c03130680edb8f7e5642e9141
setup.py
setup.py
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts', 'jinja2'] setup(name='substance', version=__version__, author='turbulent/bbeausej', author_email='b@turbulent.ca', license='MIT', long_description=readme, description='substance - local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={ 'substance': ['support/*'] }, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts=0.3.3', 'jinja2'] setup(name='substance', version=__version__, author='turbulent/bbeausej', author_email='b@turbulent.ca', license='MIT', long_description=readme, description='substance - local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={ 'substance': ['support/*'] }, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
Use 0.3.3 hosts mgmt plugin because 0.3.4 is borked.
Use 0.3.3 hosts mgmt plugin because 0.3.4 is borked.
Python
apache-2.0
turbulent/substance,turbulent/substance
--- +++ @@ -5,7 +5,7 @@ execfile('substance/_version.py') -install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts', 'jinja2'] +install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts=0.3.3', 'jinja2'] setup(name='substance', version=__version__,
b5a049b1b7b4c2d759aafc38ef2f9af148396bbd
setup.py
setup.py
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-game-info', version='0.1', packages=['game_info'], include_package_data=True, license='BSD License', description='A django app to gather information from game servers.', long_description=README, url='https://github.com/Azelphur-Servers/django-game-info', author='Alfie "Azelphur" Day', author_email='support@azelphur.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-game-info', version='0.1.1', packages=['game_info'], include_package_data=True, license='BSD License', description='A django app to gather information from game servers.', long_description=README, url='https://github.com/Azelphur-Servers/django-game-info', author='Alfie "Azelphur" Day', author_email='support@azelphur.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Update do version 0.1.1 which should hopefully trigger automatic pypi deployment
Update do version 0.1.1 which should hopefully trigger automatic pypi deployment
Python
bsd-3-clause
Azelphur-Servers/django-game-info
--- +++ @@ -9,7 +9,7 @@ setup( name='django-game-info', - version='0.1', + version='0.1.1', packages=['game_info'], include_package_data=True, license='BSD License',
e2e4b0b10dcc0cd98b0e87e63db073dd2f27882f
setup.py
setup.py
#!/usr/bin/env python # Author: Aziz Alto # email: iamaziz.alto@gmail.com try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='pydataset', description=("Provides instant access to many popular datasets right from " "Python (in dataframe structure)."), author='Aziz Alto', url='https://github.com/iamaziz/PyDataset', download_url='https://github.com/iamaziz/PyDataset/archive/master.zip', license = 'MIT', author_email='iamaziz.alto@gmail.com', version='0.1.0', install_requires=['pandas'], packages=['pydataset', 'pydataset.utils'], package_data={'pydataset': ['*.gz', 'resources.tar.gz']} )
#!/usr/bin/env python # Author: Aziz Alto # email: iamaziz.alto@gmail.com try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='pydataset', description=("Provides instant access to many popular datasets right from " "Python (in dataframe structure)."), author='Aziz Alto', url='https://github.com/iamaziz/PyDataset', download_url='https://github.com/iamaziz/PyDataset/tarball/0.1.0', license = 'MIT', author_email='iamaziz.alto@gmail.com', version='0.1.0', install_requires=['pandas'], packages=['pydataset', 'pydataset.utils'], package_data={'pydataset': ['*.gz', 'resources.tar.gz']} )
Add download URL for PyPI
Add download URL for PyPI
Python
mit
iamaziz/PyDataset
--- +++ @@ -15,7 +15,7 @@ "Python (in dataframe structure)."), author='Aziz Alto', url='https://github.com/iamaziz/PyDataset', - download_url='https://github.com/iamaziz/PyDataset/archive/master.zip', + download_url='https://github.com/iamaziz/PyDataset/tarball/0.1.0', license = 'MIT', author_email='iamaziz.alto@gmail.com', version='0.1.0',
9481843728077b8445d5e2323b40d322760064b9
setup.py
setup.py
#!/usr/bin/env python # Credit to bartTC and https://github.com/bartTC/django-memcache-status for ideas try: from setuptools import setup, find_packages from setuptools.command.test import test except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test class mytest(test): def run(self, *args, **kwargs): from runtests import runtests runtests() setup( name='nexus-memcache', version='0.3.6', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/nexus-memcache', description = 'Memcache Plugin for Nexus', packages=find_packages(), zip_safe=False, install_requires=[ 'nexus>=0.1.3', ], test_suite = 'nexus_memcache.tests', include_package_data=True, cmdclass={"test": mytest}, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python # Credit to bartTC and https://github.com/bartTC/django-memcache-status for ideas try: from setuptools import setup, find_packages from setuptools.command.test import test except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test class mytest(test): def run(self, *args, **kwargs): from runtests import runtests runtests() setup( name='nexus-memcache', version='0.3.6', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/nexus-memcache', description = 'Memcache Plugin for Nexus', packages=find_packages(), zip_safe=False, install_requires=[ 'nexus-yplan>=1.6.0', ], test_suite = 'nexus_memcache.tests', include_package_data=True, cmdclass={"test": mytest}, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Update nexus requirement so pip stops complaining.
Update nexus requirement so pip stops complaining.
Python
apache-2.0
brilliant-org/nexus-memcache,brilliant-org/nexus-memcache,brilliant-org/nexus-memcache
--- +++ @@ -27,7 +27,7 @@ packages=find_packages(), zip_safe=False, install_requires=[ - 'nexus>=0.1.3', + 'nexus-yplan>=1.6.0', ], test_suite = 'nexus_memcache.tests', include_package_data=True,
6377a1a50293c2b62eb5e29c936998ad09995c7a
service/inchi.py
service/inchi.py
import requests import json from subprocess import Popen, PIPE import tempfile import os import sys config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi)) if request.status_code == 200: cjson = request.json(); else: print >> sys.stderr, "Unable to access REST API: %s" % request.status_code return None # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
import requests import json from subprocess import Popen, PIPE import tempfile import os import sys config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi) request = requests.get(request_url) if request.status_code == 200: cjson = request.json(); else: print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code) return None # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
Fix URL for fetch CJSON
Fix URL for fetch CJSON
Python
bsd-3-clause
OpenChemistry/mongochemweb,OpenChemistry/mongochemweb
--- +++ @@ -11,12 +11,13 @@ def to_cml(inchi): - request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi)) + request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi) + request = requests.get(request_url) if request.status_code == 200: cjson = request.json(); else: - print >> sys.stderr, "Unable to access REST API: %s" % request.status_code + print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code) return None # Call convertion routine
79678296fa20cbfa11aa9a58496de09a71e88ac4
setup.py
setup.py
# -*- coding: utf-8 -*- try: from setuptools import setup from setuptools.command.install import install except ImportError: from distutils.core import setup from distutils.core.command.install import install class CustomInstallCommand(install): """Install as noteboook extension""" def install_extension(self): from os.path import dirname, abspath, join from IPython.html.nbextensions import install_nbextension from IPython.html.services.config import ConfigManager print("Installing nbextension ...") flightwidgets = join(dirname(abspath(__file__)), 'flightwidgets', 'js') install_nbextension(flightwidgets, destination='flightwidgets') def run(self): print "Installing Python module..." install.run(self) # Install Notebook extension self.install_extension() from glob import glob setup( name='flightwidgets', version='0.1', description='Flight attitude and compass widgets for the Jupyter notebook.', author='Jonathan Frederic', author_email='jon.freder@gmail.com', license='New BSD License', url='https://github.com/jdfreder/ipython-flightwidgets', keywords='data visualization interactive interaction python ipython widgets widget', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'License :: OSI Approved :: MIT License'], packages=['flightwidgets', 'flightwidgets/py'], include_package_data=True, cmdclass={ 'install': CustomInstallCommand, 'develop': CustomInstallCommand, } )
# -*- coding: utf-8 -*- try: from setuptools import setup from setuptools.command.install import install except ImportError: from distutils.core import setup from distutils.core.command.install import install class InstallCommand(install): """Install as noteboook extension""" develop = False def install_extension(self): from os.path import dirname, abspath, join from IPython.html.nbextensions import install_nbextension from IPython.html.services.config import ConfigManager print("Installing nbextension ...") flightwidgets = join(dirname(abspath(__file__)), 'flightwidgets', 'js') install_nbextension(flightwidgets, destination='flightwidgets', symlink=self.develop, user=True) def run(self): print "Installing Python module..." install.run(self) # Install Notebook extension self.install_extension() class DevelopCommand(InstallCommand): """Install as noteboook extension""" develop = True from glob import glob setup( name='flightwidgets', version='0.1', description='Flight attitude and compass widgets for the Jupyter notebook.', author='Jonathan Frederic', author_email='jon.freder@gmail.com', license='New BSD License', url='https://github.com/jdfreder/ipython-flightwidgets', keywords='data visualization interactive interaction python ipython widgets widget', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'License :: OSI Approved :: MIT License'], packages=['flightwidgets', 'flightwidgets/py'], include_package_data=True, cmdclass={ 'install': InstallCommand, 'develop': DevelopCommand, } )
Add suport for development installs.
Add suport for development installs.
Python
bsd-3-clause
jdfreder/ipython-flightwidgets,jdfreder/ipython-flightwidgets
--- +++ @@ -7,10 +7,10 @@ from distutils.core import setup from distutils.core.command.install import install +class InstallCommand(install): + """Install as noteboook extension""" + develop = False - -class CustomInstallCommand(install): - """Install as noteboook extension""" def install_extension(self): from os.path import dirname, abspath, join from IPython.html.nbextensions import install_nbextension @@ -18,7 +18,7 @@ print("Installing nbextension ...") flightwidgets = join(dirname(abspath(__file__)), 'flightwidgets', 'js') - install_nbextension(flightwidgets, destination='flightwidgets') + install_nbextension(flightwidgets, destination='flightwidgets', symlink=self.develop, user=True) def run(self): print "Installing Python module..." @@ -26,6 +26,10 @@ # Install Notebook extension self.install_extension() + +class DevelopCommand(InstallCommand): + """Install as noteboook extension""" + develop = True from glob import glob setup( @@ -43,7 +47,7 @@ packages=['flightwidgets', 'flightwidgets/py'], include_package_data=True, cmdclass={ - 'install': CustomInstallCommand, - 'develop': CustomInstallCommand, + 'install': InstallCommand, + 'develop': DevelopCommand, } )
309a8c9a39ddfa01d2e3c24aab0bc50a84121f4e
setup.py
setup.py
import os from distutils.core import setup from shortwave import VERSION def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-shortwave', version=VERSION, description='Shortwave command file management for Django apps.', url='https://github.com/benspaulding/django-shortwave/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-shortwave/tarball/v%s' % VERSION, long_description = read('README.rst'), packages = [ 'shortwave', 'shortwave.tests' ], package_data = { 'shortwave': [ 'fixtures/*', 'locale/*/LC_MESSAGES/*', 'templates/shortwave/*', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], )
import os from distutils.core import setup from shortwave import VERSION def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-shortwave', version=VERSION, description='Shortwave command file management for Django apps.', url='https://github.com/benspaulding/django-shortwave/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-shortwave/tarball/v%s' % VERSION, long_description = read('README.rst'), packages = [ 'shortwave', 'shortwave.tests' ], package_data = { 'shortwave': [ 'fixtures/*', 'locale/*/LC_MESSAGES/*', 'templates/shortwave/*', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], )
Add newline to format imports properly.
Add newline to format imports properly.
Python
bsd-3-clause
benspaulding/django-shortwave
--- +++ @@ -1,4 +1,5 @@ import os + from distutils.core import setup from shortwave import VERSION
92abc4715e001be7f4729612c31616e0d63c3a2e
setup.py
setup.py
from setuptools import setup setup( name='cb-event-duplicator', version='1.2.0', packages=['cbopensource', 'cbopensource.tools', 'cbopensource.tools.eventduplicator'], url='https://github.com/carbonblack/cb-event-duplicator', license='MIT', author='Bit9 + Carbon Black Developer Network', author_email='dev-support@bit9.com', description='Extract events from one Carbon Black server and send them to another server ' + '- useful for demo/testing purposes', install_requires=[ 'requests==2.7.0', 'paramiko==1.15.2', 'psycopg2==2.6.1' ], entry_points={ 'console_scripts': ['cb-event-duplicator=cbopensource.tools.eventduplicator.data_migration:main'] }, classifiers=[ 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ], keywords='carbonblack', )
from setuptools import setup setup( name='cb-event-duplicator', version='1.2.0', packages=['cbopensource', 'cbopensource.tools', 'cbopensource.tools.eventduplicator'], url='https://github.com/carbonblack/cb-event-duplicator', license='MIT', author='Bit9 + Carbon Black Developer Network', author_email='dev-support@bit9.com', description='Extract events from one Carbon Black server and send them to another server ' + '- useful for demo/testing purposes', install_requires=[ 'requests==2.7.0', 'paramiko<2.0', 'psycopg2==2.6.1' ], entry_points={ 'console_scripts': ['cb-event-duplicator=cbopensource.tools.eventduplicator.data_migration:main'] }, classifiers=[ 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ], keywords='carbonblack', )
Update paramiko dependency for vulnerability
Update paramiko dependency for vulnerability
Python
mit
carbonblack/cb-event-duplicator
--- +++ @@ -12,7 +12,7 @@ '- useful for demo/testing purposes', install_requires=[ 'requests==2.7.0', - 'paramiko==1.15.2', + 'paramiko<2.0', 'psycopg2==2.6.1' ], entry_points={
74a09fe1aa31db15501d260749dba12e227f91cb
setup.py
setup.py
__VERSION__ = '1.0.3' from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except OSError: # Stolen from pypandoc: if pandoc is not installed, fallback to using raw contents long_description = open('README.md').read() except ImportError: long_description = None setup( name='python-editor', version=__VERSION__, description="Programmatically open an editor, capture the result.", long_description=long_description, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries', ], keywords='editor library vim emacs', author='Peter Ruibal', author_email='ruibalp@gmail.com', url='https://github.com/fmoo/python-editor', license='Apache', py_modules=[ 'editor', ], requires=[ #'six', ], )
__VERSION__ = '1.0.3' from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except OSError: # Stolen from pypandoc: if pandoc is not installed, fallback to using raw contents long_description = open('README.md').read() except ImportError: long_description = None setup( name='python-editor', version=__VERSION__, description="Programmatically open an editor, capture the result.", long_description=long_description, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries', ], keywords='editor library vim emacs', author='Peter Ruibal', author_email='ruibalp@gmail.com', url='https://github.com/fmoo/python-editor', license='Apache', py_modules=[ 'editor', ], requires=[ #'six', ], )
Drop EOL Python 3.3, add 3.6
Drop EOL Python 3.3, add 3.6
Python
apache-2.0
fmoo/python-editor
--- +++ @@ -23,9 +23,9 @@ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries', ], keywords='editor library vim emacs',
dbbf69546f10cc7e197a61212f728f6f7b303398
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name='fortigateconf', version='0.4.1', description='Python modules to interact with Fortigate configuration rest and ssh', install_requires=['requests','paramiko','logging'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/thomnico/fortigateconf', packages=['fortigateconf'], )
#!/usr/bin/env python from setuptools import setup setup( name='fortigateconf', version='0.4.2', description='Python modules to interact with Fortigate configuration rest and ssh', install_requires=['requests','paramiko'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/thomnico/fortigateconf', packages=['fortigateconf'], )
Remove explicit deps to logging to avoir pip3 mess
Remove explicit deps to logging to avoir pip3 mess
Python
apache-2.0
thomnico/fortigateconf,thomnico/fortiosapi,thomnico/fortiosapi
--- +++ @@ -4,9 +4,9 @@ setup( name='fortigateconf', - version='0.4.1', + version='0.4.2', description='Python modules to interact with Fortigate configuration rest and ssh', - install_requires=['requests','paramiko','logging'], + install_requires=['requests','paramiko'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/thomnico/fortigateconf',
2cf9a67d578161943ea5c624a88e9114a89d7ccd
setup.py
setup.py
#!/usr/bin/env python """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages import backlog with open('README.rst') as readme_file: README = readme_file.read() setup( name='backlog', version=backlog.__version__, description=backlog.__doc__, long_description=README, license='LGPLv2+', url='https://github.com/dmtucker/backlog', author='David Tucker', author_email='david.michael.tucker@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='notes backlog todo lists', packages=find_packages(exclude=['contrib', 'docs', 'tests']), entry_points={'console_scripts': ['backlog=backlog.__main__:main']}, )
#!/usr/bin/env python # coding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from __future__ import absolute_import from setuptools import setup, find_packages import backlog with open('README.rst') as readme_file: README = readme_file.read() setup( name='backlog', version=backlog.__version__, description=backlog.__doc__, long_description=README, author='David Tucker', author_email='david.michael.tucker@gmail.com', license='LGPLv2+', url='https://github.com/dmtucker/backlog', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['backlog=backlog.__main__:main']}, keywords='notes backlog todo lists', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Development Status :: 4 - Beta', ], )
Make ordering consistent with keysmith
Make ordering consistent with keysmith
Python
lgpl-2.1
dmtucker/backlog
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python +# coding: utf-8 """A setuptools based setup module. @@ -7,6 +8,7 @@ https://github.com/pypa/sampleproject """ +from __future__ import absolute_import from setuptools import setup, find_packages import backlog @@ -18,20 +20,21 @@ version=backlog.__version__, description=backlog.__doc__, long_description=README, + author='David Tucker', + author_email='david.michael.tucker@gmail.com', license='LGPLv2+', url='https://github.com/dmtucker/backlog', - author='David Tucker', - author_email='david.michael.tucker@gmail.com', + packages=find_packages(exclude=['contrib', 'docs', 'tests']), + include_package_data=True, + entry_points={'console_scripts': ['backlog=backlog.__main__:main']}, + keywords='notes backlog todo lists', classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', + 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', - ], - keywords='notes backlog todo lists', - packages=find_packages(exclude=['contrib', 'docs', 'tests']), - entry_points={'console_scripts': ['backlog=backlog.__main__:main']}, + 'Development Status :: 4 - Beta', + ], )
70ba345d2c1bf8a695656406359c081611d01f90
setup.py
setup.py
from codecs import open as codecs_open import distutils.log import os.path import shutil from setuptools import setup, find_packages import subprocess # Try to convert README markdown to restructured text using pandoc. try: subprocess.call( 'pandoc --from=markdown --to=rst --output=README README.md', shell=True) assert os.path.exists('README') except: distutils.log.warn( "Conversion of README.md to restructured text was not successful.") shutil.copy('README.md', 'README') # Get the long description from the relevant file with codecs_open('README', encoding='utf-8') as f: long_description = f.read() setup(name='pygeobuf', version='1.0.0', description=( u"Geobuf is a compact binary geospatial format for lossless " u"compression of GeoJSON and TopoJSON data."), long_description=long_description, classifiers=[], keywords='data gis geojson topojson protobuf', author=u"Vladimir Agafonkin", author_email='vladimir@mapbox.com', url='https://github.com/mapbox/pygeobuf', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click', 'protobuf', ], extras_require={ 'test': ['pytest'], }, entry_points=""" [console_scripts] geobuf=geobuf.scripts.cli:cli """)
from codecs import open as codecs_open import distutils.log import os.path import shutil from setuptools import setup, find_packages import subprocess # Try to convert README markdown to restructured text using pandoc. try: subprocess.call( 'pandoc --from=markdown --to=rst --output=README README.md', shell=True) assert os.path.exists('README') except: distutils.log.warn( "Conversion of README.md to restructured text was not successful.") shutil.copy('README.md', 'README') # Get the long description from the relevant file with codecs_open('README', encoding='utf-8') as f: long_description = f.read() setup(name='geobuf', version='1.0.0', description=( u"Geobuf is a compact binary geospatial format for lossless " u"compression of GeoJSON and TopoJSON data."), long_description=long_description, classifiers=[], keywords='data gis geojson topojson protobuf', author=u"Vladimir Agafonkin", author_email='vladimir@mapbox.com', url='https://github.com/mapbox/pygeobuf', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click', 'protobuf', ], extras_require={ 'test': ['pytest'], }, entry_points=""" [console_scripts] geobuf=geobuf.scripts.cli:cli """)
Change package to geobuf, matching the module name.
Change package to geobuf, matching the module name.
Python
isc
mapbox/pygeobuf
--- +++ @@ -21,7 +21,7 @@ with codecs_open('README', encoding='utf-8') as f: long_description = f.read() -setup(name='pygeobuf', +setup(name='geobuf', version='1.0.0', description=( u"Geobuf is a compact binary geospatial format for lossless "
a1796f2cd30efae9f2dda77c4386f8bef9ca459f
setup.py
setup.py
"""Install Mesh TensorFlow.""" from setuptools import find_packages from setuptools import setup setup( name='mesh-tensorflow', version='0.1.14', description='Mesh TensorFlow', author='Google Inc.', author_email='no-reply@google.com', url='http://github.com/tensorflow/mesh', license='Apache 2.0', packages=find_packages(), package_data={ # Include gin files. 'transformer': ['transformer/gin/*.gin'], }, scripts=[], install_requires=[ 'absl-py', 'future', 'gin-config', 'six', ], extras_require={ 'auto_mtf': ['ortools'], 'tensorflow': ['tensorflow>=1.15.0'], 'transformer': ['tensorflow-datasets'], }, tests_require=[ 'ortools', 'pytest', 'tensorflow', 'tensorflow-datasets', ], setup_requires=['pytest-runner'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], keywords='tensorflow machine learning', )
"""Install Mesh TensorFlow.""" from setuptools import find_packages from setuptools import setup setup( name='mesh-tensorflow', version='0.1.15', description='Mesh TensorFlow', author='Google Inc.', author_email='no-reply@google.com', url='http://github.com/tensorflow/mesh', license='Apache 2.0', packages=find_packages(), package_data={ # Include gin files. '': ['*.gin'], }, scripts=[], install_requires=[ 'absl-py', 'future', 'gin-config', 'six', ], extras_require={ 'auto_mtf': ['ortools'], 'tensorflow': ['tensorflow>=1.15.0'], 'transformer': ['tensorflow-datasets'], }, tests_require=[ 'ortools', 'pytest', 'tensorflow', 'tensorflow-datasets', ], setup_requires=['pytest-runner'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], keywords='tensorflow machine learning', )
Include all gin files in pip package.
Include all gin files in pip package. PiperOrigin-RevId: 318120480
Python
apache-2.0
tensorflow/mesh,tensorflow/mesh
--- +++ @@ -5,7 +5,7 @@ setup( name='mesh-tensorflow', - version='0.1.14', + version='0.1.15', description='Mesh TensorFlow', author='Google Inc.', author_email='no-reply@google.com', @@ -14,7 +14,7 @@ packages=find_packages(), package_data={ # Include gin files. - 'transformer': ['transformer/gin/*.gin'], + '': ['*.gin'], }, scripts=[], install_requires=[
5118c78a3a89424e0577d538b2f85b1753284344
setup.py
setup.py
import os import re from setuptools import setup, find_packages def get_version(): with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f: for line in f.readlines(): m = re.match(r"__version__ = '(.*?)'", line) if m: return m.group(1) raise ValueError('Cannot find version') def parse_requirements(req_file_path): with open(req_file_path) as f: return f.readlines() setup( name="gitlab-merge-request", version=get_version(), author="Alexander Koval", author_email="kovalidis@gmail.com", description=("Console utility to create gitlab merge requests."), license="Apache License 2.0", keywords="git gitlab merge-request", url="https://github.com/anti-social/gitlab-merge-request", py_modules=[ 'gitlab_mr', ], entry_points = { 'console_scripts': ['gitlab-mr = gitlab_mr:main'], }, install_requires=parse_requirements('requirements.txt'), classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Environment :: Console", "Topic :: Software Development :: Version Control", "Topic :: Utilities", ], )
import os import re import sys from setuptools import setup, find_packages PY_VER = sys.version_info if PY_VER >= (3, 4): pass else: raise RuntimeError("Only support Python version >= 3.4") def get_version(): with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f: for line in f.readlines(): m = re.match(r"__version__ = '(.*?)'", line) if m: return m.group(1) raise ValueError('Cannot find version') def parse_requirements(req_file_path): with open(req_file_path) as f: return f.readlines() setup( name="gitlab-merge-request", version=get_version(), author="Alexander Koval", author_email="kovalidis@gmail.com", description=("Console utility to create gitlab merge requests."), license="Apache License 2.0", keywords="git gitlab merge-request", url="https://github.com/anti-social/gitlab-merge-request", py_modules=[ 'gitlab_mr', ], entry_points = { 'console_scripts': ['gitlab-mr = gitlab_mr:main'], }, install_requires=parse_requirements('requirements.txt'), classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Environment :: Console", "Topic :: Software Development :: Version Control", "Topic :: Utilities", ], )
Support only python >= 3.4
Support only python >= 3.4
Python
apache-2.0
anti-social/gitlab-merge-request
--- +++ @@ -1,6 +1,15 @@ import os import re +import sys from setuptools import setup, find_packages + + +PY_VER = sys.version_info + +if PY_VER >= (3, 4): + pass +else: + raise RuntimeError("Only support Python version >= 3.4") def get_version():
7c0d5465e282b3a55dc67a8b94f7451cbd470351
setup.py
setup.py
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import os import sys if sys.version < '3': execfile(os.path.join('icebergsdk', 'version.py')) else: exec(open("icebergsdk/version.py").read()) install_requires = [] install_requires.append('requests >= 2.3.0') install_requires.append('algoliasearch==1.5.9') install_requires.append('python-dateutil>=2.4.0') install_requires.append('pytz') setup( name='icebergsdk', version=VERSION, description='Iceberg Marketplace API Client for Python', author='Iceberg', author_email='florian@izberg-marketplace.com', url='https://github.com/Iceberg-Marketplace/Iceberg-API-PYTHON', packages = ["icebergsdk", 'icebergsdk.resources', 'icebergsdk.mixins', 'icebergsdk.utils'], install_requires = install_requires, keywords = ['iceberg', 'modizy', 'marketplace', 'saas'], classifiers = [ "Development Status :: 2 - Pre-Alpha", 'Intended Audience :: Developers', "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import os import sys if sys.version < '3': execfile(os.path.join('icebergsdk', 'version.py')) else: exec(open("icebergsdk/version.py").read()) install_requires = [] install_requires.append('requests >= 2.3.0') install_requires.append('algoliasearch>=1.7.1') install_requires.append('python-dateutil>=2.4.0') install_requires.append('pytz') setup( name='icebergsdk', version=VERSION, description='Iceberg Marketplace API Client for Python', author='Iceberg', author_email='florian@izberg-marketplace.com', url='https://github.com/Iceberg-Marketplace/Iceberg-API-PYTHON', packages = ["icebergsdk", 'icebergsdk.resources', 'icebergsdk.mixins', 'icebergsdk.utils'], install_requires = install_requires, keywords = ['iceberg', 'modizy', 'marketplace', 'saas'], classifiers = [ "Development Status :: 2 - Pre-Alpha", 'Intended Audience :: Developers', "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Update algoliasearch requirement to >=1.7.1 (Unreachable host algolia error fix)
Update algoliasearch requirement to >=1.7.1 (Unreachable host algolia error fix)
Python
mit
Iceberg-Marketplace/Iceberg-API-PYTHON,izberg-marketplace/izberg-api-python
--- +++ @@ -15,7 +15,7 @@ install_requires = [] install_requires.append('requests >= 2.3.0') -install_requires.append('algoliasearch==1.5.9') +install_requires.append('algoliasearch>=1.7.1') install_requires.append('python-dateutil>=2.4.0') install_requires.append('pytz')
225af65498426edce75ffbc0ab80ad1757446d0e
setup.py
setup.py
from setuptools import setup from webhooks import __version__ with open('README.rst') as f: long_description = f.read() setup( name='webhooks', version=__version__, description='Flask app for triggering Jenkins builds by GitHub webhooks', long_description=long_description, url='https://github.com/Wikia/jenkins-webhooks', author='macbre', author_email='macbre@wikia-inc.com', packages=['webhooks'], install_requires=[ 'Flask==0.10.1', 'jenkinsapi==0.2.25', 'pytest==2.6.0', 'pyyaml==3.11', 'mock==1.0.1', 'gunicorn==19.4.5' ], include_package_data=True, entry_points={ 'console_scripts': [ 'webhooks-server=webhooks.app:run' ], }, )
from setuptools import setup from webhooks import __version__ with open('README.rst') as f: long_description = f.read() setup( name='webhooks', version=__version__, description='Flask app for triggering Jenkins builds by GitHub webhooks', long_description=long_description, url='https://github.com/Wikia/jenkins-webhooks', author='macbre', author_email='macbre@wikia-inc.com', packages=['webhooks'], install_requires=[ 'Flask==0.10.1', 'jenkinsapi==0.2.29', 'pytest==2.6.0', 'pyyaml==3.11', 'mock==1.0.1', 'gunicorn==19.4.5' ], include_package_data=True, entry_points={ 'console_scripts': [ 'webhooks-server=webhooks.app:run' ], }, )
Revert "Revert "Upgrade to jenkinsapi==0.2.29""
Revert "Revert "Upgrade to jenkinsapi==0.2.29"" This reverts commit 35ffadfd1adb1a02875e0e0cfcf1c67f229e2ba9.
Python
mit
Wikia/jenkins-webhooks
--- +++ @@ -16,7 +16,7 @@ packages=['webhooks'], install_requires=[ 'Flask==0.10.1', - 'jenkinsapi==0.2.25', + 'jenkinsapi==0.2.29', 'pytest==2.6.0', 'pyyaml==3.11', 'mock==1.0.1',
a4d2d4c4520dfffc1c5501db671805760933b126
setup.py
setup.py
from setuptools import setup, find_packages from annotator import __version__, __license__, __author__ setup( name = 'annotator', version = __version__, packages = find_packages(), install_requires = [ 'Flask==0.8', 'Flask-WTF==0.5.2', 'Flask-SQLAlchemy==0.15', 'SQLAlchemy==0.7.4', 'pyes==0.16.0', 'nose==1.0.0', 'iso8601==0.1.4' ], # metadata for upload to PyPI author = __author__, author_email = 'annotator@okfn.org', description = 'Inline web annotation application and middleware using javascript and WSGI', long_description = """Inline javascript-based web annotation library. \ Package includeds a database-backed annotation store \ with RESTFul (WSGI-powered) web-interface.""", license = __license__, keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
from setuptools import setup, find_packages from annotator import __version__, __license__, __author__ setup( name = 'annotator', version = __version__, packages = find_packages(), install_requires = [ 'Flask==0.8', 'Flask-WTF==0.5.2', 'Flask-SQLAlchemy==0.15', 'SQLAlchemy==0.7.4', 'pyes==0.16.0', 'nose==1.0.0', 'mock==0.7.4', 'iso8601==0.1.4' ], # metadata for upload to PyPI author = __author__, author_email = 'annotator@okfn.org', description = 'Inline web annotation application and middleware using javascript and WSGI', long_description = """Inline javascript-based web annotation library. \ Package includeds a database-backed annotation store \ with RESTFul (WSGI-powered) web-interface.""", license = __license__, keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
Add forgotten dependency on mock
Add forgotten dependency on mock
Python
mit
nobita-isc/annotator-store,nobita-isc/annotator-store,ningyifan/annotator-store,openannotation/annotator-store,nobita-isc/annotator-store,happybelly/annotator-store,nobita-isc/annotator-store
--- +++ @@ -13,6 +13,7 @@ 'SQLAlchemy==0.7.4', 'pyes==0.16.0', 'nose==1.0.0', + 'mock==0.7.4', 'iso8601==0.1.4' ],
2498f0184e9cf0496fdf1e33c8aa4fe4aa643502
stats.py
stats.py
#!/usr/bin/python # encoding: utf-8 from __future__ import with_statement import argparse, re, sys def filter(args): bytes_extractor = re.compile(r"([0-9]+) bytes") with args.output: with args.input: for line in args.input: if line.find("avr-size") >= 0: # Find example name (everything after last /) example = line[line.rfind("/") + 1:-1] elif line.startswith("Program:"): # Find number of bytes of flash matcher = bytes_extractor.search(line) program = matcher.group(1) elif line.startswith("Data:"): # Find number of bytes of SRAM matcher = bytes_extractor.search(line) data = matcher.group(1) # Write new line to output args.output.write("%s\t%s\t%s\n" % (example, program, data)) if __name__ == "__main__": parser = argparse.ArgumentParser(description = 'XXXXXXXX') parser.add_argument('input', nargs='?', type=argparse.FileType('r'), default=sys.stdin) parser.add_argument('output', nargs='?', type=argparse.FileType('w'), default=sys.stdout) args = parser.parse_args() filter(args)
#!/usr/bin/python # encoding: utf-8 # In order to use this script from shell: # > make CONF=UNO clean-examples # > make CONF=UNO examples >tempsizes # > cat tempsizes | ./stats.py >sizes # > rm tempsizes # Then sizes file can be opened in LibreOffice Calc from __future__ import with_statement import argparse, re, sys def filter(args): bytes_extractor = re.compile(r"([0-9]+) bytes") with args.output: with args.input: for line in args.input: if line.find("avr-size") >= 0: # Find example name (everything after last /) example = line[line.rfind("/") + 1:-1] elif line.startswith("Program:"): # Find number of bytes of flash matcher = bytes_extractor.search(line) program = matcher.group(1) elif line.startswith("Data:"): # Find number of bytes of SRAM matcher = bytes_extractor.search(line) data = matcher.group(1) # Write new line to output args.output.write("%s\t%s\t%s\n" % (example, program, data)) if __name__ == "__main__": parser = argparse.ArgumentParser(description = 'XXXXXXXX') parser.add_argument('input', nargs='?', type=argparse.FileType('r'), default=sys.stdin) parser.add_argument('output', nargs='?', type=argparse.FileType('w'), default=sys.stdout) args = parser.parse_args() filter(args)
Document python script to extract program sizes from make output.
Document python script to extract program sizes from make output.
Python
lgpl-2.1
jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib
--- +++ @@ -1,5 +1,12 @@ #!/usr/bin/python # encoding: utf-8 + +# In order to use this script from shell: +# > make CONF=UNO clean-examples +# > make CONF=UNO examples >tempsizes +# > cat tempsizes | ./stats.py >sizes +# > rm tempsizes +# Then sizes file can be opened in LibreOffice Calc from __future__ import with_statement import argparse, re, sys
cfaed02921ba1c46c45f726aa4a008f4fa1cd66f
partner_academic_title/models/partner_academic_title.py
partner_academic_title/models/partner_academic_title.py
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of partner_academic_title, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # partner_academic_title is free software: # you can redistribute it and/or modify it under the terms of the GNU # Affero General Public License as published by the Free Software # Foundation,either version 3 of the License, or (at your option) any # later version. # # partner_academic_title is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with partner_academic_title. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class PartnerAcademicTitle(models.Model): _name = 'partner.academic.title' name = fields.Char(required=True) sequence = fields.Integer(required=True, help="""defines the order to display titles""") active = fields.Boolean(default=True)
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of partner_academic_title, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # partner_academic_title is free software: # you can redistribute it and/or modify it under the terms of the GNU # Affero General Public License as published by the Free Software # Foundation,either version 3 of the License, or (at your option) any # later version. # # partner_academic_title is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with partner_academic_title. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class PartnerAcademicTitle(models.Model): _name = 'partner.academic.title' name = fields.Char(required=True, translate=True) sequence = fields.Integer(required=True, help="""defines the order to display titles""") active = fields.Boolean(default=True)
Add translate=True on academic title name
Add translate=True on academic title name
Python
agpl-3.0
brain-tec/partner-contact,brain-tec/partner-contact
--- +++ @@ -29,7 +29,7 @@ class PartnerAcademicTitle(models.Model): _name = 'partner.academic.title' - name = fields.Char(required=True) + name = fields.Char(required=True, translate=True) sequence = fields.Integer(required=True, help="""defines the order to display titles""") active = fields.Boolean(default=True)
848a6b0fbca65679205ae47d130c7ff53c155f98
feedback/models.py
feedback/models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User FEEDBACK_TYPES = ( ('bug', 'Bug'), ('feature', 'Feature'), ('support', 'Support request'), ) class Feedback(models.Model): feedback = models.TextField() user = models.ForeignKey(User, null=True, blank=True, editable=False) url = models.URLField(blank=True) timestamp = models.DateTimeField(auto_now_add=True, editable=False) resolved = models.BooleanField(default=False) publish = models.BooleanField(default=False) type = models.CharField(max_length=128, blank=True, choices=getattr(settings, 'FEEDBACK_TYPES', FEEDBACK_TYPES)) class Meta: ordering = ['-timestamp',] verbose_name_plural = "Feedback" def __unicode__(self): return "Feedback from %s sent %s" % (self.user, self.timestamp,)
from django.conf import settings from django.db import models from django.contrib.auth.models import User FEEDBACK_TYPES = ( ('bug', 'Bug'), ('feature', 'Feature'), ('support', 'Support request'), ) class Feedback(models.Model): feedback = models.TextField() user = models.ForeignKey(User, null=True, blank=True) url = models.URLField(blank=True) timestamp = models.DateTimeField(auto_now_add=True, editable=False) resolved = models.BooleanField(default=False) publish = models.BooleanField(default=False) type = models.CharField(max_length=128, blank=True, choices=getattr(settings, 'FEEDBACK_TYPES', FEEDBACK_TYPES)) class Meta: ordering = ['-timestamp',] verbose_name_plural = "Feedback" def __unicode__(self): return "Feedback from %s sent %s" % (self.user, self.timestamp,)
Allow the user to be editable (for admin interface).
Allow the user to be editable (for admin interface).
Python
bsd-3-clause
gabrielhurley/django-user-feedback
--- +++ @@ -10,7 +10,7 @@ class Feedback(models.Model): feedback = models.TextField() - user = models.ForeignKey(User, null=True, blank=True, editable=False) + user = models.ForeignKey(User, null=True, blank=True) url = models.URLField(blank=True) timestamp = models.DateTimeField(auto_now_add=True, editable=False) resolved = models.BooleanField(default=False)
d2fe3bbf4f97ef5ece4c6c69e531e261eeed75b1
stoq/plugins/archiver.py
stoq/plugins/archiver.py
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import abstractmethod from typing import Optional from stoq.data_classes import ArchiverResponse, Payload, RequestMeta from stoq.plugins import BasePlugin class ArchiverPlugin(BasePlugin): @abstractmethod def archive( self, payload: Payload, request_meta: RequestMeta ) -> Optional[ArchiverResponse]: pass def get(self, task: str) -> Optional[Payload]: pass
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import abstractmethod from typing import Optional from stoq.data_classes import ArchiverResponse, Payload, RequestMeta from stoq.plugins import BasePlugin class ArchiverPlugin(BasePlugin): def archive( self, payload: Payload, request_meta: RequestMeta ) -> Optional[ArchiverResponse]: pass def get(self, task: str) -> Optional[Payload]: pass
Remove @abstracmethod from archive method as well
Remove @abstracmethod from archive method as well
Python
apache-2.0
PUNCH-Cyber/stoq
--- +++ @@ -22,7 +22,6 @@ class ArchiverPlugin(BasePlugin): - @abstractmethod def archive( self, payload: Payload, request_meta: RequestMeta ) -> Optional[ArchiverResponse]:
f20966d6d29371f7bb947317ee1d93a470accd6e
settings.py
settings.py
import dj_database_url DEBUG = True TEMPLATE_DEBUG = True SECRET_KEY = 'this is my secret key' # NOQA TEST_RUNNER = 'django.test.runner.DiscoverRunner' DATABASES = { 'default': dj_database_url.config(default='postgres:///localized_fields') } DATABASES['default']['ENGINE'] = 'psqlextra.backend' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'English'), ('ro', 'Romanian'), ('nl', 'Dutch') ) INSTALLED_APPS = ( 'localized_fields', 'tests', ) # set to a lower number than the default, since # we want the tests to be fast, default is 100 LOCALIZED_FIELDS_MAX_RETRIES = 3 LOCALIZED_FIELDS_EXPERIMENTAL = False
import dj_database_url DEBUG = True TEMPLATE_DEBUG = True SECRET_KEY = 'this is my secret key' # NOQA TEST_RUNNER = 'django.test.runner.DiscoverRunner' DATABASES = { 'default': dj_database_url.config(default='postgres:///localized_fields') } DATABASES['default']['ENGINE'] = 'psqlextra.backend' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'English'), ('ro', 'Romanian'), ('nl', 'Dutch') ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.admin', 'localized_fields', 'tests', ) # set to a lower number than the default, since # we want the tests to be fast, default is 100 LOCALIZED_FIELDS_MAX_RETRIES = 3 LOCALIZED_FIELDS_EXPERIMENTAL = False
Fix tests not passing for Django 2.X
Fix tests not passing for Django 2.X
Python
mit
SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields
--- +++ @@ -21,6 +21,9 @@ ) INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.admin', 'localized_fields', 'tests', )
2f4483440a98f34b650ea09a75f6dc941548f8b2
zeus/vcs/db.py
zeus/vcs/db.py
import asyncpg class Database: def __init__(self, host: str, port: int, user: str, password: str, database: str): self.host = host self.port = port self.user = user self.password = password self.database = database self._conn = None async def connect(self): self._conn = await asyncpg.connect( host=self.host, port=self.port, user=self.user, password=self.password, database=self.database, ) return self._conn async def close(self): if self._conn: await self._conn.close() self._conn = None async def fetch(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return await conn.fetch(*args, **kwargs) async def execute(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return await conn.execute(*args, **kwargs) async def transaction(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return conn.transaction(*args, **kwargs)
import asyncpg class Database: def __init__(self, host: str, port: int, user: str, password: str, database: str): self.host = host self.port = port self.user = user self.password = password self.database = database self._conn = None async def connect(self): self._conn = await asyncpg.connect( host=self.host, port=self.port, user=self.user, password=self.password, database=self.database, # https://github.com/MagicStack/asyncpg/issues/76 # we want to rely on pgbouncer max_cached_statement_lifetime=0, ) return self._conn async def close(self): if self._conn: await self._conn.close() self._conn = None async def fetch(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return await conn.fetch(*args, **kwargs) async def execute(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return await conn.execute(*args, **kwargs) async def transaction(self, *args, **kwargs): if not self._conn: conn = await self.connect() else: conn = self._conn return conn.transaction(*args, **kwargs)
Disable asyncpg prepared statement cache
Disable asyncpg prepared statement cache
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
--- +++ @@ -18,6 +18,9 @@ user=self.user, password=self.password, database=self.database, + # https://github.com/MagicStack/asyncpg/issues/76 + # we want to rely on pgbouncer + max_cached_statement_lifetime=0, ) return self._conn
24d51efaf80993352d82038d059c4435857fcd67
test/backend/test_job.py
test/backend/test_job.py
import unittest import cryptosite import saliweb.test import saliweb.backend import os class JobTests(saliweb.test.TestCase): """Check custom CryptoSite Job class""" def test_run_first_stepok(self): """Test successful run method, first step""" j = self.make_test_job(cryptosite.Job, 'RUNNING') fname = os.path.join(j.directory, 'param.txt') open(fname, 'w').write('testjob\ntest@example.com\nA\n') cls = j._run_in_job_directory(j.run) self.assert_(isinstance(cls, saliweb.backend.SGERunner), "SGERunner not returned") if __name__ == '__main__': unittest.main()
import unittest import cryptosite import saliweb.test import saliweb.backend import os class JobTests(saliweb.test.TestCase): """Check custom CryptoSite Job class""" def test_run_first_stepok(self): """Test successful run method, first step""" j = self.make_test_job(cryptosite.Job, 'RUNNING') fname = os.path.join(j.directory, 'param.txt') open(fname, 'w').write('testpdb\nA\n') cls = j._run_in_job_directory(j.run) self.assert_(isinstance(cls, saliweb.backend.SGERunner), "SGERunner not returned") if __name__ == '__main__': unittest.main()
Update to match new format for param.txt.
Update to match new format for param.txt.
Python
lgpl-2.1
salilab/cryptosite-web,salilab/cryptosite-web
--- +++ @@ -11,7 +11,7 @@ """Test successful run method, first step""" j = self.make_test_job(cryptosite.Job, 'RUNNING') fname = os.path.join(j.directory, 'param.txt') - open(fname, 'w').write('testjob\ntest@example.com\nA\n') + open(fname, 'w').write('testpdb\nA\n') cls = j._run_in_job_directory(j.run) self.assert_(isinstance(cls, saliweb.backend.SGERunner), "SGERunner not returned")
a30fa66345ab54b62af98fb428ce0cd4515525f6
proselint/__init__.py
proselint/__init__.py
"""Proselint applies advice from great writers to your writing.""" from . import tools __all__ = ['tools']
"""Proselint applies advice from great writers to your writing.""" from . import tools __all__ = ('tools')
Make __all__ immutable to stop pep257 from complaining.
Make __all__ immutable to stop pep257 from complaining.
Python
bsd-3-clause
amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint
--- +++ @@ -1,4 +1,4 @@ """Proselint applies advice from great writers to your writing.""" from . import tools -__all__ = ['tools'] +__all__ = ('tools')
c76be093ca2fe226d43e2f6ef908dfc7dbf1faf1
keys.py
keys.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # weatherBot keys # Copyright 2015 Brian Mitchell under the MIT license # See the GitHub repository: https://github.com/bman4789/weatherBot import os keys = dict( consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', flickr_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ) def set_twitter_env_vars(): if os.getenv('WEATHERBOT_CONSUMER_KEY', 0) is 0 or os.getenv('WEATHERBOT_CONSUMER_SECRET', 0) is 0 \ or os.getenv('WEATHERBOT_ACCESS_KEY', 0) is 0 or os.getenv('WEATHERBOT_ACCESS_SECRET', 0) is 0: os.environ['WEATHERBOT_CONSUMER_KEY'] = keys['consumer_key'] os.environ['WEATHERBOT_CONSUMER_SECRET'] = keys['consumer_secret'] os.environ['WEATHERBOT_ACCESS_KEY'] = keys['access_key'] os.environ['WEATHERBOT_ACCESS_SECRET'] = keys['access_secret'] def set_flickr_env_vars(): if os.getenv('WEATHERBOT_FLICKR_KEY', 0) is 0: os.environ['WEATHERBOT_FLICKR_KEY'] = keys['flickr_key']
#!/usr/bin/env python3 # weatherBot keys # Copyright 2015 Brian Mitchell under the MIT license # See the GitHub repository: https://github.com/bman4789/weatherBot import os keys = dict( consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', forecastio_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ) def set_twitter_env_vars(): if os.getenv('WEATHERBOT_CONSUMER_KEY', 0) is 0 or os.getenv('WEATHERBOT_CONSUMER_SECRET', 0) is 0 \ or os.getenv('WEATHERBOT_ACCESS_KEY', 0) is 0 or os.getenv('WEATHERBOT_ACCESS_SECRET', 0) is 0: os.environ['WEATHERBOT_CONSUMER_KEY'] = keys['consumer_key'] os.environ['WEATHERBOT_CONSUMER_SECRET'] = keys['consumer_secret'] os.environ['WEATHERBOT_ACCESS_KEY'] = keys['access_key'] os.environ['WEATHERBOT_ACCESS_SECRET'] = keys['access_secret'] def set_forecastio_env_vars(): if os.getenv('WEATHERBOT_FORECASTIO_KEY', 0) is 0: os.environ['WEATHERBOT_FORECASTIO_KEY'] = keys['forecastio_key']
Remove flickr key, add forecast.io key
Remove flickr key, add forecast.io key
Python
mit
bman4789/weatherBot,bman4789/weatherBot,BrianMitchL/weatherBot
--- +++ @@ -1,5 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +#!/usr/bin/env python3 # weatherBot keys # Copyright 2015 Brian Mitchell under the MIT license @@ -12,7 +11,7 @@ consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - flickr_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + forecastio_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ) @@ -25,6 +24,6 @@ os.environ['WEATHERBOT_ACCESS_SECRET'] = keys['access_secret'] -def set_flickr_env_vars(): - if os.getenv('WEATHERBOT_FLICKR_KEY', 0) is 0: - os.environ['WEATHERBOT_FLICKR_KEY'] = keys['flickr_key'] +def set_forecastio_env_vars(): + if os.getenv('WEATHERBOT_FORECASTIO_KEY', 0) is 0: + os.environ['WEATHERBOT_FORECASTIO_KEY'] = keys['forecastio_key']
4516b3b47d77badccaa5da020a7ec34f2fe2a88e
main.py
main.py
""" The main beast. """ from lib.Mock_DotStar import Adafruit_DotStar import time strip = Adafruit_DotStar(88) strip.begin() strip.show() try: while True: time.sleep(1) except KeyboardInterrupt: ## Close mock library (which should close window) pass
""" The main beast is alive. """ from lib.Mock_DotStar import Adafruit_DotStar import time strip = Adafruit_DotStar(88) strip.begin() strip.show() try: while True: time.sleep(1) except KeyboardInterrupt: ## Close mock library (which should close window) pass
Test to see if user is correct
Test to see if user is correct
Python
mit
dodgyrabbit/midi-light-py
--- +++ @@ -1,5 +1,5 @@ """ -The main beast. +The main beast is alive. """ from lib.Mock_DotStar import Adafruit_DotStar
f64447ca0e1442552b4a854fec5a8f847d2165cd
numpy/_array_api/_types.py
numpy/_array_api/_types.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device', 'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Literal, Optional, Tuple, Union, TypeVar import numpy as np array = np.ndarray device = TypeVar('device') dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device', 'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Literal, Optional, Tuple, Union, TypeVar from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) array = ndarray device = TypeVar('device') dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
Use the array API types for the array API type annotations
Use the array API types for the array API type annotations
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
--- +++ @@ -11,12 +11,13 @@ from typing import Literal, Optional, Tuple, Union, TypeVar -import numpy as np +from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32, + uint64, float32, float64) -array = np.ndarray +array = ndarray device = TypeVar('device') -dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, - np.uint32, np.uint64, np.float32, np.float64] +dtype = Literal[int8, int16, int32, int64, uint8, uint16, + uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
263ffc507d693854aec3fe826964b3c9031cdad8
s4v1.py
s4v1.py
from s3v3 import * import csv def write_to_file(filename, data_sample): example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect). example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in) write_to_file("_data/s4-silk_ties.csv", silk_ties) # this is going to create a new csv located in the _data directory, named s4-silk_ties.csv and it is going to contain all of that data from the silk_ties list which we created in s3v2 (silk_ties = filter_col_by_string(data_from_csv, "material", "_silk")) # returned an error because the directory and the file did not exist. Going to create the directory and try again to see if it will create the file. It worked! It needs a directory, but it can create the file from scratch
from s3v3 import * import csv # ORIGINAL VERSION - Leaves file open # def write_to_file(filename, data_sample): # example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect). # example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in) # NEW VERSION - Closes file at end def write_to_file(filename, data_sample): with open(filename, 'w', encoding='utf-8', newline='') as csvfile: example = csv.writer(csvfile, dialect='excel') example.writerows(data_sample) write_to_file("_data/s4-silk_ties.csv", silk_ties) # this is going to create a new csv located in the _data directory, named s4-silk_ties.csv and it is going to contain all of that data from the silk_ties list which we created in s3v2 (silk_ties = filter_col_by_string(data_from_csv, "material", "_silk")) # returned an error because the directory and the file did not exist. Going to create the directory and try again to see if it will create the file. It worked! It needs a directory, but it can create the file from scratch
Update export csv function to close file when finished
Update export csv function to close file when finished
Python
mit
alexmilesyounger/ds_basics
--- +++ @@ -1,10 +1,16 @@ from s3v3 import * import csv +# ORIGINAL VERSION - Leaves file open +# def write_to_file(filename, data_sample): +# example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect). +# example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in) + +# NEW VERSION - Closes file at end def write_to_file(filename, data_sample): - example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect). - example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in) + with open(filename, 'w', encoding='utf-8', newline='') as csvfile: + example = csv.writer(csvfile, dialect='excel') + example.writerows(data_sample) write_to_file("_data/s4-silk_ties.csv", silk_ties) # this is going to create a new csv located in the _data directory, named s4-silk_ties.csv and it is going to contain all of that data from the silk_ties list which we created in s3v2 (silk_ties = filter_col_by_string(data_from_csv, "material", "_silk")) # returned an error because the directory and the file did not exist. Going to create the directory and try again to see if it will create the file. It worked! It needs a directory, but it can create the file from scratch -
419bf4377e2b26434e576ff07e540a818bb2c330
experiments/2013-09-08.py
experiments/2013-09-08.py
Experiment(description='Deeper with two types of per and 5 full_iters for good measure', data_dir='../data/tsdlr/', max_depth=12, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=4, max_jobs=600, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-09-08/', iters=250, base_kernels='Per,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin', zero_mean=True, random_seed=1, period_heuristic=5, subset=True, subset_size=250, full_iters=5, bundle_size=5)
Experiment(description='Deeper with two types of per and 5 full_iters for good measure', data_dir='../data/tsdlr/', max_depth=12, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=4, max_jobs=600, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-09-08/', iters=250, base_kernels='Per,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin', zero_mean=True, random_seed=2, period_heuristic=5, subset=True, subset_size=250, full_iters=5, bundle_size=5)
Change to random seed of that experiment
Change to random seed of that experiment
Python
mit
jamesrobertlloyd/gpss-research,codeaudit/gpss-research,ekamioka/gpss-research,ElbaKramer/gpss-research,ElbaKramer/gpss-research,jamesrobertlloyd/gpss-research,jamesrobertlloyd/gpss-research,codeaudit/gpss-research,jamesrobertlloyd/gpss-research,ekamioka/gpss-research,ElbaKramer/gpss-research,ekamioka/gpss-research,codeaudit/gpss-research,jamesrobertlloyd/gpss-research,jamesrobertlloyd/gpss-research,jamesrobertlloyd/gpss-research,ekamioka/gpss-research,ekamioka/gpss-research,codeaudit/gpss-research,codeaudit/gpss-research,ekamioka/gpss-research,codeaudit/gpss-research,codeaudit/gpss-research,ElbaKramer/gpss-research,ElbaKramer/gpss-research,ElbaKramer/gpss-research,ekamioka/gpss-research,ElbaKramer/gpss-research
--- +++ @@ -15,7 +15,7 @@ iters=250, base_kernels='Per,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin', zero_mean=True, - random_seed=1, + random_seed=2, period_heuristic=5, subset=True, subset_size=250,
c2aaf1f325ba44406acacd3935a4897c833dc16c
django-row-tracker.py
django-row-tracker.py
import sys from django.core.management import setup_environ import settings setup_environ(settings) from django.db.utils import DatabaseError from django.db.transaction import rollback_unless_managed from django.db import models def get_model_info(): ''' Dump all models and their row counts to the screen ''' project_models = models.get_models(include_auto_created=True) for them in project_models: try: print them._meta.db_table + " " + str(them.objects.all().count()) except DatabaseError: print "Unexpected error and continuing:", sys.exc_info()[0] , " ", them rollback_unless_managed() except: print "Unexpected error and abending:", sys.exc_info()[0] break def main(): ''' Handle main processing ''' get_model_info() if __name__ == "__main__": main()
import argparse import sys from django.core.management import setup_environ import settings setup_environ(settings) from django.db.utils import DatabaseError from django.db.transaction import rollback_unless_managed from django.db import models def get_model_info(): ''' Dump all models and their row counts to the screen ''' project_models = models.get_models(include_auto_created=True) for them in project_models: try: print them._meta.db_table + " " + str(them.objects.all().count()) except DatabaseError: print "Unexpected error and continuing:", sys.exc_info()[0] , " ", them rollback_unless_managed() except: print "Unexpected error and abending:", sys.exc_info()[0] break def process_args(): ''' Process command line args ''' parser = argparse.ArgumentParser() parser.add_argument("path_to_project_root") parser.add_argument("project_name") args = parser.parse_args() return args def main(): ''' Handle main processing ''' args = process_args() get_model_info() if __name__ == "__main__": main()
Add argument handling for path and project name
Add argument handling for path and project name
Python
bsd-3-clause
shearichard/django-row-tracker
--- +++ @@ -1,3 +1,4 @@ +import argparse import sys from django.core.management import setup_environ @@ -26,10 +27,21 @@ print "Unexpected error and abending:", sys.exc_info()[0] break +def process_args(): + ''' + Process command line args + ''' + parser = argparse.ArgumentParser() + parser.add_argument("path_to_project_root") + parser.add_argument("project_name") + args = parser.parse_args() + return args + def main(): ''' Handle main processing ''' + args = process_args() get_model_info()
9efd7f63f12affffb58b7e243777432a331e91f2
examples/add_command_line_argument.py
examples/add_command_line_argument.py
from locust import HttpUser, TaskSet, task, between from locust import events @events.init_command_line_parser.add_listener def _(parser): parser.add_argument( '--custom-argument', help="It's working" ) @events.init.add_listener def _(environment, **kw): print("Custom argument supplied: %s" % environment.parsed_options.custom_argument) class WebsiteUser(HttpUser): """ User class that does requests to the locust web server running on localhost """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task def my_task(self): pass
from locust import HttpUser, TaskSet, task, between from locust import events @events.init_command_line_parser.add_listener def _(parser): parser.add_argument( "--my-argument", type=str, env_var="LOCUST_MY_ARGUMENT", default="", help="It's working" ) @events.init.add_listener def _(environment, **kw): print("Custom argument supplied: %s" % environment.parsed_options.my_argument) class WebsiteUser(HttpUser): """ User class that does requests to the locust web server running on localhost """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task def my_task(self): pass
Add type, env var and default value to custom argument example. And rename it so that nobody thinks the "custom" in the name has a specific meaning.
Add type, env var and default value to custom argument example. And rename it so that nobody thinks the "custom" in the name has a specific meaning.
Python
mit
mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust
--- +++ @@ -5,21 +5,27 @@ @events.init_command_line_parser.add_listener def _(parser): parser.add_argument( - '--custom-argument', + "--my-argument", + type=str, + env_var="LOCUST_MY_ARGUMENT", + default="", help="It's working" ) + @events.init.add_listener def _(environment, **kw): - print("Custom argument supplied: %s" % environment.parsed_options.custom_argument) + print("Custom argument supplied: %s" % environment.parsed_options.my_argument) class WebsiteUser(HttpUser): """ User class that does requests to the locust web server running on localhost """ + host = "http://127.0.0.1:8089" wait_time = between(2, 5) + @task def my_task(self): pass
2a37edaef3be06ab97bb1561b51d7977909e4abe
feed_sources/CTTransit.py
feed_sources/CTTransit.py
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, # and Shore Line East. Shore Line East has its own URL. ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} urls = {} for sfx in ct_suffixes: url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) filename = 'ct_%s.zip' % ct_suffixes[sfx] urls[filename] = url urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL self.urls = urls
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() self.urls = { 'ct_transit.zip': BASE_URL, 'ct_shoreline_east.zip': SHORELINE_EAST_URL, 'ct_hartford_rail.zip': HARTFORD_URL }
Update CT Transit feed fetcher
Update CT Transit feed fetcher CT Transit has changed their URLs.
Python
mit
azavea/gtfs-feed-fetcher
--- +++ @@ -5,24 +5,17 @@ LOG = logging.getLogger(__name__) -BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' +BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' +HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() - # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, - # and Shore Line East. Shore Line East has its own URL. - ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', - 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} - - urls = {} - for sfx in ct_suffixes: - url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) - filename = 'ct_%s.zip' % ct_suffixes[sfx] - urls[filename] = url - - urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL - self.urls = urls + self.urls = { + 'ct_transit.zip': BASE_URL, + 'ct_shoreline_east.zip': SHORELINE_EAST_URL, + 'ct_hartford_rail.zip': HARTFORD_URL + }
0148b417a9ce8531383f2fb4e5500d9b32794f2c
byceps/services/party/settings_service.py
byceps/services/party/settings_service.py
""" byceps.services.party.settings_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import Optional from ...typing import PartyID from .models.setting import Setting as DbSetting from .transfer.models import PartySetting def find_setting(party_id: PartyID, name: str) -> Optional[PartySetting]: """Return the setting for that party and with that name, or `None` if not found. """ setting = DbSetting.query.get((party_id, name)) if setting is None: return None return _db_entity_to_party_setting(setting) def _db_entity_to_party_setting(setting: DbSetting) -> PartySetting: return PartySetting( setting.party_id, setting.name, setting.value, )
""" byceps.services.party.settings_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import Optional from ...database import db from ...typing import PartyID from .models.setting import Setting as DbSetting from .transfer.models import PartySetting def create_setting(party_id: PartyID, name: str, value: str) -> PartySetting: """Create a setting for that party.""" setting = DbSetting(party_id, name, value) db.session.add(setting) db.session.commit() return _db_entity_to_party_setting(setting) def find_setting(party_id: PartyID, name: str) -> Optional[PartySetting]: """Return the setting for that party and with that name, or `None` if not found. """ setting = DbSetting.query.get((party_id, name)) if setting is None: return None return _db_entity_to_party_setting(setting) def find_setting_value(party_id: PartyID, name: str) -> Optional[str]: """Return the value of the setting for that party and with that name, or `None` if not found. """ setting = find_setting(party_id, name) if setting is None: return None return setting.value def _db_entity_to_party_setting(setting: DbSetting) -> PartySetting: return PartySetting( setting.party_id, setting.name, setting.value, )
Add service functions to create a party setting and to obtain one's value
Add service functions to create a party setting and to obtain one's value
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
--- +++ @@ -8,10 +8,21 @@ from typing import Optional +from ...database import db from ...typing import PartyID from .models.setting import Setting as DbSetting from .transfer.models import PartySetting + + +def create_setting(party_id: PartyID, name: str, value: str) -> PartySetting: + """Create a setting for that party.""" + setting = DbSetting(party_id, name, value) + + db.session.add(setting) + db.session.commit() + + return _db_entity_to_party_setting(setting) def find_setting(party_id: PartyID, name: str) -> Optional[PartySetting]: @@ -26,6 +37,18 @@ return _db_entity_to_party_setting(setting) +def find_setting_value(party_id: PartyID, name: str) -> Optional[str]: + """Return the value of the setting for that party and with that + name, or `None` if not found. + """ + setting = find_setting(party_id, name) + + if setting is None: + return None + + return setting.value + + def _db_entity_to_party_setting(setting: DbSetting) -> PartySetting: return PartySetting( setting.party_id,
9773ae4c85ec2ada555fe22ab4b54620c4d9bd8e
_lib/wordpress_post_processor.py
_lib/wordpress_post_processor.py
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_fj_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
Update to new multiauthor taxonomy name
Update to new multiauthor taxonomy name
Python
cc0-1.0
jimmynotjim/cfgov-refresh,kurtw/cfgov-refresh,kurtw/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,kurtw/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,jimmynotjim/cfgov-refresh,jimmynotjim/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,imuchnik/cfgov-refresh
--- +++ @@ -33,7 +33,7 @@ post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") - post['author'] = [author['title'] for author in post['taxonomy_author']] + post['author'] = [author['title'] for author in post['taxonomy_fj_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string
4bd9a94243ddc01d86ded2d592c339e464ec42fc
dedupe/convenience.py
dedupe/convenience.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPairs(len(data_list), sample_size) return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs) def blockData(data_d, blocker): blocks = dedupe.core.OrderedDict({}) record_blocks = dedupe.core.OrderedDict({}) key_blocks = dedupe.core.OrderedDict({}) blocker.tfIdfBlocks(data_d.iteritems()) for (record_id, record) in data_d.iteritems(): for key in blocker((record_id, record)): blocks.setdefault(key, {}).update({record_id : record}) blocked_records = tuple(block for block in blocks.values()) return blocked_records
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPairs(len(data_list), sample_size) return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs) def blockData(data_d, blocker): blocks = dedupe.core.OrderedDict({}) record_blocks = dedupe.core.OrderedDict({}) key_blocks = dedupe.core.OrderedDict({}) blocker.tfIdfBlocks(data_d.iteritems()) for (record_id, record) in data_d.iteritems(): for key in blocker((record_id, record)): blocks.setdefault(key, {}).update({record_id : record}) blocked_records = tuple(block for block in blocks.values()) return blocked_records
Update dataSample to index on the ints returned by random_pairs
Update dataSample to index on the ints returned by random_pairs
Python
mit
01-/dedupe,tfmorris/dedupe,01-/dedupe,nmiranda/dedupe,datamade/dedupe,neozhangthe1/dedupe,pombredanne/dedupe,tfmorris/dedupe,datamade/dedupe,dedupeio/dedupe,nmiranda/dedupe,pombredanne/dedupe,davidkunio/dedupe,dedupeio/dedupe-examples,davidkunio/dedupe,neozhangthe1/dedupe,dedupeio/dedupe
--- +++ @@ -16,7 +16,7 @@ data_list = data.values() random_pairs = dedupe.core.randomPairs(len(data_list), sample_size) - return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs) + return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs) def blockData(data_d, blocker):
5529900f5f9642f460a78ce58a2c74e021e35266
gaphor/misc/tests/test_gidlethread.py
gaphor/misc/tests/test_gidlethread.py
from gaphor.misc.gidlethread import GIdleThread def test_wait_with_timeout(): # GIVEN a running gidlethread def counter(max): for x in range(max): yield x t = GIdleThread(counter(20000)) t.start() assert t.is_alive() # WHEN waiting for 0.01 sec timeout wait_result = t.wait(0.01) # THEN timeout assert wait_result def test_wait_until_finished(): # GIVEN a short coroutine thread def counter(max): for x in range(max): yield x t = GIdleThread(counter(2)) t.start() assert t.is_alive() # WHEN wait for coroutine to finish wait_result = t.wait(0.01) # THEN coroutine finished assert not wait_result
import pytest from gaphor.misc.gidlethread import GIdleThread def counter(count): for x in range(count): yield x @pytest.fixture def gidle_counter(request): # Setup GIdle Thread with 0.01 sec timeout t = GIdleThread(counter(request.param)) t.start() assert t.is_alive() wait_result = t.wait(0.01) yield wait_result # Teardown GIdle Thread t.interrupt() @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True) def test_wait_with_timeout(gidle_counter): # GIVEN a long coroutine thread # WHEN waiting short timeout # THEN timeout is True assert gidle_counter @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True) def test_wait_until_finished(gidle_counter): # GIVEN a short coroutine thread # WHEN wait for coroutine to finish # THEN coroutine finished assert not gidle_counter
Update test to use fixtures and parameterization
Update test to use fixtures and parameterization Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
--- +++ @@ -1,31 +1,36 @@ +import pytest + from gaphor.misc.gidlethread import GIdleThread -def test_wait_with_timeout(): - # GIVEN a running gidlethread - def counter(max): - for x in range(max): - yield x +def counter(count): + for x in range(count): + yield x - t = GIdleThread(counter(20000)) + +@pytest.fixture +def gidle_counter(request): + # Setup GIdle Thread with 0.01 sec timeout + t = GIdleThread(counter(request.param)) t.start() assert t.is_alive() - # WHEN waiting for 0.01 sec timeout wait_result = t.wait(0.01) - # THEN timeout - assert wait_result + yield wait_result + # Teardown GIdle Thread + t.interrupt() -def test_wait_until_finished(): +@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True) +def test_wait_with_timeout(gidle_counter): + # GIVEN a long coroutine thread + # WHEN waiting short timeout + # THEN timeout is True + assert gidle_counter + + +@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True) +def test_wait_until_finished(gidle_counter): # GIVEN a short coroutine thread - def counter(max): - for x in range(max): - yield x - - t = GIdleThread(counter(2)) - t.start() - assert t.is_alive() # WHEN wait for coroutine to finish - wait_result = t.wait(0.01) # THEN coroutine finished - assert not wait_result + assert not gidle_counter
2ce4e16979e095f1885f35cd767b0625dcd424c6
defender/test_urls.py
defender/test_urls.py
from django.conf.urls import patterns, include from django.contrib import admin urlpatterns = patterns( '', (r'^admin/', include(admin.site.urls)), )
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
Use url method instead of patterns in test URLs setup.
Use url method instead of patterns in test URLs setup.
Python
apache-2.0
kencochrane/django-defender,kencochrane/django-defender
--- +++ @@ -1,7 +1,6 @@ -from django.conf.urls import patterns, include +from django.conf.urls import url, include from django.contrib import admin -urlpatterns = patterns( - '', - (r'^admin/', include(admin.site.urls)), -) +urlpatterns = [ + url(r'^admin/', include(admin.site.urls)), +]
8b2f95dd8399d5c354769c860e2b955c3fe212b0
semesterpage/forms.py
semesterpage/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_courses = forms.ModelMultipleChoiceField( label=_('Dine fag'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autocomplete', attrs = { 'data-placeholder': _('Tast inn fagkode eller fagnavn'), # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) ) class Meta: model = Options # The fields are further restricted in .admin.py fields = ('__all__')
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_courses = forms.ModelMultipleChoiceField( label=_('Skriv inn dine fag'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autocomplete', attrs = { 'data-placeholder': _('Tast inn fagkode eller fagnavn'), # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) ) def __init__(self, *args, **kwargs): super(OptionsForm, self).__init__(*args, **kwargs) self.fields['self_chosen_courses'].help_text = _( 'Tast inn fagkode eller fagnavn for å legge til et nytt fag\ på hjemmesiden din.' ) class Meta: model = Options # The fields are further restricted in .admin.py fields = ('__all__')
Make it more clear that users should enter courses
Make it more clear that users should enter courses
Python
mit
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
--- +++ @@ -12,7 +12,7 @@ """ self_chosen_courses = forms.ModelMultipleChoiceField( - label=_('Dine fag'), + label=_('Skriv inn dine fag'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autocomplete', @@ -25,6 +25,13 @@ ) ) + def __init__(self, *args, **kwargs): + super(OptionsForm, self).__init__(*args, **kwargs) + self.fields['self_chosen_courses'].help_text = _( + 'Tast inn fagkode eller fagnavn for å legge til et nytt fag\ + på hjemmesiden din.' + ) + class Meta: model = Options
5cf0e2e9d68d2e0fca3780608f33d5d8cdaef8a9
admin/metrics/views.py
admin/metrics/views.py
from django.views.generic import TemplateView from django.contrib.auth.mixins import PermissionRequiredMixin from admin.base.settings import KEEN_CREDENTIALS from admin.base.utils import OSFAdmin class MetricsView(OSFAdmin, TemplateView, PermissionRequiredMixin): template_name = 'metrics/osf_metrics.html' permission_required = 'admin.view_metrics' def get_context_data(self, **kwargs): kwargs.update(KEEN_CREDENTIALS.copy()) return super(MetricsView, self).get_context_data(**kwargs)
from django.views.generic import TemplateView from django.contrib.auth.mixins import PermissionRequiredMixin from admin.base.settings import KEEN_CREDENTIALS class MetricsView(TemplateView, PermissionRequiredMixin): template_name = 'metrics/osf_metrics.html' permission_required = 'admin.view_metrics' def get_context_data(self, **kwargs): kwargs.update(KEEN_CREDENTIALS.copy()) return super(MetricsView, self).get_context_data(**kwargs)
Remove one more reference to old group permissions
Remove one more reference to old group permissions
Python
apache-2.0
erinspace/osf.io,adlius/osf.io,hmoco/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,cslzchen/osf.io,saradbowman/osf.io,icereval/osf.io,icereval/osf.io,leb2dg/osf.io,icereval/osf.io,sloria/osf.io,caseyrollins/osf.io,sloria/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,felliott/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,mattclark/osf.io,cwisecarver/osf.io,mattclark/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,chennan47/osf.io,acshi/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,erinspace/osf.io,acshi/osf.io,erinspace/osf.io,mfraezz/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,aaxelb/osf.io,hmoco/osf.io,binoculars/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,binoculars/osf.io,mattclark/osf.io,hmoco/osf.io,chennan47/osf.io,chrisseto/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,caneruguz/osf.io,hmoco/osf.io,monikagrabowska/osf.io,adlius/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,aaxelb/osf.io,baylee-d/osf.io,mfraezz/osf.io,saradbowman/osf.io,chrisseto/osf.io,sloria/osf.io,caseyrollins/osf.io,caneruguz/osf.io,Nesiehr/osf.io,crcresearch/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,crcresearch/osf.io,acshi/osf.io,acshi/osf.io,brianjgeiger/osf.io,adlius/osf.io,felliott/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,felliott/osf.io,aaxelb/osf.io,acshi/osf.io,binoculars/osf.io,baylee-d/osf.io,chrisseto/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,felliott/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,adlius/osf.io,caneruguz/osf.io,baylee-d/osf.io,caseyrollins/osf.io,cwisecarver/osf.io,crcresearch/osf.io,chrisseto/osf.io,Nesiehr/osf.io
--- +++ @@ -4,10 +4,7 @@ from admin.base.settings import KEEN_CREDENTIALS -from admin.base.utils import OSFAdmin - - -class MetricsView(OSFAdmin, TemplateView, PermissionRequiredMixin): +class MetricsView(TemplateView, PermissionRequiredMixin): template_name = 'metrics/osf_metrics.html' permission_required = 'admin.view_metrics'
d1917d20f3aa26380e1e617f50b380142905d745
engines/string_template_engine.py
engines/string_template_engine.py
#!/usr/bin/env python """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
#!/usr/bin/env python """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
Transform values in string.Template engine before substitution.
Transform values in string.Template engine before substitution.
Python
mit
blubberdiblub/eztemplate
--- +++ @@ -2,7 +2,6 @@ """Provide the standard Python string.Template engine.""" from __future__ import print_function - from string import Template @@ -24,6 +23,10 @@ def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" + mapping = {name: self.str(value, tolerant=self.tolerant) + for name, value in mapping.items() + if value is not None or self.tolerant} + if self.tolerant: return self.template.safe_substitute(mapping)
5455e9c0fa81eef47f57cab046a162e56a8b822c
platformio_api/__main__.py
platformio_api/__main__.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from sys import exit as sys_exit from click import echo, group, version_option from platformio_api import __version__ from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats, sync_libs) from platformio_api.database import sync_db from platformio_api.web import app @group() @version_option(__version__, prog_name="PlatformIO-API") def cli(): pass @cli.command() def syncdb(): sync_db() echo("The database has been successfully synchronized!") @cli.command() def pendinglibs(): process_pending_libs() @cli.command() def synclibs(): sync_libs() @cli.command() def rotatelibsdlstats(): rotate_libs_dlstats() @cli.command("run") def runserver(): app.run(debug=True, reloader=True) def main(): cli() if __name__ == "__main__": sys_exit(main())
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from sys import exit as sys_exit import requests from click import echo, group, version_option from platformio_api import __version__ from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats, sync_libs) from platformio_api.database import sync_db from platformio_api.web import app @group() @version_option(__version__, prog_name="PlatformIO-API") def cli(): pass @cli.command() def syncdb(): sync_db() echo("The database has been successfully synchronized!") @cli.command() def pendinglibs(): process_pending_libs() @cli.command() def synclibs(): sync_libs() @cli.command() def rotatelibsdlstats(): rotate_libs_dlstats() @cli.command("run") def runserver(): app.run(debug=True, reloader=True) def main(): # https://urllib3.readthedocs.org # /en/latest/security.html#insecureplatformwarning requests.packages.urllib3.disable_warnings() cli() if __name__ == "__main__": sys_exit(main())
Fix URLLIb3 Insecure Platform Warning
Fix URLLIb3 Insecure Platform Warning
Python
apache-2.0
platformio/platformio-api,orgkhnargh/platformio-api
--- +++ @@ -3,6 +3,7 @@ from sys import exit as sys_exit +import requests from click import echo, group, version_option from platformio_api import __version__ @@ -45,6 +46,10 @@ def main(): + # https://urllib3.readthedocs.org + # /en/latest/security.html#insecureplatformwarning + requests.packages.urllib3.disable_warnings() + cli()
b1bc34e9a83cb3af5dd11baa1236f2b65ab823f9
cspreports/models.py
cspreports/models.py
# STANDARD LIB import json #LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) json = models.TextField() @property def data(self): """ Returns self.json loaded as a python object. """ try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data def json_as_html(self): """ Print out self.json in a nice way. """ formatted_json = json.dumps( self.data, sort_keys=True, indent=4, separators=(',', ': ') ) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
#LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe # CSP REPORTS from cspreports import utils class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) json = models.TextField() def json_as_html(self): """ Print out self.json in a nice way. """ formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
Make `CSPReport.json_as_html` use the robust `utils.format_report` for formatting.
Make `CSPReport.json_as_html` use the robust `utils.format_report` for formatting.
Python
mit
adamalton/django-csp-reports
--- +++ @@ -1,10 +1,10 @@ -# STANDARD LIB -import json - #LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe + +# CSP REPORTS +from cspreports import utils class CSPReport(models.Model): @@ -16,20 +16,8 @@ modified = models.DateTimeField(auto_now=True) json = models.TextField() - @property - def data(self): - """ Returns self.json loaded as a python object. """ - try: - data = self._data - except AttributeError: - data = self._data = json.loads(self.json) - return data - def json_as_html(self): """ Print out self.json in a nice way. """ - formatted_json = json.dumps( - self.data, sort_keys=True, - indent=4, separators=(',', ': ') - ) + formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
5183ad354943e81787010e3f108b1e819b9f703d
quran_tafseer/serializers.py
quran_tafseer/serializers.py
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.number') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name', 'language', 'author', 'book_name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.number') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
Add meta data to Serializer
[FIX] Add meta data to Serializer
Python
mit
EmadMokhtar/tafseer_api
--- +++ @@ -9,7 +9,7 @@ class Meta: model = Tafseer - fields = ['id', 'name'] + fields = ['id', 'name', 'language', 'author', 'book_name'] class TafseerTextSerializer(serializers.ModelSerializer):
a5d99bdff21c4819891d09d8b29800508929dcf4
hxl/filters/__init__.py
hxl/filters/__init__.py
""" Filter submodule for libhxl. David Megginson Started February 2015 License: Public Domain Documentation: https://github.com/HXLStandard/libhxl-python/wiki """ import sys from hxl import HXLException from hxl.model import HXLDataProvider, HXLColumn class HXLFilterException(HXLException): pass def run_script(func): try: func(sys.argv[1:], sys.stdin, sys.stdout) except BaseException, e: print >>sys.stderr, "Fatal error (" + e.__class__.__name__ + "): " + e.message print >>sys.stderr, "Exiting ..." sys.exit(2) def fix_tag(t): """trim whitespace and add # if needed""" t = t.strip() if not t.startswith('#'): t = '#' + t return t def parse_tags(s): """Parse tags out from a comma-separated list""" return list(map(fix_tag, s.split(','))) def find_column(tag, columns): """Find the first column in a list with tag""" for column in columns: if column.hxlTag == tag: return column return None
""" Filter submodule for libhxl. David Megginson Started February 2015 License: Public Domain Documentation: https://github.com/HXLStandard/libhxl-python/wiki """ import sys from hxl import HXLException from hxl.model import HXLDataProvider, HXLColumn class HXLFilterException(HXLException): pass def run_script(func): try: func(sys.argv[1:], sys.stdin, sys.stdout) except BaseException as e: print >>sys.stderr, "Fatal error (" + e.__class__.__name__ + "): " + e.message print >>sys.stderr, "Exiting ..." sys.exit(2) def fix_tag(t): """trim whitespace and add # if needed""" t = t.strip() if not t.startswith('#'): t = '#' + t return t def parse_tags(s): """Parse tags out from a comma-separated list""" return list(map(fix_tag, s.split(','))) def find_column(tag, columns): """Find the first column in a list with tag""" for column in columns: if column.hxlTag == tag: return column return None
Fix exception syntax for Python3.
Fix exception syntax for Python3.
Python
unlicense
HXLStandard/libhxl-python,HXLStandard/libhxl-python
--- +++ @@ -17,7 +17,7 @@ def run_script(func): try: func(sys.argv[1:], sys.stdin, sys.stdout) - except BaseException, e: + except BaseException as e: print >>sys.stderr, "Fatal error (" + e.__class__.__name__ + "): " + e.message print >>sys.stderr, "Exiting ..." sys.exit(2)
0be6ab488b74d628229c54a42117f5e69497737b
armstrong/apps/articles/admin.py
armstrong/apps/articles/admin.py
from django.contrib import admin from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets from .models import Article class ArticleAdmin(VersionAdmin): fieldsets = ( (None, { 'fields': ('title', 'summary', 'body', 'primary_section', 'sections', ), }), fieldsets.PUBLICATION, fieldsets.AUTHORS, ) admin.site.register(Article, ArticleAdmin)
from django.contrib import admin from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets from armstrong.core.arm_sections.admin import SectionTreeAdminMixin from .models import Article class ArticleAdmin(SectionTreeAdminMixin, VersionAdmin): fieldsets = ( (None, { 'fields': ('title', 'summary', 'body', 'primary_section', 'sections', ), }), fieldsets.PUBLICATION, fieldsets.AUTHORS, ) admin.site.register(Article, ArticleAdmin)
Add support for displaying with tree sections properly
Add support for displaying with tree sections properly
Python
apache-2.0
armstrong/armstrong.apps.articles,armstrong/armstrong.apps.articles
--- +++ @@ -2,10 +2,11 @@ from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets +from armstrong.core.arm_sections.admin import SectionTreeAdminMixin from .models import Article -class ArticleAdmin(VersionAdmin): +class ArticleAdmin(SectionTreeAdminMixin, VersionAdmin): fieldsets = ( (None, { 'fields': ('title', 'summary', 'body',
319bdba73d0ccecb229454272bb9bb12c226335a
cineapp/fields.py
cineapp/fields.py
# -*- coding: utf-8 -*- from wtforms import fields, widgets # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs) html_string += ("""<script> CKEDITOR.replace( '%s', { enterMode: CKEDITOR.ENTER_BR } ); </script>""" % field.id) return widgets.HTMLString(html_string) class CKTextAreaField(fields.TextAreaField): widget = CKTextAreaWidget() # Widget which returns a complete search bar with a glyphicon button class SearchButtonWidget(widgets.SubmitInput): html_params = staticmethod(widgets.html_params) input_type = 'submit' def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setdefault('type', self.input_type) kwargs.setdefault('value', field.label.text) if 'value' not in kwargs: kwargs['value'] = field._value() return widgets.HTMLString('<button %s><i class="glyphicon glyphicon-search"></i></button>' % self.html_params(name=field.name, **kwargs)) # SearchButtonField used for display the previous widget class SearchButtonField(fields.BooleanField): widget = SearchButtonWidget()
# -*- coding: utf-8 -*- from wtforms import fields, widgets from flask import Markup # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs) html_string += ("""<script> CKEDITOR.replace( '%s', { enterMode: CKEDITOR.ENTER_BR } ); </script>""" % field.id) return widgets.HTMLString(Markup(html_string)) class CKTextAreaField(fields.TextAreaField): widget = CKTextAreaWidget() # Widget which returns a complete search bar with a glyphicon button class SearchButtonWidget(widgets.SubmitInput): html_params = staticmethod(widgets.html_params) input_type = 'submit' def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setdefault('type', self.input_type) kwargs.setdefault('value', field.label.text) if 'value' not in kwargs: kwargs['value'] = field._value() return widgets.HTMLString('<button %s><i class="glyphicon glyphicon-search"></i></button>' % self.html_params(name=field.name, **kwargs)) # SearchButtonField used for display the previous widget class SearchButtonField(fields.BooleanField): widget = SearchButtonWidget()
Fix unwanted escape for CKEditor display
Fix unwanted escape for CKEditor display Fixes: #117
Python
mit
ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp
--- +++ @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from wtforms import fields, widgets +from flask import Markup # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): @@ -12,7 +13,7 @@ enterMode: CKEDITOR.ENTER_BR } ); </script>""" % field.id) - return widgets.HTMLString(html_string) + return widgets.HTMLString(Markup(html_string)) class CKTextAreaField(fields.TextAreaField): widget = CKTextAreaWidget()
7d5fa6a8eda793ff4cc2183992949a095d65c1b0
app/enums/registration_fields.py
app/enums/registration_fields.py
class RegistrationFields: repository = 'repository' job = 'job' labels = 'labels' requested_params = 'requested_params' branch_restrictions = 'branch_restrictions' change_restrictions = 'change_restrictions' file_restrictions = 'file_restrictions' missed_times = 'missed_times'
class RegistrationFields: repository = 'repository' job = 'job' labels = 'labels' requested_params = 'requested_params' branch_restrictions = 'branch_restrictions' change_restrictions = 'change_restrictions' file_restrictions = 'file_restrictions' missed_times = 'missed_times' jenkins_url = 'jenkins_url'
Add jenkins_url to valid registration fields
Add jenkins_url to valid registration fields
Python
mit
futuresimple/triggear
--- +++ @@ -7,3 +7,4 @@ change_restrictions = 'change_restrictions' file_restrictions = 'file_restrictions' missed_times = 'missed_times' + jenkins_url = 'jenkins_url'
a6e7f053c151fc343f0dd86010b159e21c0948b5
accountsplus/forms.py
accountsplus/forms.py
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower()
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.data['username'].lower()
Fix how we are reading user name
Fix how we are reading user name
Python
mit
foundertherapy/django-users-plus,foundertherapy/django-users-plus
--- +++ @@ -24,10 +24,10 @@ class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() + return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() + return self.data['username'].lower()
7c4442099eb3d00f0c14381d1091e45daf8e9179
all/newterm/_posix.py
all/newterm/_posix.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import os import subprocess def launch_executable(executable, args, cwd, env=None): """ Launches an executable with optional arguments :param executable: A unicode string of an executable :param args: A list of unicode strings to pass as arguments to the executable :param cwd: A unicode string of the working directory to open the executable to :param env: A dict of unicode strings for a custom environmental variables to set """ subprocess_args = [executable] subprocess_args.extend(args) if sys.version_info >= (3,): subprocess_env = dict(os.environ) else: subprocess_env = {} for key, value in os.environ.items(): subprocess_env[key.decode('utf-8', 'replace')] = value.decode('utf-8', 'replace') if env: for key, value in env.items(): subprocess_env[key] = value if sys.version_info < (3,): encoded_args = [] for arg in subprocess_args: encoded_args.append(arg.encode('utf-8')) subprocess_args = encoded_args encoded_env = {} for key, value in subprocess_env.items(): encoded_env[key.encode('utf-8')] = value.encode('utf-8') subprocess_env = encoded_env cwd = cwd.encode('utf-8') subprocess.Popen(subprocess_args, env=subprocess_env, cwd=cwd)
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import os import subprocess def launch_executable(executable, args, cwd, env=None): """ Launches an executable with optional arguments :param executable: A unicode string of an executable :param args: A list of unicode strings to pass as arguments to the executable :param cwd: A unicode string of the working directory to open the executable to :param env: A dict of unicode strings for a custom environmental variables to set """ subprocess_args = [executable] if args is not None: subprocess_args.extend(args) if sys.version_info >= (3,): subprocess_env = dict(os.environ) else: subprocess_env = {} for key, value in os.environ.items(): subprocess_env[key.decode('utf-8', 'replace')] = value.decode('utf-8', 'replace') if env: for key, value in env.items(): subprocess_env[key] = value if sys.version_info < (3,): encoded_args = [] for arg in subprocess_args: encoded_args.append(arg.encode('utf-8')) subprocess_args = encoded_args encoded_env = {} for key, value in subprocess_env.items(): encoded_env[key.encode('utf-8')] = value.encode('utf-8') subprocess_env = encoded_env cwd = cwd.encode('utf-8') subprocess.Popen(subprocess_args, env=subprocess_env, cwd=cwd)
Fix a bug launching a posix executable
Fix a bug launching a posix executable
Python
mit
codexns/newterm
--- +++ @@ -24,7 +24,8 @@ """ subprocess_args = [executable] - subprocess_args.extend(args) + if args is not None: + subprocess_args.extend(args) if sys.version_info >= (3,): subprocess_env = dict(os.environ)
5e67e16d17d06a0f4d307a035ca6b62f094995c6
network/api/serializers.py
network/api/serializers.py
from rest_framework import serializers from network.base.models import Data class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'start', 'end', 'observation', 'ground_station', 'payload') read_only_fields = ['id', 'start', 'end', 'observation', 'ground_station'] class JobSerializer(serializers.ModelSerializer): frequency = serializers.SerializerMethodField() tle0 = serializers.SerializerMethodField() tle1 = serializers.SerializerMethodField() tle2 = serializers.SerializerMethodField() class Meta: model = Data fields = ('id', 'start', 'end', 'ground_station', 'tle0', 'tle1', 'tle2', 'frequency') def get_frequency(self, obj): return obj.observation.transmitter.downlink_low def get_tle0(self, obj): return obj.observation.satellite.tle0 def get_tle1(self, obj): return obj.observation.satellite.tle1 def get_tle2(self, obj): return obj.observation.satellite.tle2
from rest_framework import serializers from network.base.models import Data class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'start', 'end', 'observation', 'ground_station', 'payload') read_only_fields = ['id', 'start', 'end', 'observation', 'ground_station'] class JobSerializer(serializers.ModelSerializer): frequency = serializers.SerializerMethodField() tle0 = serializers.SerializerMethodField() tle1 = serializers.SerializerMethodField() tle2 = serializers.SerializerMethodField() class Meta: model = Data fields = ('id', 'start', 'end', 'ground_station', 'tle0', 'tle1', 'tle2', 'frequency') def get_frequency(self, obj): return obj.observation.transmitter.downlink_low def get_tle0(self, obj): return obj.observation.tle.tle0 def get_tle1(self, obj): return obj.observation.tle.tle1 def get_tle2(self, obj): return obj.observation.tle.tle2
Adjust API to TLE code changes
Adjust API to TLE code changes
Python
agpl-3.0
cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network
--- +++ @@ -25,10 +25,10 @@ return obj.observation.transmitter.downlink_low def get_tle0(self, obj): - return obj.observation.satellite.tle0 + return obj.observation.tle.tle0 def get_tle1(self, obj): - return obj.observation.satellite.tle1 + return obj.observation.tle.tle1 def get_tle2(self, obj): - return obj.observation.satellite.tle2 + return obj.observation.tle.tle2
84e2e931ea83c25154fbcf749c797faae19ba8af
src/test_heap.py
src/test_heap.py
# _*_coding:utf-8 _*_ """Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) assert high_low.high_low[1] == data[1] def test_get_parent(): """Test parent method.""" from heap import Heap high_low = Heap() high_low.high_low.append(data[0]) high_low.high_low.append(data[1]) high_low.high_low.append(data[2]) assert high_low.high_low[high_low.get_parent(1)] == data[0] assert high_low.high_low[high_low.get_parent(2)] == data[0]
# _*_coding:utf-8 _*_ """Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) assert high_low.high_low[1] == data[1] def test_get_parent(): """Test parent method.""" from heap import Heap high_low = Heap() high_low.high_low.append(data[0]) high_low.high_low.append(data[1]) high_low.high_low.append(data[2]) assert high_low.high_low[high_low.get_parent(1)] == data[0] assert high_low.high_low[high_low.get_parent(2)] == data[0] def test_get_left(): """Test left method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) high_low.push(data[2]) assert high_low.high_low[high_low.get_left(0)] == data[1] def test_get_right(): """Test left method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) high_low.push(data[2]) assert high_low.high_low[high_low.get_right(0)] == data[2]
Test left and right method, almost identical to get test
Test left and right method, almost identical to get test
Python
mit
regenalgrant/datastructures
--- +++ @@ -18,6 +18,7 @@ high_low.push(data[1]) assert high_low.high_low[1] == data[1] + def test_get_parent(): """Test parent method.""" from heap import Heap @@ -27,3 +28,23 @@ high_low.high_low.append(data[2]) assert high_low.high_low[high_low.get_parent(1)] == data[0] assert high_low.high_low[high_low.get_parent(2)] == data[0] + + +def test_get_left(): + """Test left method.""" + from heap import Heap + high_low = Heap() + high_low.push(data[0]) + high_low.push(data[1]) + high_low.push(data[2]) + assert high_low.high_low[high_low.get_left(0)] == data[1] + + +def test_get_right(): + """Test left method.""" + from heap import Heap + high_low = Heap() + high_low.push(data[0]) + high_low.push(data[1]) + high_low.push(data[2]) + assert high_low.high_low[high_low.get_right(0)] == data[2]
72dcc89d96935ba4336ebafed5252628ecf92ed4
stables/views.py
stables/views.py
u""" 🐴 ✔ ✘ ▏ """ from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): status = get_object_or_404( models.PackageVersion, package__name=kwargs['package_name'], version=kwargs['package_version'], **{ 'result__installed_packages__%(factor_name)s' % kwargs: kwargs['factor_version'], } ) return quote( 'https://img.shields.io/badge/ 🐴 {} - {} -{}.svg'.format( *args ), )
u""" 🐴 ✔ ✘ ▏ """ from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models def badge_escape(val): return quote(val.replace('-', '--')) class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): filter_arg = Q( package__name=kwargs['package_name'], ) try: filter_arg &= Q( version=kwargs['package_version'], ) except KeyError: pass try: filter_arg &= Q( result__installed_packages__contains={ kwargs['factor_name']: kwargs['factor_version'], }, ) except KeyError: try: filter_arg &= Q result__installed_packages__has_key=kwargs['factor_name'], ) status = get_object_or_404(models.PackageVersion, filter_arg) for result in status.result_set.objects.filter( color = { 'passed': 'green', }[kwargs['result'] return quote( u'https://img.shields.io/badge/ 🐴 Supports %s - %s -%s.svg' % ( badge_escape(kwargs['package_name']), badge_escape(kwargs['factor_name']), color, ), )
Update badge view with new model schema.
Update badge view with new model schema.
Python
mit
django-stables/django-stables,django-stables/django-stables
--- +++ @@ -4,6 +4,7 @@ ✘ ▏ """ +from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView @@ -11,22 +12,45 @@ from . import models +def badge_escape(val): + return quote(val.replace('-', '--')) + + class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): - status = get_object_or_404( - models.PackageVersion, + filter_arg = Q( package__name=kwargs['package_name'], - version=kwargs['package_version'], - **{ - 'result__installed_packages__%(factor_name)s' % kwargs: - kwargs['factor_version'], - } ) + try: + filter_arg &= Q( + version=kwargs['package_version'], + ) + except KeyError: + pass + try: + filter_arg &= Q( + result__installed_packages__contains={ + kwargs['factor_name']: kwargs['factor_version'], + }, + ) + except KeyError: + try: + filter_arg &= Q + result__installed_packages__has_key=kwargs['factor_name'], + ) + + status = get_object_or_404(models.PackageVersion, filter_arg) + for result in status.result_set.objects.filter( + color = { + 'passed': 'green', + }[kwargs['result'] return quote( - 'https://img.shields.io/badge/ 🐴 {} - {} -{}.svg'.format( - *args + u'https://img.shields.io/badge/ 🐴 Supports %s - %s -%s.svg' % ( + badge_escape(kwargs['package_name']), + badge_escape(kwargs['factor_name']), + color, ), )
df95ed08135b74eb29e2e20b11a2f3cbdc76e967
bitHopper/Website/Worker_Page.py
bitHopper/Website/Worker_Page.py
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if pool.name is None: logging.debug('Ignoring %s', pool) continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers import logging @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if pool.name is None: logging.debug('Ignoring %s', pool) continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
Fix a bug, forgot to import logging
Fix a bug, forgot to import logging
Python
mit
c00w/bitHopper,c00w/bitHopper
--- +++ @@ -1,6 +1,7 @@ from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers +import logging @app.route("/worker", methods=['POST', 'GET']) def worker():
376b327379caeb0845007c3a0e7c33e1f15869f0
flatisfy/constants.py
flatisfy/constants.py
# coding: utf-8 """ Constants used across the app. """ from __future__ import absolute_import, print_function, unicode_literals # Some backends give more infos than others. Here is the precedence we want to # use. First is most important one, last is the one that will always be # considered as less trustable if two backends have similar info about a # housing. BACKENDS_BY_PRECEDENCE = [ "foncia", "seloger", "pap", "leboncoin", "explorimmo", "logicimmo", "entreparticuliers" ]
# coding: utf-8 """ Constants used across the app. """ from __future__ import absolute_import, print_function, unicode_literals # Some backends give more infos than others. Here is the precedence we want to # use. First is most important one, last is the one that will always be # considered as less trustable if two backends have similar info about a # housing. BACKENDS_BY_PRECEDENCE = [ "foncia", "seloger", "pap", "leboncoin", "explorimmo", "logicimmo" ]
Drop support for entreparticuliers Weboob module
Drop support for entreparticuliers Weboob module
Python
mit
Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy
--- +++ @@ -14,6 +14,5 @@ "pap", "leboncoin", "explorimmo", - "logicimmo", - "entreparticuliers" + "logicimmo" ]
27c3b70967e36a6f419f089ba22e8394d39981e1
api/views/share.py
api/views/share.py
from rest_framework import views from rest_framework.response import Response from django import http from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_GET from django.views.generic.base import RedirectView from share.models import Source from api import util @require_GET def source_icon_view(request, source_name): source = get_object_or_404(Source, name=source_name) if not source.icon: raise http.Http404('Favicon for source {} does not exist'.format(source_name)) response = http.HttpResponse(source.icon) response['Content-Type'] = 'image/x-icon' return response class APIVersionRedirectView(RedirectView): def get_redirect_url(self, *args, **kwargs): return '/api/v2/{}'.format(kwargs['path']) def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return util.HttpSmartResponsePermanentRedirect(url) return util.HttpSmartResponseRedirect(url) return http.HttpResponseGone() class ServerStatusView(views.APIView): def get(self, request): return Response({ 'id': '1', 'type': 'Status', 'attributes': { 'status': 'up', 'version': settings.VERSION, } })
from rest_framework import views from rest_framework.response import Response from django import http from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_GET from django.views.generic.base import RedirectView from share.models import Source from api import util @require_GET def source_icon_view(request, source_name): source = get_object_or_404(Source, name=source_name) if not source.icon: raise http.Http404('Favicon for source {} does not exist'.format(source_name)) response = http.FileResponse(source.icon) response['Content-Type'] = 'image/x-icon' return response class APIVersionRedirectView(RedirectView): def get_redirect_url(self, *args, **kwargs): return '/api/v2/{}'.format(kwargs['path']) def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return util.HttpSmartResponsePermanentRedirect(url) return util.HttpSmartResponseRedirect(url) return http.HttpResponseGone() class ServerStatusView(views.APIView): def get(self, request): return Response({ 'id': '1', 'type': 'Status', 'attributes': { 'status': 'up', 'version': settings.VERSION, } })
Revert "Don't use a streaming response for icons"
Revert "Don't use a streaming response for icons" This reverts commit 6d7b15550b9a62af4220cf73ff77d7c967cec6d8.
Python
apache-2.0
aaxelb/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,CenterForOpenScience/SHARE
--- +++ @@ -17,7 +17,7 @@ source = get_object_or_404(Source, name=source_name) if not source.icon: raise http.Http404('Favicon for source {} does not exist'.format(source_name)) - response = http.HttpResponse(source.icon) + response = http.FileResponse(source.icon) response['Content-Type'] = 'image/x-icon' return response
fe36e76dd7fcdc6249ccf36bfadcdbb909078536
apps/concept/management/commands/update_concept_totals.py
apps/concept/management/commands/update_concept_totals.py
from optparse import make_option import sys from django.core.management.base import BaseCommand from concept.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.objects.all(): concept.total_questions = concept.question_set.count() concept.save()
from optparse import make_option import sys from django.core.management.base import BaseCommand from concept.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.objects.all(): concept.total_questions = concept.questions.count() concept.save()
Add management functions for migration
Add management functions for migration
Python
bsd-3-clause
mfitzp/smrtr,mfitzp/smrtr
--- +++ @@ -9,5 +9,5 @@ def handle(self, *args, **options): for concept in Concept.objects.all(): - concept.total_questions = concept.question_set.count() + concept.total_questions = concept.questions.count() concept.save()
4b65c5ac47ecbaec8e1578074d9650c342b294e5
apps/offline/views.py
apps/offline/views.py
# -*- encoding: utf-8 -*- from django.shortcuts import render # API v1 from rest_framework import mixins, viewsets from rest_framework.permissions import AllowAny from apps.offline.models import Issue from apps.offline.serializers import OfflineIssueSerializer def main(request): issues = Issue.objects.all() years = set() for issue in issues: years.add(issue.release_date.year) years = list(reversed(sorted(years))) ctx = { "issues": issues, "years": years, } return render(request, "offline/offline.html", ctx) class OfflineIssueViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin): queryset = Issue.objects.all() serializer_class = OfflineIssueSerializer permission_classes = (AllowAny,) filter_fields = ('id', 'issue', 'release_date', 'title')
# -*- encoding: utf-8 -*- from django.shortcuts import render # API v1 from rest_framework import mixins, viewsets from rest_framework.permissions import AllowAny from apps.offline.models import Issue from apps.offline.serializers import OfflineIssueSerializer def main(request): issues = Issue.objects.all() years = set() for issue in issues: years.add(issue.release_date.year) years = list(reversed(sorted(years))) ctx = { "issues": issues, "years": years, } return render(request, "offline/offline.html", ctx) class OfflineIssueViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin): queryset = Issue.objects.all() serializer_class = OfflineIssueSerializer permission_classes = (AllowAny,) filter_fields = ('id', 'release_date', 'title')
Remove option to filter Offline on the actual files
Remove option to filter Offline on the actual files
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -29,4 +29,4 @@ queryset = Issue.objects.all() serializer_class = OfflineIssueSerializer permission_classes = (AllowAny,) - filter_fields = ('id', 'issue', 'release_date', 'title') + filter_fields = ('id', 'release_date', 'title')
5ac83deb88c8ae34a361c9a5b60dcb16fea77b35
custom/inddex/reports/master_data_file.py
custom/inddex/reports/master_data_file.py
from django.utils.functional import cached_property from memoized import memoized from custom.inddex.food import FoodData from custom.inddex.ucr_data import FoodCaseData from custom.inddex.utils import BaseGapsSummaryReport class MasterDataFileSummaryReport(BaseGapsSummaryReport): title = 'Output 1 - Master Data File' name = title slug = 'output_1_master_data_file' export_only = False show_filters = True report_comment = 'This output includes all data that appears in the output files as well as background ' \ 'data that are used to perform calculations that appear in the outputs.' @property @memoized def data_providers(self): return [ MasterDataFileData(config=self.report_config), ] class MasterDataFileData: title = 'Master Data' slug = 'master_data' def __init__(self, config): self.config = config @cached_property def food_data(self): return FoodData( self.config['domain'], FoodCaseData(self.config).get_data(), ) @property def headers(self): return self.food_data.headers @property def rows(self): return self.food_data.rows
from django.utils.functional import cached_property from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin from custom.inddex.filters import ( CaseOwnersFilter, DateRangeFilter, GapTypeFilter, RecallStatusFilter, ) from custom.inddex.food import FoodData from custom.inddex.ucr_data import FoodCaseData class MasterDataFileSummaryReport(DatespanMixin, CustomProjectReport, GenericTabularReport): title = 'Output 1 - Master Data File' name = title slug = 'output_1_master_data_file' export_only = False report_comment = 'This output includes all data that appears in the output files as well as background ' \ 'data that are used to perform calculations that appear in the outputs.' @property def fields(self): return [CaseOwnersFilter, DateRangeFilter, GapTypeFilter, RecallStatusFilter] @property def headers(self): return DataTablesHeader( *(DataTablesColumn(header) for header in self._food_data.headers) ) @property def rows(self): return self._food_data.rows @cached_property def _food_data(self): return FoodData( self.domain, FoodCaseData({ 'domain': self.domain, 'startdate': str(self.datespan.startdate), 'enddate': str(self.datespan.enddate), 'case_owners': self.request.GET.get('case_owners') or '', 'gap_type': self.request.GET.get('gap_type') or '', 'recall_status': self.request.GET.get('recall_status') or '', }).get_data(), )
Make it a normal report
Make it a normal report No need to override a bunch of stuff, assemble filters and configs through inheritance, use a custom template, etcetera
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -1,47 +1,50 @@ from django.utils.functional import cached_property -from memoized import memoized - +from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader +from corehq.apps.reports.generic import GenericTabularReport +from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin +from custom.inddex.filters import ( + CaseOwnersFilter, + DateRangeFilter, + GapTypeFilter, + RecallStatusFilter, +) from custom.inddex.food import FoodData from custom.inddex.ucr_data import FoodCaseData -from custom.inddex.utils import BaseGapsSummaryReport -class MasterDataFileSummaryReport(BaseGapsSummaryReport): +class MasterDataFileSummaryReport(DatespanMixin, CustomProjectReport, GenericTabularReport): title = 'Output 1 - Master Data File' name = title slug = 'output_1_master_data_file' export_only = False - show_filters = True report_comment = 'This output includes all data that appears in the output files as well as background ' \ 'data that are used to perform calculations that appear in the outputs.' @property - @memoized - def data_providers(self): - return [ - MasterDataFileData(config=self.report_config), - ] + def fields(self): + return [CaseOwnersFilter, DateRangeFilter, GapTypeFilter, RecallStatusFilter] - -class MasterDataFileData: - title = 'Master Data' - slug = 'master_data' - - def __init__(self, config): - self.config = config - - @cached_property - def food_data(self): - return FoodData( - self.config['domain'], - FoodCaseData(self.config).get_data(), + @property + def headers(self): + return DataTablesHeader( + *(DataTablesColumn(header) for header in self._food_data.headers) ) @property - def headers(self): - return self.food_data.headers + def rows(self): + return self._food_data.rows - @property - def rows(self): - return self.food_data.rows + @cached_property + def _food_data(self): + return FoodData( + self.domain, + FoodCaseData({ + 'domain': self.domain, + 'startdate': str(self.datespan.startdate), + 'enddate': str(self.datespan.enddate), + 'case_owners': self.request.GET.get('case_owners') or '', + 'gap_type': self.request.GET.get('gap_type') or '', + 'recall_status': self.request.GET.get('recall_status') or '', + }).get_data(), + )
40a63fd8ca5dd574e729b9f531664ce384aa404c
app/schedule/tasks.py
app/schedule/tasks.py
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=50)
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=2000, countdown=60 * 5)
Increase retry count and add countdown to retry method
Increase retry count and add countdown to retry method
Python
agpl-3.0
agendaodonto/server,agendaodonto/server
--- +++ @@ -22,4 +22,4 @@ # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) - self.retry(exc=e, max_retries=50) + self.retry(exc=e, max_retries=2000, countdown=60 * 5)
d9b5a78b36729bdb3ce11c8626d00b57555fb356
core/views.py
core/views.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissions import IsOwnerOrReadOnly from users.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = api.UserSerializer class ImageViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = Image.objects.all() serializer_class = api.ImageSerializer def create(self, request, *args, **kwargs): return super(ImageViewSet, self).create(request, *args, **kwargs) class PinViewSet(viewsets.ModelViewSet): queryset = Pin.objects.all() serializer_class = api.PinSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ("submitter__username", 'tags__name', ) ordering_fields = ('-id', ) ordering = ('-id', ) permission_classes = [IsOwnerOrReadOnly("submitter"), ] drf_router = routers.DefaultRouter() drf_router.register(r'users', UserViewSet) drf_router.register(r'pins', PinViewSet) drf_router.register(r'images', ImageViewSet)
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissions import IsOwnerOrReadOnly from users.models import User class UserViewSet(mixins.RetrieveModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = api.UserSerializer class ImageViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = Image.objects.all() serializer_class = api.ImageSerializer def create(self, request, *args, **kwargs): return super(ImageViewSet, self).create(request, *args, **kwargs) class PinViewSet(viewsets.ModelViewSet): queryset = Pin.objects.all() serializer_class = api.PinSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ("submitter__username", 'tags__name', ) ordering_fields = ('-id', ) ordering = ('-id', ) permission_classes = [IsOwnerOrReadOnly("submitter"), ] drf_router = routers.DefaultRouter() drf_router.register(r'users', UserViewSet) drf_router.register(r'pins', PinViewSet) drf_router.register(r'images', ImageViewSet)
Allow only the user-data fetching
Refactor: Allow only the user-data fetching
Python
bsd-2-clause
pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry
--- +++ @@ -9,7 +9,7 @@ from users.models import User -class UserViewSet(viewsets.ModelViewSet): +class UserViewSet(mixins.RetrieveModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = api.UserSerializer
c86d5c928cdefd09aca102b2a5c37f662e1426a6
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PosteGnerationMethodCall('set_password', 'password') class Meta: model = models.User django_get_or_create = ('username', )
import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'users.User' django_get_or_create = ('username', )
Fix typo & import in UserFactory
Fix typo & import in UserFactory
Python
bsd-3-clause
andresgz/cookiecutter-django,gappsexperts/cookiecutter-django,asyncee/cookiecutter-django,gappsexperts/cookiecutter-django,calculuscowboy/cookiecutter-django,aleprovencio/cookiecutter-django,ddiazpinto/cookiecutter-django,asyncee/cookiecutter-django,drxos/cookiecutter-django-dokku,thisjustin/cookiecutter-django,aleprovencio/cookiecutter-django,mjhea0/cookiecutter-django,schacki/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aleprovencio/cookiecutter-django,nunchaks/cookiecutter-django,Parbhat/cookiecutter-django-foundation,ad-m/cookiecutter-django,hairychris/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,pydanny/cookiecutter-django,gappsexperts/cookiecutter-django,kappataumu/cookiecutter-django,calculuscowboy/cookiecutter-django,ryankanno/cookiecutter-django,hairychris/cookiecutter-django,hairychris/cookiecutter-django,kappataumu/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,kappataumu/cookiecutter-django,HandyCodeJob/hcj-django-temp,Parbhat/cookiecutter-django-foundation,ryankanno/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,aeikenberry/cookiecutter-django-rest-babel,schacki/cookiecutter-django,nunchaks/cookiecutter-django,webyneter/cookiecutter-django,crdoconnor/cookiecutter-django,webspired/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,drxos/cookiecutter-django-dokku,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,pydanny/cookiecutter-django,jondelmil/cookiecutter-django,ad-m/cookiecutter-django,kappataumu/cookiecutter-django,hackebrot/cookiecutter-django,pydanny/cookiecutter-django,ad-m/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,gappsexperts/cookiecutter-django,HandyCodeJob/hcj-django-temp,hairychris/cookiecutter-django,webspired/cookiecutter-django,hackebrot/cookiecutter-django,topwebmaster/cookiecutter-django,calculuscowboy/cookiecutter-django,jondelmil/cookiecutter-django,mistalaba/cookiecutter-django,trungdong/cookiecutter-django,ovidner/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aeikenberry/cookiecutter-django-rest-babel,jondelmil/cookiecutter-django,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,webspired/cookiecutter-django,nunchaks/cookiecutter-django,andresgz/cookiecutter-django,ad-m/cookiecutter-django,ovidner/cookiecutter-django,mistalaba/cookiecutter-django,bopo/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,ddiazpinto/cookiecutter-django,calculuscowboy/cookiecutter-django,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,webyneter/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,asyncee/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,crdoconnor/cookiecutter-django,nunchaks/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,hackebrot/cookiecutter-django,asyncee/cookiecutter-django,aleprovencio/cookiecutter-django,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,luzfcb/cookiecutter-django,topwebmaster/cookiecutter-django,drxos/cookiecutter-django-dokku,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,hackebrot/cookiecutter-django,trungdong/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,andresgz/cookiecutter-django,webyneter/cookiecutter-django,webyneter/cookiecutter-django,andresgz/cookiecutter-django,thisjustin/cookiecutter-django,mjhea0/cookiecutter-django,drxos/cookiecutter-django-dokku,jondelmil/cookiecutter-django,bopo/cookiecutter-django,webspired/cookiecutter-django
--- +++ @@ -1,12 +1,11 @@ -from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) - password = factory.PosteGnerationMethodCall('set_password', 'password') + password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: - model = models.User + model = 'users.User' django_get_or_create = ('username', )
98f638e5a42765a284a4fd006190507efee5363a
runtests.py
runtests.py
#!/usr/bin/env python import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") this_dir = os.path.abspath(os.path.dirname(__file__)) if this_dir not in sys.path: sys.path.insert(0, this_dir) import django from django.test.utils import get_runner from django.conf import settings def runtests(): if not settings.configured: django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(["base", "threads", "events", "managers"]) sys.exit(bool(failures)) if __name__ == "__main__": runtests()
#!/usr/bin/env python import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") this_dir = os.path.abspath(os.path.dirname(__file__)) if this_dir not in sys.path: sys.path.insert(0, this_dir) import django from django.test.runner import DiscoverRunner from django.conf import settings def runtests(): if not settings.configured: django.setup() test_runner = DiscoverRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(["base", "threads", "events", "managers"]) sys.exit(bool(failures)) if __name__ == "__main__": runtests()
Use the new test runner
Use the new test runner
Python
bsd-2-clause
knagra/farnsworth,knagra/farnsworth,knagra/farnsworth,knagra/farnsworth
--- +++ @@ -9,15 +9,14 @@ sys.path.insert(0, this_dir) import django -from django.test.utils import get_runner +from django.test.runner import DiscoverRunner from django.conf import settings def runtests(): if not settings.configured: django.setup() - TestRunner = get_runner(settings) - test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) + test_runner = DiscoverRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(["base", "threads", "events", "managers"]) sys.exit(bool(failures))
9d1a21e046bac48719e6f396a55489bffe631cf7
runtests.py
runtests.py
#!/usr/bin/env python import os, sys from django.conf import settings def runtests(*test_args): if not test_args: test_args = ['lockdown'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) settings.configure( DATABASE_ENGINE='sqlite3', INSTALLED_APPS = ('django.contrib.sessions', 'lockdown'), ROOT_URLCONF='lockdown.tests.urls', ) from django.test.utils import get_runner test_runner = get_runner(settings) failures = test_runner(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python import os, sys from django.conf import settings def runtests(*test_args): if not test_args: test_args = ['lockdown'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) settings.configure( DATABASE_ENGINE='sqlite3', INSTALLED_APPS = ( 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.auth', 'lockdown' ), ROOT_URLCONF='lockdown.tests.urls', ) from django.test.utils import get_runner test_runner = get_runner(settings) failures = test_runner(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Add in django.contrib.auth to the default test runner
Add in django.contrib.auth to the default test runner
Python
bsd-3-clause
Dunedan/django-lockdown,Dunedan/django-lockdown
--- +++ @@ -12,7 +12,12 @@ sys.path.insert(0, parent) settings.configure( DATABASE_ENGINE='sqlite3', - INSTALLED_APPS = ('django.contrib.sessions', 'lockdown'), + INSTALLED_APPS = ( + 'django.contrib.sessions', + 'django.contrib.contenttypes', + 'django.contrib.auth', + 'lockdown' + ), ROOT_URLCONF='lockdown.tests.urls', ) from django.test.utils import get_runner
b0e614ea7ac59b6b869155b9ac8ea370cb56f83d
cardinal/decorators.py
cardinal/decorators.py
import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
Allow for single trigger in @command decorator
Allow for single trigger in @command decorator
Python
mit
BiohZn/Cardinal,JohnMaguire/Cardinal
--- +++ @@ -1,6 +1,9 @@ import functools def command(triggers): + if isinstance(triggers, basestring): + triggers = [triggers] + def wrap(f): @functools.wraps(f) def inner(*args, **kwargs):
67c90087bad42d54b44044c3d1afae02538c456f
tests/logging.py
tests/logging.py
import os def save_logs(groomer, test_description): divider = ('=' * 10 + '{}' + '=' * 10 + '\n') test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) with open(groomer.logger.log_path, 'r') as logfile: log = logfile.read() test_log.write(log) if os.path.exists(groomer.logger.log_debug_err): test_log.write(divider.format('ERR LOG')) with open(groomer.logger.log_debug_err, 'r') as debug_err: err = debug_err.read() test_log.write(err) if os.path.exists(groomer.logger.log_debug_out): test_log.write(divider.format('OUT LOG')) with open(groomer.logger.log_debug_out, 'r') as debug_out: out = debug_out.read() test_log.write(out)
import os from datetime import datetime def save_logs(groomer, test_description): divider = ('=' * 10 + '{}' + '=' * 10 + '\n') test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) test_log.write(str(datetime.now().time()) + '\n') test_log.write(test_description + '\n') test_log.write('-' * 20 + '\n') with open(groomer.logger.log_path, 'r') as logfile: log = logfile.read() test_log.write(log) if os.path.exists(groomer.logger.log_debug_err): test_log.write(divider.format('ERR LOG')) with open(groomer.logger.log_debug_err, 'r') as debug_err: err = debug_err.read() test_log.write(err) if os.path.exists(groomer.logger.log_debug_out): test_log.write(divider.format('OUT LOG')) with open(groomer.logger.log_debug_out, 'r') as debug_out: out = debug_out.read() test_log.write(out)
Add time information to test logs
Add time information to test logs
Python
bsd-3-clause
CIRCL/PyCIRCLean,Rafiot/PyCIRCLean,Rafiot/PyCIRCLean,CIRCL/PyCIRCLean
--- +++ @@ -1,4 +1,5 @@ import os +from datetime import datetime def save_logs(groomer, test_description): @@ -6,6 +7,9 @@ test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) + test_log.write(str(datetime.now().time()) + '\n') + test_log.write(test_description + '\n') + test_log.write('-' * 20 + '\n') with open(groomer.logger.log_path, 'r') as logfile: log = logfile.read() test_log.write(log)
2aac8cafc0675d38cabcc137d063de0119b3ff3d
game.py
game.py
import pygame, sys """ A simple four in a row game. Author: Isaac Arvestad """ class Game: def __init__(self): def update(self): "Handle input." for event in pygame.event.get(): if event.type == pygame.QUIT: return False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return False def render(self): "Starts the game." def start(self): while True: if not self.update(): break self.render() pygame.display.update() self.exit() def exit(self): pygame.quit() sys.exit()
import pygame, sys from board import Board """ A simple four in a row game. Author: Isaac Arvestad """ class Game: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((600,600)) self.background = pygame.Surface(self.screen.get_size()) self.background.fill((255,255,255)) self.background = self.background.convert() self.screen.blit(self.background, (0,0)) self.screenWidth = self.screen.get_size()[0] self.screenHeight = self.screen.get_size()[1] self.board = Board(7, 7) self.pieceWidth = 50 self.pieceHeight = 50 def update(self): "Handle input." for event in pygame.event.get(): if event.type == pygame.QUIT: return False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return False return True def render(self, screen): for x in range(self.board.columns): for y in range(self.board.rows): pygame.draw.rect(screen, (0,0,0), (x*self.pieceWidth, y*self.pieceHeight, self.pieceWidth, self.pieceHeight)) "Starts the game." def start(self): while True: if not self.update(): break self.render(self.screen) pygame.display.update() self.exit() def exit(self): pygame.quit() sys.exit() game = Game() game.start()
Create screen and draw board to screen.
Create screen and draw board to screen.
Python
mit
isaacarvestad/four-in-a-row
--- +++ @@ -1,4 +1,6 @@ import pygame, sys + +from board import Board """ A simple four in a row game. @@ -7,7 +9,22 @@ """ class Game: def __init__(self): - + pygame.init() + + self.screen = pygame.display.set_mode((600,600)) + + self.background = pygame.Surface(self.screen.get_size()) + self.background.fill((255,255,255)) + self.background = self.background.convert() + + self.screen.blit(self.background, (0,0)) + + self.screenWidth = self.screen.get_size()[0] + self.screenHeight = self.screen.get_size()[1] + + self.board = Board(7, 7) + self.pieceWidth = 50 + self.pieceHeight = 50 def update(self): "Handle input." @@ -17,10 +34,12 @@ elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return False - + return True - def render(self): - + def render(self, screen): + for x in range(self.board.columns): + for y in range(self.board.rows): + pygame.draw.rect(screen, (0,0,0), (x*self.pieceWidth, y*self.pieceHeight, self.pieceWidth, self.pieceHeight)) "Starts the game." def start(self): @@ -28,7 +47,7 @@ if not self.update(): break - self.render() + self.render(self.screen) pygame.display.update() self.exit() @@ -36,3 +55,6 @@ def exit(self): pygame.quit() sys.exit() + +game = Game() +game.start()
00208e088ea62eb3c405e22f54a96e6e46869844
pubsub/backend/rabbitmq.py
pubsub/backend/rabbitmq.py
from gevent import monkey monkey.patch_all() import uuid from kombu.mixins import ConsumerMixin from pubsub.backend.base import BaseSubscriber, BasePublisher from pubsub.helpers import get_config from pubsub.backend.handlers import RabbitMQHandler class RabbitMQPublisher(BasePublisher, RabbitMQHandler): def __init__(self): self.config = get_config('rabbitmq').get('publisher', None) self.connection = self._connect() def start(self): self._exchange = self._create_exchange() self._producer = self._create_producer() def publish(self, message): message_id = str(uuid.uuid4()) message = {'payload': message, 'message_id': message_id, 'reply_to': None} self._producer.publish( message, exchange=self._exchange, **self.config.get('publish')) return message_id class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler): def __init__(self): self.config = get_config('rabbitmq').get('subscriber', None) self.connection = self._connect() def start(self): self._exchange = self._create_exchange() self._queue = self._create_queue() def run_forever(self): self.run() def get_consumers(self, consumer, channel): return [consumer( queues=[self._queue], callbacks=[self.on_message], **self.config.get('consumer'))] def on_message(self, body, message): message.ack()
from gevent import monkey monkey.patch_all() import uuid from kombu.mixins import ConsumerMixin from pubsub.backend.base import BaseSubscriber, BasePublisher from pubsub.helpers import get_config from pubsub.backend.handlers import RabbitMQHandler class RabbitMQPublisher(BasePublisher, RabbitMQHandler): def __init__(self, config=None): self.config = config or get_config('rabbitmq').get('publisher', None) self.connection = self._connect() def start(self): self._exchange = self._create_exchange() self._producer = self._create_producer() def publish(self, message): message_id = str(uuid.uuid4()) message = {'payload': message, 'message_id': message_id, 'reply_to': None} self._producer.publish( message, exchange=self._exchange, **self.config.get('publish')) return message_id class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler): def __init__(self, config=None): self.config = config or get_config('rabbitmq').get('subscriber', None) self.connection = self._connect() def start(self): self._exchange = self._create_exchange() self._queue = self._create_queue() def run_forever(self): self.run() def get_consumers(self, consumer, channel): return [consumer( queues=[self._queue], callbacks=[self.on_message], **self.config.get('consumer'))] def on_message(self, body, message): message.ack()
Add the possiblity to pass a conf file to Publisher and Subscriber class
Add the possiblity to pass a conf file to Publisher and Subscriber class Closes #20
Python
mit
WeLikeAlpacas/Qpaca,WeLikeAlpacas/python-pubsub,csarcom/python-pubsub
--- +++ @@ -11,8 +11,8 @@ class RabbitMQPublisher(BasePublisher, RabbitMQHandler): - def __init__(self): - self.config = get_config('rabbitmq').get('publisher', None) + def __init__(self, config=None): + self.config = config or get_config('rabbitmq').get('publisher', None) self.connection = self._connect() def start(self): @@ -31,8 +31,8 @@ class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler): - def __init__(self): - self.config = get_config('rabbitmq').get('subscriber', None) + def __init__(self, config=None): + self.config = config or get_config('rabbitmq').get('subscriber', None) self.connection = self._connect() def start(self):
147257537f1233759dd89a291d6e40b95450ed5e
src/wrapt/__init__.py
src/wrapt/__init__.py
__version_info__ = ('1', '13', '3') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wrapper, wrap_function_wrapper, patch_function_wrapper, transient_function_wrapper) from .decorators import (adapter_factory, AdapterFactory, decorator, synchronized) from .importer import (register_post_import_hook, when_imported, notify_module_loaded, discover_post_import_hooks) from inspect import getcallargs
__version_info__ = ('1', '14', '0dev1') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wrapper, wrap_function_wrapper, patch_function_wrapper, transient_function_wrapper) from .decorators import (adapter_factory, AdapterFactory, decorator, synchronized) from .importer import (register_post_import_hook, when_imported, notify_module_loaded, discover_post_import_hooks) from inspect import getcallargs
Increment version to 1.14.0dev1 for new changes.
Increment version to 1.14.0dev1 for new changes.
Python
bsd-2-clause
GrahamDumpleton/wrapt,GrahamDumpleton/wrapt
--- +++ @@ -1,4 +1,4 @@ -__version_info__ = ('1', '13', '3') +__version_info__ = ('1', '14', '0dev1') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
1acb0e5db755b0d4cc389ed32f740d7e65218a5e
celestial/views.py
celestial/views.py
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_queryset(self): return super(PlanetMixin, self).get_queryset().filter( solar_system__radius__isnull=False, radius__isnull=False) class SystemList(SystemMixin, ListView): pass class SystemDetail(SystemMixin, DetailView): def get_context_data(self, **kwargs): data = super(SystemDetail, self).get_context_data(**kwargs) data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False)}) return data class PlanetList(PlanetMixin, ListView): pass class PlanetDetail(PlanetMixin, DetailView): pass
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_queryset(self): return super(PlanetMixin, self).get_queryset().filter( solar_system__radius__isnull=False, radius__isnull=False) class SystemList(SystemMixin, ListView): pass class SystemDetail(SystemMixin, DetailView): def get_context_data(self, **kwargs): data = super(SystemDetail, self).get_context_data(**kwargs) data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')}) return data class PlanetList(PlanetMixin, ListView): pass class PlanetDetail(PlanetMixin, DetailView): pass
Order planets by distance form their star.
Order planets by distance form their star.
Python
mit
Floppy/kepler-explorer,Floppy/kepler-explorer,Floppy/kepler-explorer
--- +++ @@ -24,7 +24,7 @@ class SystemDetail(SystemMixin, DetailView): def get_context_data(self, **kwargs): data = super(SystemDetail, self).get_context_data(**kwargs) - data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False)}) + data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')}) return data class PlanetList(PlanetMixin, ListView):
ade031dc91d75de8ce290fa4b6652c2f46a3171e
streak-podium/read.py
streak-podium/read.py
def input_file(filename): """ Return username list, assuming on username per line. """ with open(filename, 'r') as f: return list(strip(x) for x in f) def org_members(org_name): """ Return all members from a Github organization. """ # TODO: Return github org members, not a placeholder return ['supermitch']
def input_file(filename): """ Return username list, assuming on username per line. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Return all members from a Github organization. """ # TODO: Return github org members, not a placeholder return ['supermitch']
Fix bug ... .strip() is a method not a function
Fix bug ... .strip() is a method not a function
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-streak-podium,supermitch/streak-podium
--- +++ @@ -3,7 +3,8 @@ Return username list, assuming on username per line. """ with open(filename, 'r') as f: - return list(strip(x) for x in f) + return list(line.strip() for line in f if line.strip()) + def org_members(org_name): """
8858cf1f0b87026ce913a19c4e5df415409cfd79
streak-podium/read.py
streak-podium/read.py
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ if org_name is None: org_name = 'pulseenergy' url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Handle None for org or file with default org name
Handle None for org or file with default org name
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium
--- +++ @@ -17,6 +17,9 @@ """ Query Github API and return list of members from a Github organization. """ + if org_name is None: + org_name = 'pulseenergy' + url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try:
b9f8012084a0f7faae4b1a820b25ceb93b29e04c
install_steps/create_bosh_cert.py
install_steps/create_bosh_cert.py
from subprocess import call from os import makedirs from shutil import copy def do_step(context): makedirs("bosh/manifests") # Generate the private key and certificate call("sh create_cert.sh", shell=True) copy("bosh.key", "./bosh/bosh") with open('bosh_cert.pem', 'r') as tmpfile: ssh_cert = tmpfile.read() ssh_cert = "|\n" + ssh_cert ssh_cert = "\n ".join([line for line in ssh_cert.split('\n')]) context.meta['settings']['SSH_CERTIFICATE'] = ssh_cert return context
from subprocess import call from os import makedirs from os import path from shutil import copy def do_step(context): if not path.isdir("bosh/manifests"): makedirs("bosh/manifests") # Generate the private key and certificate call("sh create_cert.sh", shell=True) copy("bosh.key", "./bosh/bosh") with open('bosh_cert.pem', 'r') as tmpfile: ssh_cert = tmpfile.read() ssh_cert = "|\n" + ssh_cert ssh_cert = "\n ".join([line for line in ssh_cert.split('\n')]) context.meta['settings']['SSH_CERTIFICATE'] = ssh_cert return context
Check to see if manifests path exists
Check to see if manifests path exists
Python
apache-2.0
cf-platform-eng/bosh-azure-template,cf-platform-eng/bosh-azure-template
--- +++ @@ -1,11 +1,13 @@ from subprocess import call from os import makedirs +from os import path from shutil import copy def do_step(context): - makedirs("bosh/manifests") + if not path.isdir("bosh/manifests"): + makedirs("bosh/manifests") # Generate the private key and certificate call("sh create_cert.sh", shell=True)
9109e3803b139c349d17b9b413b0ff9d5b965b55
hassio/addons/util.py
hassio/addons/util.py
"""Util addons functions.""" import hashlib import pathlib import re import unicodedata RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') def slugify(text): """Slugify a given text.""" text = unicodedata.normalize('NFKD', text) text = text.lower() text = text.replace(" ", "_") text = RE_SLUGIFY.sub("", text) return text def get_hash_from_repository(repo): """Generate a hash from repository.""" key = repo.lower().encode() return hashlib.sha1(key).hexdigest()[:8] def extract_hash_from_path(base_path, options_path): """Extract repo id from path.""" base_dir = pathlib.PurePosixPath(base_path).parts[-1] dirlist = iter(pathlib.PurePosixPath(options_path).parts) for obj in dirlist: if obj != base_dir: continue return slugify(next(dirlist))
"""Util addons functions.""" import hashlib import pathlib import re RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') RE_SHA1 = re.compile(r"[a-f0-9]{40}") def get_hash_from_repository(repo): """Generate a hash from repository.""" key = repo.lower().encode() return hashlib.sha1(key).hexdigest()[:8] def extract_hash_from_path(base_path, options_path): """Extract repo id from path.""" base_dir = pathlib.PurePosixPath(base_path).parts[-1] dirlist = iter(pathlib.PurePosixPath(options_path).parts) for obj in dirlist: if obj != base_dir: continue repo_dir = next(dirlist) if not RE_SHA1.match(repo_dir): return get_hash_from_repository(repo_dir) return repo_dir
Use in every case a hash for addon name
Use in every case a hash for addon name
Python
bsd-3-clause
pvizeli/hassio,pvizeli/hassio
--- +++ @@ -2,19 +2,9 @@ import hashlib import pathlib import re -import unicodedata RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') - - -def slugify(text): - """Slugify a given text.""" - text = unicodedata.normalize('NFKD', text) - text = text.lower() - text = text.replace(" ", "_") - text = RE_SLUGIFY.sub("", text) - - return text +RE_SHA1 = re.compile(r"[a-f0-9]{40}") def get_hash_from_repository(repo): @@ -31,4 +21,8 @@ for obj in dirlist: if obj != base_dir: continue - return slugify(next(dirlist)) + + repo_dir = next(dirlist) + if not RE_SHA1.match(repo_dir): + return get_hash_from_repository(repo_dir) + return repo_dir
dcd3e4f5ded298b79b40d16a9f0274752ed96ad1
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = ('c++', 'c') # Make it able to work under C mode cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = { 'c++': 'cpp', 'c' : 'c' } defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]'
Add support to C files
Add support to C files
Python
mit
SublimeLinter/SublimeLinter-cppcheck,ftoulemon/SublimeLinter-cppcheck
--- +++ @@ -17,11 +17,14 @@ """Provides an interface to cppcheck.""" - syntax = 'c++' + syntax = ('c++', 'c') # Make it able to work under C mode cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout - tempfile_suffix = 'cpp' + tempfile_suffix = { + 'c++': 'cpp', + 'c' : 'c' + } defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style',
f3668e36e93d990213c4c8ab1db6dea26328b4eb
AFQ/utils/volume.py
AFQ/utils/volume.py
import scipy.ndimage as ndim from skimage.filters import gaussian from skimage.morphology import convex_hull_image def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. truncate : float The truncation for the Gaussian Returns ------- ROI after dilation and hole-filling """ return convex_hull_image(gaussian(ndim.binary_fill_holes(roi), sigma=sigma, truncate=truncate) > 0.1)
import scipy.ndimage as ndim from skimage.filters import gaussian from skimage.morphology import convex_hull_image def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. truncate : float The truncation for the Gaussian Returns ------- ROI after dilation and hole-filling """ return convex_hull_image(gaussian(ndim.binary_fill_holes(roi), sigma=sigma, truncate=truncate) > 0)
Set the Gaussian threshold to 0.
Set the Gaussian threshold to 0.
Python
bsd-2-clause
yeatmanlab/pyAFQ,arokem/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ
--- +++ @@ -25,4 +25,4 @@ """ return convex_hull_image(gaussian(ndim.binary_fill_holes(roi), - sigma=sigma, truncate=truncate) > 0.1) + sigma=sigma, truncate=truncate) > 0)
301a70469dba6fdfe8d72d3d70fa75e4146756c6
integration-test/843-normalize-underscore.py
integration-test/843-normalize-underscore.py
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 # verify that no aerialway subkind exists when its value is yes with features_in_tile_layer(16, 10910, 25120, 'roads') as features: for feature in features: props = feature['properties'] if props['id'] == 258132198: assert props['kind'] == 'aerialway' assert 'aerialway' not in props break else: assert 0, 'No feature with id 258132198 found'
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 assert_has_feature( 16, 10910, 25120, 'roads', { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) })
Simplify test to check for no aerialway property
Simplify test to check for no aerialway property
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -14,13 +14,6 @@ { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 -# verify that no aerialway subkind exists when its value is yes -with features_in_tile_layer(16, 10910, 25120, 'roads') as features: - for feature in features: - props = feature['properties'] - if props['id'] == 258132198: - assert props['kind'] == 'aerialway' - assert 'aerialway' not in props - break - else: - assert 0, 'No feature with id 258132198 found' +assert_has_feature( + 16, 10910, 25120, 'roads', + { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) })
a2fef3f2090f0df5425cf21a70d24c77224eae17
tests/cyclus_tools.py
tests/cyclus_tools.py
#! /usr/bin/env python from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(sim_output): os.makedirs(sim_output) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
Add a check if the target output directories exist
Add a check if the target output directories exist
Python
bsd-3-clause
rwcarlsen/cycamore,Baaaaam/cyCLASS,jlittell/cycamore,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cyCLASS,rwcarlsen/cycamore,Baaaaam/cyBaM,cyclus/cycaless,jlittell/cycamore,Baaaaam/cyBaM,rwcarlsen/cycamore,Baaaaam/cycamore,gonuke/cycamore,Baaaaam/cyBaM,gonuke/cycamore,cyclus/cycaless,rwcarlsen/cycamore,Baaaaam/cyBaM,Baaaaam/cycamore,Baaaaam/cycamore,gonuke/cycamore
--- +++ @@ -1,4 +1,6 @@ #! /usr/bin/env python + +import os from tools import check_cmd @@ -8,6 +10,10 @@ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator + # make sure the output target directory exists + if not os.path.exists(sim_output): + os.makedirs(sim_output) + cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0]
7bf477f2ce728ed4af4163a0a96f9ec1b3b76d8d
tests/cyclus_tools.py
tests/cyclus_tools.py
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(sim_output): os.makedirs(sim_output) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(os.path.dirname(sim_output)): os.makedirs(os.path.dirname(sim_output)) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
Correct a bug in creating directories as needed for output.
Correct a bug in creating directories as needed for output.
Python
bsd-3-clause
Baaaaam/cyBaM,Baaaaam/cyBaM,Baaaaam/cyBaM,rwcarlsen/cycamore,rwcarlsen/cycamore,gonuke/cycamore,Baaaaam/cycamore,Baaaaam/cyBaM,jlittell/cycamore,rwcarlsen/cycamore,jlittell/cycamore,cyclus/cycaless,gonuke/cycamore,Baaaaam/cyCLASS,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cycamore,gonuke/cycamore,cyclus/cycaless,Baaaaam/cyCLASS,rwcarlsen/cycamore,Baaaaam/cycamore
--- +++ @@ -11,8 +11,8 @@ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists - if not os.path.exists(sim_output): - os.makedirs(sim_output) + if not os.path.exists(os.path.dirname(sim_output)): + os.makedirs(os.path.dirname(sim_output)) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn)
ad31b6f0226ecd642289f54ec649964aeb9b5799
tests/sanity_tests.py
tests/sanity_tests.py
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') isofile = isomedia.load(mp4file) root = isofile.root moov_atom = [atom for atom in root.children if atom.type() == 'moov'] self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.') def test_lossless_write(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') infile = open(mp4filename, 'rb') isofile = isomedia.load(infile) outfile = tempfile.NamedTemporaryFile(delete=False) isofile.write(outfile) infile.close() outfile.close() self.assertTrue(filecmp.cmp(infile.name, outfile.name)) if __name__ == '__main__': unittest.main()
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') isofile = isomedia.load(mp4file) root = isofile.root moov_atom = [atom for atom in root.children if atom.type() == 'moov'] self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.') mp4file.close() def test_lossless_write(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') infile = open(mp4filename, 'rb') isofile = isomedia.load(infile) outfile = tempfile.NamedTemporaryFile(delete=False) isofile.write(outfile) infile.close() outfile.close() self.assertTrue(filecmp.cmp(infile.name, outfile.name)) os.remove(outfile.name) if __name__ == '__main__': unittest.main()
Clean up more in tests
Clean up more in tests
Python
mit
flxf/isomedia
--- +++ @@ -17,6 +17,8 @@ moov_atom = [atom for atom in root.children if atom.type() == 'moov'] self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.') + mp4file.close() + def test_lossless_write(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') infile = open(mp4filename, 'rb') @@ -30,5 +32,7 @@ self.assertTrue(filecmp.cmp(infile.name, outfile.name)) + os.remove(outfile.name) + if __name__ == '__main__': unittest.main()