commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
8348cf481dc098cb5cf583dd86a6923c9c03d5f5
freight/utils/auth.py
freight/utils/auth.py
from __future__ import absolute_import from flask import current_app, request, session from freight.models import User from freight.testutils.fixtures import Fixtures NOT_SET = object() def get_current_user(): """ Return the currently authenticated user based on their active session. Will return a dum...
from __future__ import absolute_import from flask import current_app, request, session from freight.models import User NOT_SET = object() def get_current_user(): """ Return the currently authenticated user based on their active session. Will return a dummy user if in development mode. """ if ge...
Move fixture import to only be in DEV
Move fixture import to only be in DEV
Python
apache-2.0
getsentry/freight,getsentry/freight,getsentry/freight,getsentry/freight,getsentry/freight
310ed88c1e0e5014d28f9221363693fe3d729d6b
irrigator_pro/common/views.py
irrigator_pro/common/views.py
from django.shortcuts import render # Create your views here.
from django.forms import ModelForm from common.models import Audit class AuditForm(ModelForm): class Meta: model = Audit exclude = ( 'cdate', 'mdate', 'cuser', 'muser', ) def save(self, *args, **kwargs): kwargs['commit...
Create abstract AuditForm class to be used by Forms by classes that inherit from Audit model.
Create abstract AuditForm class to be used by Forms by classes that inherit from Audit model.
Python
mit
warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro
4e1b5e0df263e1d7746cf44c1896c9452f0454e4
src/filmyou/models.py
src/filmyou/models.py
from django.db import models class Person(models.Model): name = models.CharField(max_length=80) def __unicode__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): movie_id...
from django.db import models class Person(models.Model): person_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=120) def __unicode__(self): return self.name class Genre(models.Model): genre_id = models.PositiveIntegerField(primary_key=True) name = m...
Update model to fit data properly.
Update model to fit data properly. There are some huge titles...
Python
apache-2.0
dvalcarce/filmyou-web,dvalcarce/filmyou-web,dvalcarce/filmyou-web
00680e5b6b6a5d1a16e8563c4ed2b5ca5e751901
shopping_app/utils/helpers.py
shopping_app/utils/helpers.py
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datet...
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datet...
Update secret key generator to exclude pantuations
Update secret key generator to exclude pantuations
Python
mit
gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list
6e8e84fad2036b7df32376b617c97cb1a2144e94
shopping_app/utils/helpers.py
shopping_app/utils/helpers.py
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datet...
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datet...
Update secret file from to
Update secret file from to
Python
mit
gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list
e1b1b4ce02b3504c406208e77df01cf9a047924c
src/ansible/views.py
src/ansible/views.py
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from formtools.wizard.views import SessionWizardView from ansible.models import Github def index(request): return HttpResponse("200") class PlaybookWizard(SessionWizardView): def get_form_initial(...
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from formtools.wizard.views import SessionWizardView from ansible.models import Github, Playbook import sys def index(request): return HttpResponse("200") class PlaybookWizard(SessionWizardView): ...
Save form data to DB on each step
Save form data to DB on each step
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
ef5a6507c7c409ce3aeca3ac3c61960cbad32ce5
tests/test_memcache.py
tests/test_memcache.py
#!/usr/bin/env python # coding=utf8 from simplekv.memory.memcachestore import MemcacheStore from basic_store import BasicStore, TTLStore import pytest memcache = pytest.importorskip('memcache') class TestMemcacheStore(TTLStore, BasicStore): @pytest.yield_fixture() def store(self): mc = memcache.Cl...
#!/usr/bin/env python # coding=utf8 from simplekv.memory.memcachestore import MemcacheStore from basic_store import BasicStore, TTLStore import pytest memcache = pytest.importorskip('memcache') class TestMemcacheStore(TTLStore, BasicStore): @pytest.yield_fixture() def store(self): mc = memcache.Cl...
Disable more tests on memcache.
Disable more tests on memcache.
Python
mit
mbr/simplekv,fmarczin/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv,karteek/simplekv
69fb681cd27b43cc2d5500fcca89df3744b3661c
tests/test_registry.py
tests/test_registry.py
import pytest from web_test_base import * class TestIATIRegistry(WebTestBase): requests_to_load = { 'IATI Registry Homepage - http, no www': { 'url': 'http://iatiregistry.org/' } , 'IATI Registry Homepage - http, with www': { 'url': 'http://www.iatiregistry.org/' ...
import pytest from web_test_base import * class TestIATIRegistry(WebTestBase): requests_to_load = { 'IATI Registry Homepage - http, no www': { 'url': 'http://iatiregistry.org/' } , 'IATI Registry Homepage - http, with www': { 'url': 'http://www.iatiregistry.org/' ...
Add test for registry registration form
Add test for registry registration form This adds a test to ensure that the registry registration page has a registration form with the expected method and number of inputs.
Python
mit
IATI/IATI-Website-Tests
c0673083709d08f80672cfa58623a667e0edeffa
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name in adzerk_test_srs: url_key = "adzerk_https_url" if c.secure...
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name in adzerk_test_srs: url_key = "adz...
Add subreddit query param to adzerk frame.
Add subreddit query param to adzerk frame. For tracking / targeting.
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
7e63e514c041ccc12ff5caa01fb4f6684727788b
src/PerformerIndexEntry.py
src/PerformerIndexEntry.py
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.per...
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): '''A class to hold index data for performers. Performers have titles and albums. ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set t...
Store references to albums, add new methods.
Store references to albums, add new methods.
Python
apache-2.0
chrrrisw/kmel_db,chrrrisw/kmel_db
605013815867798a30261e57066163581575832f
tinycart/middleware.py
tinycart/middleware.py
from django.utils.functional import SimpleLazyObject from tinycart.models import Cart class CartMiddleware(object): def process_request(self, request): request.cart = SimpleLazyObject( lambda: Cart.objects.get_for_request(request) ) class HTTPMethodOverrideMiddleware(object): a...
from django.utils.functional import SimpleLazyObject from tinycart.models import Cart class CartMiddleware(object): def process_request(self, request): request.cart = SimpleLazyObject( lambda: Cart.objects.get_for_request(request) ) class HTTPMethodOverrideMiddleware(object): a...
Handle encoding in Content-Type header correctly in HTTPMethodOverrideMiddleware
Handle encoding in Content-Type header correctly in HTTPMethodOverrideMiddleware
Python
bsd-3-clause
vinay13/django-tinycart,trilan/django-tinycart,vinay13/django-tinycart
44fd433eec5126bdeac28df2827b452cd2e6bb1a
pavement.py
pavement.py
from paver.easy import sh, task config = """# replace pass with values you would like to overwrite from DefaultConfig in # default_config.py. Values you do not explicitly overwrite will be inherited # from DefaultConfig. At the very least, you must set secret_key and # tmdb_api_key. from default_config import Defaul...
import os.path from paver.easy import sh, task config = """# replace pass with values you would like to overwrite from DefaultConfig in # default_config.py. Values you do not explicitly overwrite will be inherited # from DefaultConfig. At the very least, you must set secret_key and # tmdb_api_key. from default_confi...
Check for existing config before writing default
Check for existing config before writing default
Python
mit
simon-andrews/movieman2,simon-andrews/movieman2
bd43c574411d3cc1fa730b792d7648f3dfc799b5
bibpy/entry/base.py
bibpy/entry/base.py
# -*- coding: utf-8 -*- """Base class for all types of entries.""" class BaseEntry(object): """Base class for all types of entries.""" def format(self, **options): raise NotImplementedError() @property def entry_type(self): raise NotImplementedError() @property def entry_ke...
# -*- coding: utf-8 -*- """Base class for all types of entries.""" class BaseEntry(object): """Base class for all types of entries.""" def format(self, **options): raise NotImplementedError() @property def entry_type(self): raise NotImplementedError() @property def entry_ke...
Implement __unicode__ for entry objects
Implement __unicode__ for entry objects
Python
mit
MisanthropicBit/bibpy,MisanthropicBit/bibpy
12791da5f9e4a19e670dcf8459572517d0f467cd
comics/urls.py
comics/urls.py
from __future__ import absolute_import from django.conf import settings from django.conf.urls import include, patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = patterns(''...
from __future__ import absolute_import from django.conf import settings from django.conf.urls import include, patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = patterns( ...
Fix all warnings in top-level urlconf
flake8: Fix all warnings in top-level urlconf
Python
agpl-3.0
jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
5bffcac159bc28adaf03b05ca75cd7387aad3240
linked-list/linked-list.py
linked-list/linked-list.py
# LINKED LIST # define constructor class Node(object): def __init__(self, data): self.data = data self.next = None
# LINKED LIST # define constructor class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head
Set up linked list class
Set up linked list class
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
7e7281bf4b5b6e1bc0284e5d8915a3f740a231dd
setup.py
setup.py
#!/usr/bin/env python import octo from distutils.core import setup if __name__ == "__main__": with open('README.rst') as file: long_description = file.read() setup(name='Octo', version=octo.__version__, description=octo.__doc__, long_description=long_description, author=octo.__author_...
#!/usr/bin/env python import octo from distutils.core import setup if __name__ == "__main__": with open('README.rst') as file: long_description = file.read() setup(name='Octo', version=octo.__version__, description=octo.__doc__, long_description=long_description, author=octo.__author_...
Add "Programming Language :: Python :: 2.7" PyPi trove classifier
Add "Programming Language :: Python :: 2.7" PyPi trove classifier
Python
bsd-2-clause
zoni/octo
63c8f5f56c9fc14258be62be41a42525cd616a81
setup.py
setup.py
from distutils.core import setup setup( name='docker-pipeline', version='1.0.0', packages=[''], url='https://github.com/Duke-GCB/docker-pipeline', license='MIT', author='dcl9', author_email='dan.leehr@duke.edu', description='Run docker containers in sequence, for reproducible computatio...
from distutils.core import setup setup( name='docker-pipeline', version='1.0.0', packages=[''], package_data={'': ['docker-pipeline-wrapper.sh']}, include_package_data=True, url='https://github.com/Duke-GCB/docker-pipeline', license='MIT', author='dcl9', author_email='dan.leehr@duke...
Include wrapper script in dist
Include wrapper script in dist
Python
mit
Duke-GCB/docker-pipeline,Duke-GCB/docker-pipeline
df038a485a2aaf80bcfbd872e94ffb87bcb5b33c
testinfra/__init__.py
testinfra/__init__.py
# coding: utf-8 # 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 # dist...
# coding: utf-8 # 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 # dist...
Add warning about unmaintained python2
Add warning about unmaintained python2
Python
apache-2.0
philpep/testinfra
779bc379a3c4d9b0a40c5ad7aa042cdb422efdd5
package_name/__meta__.py
package_name/__meta__.py
name = 'package-name' path = name.lower().replace("-", "_").replace(" ", "_") version = '0.0.0' author = 'Author Name' author_email = '' description = '' url = '' # project homepage license = 'MIT' # See https://choosealicense.com
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/ path = name.lower().replace("-", "_").replace(" ", "_") version = '0.1.0' # See https://www.python.org/dev/peps/pep-0440/ and https://semver.org/ author = 'Author Name' author_email = '' description = '' # One-liner url = '' # your project homepa...
Add descriptions/links for meta fields
DOC: Add descriptions/links for meta fields
Python
mit
scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration
1a0e78756843819a1634c80da8d2cdb8ed4a7bc5
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup from clusterjob import __version__ setup(name='clusterjob', version=__version__, description='Manage traditional HPC cluster workflows in Python', author='Michael Goerz', author_email='goerz@stanford.edu', url='https://github.com/goe...
#!/usr/bin/env python from distutils.core import setup from clusterjob import __version__ try: # In Python >3.3, 'mock' is part of the standard library import unittest.mock mock_package = [] except ImportError: # In other versions, it has be to be installed as an exernal package mock_package = ['mo...
Install mock package when not in stdlib
Install mock package when not in stdlib
Python
mit
goerz/clusterjob,goerz/clusterjob
659d9be59ad816680d9c8fc13e4be67627e1d290
ecommerce/courses/utils.py
ecommerce/courses/utils.py
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the spe...
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the spe...
Handle for missing product attribute
mattdrayer/WL-525: Handle for missing product attribute
Python
agpl-3.0
mferenca/HMS-ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,mferenca/HMS-ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,mferenca/HMS-ecommerce,edx/ecommerce
9c32e25169fa2d0be74bdf320da401ddcb2491e3
studygroups/forms.py
studygroups/forms.py
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, se...
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, se...
Update question about computer access
Update question about computer access
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
9e5be1a70936ce206e9f99dd90e4f26b3a78616e
fjord/settings/__init__.py
fjord/settings/__init__.py
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings...
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings...
Add debugging print statment for jenkins
Add debugging print statment for jenkins
Python
bsd-3-clause
staranjeet/fjord,rlr/fjord,rlr/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,Ritsyy/fjord,staranjeet/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,DESHRAJ/fjord,mozilla/fjord,Ritsyy/fjord,staranjeet/fjord,rlr/fjord,DESHRAJ/fjord,hoosteeno/fjord,staranjeet/fjord,mozilla/fjord,rl...
734100112759b8f52be6013fb69988bd4b203f71
magnum/tests/functional/mesos/test_mesos_python_client.py
magnum/tests/functional/mesos/test_mesos_python_client.py
# 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 Li...
# 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 Li...
Fix mesos baymodel creation case
Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17
Python
apache-2.0
openstack/magnum,openstack/magnum,ArchiFleKs/magnum,jay-lau/magnum,ArchiFleKs/magnum
828c300973d47ce09844840176f2e9e68d955bbd
wrt/wrt-manifest-tizen-tests/const.py
wrt/wrt-manifest-tizen-tests/const.py
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path ...
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs"...
Update pyunit TIZEN_USER for default value
[wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0
Python
bsd-3-clause
jiajiax/crosswalk-test-suite,ibelem/crosswalk-test-suite,chunywang/crosswalk-test-suite,BruceDai/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,yunxliu/crosswalk-test-suite,jiajiax/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,zqzhang/c...
0f4208dd6088a6a96a0145045b11cf2d152db30d
src/samples/pillow.py
src/samples/pillow.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64....
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") ...
Update link in the comment and change saved image format to .png
Update link in the comment and change saved image format to .png
Python
lgpl-2.1
libavg/libavg,libavg/libavg,libavg/libavg,libavg/libavg
75ff727cd29ae1b379c551f46217fa75bf0fb2bc
videoeditor.py
videoeditor.py
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center",...
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center",...
Make pause dependant on annotation text length
Make pause dependant on annotation text length
Python
mit
melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter
412233eff937f64579827e7a7c64963d23a716fa
zipa/module.py
zipa/module.py
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{...
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.start...
Make the logic more readable
Make the logic more readable
Python
apache-2.0
PressLabs/zipa
6aee1c51d2607047091280abb56d2956cebe1ebb
zvm/zstring.py
zvm/zstring.py
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and ...
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and ...
Make the string translator return the actual right values!
Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.
Python
bsd-3-clause
sussman/zvm,sussman/zvm
16372a41a14ccb5ff7148bcb913864598f5be321
src/twitchHandler.py
src/twitchHandler.py
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] ...
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: ...
Fix Bot Errors with Selecting Wrong Users
Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.
Python
mit
lgkern/PriestPy
9834830788bf9fe594bf4a4e67de36231fcd8990
stars/serializers.py
stars/serializers.py
from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: ...
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer)...
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
Python
apache-2.0
belatrix/BackendAllStars
dcb2c6d3472282c7dde4522e68cf45c27cb46b37
tests/accounts/test_models.py
tests/accounts/test_models.py
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.userna...
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.userna...
Add a silly failing test.
Add a silly failing test.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
e6a991b91587f0ef081114b0d15390f682563071
antfarm/base.py
antfarm/base.py
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You...
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You...
Update the app with all supplied config arguments
Update the app with all supplied config arguments
Python
mit
funkybob/antfarm
fc39c6afa49a312413468dfdffcc2de94bb7d78e
tests/test_runner.py
tests/test_runner.py
import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'def...
import unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name',...
Add some more tests for tasks
Add some more tests for tasks
Python
mit
thomasleese/mo
5bb8d24d90b7e6fab72f4f4988ea3055d3250b7e
src/nodeconductor_assembly_waldur/invoices/serializers.py
src/nodeconductor_assembly_waldur/invoices/serializers.py
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lo...
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lo...
Remove redundant view_name variable in serializer
Remove redundant view_name variable in serializer - WAL-109
Python
mit
opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
608fc063e5b153b99b79cab2248b586db3ebda1f
tests/test_pybind11.py
tests/test_pybind11.py
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # p...
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec...
Remove sys.path hacking from test
Remove sys.path hacking from test
Python
bsd-2-clause
jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/jtrace
69f5ee4a703a52d09799b0a9978cb35a05ab18c6
docs/cryptography-docs.py
docs/cryptography-docs.py
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns...
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns...
Fix latex compilation (needed for pdf on read the docs)
Fix latex compilation (needed for pdf on read the docs)
Python
bsd-3-clause
skeuomorf/cryptography,sholsapp/cryptography,Lukasa/cryptography,glyph/cryptography,glyph/cryptography,Hasimir/cryptography,sholsapp/cryptography,kimvais/cryptography,kimvais/cryptography,Lukasa/cryptography,dstufft/cryptography,dstufft/cryptography,Ayrx/cryptography,kimvais/cryptography,dstufft/cryptography,bwhmather/...
a8e42b122916696dbe63ddae3190502b296b47ec
label_response/__init__.py
label_response/__init__.py
import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment...
import json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
Support for multiple methods, and leave the config file to hooker
Support for multiple methods, and leave the config file to hooker
Python
mpl-2.0
servo-automation/highfive,servo-automation/highfive,servo-highfive/highfive
a01e924ccd80a11b2f5c59828c5395b92d9fd5a7
scripts/load_firebase.py
scripts/load_firebase.py
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) f...
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) f...
Update ID of device in load script
Update ID of device in load script
Python
mit
easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015
07096ba58e61580168c85dbcbecb107824096871
python/tutorial/example.py
python/tutorial/example.py
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] ...
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] ...
Change XOR to flip second last bit
Change XOR to flip second last bit Making change to cause merge conflict as an example.
Python
mit
TheLunchtimeAttack/matasano-challenges,TheLunchtimeAttack/matasano-challenges
be3e22f391e50bfdfb83f73382c392afc2fc9f1f
scripts/registrations.py
scripts/registrations.py
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): pri...
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): pri...
Add email address to registration script output
Add email address to registration script output
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
f2752572d915563ea5a3361dbb7a3fee08b04660
tests/test_mmstats.py
tests/test_mmstats.py
import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat man...
import mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.fi...
Make basic test a bit more thorough
Make basic test a bit more thorough
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
18c287a9cfba6e06e1e41db5e23f57b58db64980
command_line/small_molecule.py
command_line/small_molecule.py
import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run()
from __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeatin...
Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out
Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out
Python
bsd-3-clause
xia2/xia2,xia2/xia2
986675f8b415ddbe3d9bccc9d9c88ee00f9d589c
tldextract_app/handlers.py
tldextract_app/handlers.py
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='')....
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').ur...
Fix viewing live TLD definitions on GAE
Fix viewing live TLD definitions on GAE
Python
bsd-3-clause
john-kurkowski/tldextract,jvrsantacruz/tldextract,TeamHG-Memex/tldextract,pombredanne/tldextract,jvanasco/tldextract
3fc765bad65e405f6303bf5ea76e8b4f6de17c13
Instanssi/admin_programme/forms.py
Instanssi/admin_programme/forms.py
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super...
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super...
Add active field to form.
admin_programme: Add active field to form.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
f14107b723bcf62b327b10d8726b2bf8ef2031eb
tests/test_manifest_delivery_base.py
tests/test_manifest_delivery_base.py
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() fo...
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() fo...
Fix test that checks queues
Fix test that checks queues
Python
mit
alphagov/notifications-api,alphagov/notifications-api
e889b37d6db1ca29e874e11cdc122159fe9da136
trigrams.py
trigrams.py
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punc...
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip pu...
Add return statement to strip_punct
Add return statement to strip_punct
Python
mit
bgarnaat/401_trigrams
3375ac1b2f44a18db1b5014de72fe048005c954c
txircd/modules/cmd_pass.py
txircd/modules/cmd_pass.py
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(ir...
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized comma...
Make the PASS command take advantage of processParams and handle the data dict correctly
Make the PASS command take advantage of processParams and handle the data dict correctly
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
8bd94920eb508849851ea851554d05c7a16ee932
Source/Common/Experiments/scintilla_simple.py
Source/Common/Experiments/scintilla_simple.py
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) sc...
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertT...
Add indicator example to simple test.
Add indicator example to simple test.
Python
apache-2.0
barry-scott/scm-workbench,barry-scott/git-workbench,barry-scott/git-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench
2168557dc088be1b991f7eb42dabac144e3add3b
src/ggrc/models/event.py
src/ggrc/models/event.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), null...
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), null...
Remove redundant index declaration from Event
Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.
Python
apache-2.0
plamut/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core
fe11cc39e394d44f06b743d5b967625b6d12575f
api/parsers/datanasa.py
api/parsers/datanasa.py
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represen...
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): ...
Add slug to the db and allow querying it
Add slug to the db and allow querying it
Python
mit
oxford-space-apps/open-data-api
56e6ab84025f071c04701d3dc736b68e82361139
apitestcase/testcase.py
apitestcase/testcase.py
import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self...
import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: ...
Change assertGet body check from StringType to str
Change assertGet body check from StringType to str
Python
mit
bramwelt/apitestcase
8126e8951ced9462afce1964cb4f256fabcc05a9
tests/test__utils.py
tests/test__utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with ...
Test mismatched array lengths error in utils
Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.
Python
bsd-3-clause
jakirkham/dask-distance
2313e2aae705481df5d7ea6c09fcf5e4eaa80cf7
tests/test_client.py
tests/test_client.py
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( ...
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcCl...
Add test for client connect/disconnect methods
Add test for client connect/disconnect methods
Python
apache-2.0
pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc
135b949eb33c75ba097aa17ade777bd39877365e
tests/test_flake8.py
tests/test_flake8.py
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines packag...
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: ...
Revert "flake8: Ignore geoid.py issues"
Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.
Python
agpl-3.0
shadowoneau/skylines,skylines-project/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,kerel-fs/skylines,TobiasLohner/SkyLines,skylines-project/skylines,Harry-R/skylines,shadowoneau/skylines,Harry-R/skylines,snip/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,Turbo...
776fcbce9f23e799cd3101ddfa0bb966898d7064
tests/test_status.py
tests/test_status.py
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = ru...
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = r...
Test search for more than one distribution.
Test search for more than one distribution.
Python
mit
fiber-space/pip,qwcode/pip,msabramo/pip,blarghmatey/pip,jamezpolley/pip,jythontools/pip,ChristopherHogan/pip,rouge8/pip,rbtcollins/pip,qwcode/pip,nthall/pip,esc/pip,chaoallsome/pip,ianw/pip,jamezpolley/pip,jamezpolley/pip,pradyunsg/pip,KarelJakubec/pip,haridsv/pip,zorosteven/pip,fiber-space/pip,pfmoore/pip,h4ck3rm1k3/p...
c143503012ee0e726e199882afaed0b00541f32d
tests/web_api/test_handlers.py
tests/web_api/test_handlers.py
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters':...
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters':...
Fix error on flat trace with cahe test
Fix error on flat trace with cahe test
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
2a47ff10958d27785a35d3f5f3a3ccc6b1283021
app/commands.py
app/commands.py
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): user...
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): user...
Use kwargs when calling User.__init__
Use kwargs when calling User.__init__
Python
mit
cburmeister/flask-bones,cburmeister/flask-bones,cburmeister/flask-bones
957a311d8fa26b18715eada3484f07bbe609818a
stationspinner/libs/drf_extensions.py
stationspinner/libs/drf_extensions.py
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. ...
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. ...
Add mixin for evaluating characterIDs
Add mixin for evaluating characterIDs
Python
agpl-3.0
kriberg/stationspinner,kriberg/stationspinner
ec7791663ed866d240edbaf5e0dd766e9418e1ff
cla_backend/apps/status/tests/smoketests.py
cla_backend/apps/status/tests/smoketests.py
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone(...
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') ...
Add docstrings so that hubot can say what went wrong
Add docstrings so that hubot can say what went wrong
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
25027605e5a370dfb0cb40ab9aeddafc89090441
download.py
download.py
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\...
# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', ...
Rewrite the script in a package fasshion.
Rewrite the script in a package fasshion.
Python
mit
bangbangbear/ximalayaDownloader
fd10df8ff5e1312a3ec93bcb6abc1800aafa78cc
collaboration/dispatch/__init__.py
collaboration/dispatch/__init__.py
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
Remove unused import 'Signal' (F401)
Remove unused import 'Signal' (F401)
Python
mit
walterbender/turtleart,AlanJAS/turtleart
febf5e96847fd01b82f7b9a8e30a5cdae30120f5
layers.py
layers.py
import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolin...
import lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwarg...
Fix syntax in spatial layer
Fix syntax in spatial layer
Python
mit
dimmddr/roadSignsNN
589bfc0f5e57215aa69746e82100375d6f3b8cc9
kpub/tests/test_counts.py
kpub/tests/test_counts.py
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers sta...
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers sta...
Add a test for the new multi-year feature
Add a test for the new multi-year feature
Python
mit
KeplerGO/kpub
276111f633b6151368eb38f01b222567c5ebed97
labsys/auth/decorators.py
labsys/auth/decorators.py
from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): ...
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) ...
Verify if it's a testing app for permissioning
:rocket: Verify if it's a testing app for permissioning
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
e39e3f1c512c7766dd72b728dae322b427ab60a3
wluopensource/osl_flatpages/models.py
wluopensource/osl_flatpages/models.py
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name ...
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = mod...
Change osl_flatpage model to separate meta data from content
Change osl_flatpage model to separate meta data from content
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
d6052e0c1aafef8fa0a5c051838d649c080e0b10
invite/urls.py
invite/urls.py
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), pat...
from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, ...
Replace usage of url with re_path.
Replace usage of url with re_path.
Python
bsd-3-clause
unt-libraries/django-invite,unt-libraries/django-invite
dc60ed6efdd4eb9a78e29623acee7505f2d864e6
Lib/test/test_fork1.py
Lib/test/test_fork1.py
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LO...
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LO...
Use a constant to specify the number of child threads to create.
Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent proc...
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
e83266987db962f2546da84f5f507ff4f67e3499
django_vend/stores/outlet_urls.py
django_vend/stores/outlet_urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
Add urlconf entry for VendOutlet detail
Add urlconf entry for VendOutlet detail
Python
bsd-3-clause
remarkablerocket/django-vend,remarkablerocket/django-vend
1b28a83dd7a8c5698de266656f07dcd3f98826f2
tensorforce/core/memories/__init__.py
tensorforce/core/memories/__init__.py
# Copyright 2017 reinforce.io. All Rights Reserved. # # 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...
# Copyright 2017 reinforce.io. All Rights Reserved. # # 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...
Change import order in memories
Change import order in memories
Python
apache-2.0
lefnire/tensorforce,reinforceio/tensorforce
9dffd8819d998d9e850709ee0a7a0f33e6cb186d
tools/np_suppressions.py
tools/np_suppressions.py
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be sup...
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be sup...
Add supressions for array casting functions that don't seem to be callable.
Add supressions for array casting functions that don't seem to be callable.
Python
bsd-3-clause
teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor
627c1fb7128a1419e7a1598f4585bef1c216910d
ckanext/nhm/settings.py
ckanext/nhm/settings.py
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm....
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this li...
Use an OrderedDict to ensure the first option is the default option
Use an OrderedDict to ensure the first option is the default option
Python
mit
NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm
bcaee4414402017985f8a25134a5cecc99a1c8bb
docker/build_scripts/ssl-check.py
docker/build_scripts/ssl-check.py
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL...
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit...
Remove leftover relic from supporting CPython 2.6.
Remove leftover relic from supporting CPython 2.6.
Python
mit
pypa/manylinux,manylinux/manylinux,pypa/manylinux,pypa/manylinux,manylinux/manylinux,Parsely/manylinux,Parsely/manylinux
3912afaf9e069ae914c535af21155d10da930494
tests/unit/utils/test_translations.py
tests/unit/utils/test_translations.py
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") tra...
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "tran...
Remove the compiled translations for testing
Remove the compiled translations for testing
Python
bsd-3-clause
zky001/flaskbb,realityone/flaskbb,dromanow/flaskbb,qitianchan/flaskbb,realityone/flaskbb,SeanChen0617/flaskbb,SeanChen0617/flaskbb-1,SeanChen0617/flaskbb,zky001/flaskbb,emile2016/flaskbb,China-jp/flaskbb,dromanow/flaskbb,lucius-feng/flaskbb,dromanow/flaskbb,SeanChen0617/flaskbb-1,qitianchan/flaskbb,emile2016/flaskbb,re...
6daf3d416be4a54b8fbb4cbedc833d086b40fe9d
importlib_resources/tests/test_path.py
importlib_resources/tests/test_path.py
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTest...
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTest...
Test zip data for path()
Test zip data for path()
Python
apache-2.0
python/importlib_resources
8aa855fc2a0242f90301404062eaa3e62352d627
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
Use list comprehensions and consolidate error formatting where error details are either a list or a string.
Use list comprehensions and consolidate error formatting where error details are either a list or a string.
Python
apache-2.0
felliott/osf.io,samchrisinger/osf.io,Ghalko/osf.io,kch8qx/osf.io,kwierman/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,kch8qx/osf.io,cslzchen/osf.io,arpitar/osf.io,kwierman/osf.io,billyhunt/osf.io,mattclark/osf.io,danielneis/osf.io,danielneis/osf.io,cwisecarver/os...
e84a06ea851a81648ba6ee54c88a61c049e913f2
gorilla/__init__.py
gorilla/__init__.py
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LIC...
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LIC...
Remove the `get_original_attribute` shortcut from the root module.
Remove the `get_original_attribute` shortcut from the root module.
Python
mit
christophercrouzet/gorilla
ddab25e03c96ad6c4950ee38fe5dcd73da5aa05c
shared/api.py
shared/api.py
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceReposito...
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceReposito...
Add wrapper for event data elem
Add wrapper for event data elem
Python
apache-2.0
bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball
d1911215a0c7043c5011da55707f6a40938c7d59
alarme/extras/sensor/web/views/home.py
alarme/extras/sensor/web/views/home.py
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sens...
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return aw...
Remove debug app exit on / access (web sensor)
Remove debug app exit on / access (web sensor)
Python
mit
insolite/alarme,insolite/alarme,insolite/alarme
41deccb4cde9d553db021f1da90759b4b1b14665
picaxe/urls.py
picaxe/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.url...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ...
Remove django.contrib.sites from admin interface
Remove django.contrib.sites from admin interface
Python
mit
TuinfeesT/PicAxe
32cdc4fa334f3d415c0ce8f4fa37fa7d4c721915
fabfile.py
fabfile.py
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') loc...
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') loc...
Use shell=False when chowning logs folder.
Use shell=False when chowning logs folder.
Python
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
bc31bb2ddbf5b7f2e5d375a8b0d6e01f631d0aef
txircd/modules/extra/snotice_links.py
txircd/modules/extra/snotice_links.py
from twisted.plugin import IPlugin from txircd.modbase import IModuleData, ModuleData from zope.interface import implements class SnoLinks(ModuleData): implements(IPlugin, IModuleData) name = "ServerNoticeLinks" def actions(self): return [ ("serverconnect", 1, self.announceConnect), ("serverquit", ...
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class SnoLinks(ModuleData): implements(IPlugin, IModuleData) name = "ServerNoticeLinks" def actions(self): return [ ("serverconnect", 1, self.announceConnect), ("serv...
Fix module data import on links server notice
Fix module data import on links server notice
Python
bsd-3-clause
Heufneutje/txircd
96f933bcfef90ba984e43947b46f9557e760e838
project/category/views.py
project/category/views.py
from flask import render_template, Blueprint, url_for, \ redirect, flash, request from project.models import Category, Webinar from .helpers import slugify category_blueprint = Blueprint('category', __name__,)
from flask import render_template, Blueprint, url_for, \ redirect, flash, request from project.models import Category, Webinar from .helpers import slugify category_blueprint = Blueprint('category', __name__,) @category_blueprint.route('/categories') def index(): categories = Category.query.all() return...
Create simple categories page view
Create simple categories page view
Python
mit
dylanshine/streamschool,dylanshine/streamschool
a736355efe592d4a6418740f791f3526db2fc67a
protocols/no_reconnect.py
protocols/no_reconnect.py
try: from .. import api, shared as G from ... import editor from ..exc_fmt import str_e from ..protocols import floo_proto except (ImportError, ValueError): from floo import editor from floo.common import api, shared as G from floo.common.exc_fmt import str_e from floo.common.protocols i...
try: from .. import api, shared as G from ... import editor from ..exc_fmt import str_e from ..protocols import floo_proto except (ImportError, ValueError): from floo import editor from floo.common import api, shared as G from floo.common.exc_fmt import str_e from floo.common.protocols i...
Call connect instead of reconnect.
Call connect instead of reconnect.
Python
apache-2.0
Floobits/plugin-common-python
7aa74665e69aa7117ebae24e7aa12baa07d2119a
tests/test__compat.py
tests/test__compat.py
# -*- coding: utf-8 -*-
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import numpy as np import dask import dask.array as da import dask.array.utils as dau import dask_distance._compat @pytest.mark.parametrize("x", [ list(range(5)), np.random.randint(10, size=(15, 16)), da.random.randint(10, size=(15, 16), chu...
Include some tests for _asarray
Include some tests for _asarray Make sure that it correctly converts everything to a Dask Array. Try using a Python list, NumPy array, and Dask Array. Also make sure the final array has the same contents as the original. Borrowed from `dask-ndmeasure`.
Python
bsd-3-clause
jakirkham/dask-distance
44fe60f561abd98df1a1a39f3fbf96c06267c3ec
tests/test_wheeler.py
tests/test_wheeler.py
# coding=utf-8 import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') ...
# coding=utf-8 import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') ...
Fix test covering pip 1.5.2 error handling.
Fix test covering pip 1.5.2 error handling.
Python
bsd-3-clause
tylerdave/devpi-builder
8646f5af48dc011799a5c7ab9d89b7e6a09ed95b
editor/views.py
editor/views.py
# thesquirrel.org # # Copyright (C) 2015 Flying Squirrel Community Space # # thesquirrel.org 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 la...
# thesquirrel.org # # Copyright (C) 2015 Flying Squirrel Community Space # # thesquirrel.org 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 la...
Return exception when we have an issue reading an image file
Return exception when we have an issue reading an image file
Python
agpl-3.0
bendk/thesquirrel,bendk/thesquirrel,bendk/thesquirrel,bendk/thesquirrel
9cd72406d63d1ce3a6cd75a65131c8bde3df95ba
push_plugin.py
push_plugin.py
import requests class PushClient: def __init__(self, app): self.app = app def handle_new_or_edit(self, post): data = { 'hub.mode' : 'publish', 'hub.url' : 'http://kylewm.com/all.atom' } response = requests.post('https://pubsubhubbub.appspot.com/', data) if res...
import requests class PushClient: def __init__(self, app): self.app = app def publish(self, url): data = { 'hub.mode' : 'publish', 'hub.url' : url } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.i...
Send the all.atom feed and the articles/notes feeds to PuSH
Send the all.atom feed and the articles/notes feeds to PuSH
Python
bsd-2-clause
thedod/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind,Lancey6/redwind
a06dc82df053ea47f8a39b46d938f52679b2cff5
grow/preprocessors/blogger_test.py
grow/preprocessors/blogger_test.py
from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { '...
from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { '...
Use different blog for test data.
Use different blog for test data.
Python
mit
grow/pygrow,denmojo/pygrow,denmojo/pygrow,denmojo/pygrow,grow/grow,grow/pygrow,grow/grow,grow/grow,grow/grow,grow/pygrow,denmojo/pygrow
783766b4f4d65dfb4b41e6386edd8ea2df32d727
tests/test_creation.py
tests/test_creation.py
import generic as g class CreationTest(g.unittest.TestCase): def test_soup(self): count = 100 mesh = g.trimesh.creation.random_soup(face_count=count) self.assertTrue(len(mesh.faces) == count) self.assertTrue(len(mesh.face_adjacency) == 0) self.assertTrue(len(mesh.split(on...
import generic as g class CreationTest(g.unittest.TestCase): def test_soup(self): count = 100 mesh = g.trimesh.creation.random_soup(face_count=count) self.assertTrue(len(mesh.faces) == count) self.assertTrue(len(mesh.face_adjacency) == 0) self.assertTrue(len(mesh.split(on...
Add integration test for extrusion
Add integration test for extrusion
Python
mit
mikedh/trimesh,mikedh/trimesh,mikedh/trimesh,dajusc/trimesh,mikedh/trimesh,dajusc/trimesh
f7a201f61382593baa6e8ebadfedea68563f1fef
examples/repeat.py
examples/repeat.py
#!/usr/bin/env python import sys, os, json, logging sys.path.append(os.path.abspath(".")) import gevent import msgflo class Repeat(msgflo.Participant): def __init__(self, role): d = { 'component': 'PythonRepeat', 'label': 'Repeat input data without change', } msgflo.Participant.__init__(sel...
#!/usr/bin/env python import sys, os, json, logging sys.path.append(os.path.abspath(".")) import gevent import msgflo class Repeat(msgflo.Participant): def __init__(self, role): d = { 'component': 'PythonRepeat', 'label': 'Repeat input data without change', } msgflo.Participant.__init__(sel...
Allow to specify role name on commandline
examples: Allow to specify role name on commandline
Python
mit
msgflo/msgflo-python
97c26c367c2c4597842356e677064a012ea19cb6
events/forms.py
events/forms.py
from django import forms from events.models import Event, City class EventForm(forms.ModelForm): city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville") class Meta: model = Event exclude = ('submission_time', 'updated_time', 'decision_time', 'moderat...
# -*- encoding:utf-8 -*- from django import forms from events.models import Event, City from django.forms.util import ErrorList from datetime import datetime class EventForm(forms.ModelForm): city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville") class Meta: model = Event ...
Validate entered dates in Event form
Validate entered dates in Event form
Python
agpl-3.0
vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord
c39a64c5dc83d55632ffc19a96196aef07474114
pylab/accounts/tests/test_settings.py
pylab/accounts/tests/test_settings.py
import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_settings(self): resp = self.app.ge...
import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_user_settings(self): resp = self.a...
Split user settings test into two tests
Split user settings test into two tests
Python
agpl-3.0
python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website
090bcbf8bbc32a2a8da5f0ab2be097e5a6716c3d
src/adhocracy_frontend/adhocracy_frontend/tests/integration/test_jasmine.py
src/adhocracy_frontend/adhocracy_frontend/tests/integration/test_jasmine.py
"""This is structurally equivalent to ../unit/test_jasmine.py. The difference is that it runs igtest.html instead of test.html. also, it is located next to acceptance tests, because it has to be allowed to import components other than adhocracy, like adhocracy_core. """ from pytest import fixture from pytest import m...
"""This is structurally equivalent to ../unit/test_jasmine.py. The difference is that it runs igtest.html instead of test.html. also, it is located next to acceptance tests, because it has to be allowed to import components other than adhocracy, like adhocracy_core. """ from pytest import fixture from pytest import m...
Mark integration tests as xfail
Mark integration tests as xfail
Python
agpl-3.0
fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocr...
d9a266ccd3c4873478f0524afa6a3068858bbea6
django_seo_js/middleware/useragent.py
django_seo_js/middleware/useragent.py
import re from django_seo_js import settings from django_seo_js.backends import SelectedBackend from django_seo_js.helpers import request_should_be_ignored import logging logger = logging.getLogger(__name__) class UserAgentMiddleware(SelectedBackend): def __init__(self, *args, **kwargs): super(UserAgentM...
import re from django_seo_js import settings from django_seo_js.backends import SelectedBackend from django_seo_js.helpers import request_should_be_ignored import logging logger = logging.getLogger(__name__) class UserAgentMiddleware(SelectedBackend): def __init__(self, *args, **kwargs): super(UserAgentM...
Fix issue where ENABLED is not defined
Fix issue where ENABLED is not defined
Python
mit
skoczen/django-seo-js
d76398b40844e969439d495d4ea3604e5b2011b4
mock-recipe-server/test_mock_server.py
mock-recipe-server/test_mock_server.py
""" Tests for the mock-server itself. """ from utils import APIPath def test_testcase_difference(root_path): """Ensure that different testcases output different data.""" recipes = set() testcase_paths = ( APIPath(path, 'http://example.com') for path in root_path.path.iterdir() if path.is_...
""" Tests for the mock-server itself. """ from utils import APIPath def test_testcase_difference(root_path): """Ensure that different testcases output different data.""" recipes = set() testcase_paths = ( APIPath(path, 'http://example.com') for path in root_path.path.iterdir() if path.is_...
Handle error testcases in mock-server tests.
Handle error testcases in mock-server tests.
Python
mpl-2.0
Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy
9ea4164f739b06752719ad4e68f5af85b18f9f1c
tests/scripts/constants.py
tests/scripts/constants.py
#!/usr/bin/python # -*- coding: utf-8 -*- # For better print formatting from __future__ import print_function # Imports import os ############################################ # CONSTANTS ############################################ DEFAULT_SKIP = True DEFAULT_NUM_RETRIES = 3 DEFAULT_FAIL_FAST = False DEFAULT_FAMIL...
#!/usr/bin/python # -*- coding: utf-8 -*- # For better print formatting from __future__ import print_function # Imports import os ############################################ # CONSTANTS ############################################ DEFAULT_SKIP = True DEFAULT_NUM_RETRIES = 3 DEFAULT_FAIL_FAST = False DEFAULT_FAMIL...
Include agents as a default test family
Include agents as a default test family
Python
apache-2.0
mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs
cc96c599cb7e83034f13f8277399dea59a6226ec
mooc_aggregator_restful_api/udacity.py
mooc_aggregator_restful_api/udacity.py
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and method...
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and method...
Add docstring to instance methods
Add docstring to instance methods
Python
mit
ueg1990/mooc_aggregator_restful_api
4696efdee643bb3d86995fea4c35f7947535111d
foundation/offices/tests/factories.py
foundation/offices/tests/factories.py
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundatio...
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundatio...
Fix EmailFactory by missing created_by
Fix EmailFactory by missing created_by
Python
bsd-3-clause
ad-m/foundation-manager,ad-m/foundation-manager,pilnujemy/pytamy,pilnujemy/pytamy,ad-m/foundation-manager,ad-m/foundation-manager,pilnujemy/pytamy,pilnujemy/pytamy
1639200e5700b1170a9d2312a32c7991ed5198b4
tests/basics/boundmeth1.py
tests/basics/boundmeth1.py
# tests basics of bound methods # uPy and CPython differ when printing a bound method, so just print the type print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no ext...
# tests basics of bound methods # uPy and CPython differ when printing a bound method, so just print the type print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no ext...
Add test for assignment of attribute to bound method.
tests/basics: Add test for assignment of attribute to bound method.
Python
mit
ryannathans/micropython,bvernoux/micropython,HenrikSolver/micropython,dmazzella/micropython,lowRISC/micropython,toolmacher/micropython,ryannathans/micropython,cwyark/micropython,deshipu/micropython,mhoffma/micropython,HenrikSolver/micropython,Peetz0r/micropython-esp32,Timmenem/micropython,MrSurly/micropython,tralamazza...