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
4a8540dd374d4f75f4ded6a3e555776489b8d190
imagersite/imager_images/tests.py
imagersite/imager_images/tests.py
from __future__ import unicode_literals from django.contrib.auth.models import User from django.test import TestCase import factory from faker import Faker from imager_profile.models import ImagerProfile from .models import Album, Photo # Create your tests here. fake = Faker() class UserFactory(factory.Factory): ...
from __future__ import unicode_literals from django.contrib.auth.models import User from django.test import TestCase import factory from faker import Faker from imager_profile.models import ImagerProfile from .models import Album, Photo # Create your tests here. fake = Faker() class UserFactory(factory.django.Djang...
Use DjangoModelFactory subclass for images test
Use DjangoModelFactory subclass for images test
Python
mit
jesseklein406/django-imager,jesseklein406/django-imager,jesseklein406/django-imager
cd26af9f5edb1b39e2ead09102c7dee409263c15
sensor_consumers/bathroom_door.py
sensor_consumers/bathroom_door.py
# coding=utf-8 from utils import SensorConsumerBase import sys class Bathroom(SensorConsumerBase): def __init__(self): SensorConsumerBase.__init__(self, "home") def run(self): self.subscribe("bathroom-pubsub", self.pubsub_callback) def pubsub_callback(self, data): if "action" i...
# coding=utf-8 from utils import SensorConsumerBase import sys class Bathroom(SensorConsumerBase): def __init__(self): SensorConsumerBase.__init__(self, "home") def run(self): self.subscribe("bathroom-pubsub", self.pubsub_callback) def pubsub_callback(self, data): if "action" i...
Add sanity checks for temperature readings
Add sanity checks for temperature readings
Python
bsd-3-clause
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
72658874727d877996b413aa7d7d1beb1375a9c3
stagecraft/libs/backdrop_client/backdrop_client.py
stagecraft/libs/backdrop_client/backdrop_client.py
from __future__ import unicode_literals import json import requests from django.conf import settings class BackdropError(Exception): pass def create_dataset(name, capped_size): """ Connect to Backdrop and create a new collection called ``name``. Specify ``capped_size`` in bytes to create a capped ...
from __future__ import unicode_literals import json import requests from django.conf import settings class BackdropError(Exception): pass def create_dataset(name, capped_size): """ Connect to Backdrop and create a new collection called ``name``. Specify ``capped_size`` in bytes to create a capped ...
Add further constrains to create_dataset
Add further constrains to create_dataset To clarify that it capped_size must be zero or a positive integer.
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
8f42513d6845b6b1461150b1e92890c78c72280e
find_text_type_file.py
find_text_type_file.py
#!/usr/bin/env python3 import os import subprocess import sys def find_text_files(directory): ''' , ''' file_list = [] abspath = os.path.abspath(directory) for i in os.listdir(directory): result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE) if 'text'...
#!/usr/bin/env python3 from pathlib import Path import os import subprocess import sys LINE_LIMIT = 100 def find_text_files(directory): ''' find text files and look for file content less than 100 characters. ''' file_list = [] abspath = os.path.abspath(directory) files = [i[0] for i in os.walk(abs...
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Update find text, walk through the directories with os.walk and print line length less than 100 characters. Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>
Python
apache-2.0
sjh/python
c53e8aaadb35b6ca23d60bf4f4aa84812f186128
flake8_respect_noqa.py
flake8_respect_noqa.py
# -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if pep8.noqa(self.lines[line_number - 1]): return else: return super(RespectNoq...
# -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]): return els...
Fix for case when file can't be opened due to IOError or similar
Fix for case when file can't be opened due to IOError or similar
Python
mit
spookylukey/flake8-respect-noqa
c54bca55a4b0be4f1b2be7bda5ae5cdb215959ed
flask_toybox/compat.py
flask_toybox/compat.py
""" Cross-version compatibility module. """ from __future__ import absolute_import try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict
""" Cross-version compatibility module. """ from __future__ import absolute_import try: from collections import OrderedDict except ImportError: # pragma: no cover from ordereddict import OrderedDict
Exclude fallback from coverage reporting
Exclude fallback from coverage reporting
Python
mit
drdaeman/flask-toybox
e317812daaae4ff1b50c7d56931425e86a7255b8
run_IRIDA_Uploader.py
run_IRIDA_Uploader.py
#!/usr/bin/env python import wx from GUI.iridaUploaderMain import MainFrame if __name__ == "__main__": app = wx.App(False) frame = MainFrame() frame.Show() frame.mp.api = frame.settings_frame.attempt_connect_to_api() app.MainLoop()
#!/usr/bin/env python import wx from GUI.MainFrame import MainFrame if __name__ == "__main__": app = wx.App(False) frame = MainFrame() frame.Show() frame.mp.api = frame.settings_frame.attempt_connect_to_api() app.MainLoop()
Use the right package name for running the uploader.
Use the right package name for running the uploader.
Python
apache-2.0
phac-nml/irida-miseq-uploader,phac-nml/irida-miseq-uploader
e3c79b7851aafad2a491c0ceafe2d3f539a4e3df
number_to_words.py
number_to_words.py
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',...
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',...
Add initial function definition and documentation for function to do conversion
Add initial function definition and documentation for function to do conversion
Python
mit
ianfieldhouse/number_to_words
27c3ebfee3789de817defc18ac4a3dbc37a7d03f
tests/munge_js_test.py
tests/munge_js_test.py
import os.path import unittest import munge_js class TestCase(unittest.TestCase): pass TestCase.assert_false = TestCase.assertFalse TestCase.assert_equal = TestCase.assertEqual fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures') def get_fixtures(): dir = os.path.join(fixture_root, 'input') ...
import os.path import unittest import munge_js class TestCase(unittest.TestCase): pass TestCase.assert_false = TestCase.assertFalse TestCase.assert_equal = TestCase.assertEqual fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures') def get_fixtures(): dir = os.path.join(fixture_root, 'input') ...
Use an additional function to scope everything properly
Use an additional function to scope everything properly
Python
mit
p/munge-js,p/munge-js
29b26aa8b44ea5820cfcd20e324d2c3631338228
portal/models/research_protocol.py
portal/models/research_protocol.py
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name ...
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name ...
Implement common pattern from_json calls update_from_json
Implement common pattern from_json calls update_from_json
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
f0d19857914f196db624abcd9de718d1d4b73e84
organizer/views.py
organizer/views.py
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(c...
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(c...
Tag Detail: create view skeleton.
Ch05: Tag Detail: create view skeleton.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
12c57c385ad60cf48f99082bb486b429250e5921
gittip/orm/__init__.py
gittip/orm/__init__.py
from __future__ import unicode_literals import os import pdb from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session class Model(object): def __repr__(self): cols = self.__mapper__.c.keys() class...
from __future__ import unicode_literals import os import pdb from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session class Model(object): def __repr__(self): cols = self.__mapper__.c.keys() class...
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com>
Python
cc0-1.0
bountysource/www.gittip.com,gratipay/gratipay.com,bountysource/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,bountysource/www.gittip.com,bountysource/www....
393abd296c65a5fd8fd094ca2c6925f132b77ad4
utc-time/utc-time.py
utc-time/utc-time.py
#!/usr/bin/env python import time print 'Content-Type: text/javascript' print '' print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
#!/usr/bin/env python import time t = time.time() u = time.gmtime(t) s = time.strftime('%a, %e %b %Y %T GMT', u) print 'Content-Type: text/javascript' print 'Cache-Control: no-cache' print 'Date: ' + s print 'Expires: ' + s print '' print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
Disable caching of stale time stamp information.
Disable caching of stale time stamp information.
Python
apache-2.0
google/google-authenticator-libpam,google/google-authenticator-libpam,google/google-authenticator-libpam,google/google-authenticator-libpam
745568d54b705cf767142911556c7d87a0397919
lfs/shipping/migrations/0002_auto_20170216_0739.py
lfs/shipping/migrations/0002_auto_20170216_0739.py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-16 07:39 from __future__ import unicode_literals from django.db import migrations def update_price_calculator(apps, schema_editor): ShippingMethod = apps.get_model("shipping", "ShippingMethod") for shipping_method in ShippingMethod.objects.filter(...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-16 07:39 from __future__ import unicode_literals from django.db import migrations def update_price_calculator(apps, schema_editor): ShippingMethod = apps.get_model("shipping", "ShippingMethod") for shipping_method in ShippingMethod.objects.filter(...
Fix price calculator class names
Fix price calculator class names
Python
bsd-3-clause
diefenbach/django-lfs,diefenbach/django-lfs,diefenbach/django-lfs
46c535faf5dec41c34740104d4f6ee6770309ccf
spicedham/__init__.py
spicedham/__init__.py
from pkg_resources import iter_entry_points from config import config plugins = [] for plugin in iter_entry_points(group='spicedham.classifiers', name=None): plugins.append(plugin.load()) def train(training_data, is_spam): for plugin in plugins: plugin.train(training_data, is_spam) def classify(c...
from pkg_resources import iter_entry_points from config import config plugins = [] for plugin in iter_entry_points(group='spicedham.classifiers', name=None): pluginClass = plugin.load() plugins.append(pluginClass()) def train(training_data, is_spam): for plugin in plugins: plugin.train(training...
Fix plugin system loader and remove setup
Fix plugin system loader and remove setup * We don't need a setup function, that's waht __init__ is for * There were copy pasta problems with classify. They're fixed.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
fbae85917839aabaf83ff3dd003a6f3b239360d3
python/convert_line_endings.py
python/convert_line_endings.py
#!/usr/bin/python import os def convert_line_endings(file): if '\r\n' in open(file, 'rb').read(): print '%s contains DOS line endings. Converting' % file with open(file, 'rb') as infile: text = infile.read() text = text.replace('\r\n', '\n') with open(file, 'wb') as outfile: outfile.wr...
#!/usr/bin/python import os import sys def convert_line_endings(file): if '\r\n' in open(file, 'rb').read(): print '%s contains DOS line endings. Converting' % file with open(file, 'rb') as infile: text = infile.read() text = text.replace('\r\n', '\n') with open(file, 'wb') as outfile: ...
Add option to Python line ending conversion to specify a single filename on the command line
[trunk] Add option to Python line ending conversion to specify a single filename on the command line
Python
bsd-3-clause
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
c0d0ea6b01ed7ddd9f5817b2debe7c58f64a8ba5
tests/test_service.py
tests/test_service.py
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import base64 import unittest import sys import os sys.path.append(os.path.abspath('../server.py')) import server class TestPosieService(unittest.TestCase): def test_key_generation(self): ...
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding from server import app import base64 import unittest class TestPosieService(unittest.TestCase): key_endpoint = "/key" decryp...
Update tests to init flask and use test client
Update tests to init flask and use test client
Python
mit
ONSdigital/edcdi
5ac6cc208bf1a3fbe4e860a2356102a2457a1e43
server/mod_auth/auth.py
server/mod_auth/auth.py
from app_factory.create_app import db from models import User from forms import RegistrationForm, LoginForm def load_user(user_id): return User.query.filter_by(id=user_id).first() def login(request): form = LoginForm.from_json(request.form) if request.method == 'POST' and form.validate(): return...
from models import User from forms import LoginForm def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def login(request): """Handle a login request from a user.""" form = LoginForm.from_json(request.form) if request.m...
Clean up unused imports and add docstrings
Clean up unused imports and add docstrings
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
276cb99f893443e4f1d242f861cd74d77770def4
inselect/tests/lib/test_segment.py
inselect/tests/lib/test_segment.py
import json import unittest from pathlib import Path from inselect.lib.document import InselectDocument from inselect.lib.segment import segment_document TESTDATA = Path(__file__).parent.parent / 'test_data' class TestSegment(unittest.TestCase): def test_segment_document(self): doc = InselectDocument.l...
import json import unittest from pathlib import Path from inselect.lib.document import InselectDocument from inselect.lib.segment import segment_document TESTDATA = Path(__file__).parent.parent / 'test_data' class TestSegment(unittest.TestCase): def test_segment_document(self): doc = InselectDocument.l...
Remove commented-out debug code :-(
Remove commented-out debug code :-(
Python
bsd-3-clause
NaturalHistoryMuseum/inselect,NaturalHistoryMuseum/inselect
eed7727afd1622cbefb8ef1e113f15706170dfdf
parens.py
parens.py
def balanceness(paren_series): indicator = 0 for paren in paren_series: if paren == u'(': indicator += 1 elif paren == u')': indicator -= 1 # At any point in time, if a ')' precedes a '(', then the series # of parenthesis is broken. if indicator <...
def balanceness(paren_series): indicator = 0 for paren in paren_series: print paren if paren == u'(': indicator += 1 elif paren == u')': indicator -= 1 # At any point in time, if a ')' precedes a '(', then the series # of parenthesis is broken, an...
Complete quick attempt at function.
Complete quick attempt at function.
Python
mit
jefimenko/data-structures
0d2667684f0b65cb832528a80ef7bf008bf9c706
pentai/ai/standardise.py
pentai/ai/standardise.py
import rot_standardise as rs_m import trans_standardise as t_m def standardise(orig_state): # Test code only possibilities = rs_m.rot_possibilities(orig_state) all_combined = [] for p in possibilities: c = combine_and_trim(p) all_combined.append((c[0], c)) try: s = min(all_comb...
import rot_standardise as rs_m import trans_standardise as t_m def standardise(orig_state): possibilities = rs_m.rot_possibilities(orig_state) all_combined = [] for p in possibilities: c = combine_and_trim(p) all_combined.append((c[0], c)) try: s = max(all_combined)[1] exce...
Use max representation for smaller space usage.
Use max representation for smaller space usage.
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
7560c3efc638940cca8f25a6e58e4ea1f85dc9dc
src/sentry/filters/builtins.py
src/sentry/filters/builtins.py
""" sentry.filters.base ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from django.utils.datastructures import SortedDict from django.utils.translation import ugettext_lazy as _ from sentry.conf import settings from .base...
""" sentry.filters.base ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from django.utils.datastructures import SortedDict from django.utils.translation import ugettext_lazy as _ from sentry.conf import settings from sentr...
Change Status filters to build from constant
Change Status filters to build from constant
Python
bsd-3-clause
jean/sentry,zenefits/sentry,camilonova/sentry,mitsuhiko/sentry,nicholasserra/sentry,wujuguang/sentry,zenefits/sentry,rdio/sentry,BuildingLink/sentry,JamesMura/sentry,drcapulet/sentry,imankulov/sentry,fotinakis/sentry,llonchj/sentry,BayanGroup/sentry,looker/sentry,felixbuenemann/sentry,fotinakis/sentry,Kryz/sentry,NickP...
ada858de787991c885030bb122e50df36b6fdc11
github3/__init__.py
github3/__init__.py
""" github3 ======= See http://github3py.rtfd.org/ for documentation. :copyright: (c) 2012 by Ian Cordasco :license: Modified BSD, see LICENSE for more details """ __title__ = 'github3' __author__ = 'Ian Cordasco' __license__ = 'Modified BSD' __copyright__ = 'Copyright 2012 Ian Cordasco' __version__ = '0.1a5' from...
""" github3 ======= See http://github3py.rtfd.org/ for documentation. :copyright: (c) 2012 by Ian Cordasco :license: Modified BSD, see LICENSE for more details """ __title__ = 'github3' __author__ = 'Ian Cordasco' __license__ = 'Modified BSD' __copyright__ = 'Copyright 2012 Ian Cordasco' __version__ = '0.1a5' from...
Clean up namespace as mentioned.
Clean up namespace as mentioned.
Python
bsd-3-clause
balloob/github3.py,krxsky/github3.py,icio/github3.py,sigmavirus24/github3.py,wbrefvem/github3.py,christophelec/github3.py,ueg1990/github3.py,itsmemattchung/github3.py,agamdua/github3.py,h4ck3rm1k3/github3.py,degustaf/github3.py,jim-minter/github3.py
f56f98d5ec2b9cd689349cc239ca550f1182563e
src/olympia/core/tests/test_db.py
src/olympia/core/tests/test_db.py
# -*- coding: utf-8 -*- import pytest from olympia.core.tests.db_tests_testapp.models import TestRegularCharField @pytest.mark.django_db @pytest.mark.parametrize('value', [ u'a', u'🔍', # Magnifying Glass Tilted Left (U+1F50D) u'❤', # Heavy Black Heart (U+2764, U+FE0F) ]) def test_max_length_utf8mb4(va...
# -*- coding: utf-8 -*- import os import pytest from olympia.core.tests.db_tests_testapp.models import TestRegularCharField @pytest.mark.django_db @pytest.mark.parametrize('value', [ u'a', u'🔍', # Magnifying Glass Tilted Left (U+1F50D) u'❤', # Heavy Black Heart (U+2764, U+FE0F) ]) def test_max_length_...
Add simple test to fail in case of duplicate migration ids.
Add simple test to fail in case of duplicate migration ids. The test fails by showing which migrations are duplicated. ```python src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids assert not duplicates E AssertionError: assert not {'99'} ``` Fixes #11852
Python
bsd-3-clause
eviljeff/olympia,eviljeff/olympia,psiinon/addons-server,eviljeff/olympia,psiinon/addons-server,psiinon/addons-server,bqbn/addons-server,diox/olympia,mozilla/addons-server,mozilla/olympia,bqbn/addons-server,wagnerand/addons-server,eviljeff/olympia,mozilla/olympia,wagnerand/addons-server,mozilla/olympia,wagnerand/addons-...
d483e49d826607c0f59ee4b531a2b8e98beffa40
guizero/__init__.py
guizero/__init__.py
try: from tkinter import * except: from Tkinter import * # ----------------------------- import utilities as utils from alerts import * from App import App from Box import Box from ButtonGroup import ButtonGroup from CheckBox import CheckBox from Combo import Combo from MenuBar import MenuBar from Picture...
try: from tkinter import * except: from Tkinter import * # ----------------------------- __all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton', 'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton'] import utilities as utils from ...
Add an all to init
Add an all to init
Python
bsd-3-clause
lawsie/guizero,lawsie/guizero,lawsie/guizero
9a1272082f8750565f727f2c97a71768a9ceb7ca
books/search_indexes.py
books/search_indexes.py
from haystack import indexes from books.models import Book, Series class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) library = indexes.IntegerField(model_attr="library_id") def get_model(self): return Book def index_queryset(...
from haystack import indexes from books.models import Book, Series class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) library = indexes.IntegerField(model_attr="library_id") def get_model(self): return Book def index_queryset(...
Add fields to index so 'update_index' works
Add fields to index so 'update_index' works
Python
mit
phildini/bockus,phildini/bockus,phildini/bockus
3fd3795eb1f055e93c74362dfa5bdf46a5141551
py-bindings/ompl/util/__init__.py
py-bindings/ompl/util/__init__.py
from os.path import abspath, dirname from sys import platform if platform != 'nt' and platform != 'win32': from ompl import dll_loader dll_loader('ompl', dirname(abspath(__file__))) from _util import *
from os.path import abspath, dirname from ompl import dll_loader dll_loader('ompl', dirname(abspath(__file__))) from _util import *
Revert changes to py-bindings script
Revert changes to py-bindings script --HG-- branch : windows
Python
bsd-3-clause
jvgomez/ompl,davetcoleman/ompl,davetcoleman/ompl,florianhauer/ompl,florianhauer/ompl,florianhauer/ompl,sonny-tarbouriech/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,davetcoleman/ompl,jvgomez/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,davetcoleman/ompl,sonny-tarbouriech/ompl,florianhauer/o...
6e1892daec726b44b1bbb4d085e27fa03c0a419b
server/kcaa/kcsapi/client_test.py
server/kcaa/kcsapi/client_test.py
#!/usr/bin/env python import pytest import client from kcaa import screens class TestScreen(object): def test_mission_result(self): screen = client.Screen() assert screen.screen == screens.UNKNOWN screen.update('/api_get_member/deck_port', None, None, None, False) assert screen....
#!/usr/bin/env python import pytest import client from kcaa import screens class TestScreen(object): def update(self, screen, api_name): screen.update(api_name, None, None, None, False) def update_sequence(self, screen, api_names): for api_name in api_names: screen.update(api_n...
Add a Screen test for sequence of KCSAPI responses.
Add a Screen test for sequence of KCSAPI responses.
Python
apache-2.0
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
5a9ff0cbfade513b592bf309953bd2f927eb705c
mozillians/graphql/views.py
mozillians/graphql/views.py
from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView class MozilliansGraphQLView(GraphQLView): """Class Based View to handle GraphQL requests.""" @csrf_exempt def dispatch(self, *args, **kwargs): """Override dispatch method to allow the use of multip...
from django.http import Http404 from django.views.decorators.csrf import csrf_exempt import waffle from graphene_django.views import GraphQLView class MozilliansGraphQLView(GraphQLView): """Class Based View to handle GraphQL requests.""" @csrf_exempt def dispatch(self, *args, **kwargs): """Overr...
Add a waffle flag for GraphQL.
Add a waffle flag for GraphQL.
Python
bsd-3-clause
akatsoulas/mozillians,akatsoulas/mozillians,johngian/mozillians,akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,johngian/mozillians
0731a34fd55477b20ffcd19c9b41cda0dd084d75
ggplot/utils/date_breaks.py
ggplot/utils/date_breaks.py
from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator def parse_break_str(txt): "parses '10 weeks' into tuple (10, week)." txt = txt.strip() if len(txt.split()) == 2: n, units = txt.split() else: n,units = 1, txt units = units.rstrip('s') # e.g. weeks =>...
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator def parse_break_str(txt): "parses '10 weeks' into tuple (10, week)." txt = txt.strip() if len(txt.split()) == 2: n, units = txt.split() else: n,unit...
Add more granular date locators
Add more granular date locators
Python
bsd-2-clause
xguse/ggplot,andnovar/ggplot,benslice/ggplot,bitemyapp/ggplot,kmather73/ggplot,benslice/ggplot,udacity/ggplot,ricket1978/ggplot,mizzao/ggplot,wllmtrng/ggplot,smblance/ggplot,assad2012/ggplot,Cophy08/ggplot,xguse/ggplot,ricket1978/ggplot,mizzao/ggplot
6514e75b9a9b3bfeba1c43f95e386afcf67354bd
tests/test_django1_8_fixers.py
tests/test_django1_8_fixers.py
from __future__ import absolute_import, print_function, unicode_literals import os import pytest import _test_utilities def test_fix_outsourcing_contrib_comments(): if os.environ.get( "IGNORE_CONTRIB_COMMENTS" ): # case where external dependency "django_comments" isn't loaded with pytest...
from __future__ import absolute_import, print_function, unicode_literals import os import pytest import _test_utilities def test_fix_outsourcing_contrib_comments(): if os.environ.get( "IGNORE_CONTRIB_COMMENTS" ): # case where external dependency "django_comments" isn't loaded with pytest...
Fix buggy use of pytest.raises() in tests.
Fix buggy use of pytest.raises() in tests.
Python
mit
pakal/django-compat-patcher,pakal/django-compat-patcher
61e4b4fe80a2d89de5bb30310d65e08e45548208
tests/test_read_user_choice.py
tests/test_read_user_choice.py
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI...
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI...
Implement a test checking that options needs to be a non empty list
Implement a test checking that options needs to be a non empty list
Python
bsd-3-clause
pjbull/cookiecutter,benthomasson/cookiecutter,dajose/cookiecutter,atlassian/cookiecutter,dajose/cookiecutter,nhomar/cookiecutter,ionelmc/cookiecutter,christabor/cookiecutter,sp1rs/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,lgp171188/cookiecutter,Springerle/cookiecutter,agconti/cookiecutter,lucius-feng/cook...
0b746180bbb3d7008ac0ece14407b661b01941e2
website/tests/models/test_short_url.py
website/tests/models/test_short_url.py
import app from models import ShortURL def test_encode_decode(): base = ShortURL.base ids_to_test = ( 0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567, base, base - 1, base + 1, base * 2, base * 2 - 1, base * base ) for test_id in ids_to_test: encoded = ShortURL(id=tes...
from models import ShortURL def test_encode_decode(): base = ShortURL.base ids_to_test = ( 0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567, base, base - 1, base + 1, base * 2, base * 2 - 1, base * base ) for test_id in ids_to_test: encoded = ShortURL(id=test_id, addre...
Remove unused import from test short url
Remove unused import from test short url
Python
lgpl-2.1
reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-...
b5c85d3bbeb34dd3e5dd9c376bc3e121e518084e
src/zeit/workflow/xmlrpc/tests.py
src/zeit/workflow/xmlrpc/tests.py
# Copyright (c) 2008-2011 gocept gmbh & co. kg # See also LICENSE.txt from zope.testing import doctest import unittest import zeit.cms.testing import zeit.workflow.testing def test_suite(): suite = unittest.TestSuite() suite.addTest(zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer...
# Copyright (c) 2008-2012 gocept gmbh & co. kg # See also LICENSE.txt import zeit.cms.testing import zeit.workflow.testing def test_suite(): return zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer=zeit.workflow.testing.WorkflowLayer )
Remove superfluous (and wrong!) product config declaration
Remove superfluous (and wrong!) product config declaration
Python
bsd-3-clause
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
b9745075ba2383e77d7ebd10507f2b943efbfe88
integration/test_contrib.py
integration/test_contrib.py
import types from fabric.api import env, run from fabric.contrib import files class Integration(object): def setup(self): env.host_string = "127.0.0.1" def tildify(path): home = run("echo ~", quiet=True).stdout.strip() return path.replace('~', home) def expect(path): assert files.exists(ti...
import types from fabric.api import env, run, local from fabric.contrib import files class Integration(object): def setup(self): env.host_string = "127.0.0.1" def tildify(path): home = run("echo ~", quiet=True).stdout.strip() return path.replace('~', home) def expect(path): assert files.ex...
Fix up template crap to not use same name locally hurr
Fix up template crap to not use same name locally hurr
Python
bsd-2-clause
TarasRudnyk/fabric,likesxuqiang/fabric,ploxiln/fabric,haridsv/fabric,SamuelMarks/fabric,rodrigc/fabric,tolbkni/fabric,MjAbuz/fabric,jaraco/fabric,getsentry/fabric,askulkarni2/fabric,amaniak/fabric,bspink/fabric,pgroudas/fabric,qinrong/fabric,kxxoling/fabric,opavader/fabric,bitmonk/fabric,tekapo/fabric,raimon49/fabric,r...
e0298e3897752644f7592cf3e9aad4684dcbbbfe
kokekunster/urls.py
kokekunster/urls.py
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
Fix bug where admin panel was redirected to semesterpage app
Fix bug where admin panel was redirected to semesterpage app
Python
mit
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
15feb7ac3e58d77c00a7fc0fa4ff44d408cb9976
getMesosStats.py
getMesosStats.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import argparse def get_metric(host, port, metric): response = urllib2.urlopen( 'http://' + host + ':' + port + '/metrics/snapshot') data = json.load(response) # print json.dumps(data, indent=4, sort_keys=Tru...
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import argparse def get_metric(host, port, metric): response = urllib2.urlopen( 'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port) ) data = json.load(response) # print json.dumps(dat...
Add pythonic way to concatenate strings.
Add pythonic way to concatenate strings.
Python
mit
zolech/zabbix-mesos-template
5604ae9d4b9d00e0c24720056942d94b2cdd3f5d
test/test_people_GET.py
test/test_people_GET.py
from test.utils.assertions import assert_header_value, assert_json_response from test.utils.helpers import get_json_from_response, get_identifier_for_created_person # noinspection PyPep8Naming,PyShadowingNames class Test_When_No_People_Exist(object): def test_status_code(self, get_people): assert get_peo...
from test.utils.assertions import assert_header_value, assert_json_response from test.utils.helpers import get_json_from_response, get_identifier_for_created_person # noinspection PyPep8Naming,PyShadowingNames class Test_When_No_People_Exist(object): def test_status_code(self, get_people): assert get_peo...
Add assertion for number of fields on person
Add assertion for number of fields on person
Python
mit
wileykestner/falcon-sqlalchemy-demo,wileykestner/falcon-sqlalchemy-demo
82cbe36e00f2a363c1d613b1aa0ffc5f7550adc1
main.py
main.py
import numpy as np import pandas as pd from transform import transform # Load the questions questions = pd.read_csv('questions.csv') # Initialise the position of the user at the origin pos = np.zeros(3) input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): ' # Using a C-style loop over qu...
import numpy as np import pandas as pd from transform import transform # Load the questions questions = pd.read_csv('questions.csv') # Initialise the position of the user at the origin pos = np.zeros(3) input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): ' # Using a C-style loop over qu...
Correct for older Python3 version errors
Correct for older Python3 version errors
Python
mit
eggplantbren/StatisticalCompass,eggplantbren/StatisticalCompass,eggplantbren/StatisticalCompass
082a2d481c0ae118dfcb1456bb7f095d05a5eb0e
mycroft/tts/dummy_tts.py
mycroft/tts/dummy_tts.py
# Copyright 2020 Mycroft AI Inc. # # 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 writin...
# Copyright 2020 Mycroft AI Inc. # # 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 writin...
Mark that audio has completed in dummy tts
Mark that audio has completed in dummy tts
Python
apache-2.0
forslund/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core,MycroftAI/mycroft-core
a36abcdc8f8b6cbc7ca83c786bfe3c4eca2d3c44
cairis/test/CairisDaemonTestCase.py
cairis/test/CairisDaemonTestCase.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
Use os.system to initialise db in tests
Use os.system to initialise db in tests
Python
apache-2.0
failys/CAIRIS,nathanbjenx/cairis,nathanbjenx/cairis,nathanbjenx/cairis,failys/CAIRIS,nathanbjenx/cairis,failys/CAIRIS
3f64d95cae68548cbb0d5a200247b3f7d6c3ccf4
mongorm/__init__.py
mongorm/__init__.py
# -*- coding: utf-8 -*- from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'VERSION', 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncode...
# -*- coding: utf-8 -*- from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ]
Remove VERSION that prevented import *.
Remove VERSION that prevented import *.
Python
bsd-2-clause
rahulg/mongorm
131ca5942d6b5b24cfe02cb2fc844829af38cd0f
nipy/testing/__init__.py
nipy/testing/__init__.py
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from nipy.testing import funcfile >>> from nipy.io.api import load_image >>> img =...
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy data packages that you can download separately - see :mod:`nipy.utils.data` .. note: We use the ``nose`` testing framework for tests. Nose is a dependenc...
Allow failed nose import without breaking nipy import
Allow failed nose import without breaking nipy import
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
b1ae1c97095b69da3fb6a7f394ffc484dd6b4780
main.py
main.py
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' b = document.createElement('button') b.innerHTML = 'Run' b.setAttribute('id', 'runinjector') b.setAttribute('onclick', eval...
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' pre = document.getElementById('edoutput') b = document.getElementById('runinjector') if b == None: b = document.createEle...
Fix funny things when rerunning code
Fix funny things when rerunning code Prevent multiple "Run" buttons from appearing. Remove the canvas after pressing the Skulpt "Run" button.
Python
mit
Zirientis/skulpt-canvas,Zirientis/skulpt-canvas
9eafbdc888d29c19c930c69366b1d3ad431dde73
street_score/project/resources.py
street_score/project/resources.py
from djangorestframework import views from djangorestframework import resources from . import models class RatingResource (resources.ModelResource): model = models.Rating class RatingInstanceView (views.InstanceModelView): resource = RatingResource class RatingListView (views.ListOrCreateModelView): reso...
from djangorestframework import views from djangorestframework import resources from . import models class RatingResource (resources.ModelResource): model = models.Rating class RatingInstanceView (views.InstanceModelView): resource = RatingResource class RatingListView (views.ListOrCreateModelView): reso...
Add a function for questions to the survey resource
Add a function for questions to the survey resource
Python
mit
openplans/streetscore,openplans/streetscore,openplans/streetscore
469688be2069182016b74e9132307755abc7ed77
lutrisweb/settings/local.py
lutrisweb/settings/local.py
from base import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lutris', 'USER': 'lutris', 'PASSWORD': 'admin', 'HOST': 'localhost', } } STEAM_API_KEY = os.environ['STEAM_API_KEY']
import os from base import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lutris', 'USER': 'lutris', 'PASSWORD': 'admin', 'HOST': 'localhost', } } STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
Make Steam api key optional
Make Steam api key optional
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website
18f9771b5a02621c94b882042547dc2db751e134
open511/utils/geojson.py
open511/utils/geojson.py
import json from lxml import etree GML_NS = 'http://www.opengis.net/gml' def geojson_to_gml(gj): """Given a dict deserialized from a GeoJSON object, returns an lxml Element of the corresponding GML geometry.""" if gj['type'] == 'Point': coords = ','.join(str(c) for c in gj['coordinates']) eli...
import json from lxml import etree GML_NS = 'http://www.opengis.net/gml' def geojson_to_gml(gj): """Given a dict deserialized from a GeoJSON object, returns an lxml Element of the corresponding GML geometry.""" if gj['type'] == 'Point': coords = ','.join(str(c) for c in gj['coordinates']) eli...
Implement some GML-to-GeoJSON logic in Python
Implement some GML-to-GeoJSON logic in Python
Python
mit
Open511/open511-server,Open511/open511-server,Open511/open511-server
15619b7f0eeac9be4cbeaea35185abc413992e5c
devito/yask/grid.py
devito/yask/grid.py
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid context...
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid context...
Fix Grid pickling in YASK
mpi: Fix Grid pickling in YASK
Python
mit
opesci/devito,opesci/devito
01f43d80fd4324f596904e22409c0b76bcb1b015
totalsum/templatetags/totalsum.py
totalsum/templatetags/totalsum.py
""" Contains some common filter as utilities """ from django.template import Library, loader, Context from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def...
""" Contains some common filter as utilities """ from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum...
Update for Django version 1.11
Update for Django version 1.11
Python
mit
20tab/twentytab-totalsum-admin,20tab/twentytab-totalsum-admin
49c4b3a35aa8c50740761be6e84e3439d8084458
main.py
main.py
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() lastPingTime = 0 while True: for message in slackClient.rtm_read(): if message["type"] == "team_join": username = message["user"]["name"] message = "We...
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() lastPingTime = 0 while True: for message in slackClient.rtm_read(): if message["type"] == "team_join": username = message["user"]["name"] message = {}....
Replace string withe nvironment variable
Replace string withe nvironment variable
Python
mit
ollien/Slack-Welcome-Bot
059cc7ec7cd7c8b078b896be67a2041eaa3ea8da
accounts/backends.py
accounts/backends.py
from django.contrib.auth import get_user_model from django.conf import settings from django.contrib.auth.models import check_password from django.core.validators import validate_email from django.forms import ValidationError User = get_user_model() class EmailOrUsernameAuthBackend(): """ A custom authenticati...
from django.contrib.auth import get_user_model from django.conf import settings from django.contrib.auth.models import check_password from django.core.validators import validate_email from django.forms import ValidationError User = get_user_model() class EmailOrUsernameAuthBackend(): """ A custom authenticati...
Move return statement in _lookup_user into except/else flow
Move return statement in _lookup_user into except/else flow
Python
bsd-2-clause
ScottyMJacobson/django-email-or-username
013226abfe6f6594ffba85c28e90a90bd7befa68
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
Add check for fixture loading
Add check for fixture loading
Python
bsd-2-clause
barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore
2d2819a18f4b2997babb85ef3b942990683b7bb7
pontoon/base/urls.py
pontoon/base/urls.py
from django.conf.urls.defaults import * import views urlpatterns = patterns('', url(r'^$', views.home, name='pontoon.home'), url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'), url(r'^a/project/$', views.admin_project, name='pontoon.admin.project....
from django.conf.urls.defaults import * import views urlpatterns = patterns('', url(r'^$', views.home, name='pontoon.home'), url(r'^error/$', views.home, name='pontoon.home'), url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'), url(r'^a/projec...
Add missing error URL regex
Add missing error URL regex
Python
bsd-3-clause
participedia/pontoon,mastizada/pontoon,mastizada/pontoon,m8ttyB/pontoon,mathjazz/pontoon,mastizada/pontoon,yfdyh000/pontoon,sudheesh001/pontoon,mozilla/pontoon,vivekanand1101/pontoon,mastizada/pontoon,sudheesh001/pontoon,yfdyh000/pontoon,mathjazz/pontoon,participedia/pontoon,participedia/pontoon,vivekanand1101/pontoon,...
f6a8e84a2557c5edf29a6f3afa4d1cce1d42d389
tests/basics/try_finally_loops.py
tests/basics/try_finally_loops.py
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3...
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3...
Add test for break from within try within a for-loop.
tests/basics: Add test for break from within try within a for-loop.
Python
mit
turbinenreiter/micropython,Peetz0r/micropython-esp32,hosaka/micropython,ryannathans/micropython,bvernoux/micropython,tralamazza/micropython,cwyark/micropython,turbinenreiter/micropython,alex-march/micropython,SHA2017-badge/micropython-esp32,dxxb/micropython,swegener/micropython,adafruit/circuitpython,SHA2017-badge/micr...
3b6162de670d47856e6d377912c2fdf4d5f430a9
moto/forecast/exceptions.py
moto/forecast/exceptions.py
from __future__ import unicode_literals import json class AWSError(Exception): TYPE = None STATUS = 400 def __init__(self, message, type=None, status=None): self.message = message self.type = type if type is not None else self.TYPE self.status = status if status is not None else ...
from __future__ import unicode_literals from moto.core.exceptions import AWSError class InvalidInputException(AWSError): TYPE = "InvalidInputException" class ResourceAlreadyExistsException(AWSError): TYPE = "ResourceAlreadyExistsException" class ResourceNotFoundException(AWSError): TYPE = "ResourceNo...
Refactor Forecast to also use shared AWSError class
Refactor Forecast to also use shared AWSError class
Python
apache-2.0
spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,william-richard/moto,spulec/moto,spulec/moto,william-richard/moto
9083afc0e308588345c74675654a4c0d3061f39d
test/test_machine.py
test/test_machine.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import join import six from asv import machine def test_machine(tmpdir): tmpdir = six.text_type(tmpd...
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import join import six from asv import machine def test_machine(tmpdir): tmpdir = six.text_type(tmpd...
Add a test for asv machine --yes using defaults values
Add a test for asv machine --yes using defaults values
Python
bsd-3-clause
pv/asv,spacetelescope/asv,qwhelan/asv,airspeed-velocity/asv,airspeed-velocity/asv,pv/asv,qwhelan/asv,spacetelescope/asv,airspeed-velocity/asv,pv/asv,pv/asv,qwhelan/asv,spacetelescope/asv,spacetelescope/asv,airspeed-velocity/asv,qwhelan/asv
f9ebca863ff2fd1a0ea160047cd70c59b4663b9d
test_bert_trainer.py
test_bert_trainer.py
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
Print eval results in test
Print eval results in test
Python
apache-2.0
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
154c493b64cf227c366e63dc8346d76601d36ba6
submodules-to-glockfile.py
submodules-to-glockfile.py
#!/usr/bin/python import re import subprocess def main(): source = open(".gitmodules").read() paths = re.findall(r"path = (.*)", source) print "github.com/localhots/satan {}".format(path_sha1(".")) for path in paths: print "{repo} {sha}".format( repo = path[7:], sha = ...
#!/usr/bin/python import re import subprocess def main(): source = open(".gitmodules").read() paths = re.findall(r"path = (.*)", source) print("github.com/localhots/satan {}".format(path_sha1("."))) for path in paths: print("{} {}".format(path[7:], path_sha1(path))) def path_sha1(path): ...
Make submodules script work in both 2 and 3 pythons
Make submodules script work in both 2 and 3 pythons
Python
mit
localhots/satan,localhots/satan,localhots/satan,localhots/satan
9364cf8e738b048e16f8f6504674536a39be96e0
graphiter/models.py
graphiter/models.py
from django.db import models class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() charts = models.ManyToManyField(Chart)...
from django.db import models class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() charts = models.ManyToManyField(Chart)...
Add get_absolute_url to Page model
Add get_absolute_url to Page model
Python
bsd-2-clause
jwineinger/django-graphiter
e07f095944a0a6edd125d75f4980a45fc10c6dfd
wiblog/util/comments.py
wiblog/util/comments.py
# This file is part of the FragDev Website. # # the FragDev Website is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # the FragDev W...
# This file is part of the FragDev Website. # # the FragDev Website is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # the FragDev W...
Fix wiblog's use of the anti-spam validator
Fix wiblog's use of the anti-spam validator
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
3382b5003eadec99f0816d9190038bd2caf6c412
system_maintenance/urls.py
system_maintenance/urls.py
from django.conf.urls import patterns, url from .views import (DocumentationRecordListView, DocumentationRecordDetailView, MaintenanceRecordDetailView, MaintenanceRecordListView, system_maintenance_home_view) urlpatterns = patterns('', url(r'^$', system_maintenance_home_view, name='system_maintenance_hom...
from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import (DocumentationRecordListView, DocumentationRecordDetailView, MaintenanceRecordDetailView, MaintenanceRecordListView, system_maintenance_home_view) urlpatterns = [ url(r'^$', system_maintenance_home_vie...
Resolve Django 1.10 deprecation warnings
Resolve Django 1.10 deprecation warnings
Python
bsd-3-clause
mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance
e3d1805094ea3df86c94fdc116d1f718975a338e
src/me/maxwu/cistat/app/cistat.py
src/me/maxwu/cistat/app/cistat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxwu' import json from me.maxwu.cistat import config from me.maxwu.cistat.reqs.circleci_request import CircleCiReq from me.maxwu.cistat.model.xunit_report import Xunitrpt """Main script file to provide configuration loading, cli_app and version. """ VERSI...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxwu' import pprint from me.maxwu.cistat import config from me.maxwu.cistat.reqs.circleci_request import CircleCiReq from me.maxwu.cistat.model.xunit_report import Xunitrpt """Main script file to provide configuration loading, cli_app and version. """ VERS...
Update sample task with pprint
Update sample task with pprint
Python
mit
maxwu/cistat,maxwu/cistat
3afa75c48d680111dc32368553cdc741eb0c07fa
imgfac/Singleton.py
imgfac/Singleton.py
# Copyright 2011 Red Hat, Inc. # # 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 t...
# Copyright 2011 Red Hat, Inc. # # 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 t...
Allow for parameters to __init__()
Allow for parameters to __init__() Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com>
Python
apache-2.0
henrysher/imagefactory,LalatenduMohanty/imagefactory,jmcabandara/imagefactory,henrysher/imagefactory,redhat-imaging/imagefactory,jmcabandara/imagefactory,redhat-imaging/imagefactory,LalatenduMohanty/imagefactory
b8cf6f096e14ee7311c18117d57f98b1745b8105
pyuvdata/__init__.py
pyuvdata/__init__.py
# -*- mode: python; coding: utf-8 -*- # Copyright (c) 2018 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """init file for pyuvdata. """ from __future__ import absolute_import, division, print_function from .uvdata import * from .telescopes import * from .uvcal import * from .uvbeam import ...
# -*- mode: python; coding: utf-8 -*- # Copyright (c) 2018 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """init file for pyuvdata. """ from __future__ import absolute_import, division, print_function # Filter annoying Cython warnings that serve no good purpose. see numpy#432 import warnin...
Move warning filter above other imports in init
Move warning filter above other imports in init
Python
bsd-2-clause
HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata
675c7442b6fcee3fd9bd57d7a4ef68c7de23d48c
reddit_adzerk/adzerkkeywords.py
reddit_adzerk/adzerkkeywords.py
# Polls Adzerk for current list of flights and saves the current targeting # information to zookeeper (to be run periodically with upstart) import adzerk_api import json from pylons import app_globals as g def update_global_keywords(): active_flights = adzerk_api.Flight.list(is_active=True) keyword_targe...
# Polls Adzerk for current list of flights and saves the current targeting # information to zookeeper (to be run periodically with upstart) import adzerk_api import json from pylons import app_globals as g KEYWORD_NODE = "/keyword-targets" def update_global_keywords(): active_flights = adzerk_api.Flight.list...
Create zookeeper node if it doesn't exist
Create zookeeper node if it doesn't exist
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
92adf36a7aaf6d4741944b6c606f0cf4902f232d
letters/admin.py
letters/admin.py
from dal import autocomplete from django import forms from django.contrib import admin from .models import Letter, Topic from prosopography.models import Person class PersonInlineForm(forms.ModelForm): class Meta: model = Person.letters_to.through fields = ('__all__') widgets = { ...
from dal import autocomplete from django import forms from django.contrib import admin from letters.models import Letter, Topic from prosopography.models import Person class PersonInlineForm(forms.ModelForm): """Configure inline admin form for :class:`prosopography.models.Person` """ class Meta: model...
Add some documentation to letters
Add some documentation to letters
Python
mit
bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject
2118cc5efbe70a10c67ddf9b949607b243e05687
rest_framework_docs/api_docs.py
rest_framework_docs/api_docs.py
from django.conf import settings from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from rest_framework.views import APIView from rest_framework_docs.api_endpoint import ApiEndpoint class ApiDocumentation(object): def __init__(self): self.endpoints = [] root_urlconf = __import...
from django.conf import settings from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from rest_framework.views import APIView from rest_framework_docs.api_endpoint import ApiEndpoint class ApiDocumentation(object): def __init__(self): self.endpoints = [] root_urlconf = __import...
Return conditional without using if/else to return boolean values
Return conditional without using if/else to return boolean values In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditional
Python
bsd-2-clause
ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,manosim/django-rest-framework-docs
19dfc716d31abaf2e82475b097d42d02bfc2259e
fuzza/data_broker.py
fuzza/data_broker.py
import glob import io class DataBroker(object): """ Read data and apply transformation to it as necessary. Args: config: A `dict` containing the fuzzer configurations. Attributes: _data_path: Path to data files as specified in configuration. _data: A list of data loaded from ...
import glob import io class DataBroker(object): """ Read data from data files. Args: config: A `dict` containing the fuzzer configurations. Attributes: _data_path: Path to data files as specified in configuration. _data: A list of data loaded from data files. """ def...
Add data property for DataBroker class
Add data property for DataBroker class
Python
mit
Raphx/fuzza
c9229922772a4d7f92a26786d6ea441609043a09
tests/CrawlerRunner/ip_address.py
tests/CrawlerRunner/ip_address.py
from urllib.parse import urlparse from twisted.internet import reactor from twisted.names.client import createResolver from scrapy import Spider, Request from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from tests.mockserver import MockServer, MockDNSServer class LocalhostSpi...
from urllib.parse import urlparse from twisted.internet import reactor from twisted.names.client import createResolver from scrapy import Spider, Request from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from tests.mockserver import MockServer, MockDNSServer class LocalhostSpi...
Move code inside __main__ block
Tests: Move code inside __main__ block
Python
bsd-3-clause
starrify/scrapy,scrapy/scrapy,starrify/scrapy,starrify/scrapy,elacuesta/scrapy,elacuesta/scrapy,pablohoffman/scrapy,pablohoffman/scrapy,pawelmhm/scrapy,pawelmhm/scrapy,dangra/scrapy,dangra/scrapy,scrapy/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,elacuesta/scrapy,scrapy/scrapy
b3fa14e85182d1b0efa47452de51d93a66c63503
tests/test_unstow.py
tests/test_unstow.py
import os import steeve def test_unstow(runner, stowed_foo_package): """Must remove all previously linked files.""" result = runner.invoke(steeve.cli, ['unstow', 'foo']) assert result.exit_code == 0 assert not os.path.exists(os.path.join('bin', 'foo')) def test_strict(runner): """Must fail when...
import os import steeve def test_no_current(runner, foo_package): """Must fail when unstowing a package with no 'current' symlink.""" result = runner.invoke(steeve.cli, ['unstow', 'foo']) assert result.exit_code == 1 assert 'not stowed' in result.output def test_unstow(runner, stowed_foo_package): ...
Test unstowing a package with no 'current' symlink
Test unstowing a package with no 'current' symlink
Python
bsd-3-clause
Perlence/steeve,Perlence/steeve
43ef10b1ea2ef5744b9558ff9c6afacdbfb1ee80
cacheops/__init__.py
cacheops/__init__.py
VERSION = (3, 2, 1) __version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2])) from django.apps import AppConfig from .simple import * from .query import * from .invalidation import * from .templatetags.cacheops import * from .transaction import install_cacheops_transaction_support class CacheopsCon...
__version__ = '3.2.1' VERSION = tuple(__version__.split('.')) from django.apps import AppConfig from .simple import * from .query import * from .invalidation import * from .templatetags.cacheops import * from .transaction import install_cacheops_transaction_support class CacheopsConfig(AppConfig): name = 'cach...
Use cacheops.__version__ as source of truth
Use cacheops.__version__ as source of truth
Python
bsd-3-clause
LPgenerator/django-cacheops,Suor/django-cacheops
7c8a256f5d87ae70ac3f187f0010a8d66d8b95d5
seabird/modules/metar.py
seabird/modules/metar.py
import asyncio import aiohttp from seabird.decorators import command from seabird.plugin import Plugin METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' class MetarPlugin(Plugin): @command def metar(self, msg): """<station> Returns the METAR report given an...
import asyncio import aiohttp from seabird.decorators import command from seabird.plugin import Plugin METAR_URL = ('http://weather.noaa.gov/pub/data' '/observations/metar/stations/%s.TXT') class MetarPlugin(Plugin): @command def metar(self, msg): """<station> Returns the MET...
Fix a line too long lint error
Fix a line too long lint error
Python
mit
belak/python-seabird,belak/pyseabird
66ae18a11290e73a996d1e2f2ba8018e29c0f92b
sheepdog_tables/forms.py
sheepdog_tables/forms.py
import logging from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, HTML, Div, Submit logger = logging.getLogger("sheepdog_tables") class CSVExportForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) class EditTableSubmitForm(forms.Form): ...
import logging from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, HTML, Div, Submit logger = logging.getLogger("sheepdog_tables") class CSVExportForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) class EditTableSubmitForm(forms.Form): ...
Remove logger warning in favor of print for now
Remove logger warning in favor of print for now
Python
bsd-3-clause
SheepDogInc/sheepdog_tables,SheepDogInc/sheepdog_tables
ae61346af8a813b6c0ecbb9f232f235ada982356
main.py
main.py
import json from datetime import date from boto import sqs from boto.dynamodb2.table import Table def playlists_to_process(): accounts = Table('accounts') target_date = date.isoformat(date.today()) attributes = ('spotify_username', 'spotify_playlist_id', ) return accounts.scan(last_processed__ne=targe...
import json from datetime import date from boto import sqs from boto.dynamodb2.table import Table def playlists_to_process(target_date): accounts = Table('accounts') attributes = ('spotify_username', 'spotify_playlist_id', ) return accounts.scan(last_processed__ne=target_date, attributes=attributes) def...
Send date to process in message
Send date to process in message
Python
mit
projectweekend/song-feed-queue-builder
b24fa6443e70cca01ff5059fe29ba6e33c0262ea
pylisp/packet/ip/protocol.py
pylisp/packet/ip/protocol.py
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class Protocol(object): __metaclass__ = ABCMeta header_type = None @abstractmethod def __init__(self, next_header=None, payload=''): ''' Constructor ''' self.next_header = next_he...
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class ProtocolElement(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self): ''' Constructor ''' def __repr__(self): # This works as long as we accept all properties...
Split Protocol class in Protocol and ProtocolElement
Split Protocol class in Protocol and ProtocolElement
Python
bsd-3-clause
steffann/pylisp
94124a65b5aa540f9f997dfcdbd856207d011555
wafer/conf_registration/models.py
wafer/conf_registration/models.py
from django.contrib.auth.models import User from django.db import models class ConferenceOptionGroup(models.Model): """Used to manage relationships""" name = models.CharField(max_length=255) class ConferenceOption(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(ma...
from django.contrib.auth.models import User from django.db import models class ConferenceOptionGroup(models.Model): """Used to manage relationships""" name = models.CharField(max_length=255) def __unicode__(self): return u'%s' % self.name class ConferenceOption(models.Model): name = models...
Make requirements optional. Add help text and fix display in admin form
Make requirements optional. Add help text and fix display in admin form
Python
isc
CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer
4e67491bda3204d449c540fa80cbbb8ab73921dd
wagtail/wagtailadmin/edit_bird.py
wagtail/wagtailadmin/edit_bird.py
from django.core.urlresolvers import reverse from django.template import RequestContext from django.template.loader import render_to_string class BaseItem(object): template = 'wagtailadmin/edit_bird/base_item.html' def render(self, request): return render_to_string(self.template, dict(self=self, requ...
from django.core.urlresolvers import reverse from django.template import RequestContext from django.template.loader import render_to_string class BaseItem(object): template = 'wagtailadmin/edit_bird/base_item.html' def render(self, request): return render_to_string(self.template, dict(self=self, requ...
Edit bird now checks if the user has permission to access admin and edit the page before displaying edit page option
Edit bird now checks if the user has permission to access admin and edit the page before displaying edit page option
Python
bsd-3-clause
rjsproxy/wagtail,jnns/wagtail,taedori81/wagtail,thenewguy/wagtail,willcodefortea/wagtail,serzans/wagtail,inonit/wagtail,tangentlabs/wagtail,rsalmaso/wagtail,chimeno/wagtail,Toshakins/wagtail,jorge-marques/wagtail,wagtail/wagtail,quru/wagtail,kurtw/wagtail,rv816/wagtail,mayapurmedia/wagtail,darith27/wagtail,marctc/wagta...
e4dd679f20a066c86a87a42199f66b288a314fcf
scons-tools/gmcs.py
scons-tools/gmcs.py
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', ...
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', ...
Use -platform:anycpu while compiling .NET assemblies
Use -platform:anycpu while compiling .NET assemblies
Python
lgpl-2.1
eyecreate/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,juhovh/tapcfg
17ac329783bce0cb88d92659cf58a3ea476c66ef
scripts/sound_output_test.py
scripts/sound_output_test.py
import pyaudio import wave import time import sys import numpy as np if len(sys.argv) < 2: print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0]) sys.exit(-1) wf = wave.open(sys.argv[1], 'rb') p = pyaudio.PyAudio() DEVICE_ID=2 def callback(in_data, frame_count, time_info, status): data = w...
import pyaudio import wave import time import sys import numpy as np if len(sys.argv) < 2: print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0]) sys.exit(-1) wf = wave.open(sys.argv[1], 'rb') p = pyaudio.PyAudio() n_bytes_to_test = 1024 * 2 * 6 DEVICE_ID=2 def callback(in_data, frame_count, ...
Add support for looping sample
Add support for looping sample
Python
bsd-2-clause
mfergie/human-hive
32f1ce16ce9df1f4615a0403ed56bf6fd7dbbef4
slackbotpry/event.py
slackbotpry/event.py
class Event: def __init__(self, bot, data): self.bot = bot self.data = data def post_message(self, text, channel=None): if channel is None: channel = self.data['channel'] self.bot.post_message(text, channel) def add_reaction(self, emoji, channel=None, timestamp=No...
class Event: def __init__(self, bot, data): self.bot = bot self.data = data def post_message(self, text, channel=None): if channel is None: channel = self.data['channel'] return self.bot.post_message(text, channel) def add_reaction(self, emoji, channel=None, times...
Add missing return of Event methods
Add missing return of Event methods
Python
mit
rokurosatp/slackbotpry
9bb7dc9c8f7b5208c332017df8b1501315e2601f
py/gaarf/utils.py
py/gaarf/utils.py
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Fix incorrect signature for get_customer_ids function
Fix incorrect signature for get_customer_ids function Change-Id: Ib44af3ac6437ad9fa4cbfd9fda9b055b7eff4547
Python
apache-2.0
google/ads-api-report-fetcher,google/ads-api-report-fetcher,google/ads-api-report-fetcher,google/ads-api-report-fetcher
e457f09f280bc86bc7b5cdcfb4fa3ebf093402ec
services/dropbox.py
services/dropbox.py
import foauth.providers from oauthlib.oauth1.rfc5849 import SIGNATURE_PLAINTEXT class Dropbox(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.dropbox.com/' docs_url = 'https://www.dropbox.com/developers/reference/api' favicon_url = 'https://cf.dropboxstatic.com/...
import foauth.providers class Dropbox(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.dropbox.com/' docs_url = 'https://www.dropbox.com/developers/reference/api' favicon_url = 'https://cf.dropboxstatic.com/static/images/favicon-vflk5FiAC.ico' category = 'Fil...
Upgrade Dropbox to OAuth 2
Upgrade Dropbox to OAuth 2
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
b39dcbd12164cdd682aea2d39e298fe968dcf38e
pkg_resources/py31compat.py
pkg_resources/py31compat.py
import os import errno import sys def _makedirs_31(path, exist_ok=False): try: os.makedirs(path) except OSError as exc: if not exist_ok or exc.errno != errno.EEXIST: raise # rely on compatibility behavior until mode considerations # and exists_ok considerations are disentangled....
import os import errno import sys def _makedirs_31(path, exist_ok=False): try: os.makedirs(path) except OSError as exc: if not exist_ok or exc.errno != errno.EEXIST: raise # rely on compatibility behavior until mode considerations # and exists_ok considerations are disentangled....
Correct bounds and boolean selector.
Correct bounds and boolean selector.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
0ee2b337b61155044a66ae1f6f173492a51c1150
dipsim/fluorophore.py
dipsim/fluorophore.py
import numpy as np class Fluorophore: """A single fluorophore is specified by its 3D position, (unit) absorption dipole moment (theta, phi), and (unit) emission dipole moment (theta, phi). """ def __init__(self, position=np.array([0, 0, 0]), mu_abs=np.array([0, 0]), mu...
import numpy as np class Fluorophore: """A fluorophore is specified by its orientation (in theta and phi spherical coordinates), it distribution (using a kappa watson distribution), and a constant (c) proportional to the fluorohphore's brightness. """ def __init__(self, theta=np.pi/2, phi=0, kappa=...
Modify Fluorophore for more convenient coordinates.
Modify Fluorophore for more convenient coordinates.
Python
mit
talonchandler/dipsim,talonchandler/dipsim
79e5cab2908c26ff80ae5c5e4b37ced9765a952c
dbaas/physical/forms/database_infra.py
dbaas/physical/forms/database_infra.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import logging from django import forms from .. import models log = logging.getLogger(__name__) class DatabaseInfraForm(forms.ModelForm): class Meta: model = models.DatabaseInfra def __init__(self, *args, **kwargs): ...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import logging from django import forms from .. import models log = logging.getLogger(__name__) class DatabaseInfraForm(forms.ModelForm): class Meta: model = models.DatabaseInfra def __init__(self, *args, **kwargs): ...
Fix database infra save method
Fix database infra save method
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
1e264b61d82b009778780926ca730b5dc990a635
scikits/image/analysis/__init__.py
scikits/image/analysis/__init__.py
from spath import shortest_path
try: from spath import shortest_path except ImportError: print """*** The shortest path extension has not been compiled. Run python setup.py build_ext -i in the source directory to build in-place. Please refer to INSTALL.txt for further detail."""
Allow importing even when not compiled.
spath: Allow importing even when not compiled.
Python
bsd-3-clause
youprofit/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,WarrenWeckesser/scikits-image,ajaybhat/scikit-image,bennlich/scikit-image,paalge/scikit-image,chintak/scikit-image,rjeli/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,rjeli/scikit-image,newville/scikit-image,vighne...
ab20fb46cf1afb4b59d40a7bd8aba6a29cdebb64
eris/pydoc_color.py
eris/pydoc_color.py
#!/usr/bin/env python3.7 # Copyright (C) 2019 Andrew Hamilton. All rights reserved. # Licensed under the Artistic License 2.0. import pydoc import sys import eris.termstr class TermDoc(pydoc.TextDoc): def bold(self, text): return str(eris.termstr.TermStr(text).bold()) def main(): path = sys.arg...
#!/usr/bin/env python3.7 # Copyright (C) 2019 Andrew Hamilton. All rights reserved. # Licensed under the Artistic License 2.0. import pydoc import sys import eris.termstr class TermDoc(pydoc.TextDoc): def bold(self, text): return str(eris.termstr.TermStr(text).bold()) def main(): path = sys.arg...
Make pydoc quieter on error.
tools: Make pydoc quieter on error.
Python
artistic-2.0
ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil,ahamilton/vigil
e9bfe96cb3463fe99f08305aab44bd3d7556825a
api/radar_api/serializers/group_users.py
api/radar_api/serializers/group_users.py
from radar_api.serializers.groups import GroupReferenceField from radar_api.serializers.meta import MetaSerializerMixin from radar_api.serializers.user_mixins import UserSerializerMixin from radar.models.groups import GroupUser from radar.roles import ROLE, ROLE_NAMES from radar.serializers.fields import ListField, Str...
from radar_api.serializers.groups import GroupReferenceField from radar_api.serializers.meta import MetaSerializerMixin from radar_api.serializers.user_mixins import UserSerializerMixin from radar.models.groups import GroupUser from radar.roles import ROLE, ROLE_NAMES from radar.serializers.fields import ListField, Str...
Add managed roles to serializer
Add managed roles to serializer
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
f01841e5b3fb9fe6a4f30b15dbf12146971d1b6f
flask_aggregator.py
flask_aggregator.py
import json from flask import request as current_request, Response from werkzeug.exceptions import BadRequest class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def...
import json from flask import request, Request, Response from werkzeug.exceptions import BadRequest from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: ...
Use app request context directly rather than hacking with a test client
Use app request context directly rather than hacking with a test client
Python
mit
ramnes/flask-aggregator
69baf68b436255eca71ec63578a2fdef4bc03165
books.py
books.py
import falcon class BooksResource: def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.body = open('/home/sanchopanca/Documents/thunder.txt').read() app = falcon.API() books = BooksResource() app.add_route('/books', books)
import falcon def get_paragraphs(pathname): result = [] with open(pathname) as f: for line in f.readlines(): if line != '\n': result.append(line[:-1]) return result class BooksResource: def on_get(self, req, resp): resp.status = falcon.HTTP_200 res...
Add function which divide text to paragraphs
Add function which divide text to paragraphs
Python
agpl-3.0
sanchopanca/reader,sanchopanca/reader
5c8780c1f4ba914f20f0dc022cc26becb381f2f1
markymark/fields.py
markymark/fields.py
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) cl...
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(mode...
Revert "Allow widget overwriting on form field"
Revert "Allow widget overwriting on form field" This reverts commit 23a9aaae78cc4d9228f8d0705647fbcadcaf7975.
Python
mit
moccu/django-markymark,moccu/django-markymark,moccu/django-markymark
3330678d6474a876e2d18edce995bd82ba027472
gittools.py
gittools.py
import os import sha def gitsha(path): h = sha.sha() data = file(path).read() h.update("blob %d\0" % len(data)) h.update(data) return h.hexdigest() def git_info(): commithash = file('.git/HEAD').read().strip() if os.getuid() == os.stat(".git/index").st_uid: os.system('git-update-in...
import os import sha def gitsha(path): h = sha.sha() data = file(path).read() h.update("blob %d\0" % len(data)) h.update(data) return h.hexdigest() def git_info(): commithash = file('.git/HEAD').read().strip() if commithash.startswith("ref: "): commithash = file(commithash[5:]).rea...
Handle symbolic refs in .git/HEAD
OTHER: Handle symbolic refs in .git/HEAD
Python
lgpl-2.1
xmms2/xmms2-stable,dreamerc/xmms2,oneman/xmms2-oneman,xmms2/xmms2-stable,chrippa/xmms2,theefer/xmms2,oneman/xmms2-oneman-old,six600110/xmms2,mantaraya36/xmms2-mantaraya36,mantaraya36/xmms2-mantaraya36,mantaraya36/xmms2-mantaraya36,chrippa/xmms2,theeternalsw0rd/xmms2,krad-radio/xmms2-krad,theeternalsw0rd/xmms2,oneman/xm...
03671a01cb5ea359c22e954a8381bbfd30bce094
lc560_subarray_sum_equals_k.py
lc560_subarray_sum_equals_k.py
"""560. Subarray Sum Equals K Medium Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 100...
"""560. Subarray Sum Equals K Medium Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 100...
Complete naive solution by nested for loops
Complete naive solution by nested for loops
Python
bsd-2-clause
bowen0701/algorithms_data_structures
7bcd595429c18a38dfcb81e39cbf793dc969136f
mongoforms/utils.py
mongoforms/utils.py
from django import forms from mongoengine.base import ValidationError from bson.objectid import ObjectId def mongoengine_validate_wrapper(old_clean, new_clean): """ A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are ...
from django import forms from mongoengine.base import ValidationError from bson.objectid import ObjectId def mongoengine_validate_wrapper(old_clean, new_clean): """ A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are ...
Order MongoForm fields according to the Document
Order MongoForm fields according to the Document
Python
bsd-3-clause
pimentech/django-mongoforms,pimentech/django-mongoforms
1510bc44b8017771e60618d617cfefd4eaf32cde
addie/initialization/init_step1.py
addie/initialization/init_step1.py
from PyQt4 import QtGui from addie.step1_handler.step1_gui_handler import Step1GuiHandler class InitStep1(object): def __init__(self, parent=None): self.parent = parent self.parent.ui.diamond.setFocus(True) self.set_statusBar() self.set_title() def set_title(self...
from qtpy.QtWidgets import (QLabel) from addie.step1_handler.step1_gui_handler import Step1GuiHandler class InitStep1(object): def __init__(self, parent=None): self.parent = parent self.parent.ui.diamond.setFocus(True) self.set_statusBar() self.set_title() def set_title(self...
Convert from pyqt4 to qtpy
Convert from pyqt4 to qtpy
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
2aa41403436a1629d3d0f8c83b51f685f7b0f421
main/remote_exe.py
main/remote_exe.py
#!/usr/bin/python import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.getcwd(),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_name= os.path....
#!/usr/bin/python import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.path.dirname(__file__),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_...
Fix bug: log dir path: set it thru file location, not current working path
Fix bug: log dir path: set it thru file location, not current working path
Python
mit
trelay/multi-executor
02454937b500afe1dc9b7387e63f9b3327be6a16
contrail_provisioning/config/templates/contrail_discovery_conf.py
contrail_provisioning/config/templates/contrail_discovery_conf.py
import string template = string.Template(""" [DEFAULTS] zk_server_ip=$__contrail_zk_server_ip__ zk_server_port=$__contrail_zk_server_port__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ log_local=$__contrail_log_local__ log_file=$__contrail_log_file__ cassandra_server_list=$__contra...
import string template = string.Template(""" [DEFAULTS] zk_server_ip=$__contrail_zk_server_ip__ zk_server_port=$__contrail_zk_server_port__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ log_local=$__contrail_log_local__ log_file=$__contrail_log_file__ cassandra_server_list=$__contra...
Enable consistent-hashing policy for Collector
Enable consistent-hashing policy for Collector Change-Id: I7ed6747b6c3ef95d8fed0c62e786c7039fb510a6 Fixes-Bug: #1600368
Python
apache-2.0
Juniper/contrail-provisioning,Juniper/contrail-provisioning
32c40710a562b194385f2340bf882cb3709b74e3
masquerade/urls.py
masquerade/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^mask/$', 'masquerade.views.mask'), url(r'^unmask/$', 'masquerade.views.unmask'), )
from django.conf.urls import patterns, url from masquerade.views import mask from masquerade.views import unmask urlpatterns = [ url(r'^mask/$', mask), url(r'^unmask/$', unmask), ]
Fix Django 1.10 deprecation warning
Fix Django 1.10 deprecation warning
Python
apache-2.0
erikcw/django-masquerade,erikcw/django-masquerade,erikcw/django-masquerade
69304be6df25ba2db53985b3d1e2e66954b7d655
genes/lib/traits.py
genes/lib/traits.py
from functools import wraps def if_any(*conds): def wrapper(func): @wraps def run_if_any(*args, **kwargs): if any(conds): return func(*args, **kwargs) return run_if_any return wrapper def if_all(*conds): def wrapper(func): @wraps de...
from functools import wraps def if_any(*conds): def wrapper(func): @wraps(func) def run_if_any(*args, **kwargs): if any(conds): return func(*args, **kwargs) return run_if_any return wrapper def if_all(*conds): def wrapper(func): @wraps(func...
Add argument to @wraps decorator
Add argument to @wraps decorator
Python
mit
hatchery/Genepool2,hatchery/genepool
76244d9a9750d1e095884b3a453caffa6d1ef3c4
main/views/views.py
main/views/views.py
from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg def index(request): users = UserProfile.objects.all() return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)...
from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg from voting.models import Vote def index(request): users = UserProfile.objects.all() tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10] votes ...
Hide last task and services with negative score from main page
Hide last task and services with negative score from main page
Python
agpl-3.0
Davidyuk/witcoin,Davidyuk/witcoin