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
d40ba3bcceb1dcc7338b689194cd7214d7b2d5ff
syncano_cli/execute/commands.py
syncano_cli/execute/commands.py
# -*- coding: utf-8 -*- from __future__ import print_function import json import sys from ConfigParser import NoOptionError import click from syncano_cli import LOG from .connection import create_connection @click.group() def top_execute(): pass @top_execute.command() @click.option('--config', help=u'Account...
# -*- coding: utf-8 -*- from __future__ import print_function import json import sys from ConfigParser import NoOptionError import click from syncano.exceptions import SyncanoDoesNotExist from syncano_cli import LOG from .connection import create_connection @click.group() def top_execute(): pass @top_execute...
Refactor the code: add error handling of invalid or empty parameters, improve output format.
Refactor the code: add error handling of invalid or empty parameters, improve output format.
Python
mit
Syncano/syncano-cli,Syncano/syncano-cli,Syncano/syncano-cli
5f89ad72905947ac47c3246a15fae99c15571435
django/signups/tests.py
django/signups/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.test.client import Client from signups.models import User from splinter_demo.test_runner im...
from django.test import TestCase from django.test.client import Client from signups.models import User from splinter_demo.test_runner import BROWSER class TestSignup(TestCase): def visit(self, path): BROWSER.visit('http://localhost:65432' + path) def test_sign_up(self): Client().post('/', {'e...
Remove a bit of django boilerplate
Remove a bit of django boilerplate
Python
mit
ErinCall/splinter_demo,ErinCall/splinter_demo
bb85df8a9a8cecaf6f3db276347aa8f5f9b39d0c
bot/game/api/api_data.py
bot/game/api/api_data.py
import codecs import json from tools.cipher import salted_digest DATA_ENCODING = "utf-8" TRANSPORT_ENCODING = "base64" DUMMY_ENCODING = "ascii" DATA_DIGEST_SEPARATOR = "-" def encode(data): dumped_data = json.dumps(data) encoded_dumped_data = dumped_data.encode(DATA_ENCODING) encoded = codecs.encode(e...
import codecs import json from tools.cipher import salted_digest DATA_ENCODING = "utf-8" TRANSPORT_ENCODING = "base64" DUMMY_ENCODING = "ascii" DATA_DIGEST_SEPARATOR = "-" def encode(data): dumped_data = json.dumps(data) encoded_dumped_data = dumped_data.encode(DATA_ENCODING) encoded = _transport_enco...
Remove newlines from exported url_data
Remove newlines from exported url_data
Python
apache-2.0
alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games
4b6b5effc744583eb0227d14d0c5e324c50cf074
tests/integration/test_proxy.py
tests/integration/test_proxy.py
# -*- coding: utf-8 -*- '''Test using a proxy.''' # External imports import multiprocessing import pytest from six.moves import socketserver, SimpleHTTPServer from six.moves.urllib.request import urlopen # Internal imports import vcr # Conditional imports requests = pytest.importorskip("requests") class Proxy(Sim...
# -*- coding: utf-8 -*- '''Test using a proxy.''' # External imports import multiprocessing import pytest from six.moves import socketserver, SimpleHTTPServer from six.moves.urllib.request import urlopen # Internal imports import vcr # Conditional imports requests = pytest.importorskip("requests") class Proxy(Sim...
Add headers in proxy server response
Add headers in proxy server response
Python
mit
kevin1024/vcrpy,kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy
e9ad33a12dcb3f678c2aa7a8bcc0339dcb88bd5b
tests/unit/test_authenticate.py
tests/unit/test_authenticate.py
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call import pytest @pytest.fixture() def create_environment(api_key, domain, fqdn, auth_token): return { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBO...
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call import pytest @pytest.fixture() def create_environment(api_key, domain, fqdn, auth_token): return { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBO...
Reword Test Names for Clarity
Reword Test Names for Clarity I didn't like how the test names were sounding. Hopefully this is better.
Python
apache-2.0
Jitsusama/lets-do-dns
e75b79fb5dd614d117289acdab758c5c86b89e35
update-database/stackdoc/questionimport.py
update-database/stackdoc/questionimport.py
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, nam...
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, nam...
Include answer count in stored data.
Include answer count in stored data.
Python
bsd-3-clause
alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc
bd4812a1ef93c51bedbc92e8064b3457b5d88992
tests/test_slice.py
tests/test_slice.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> import pytest import numpy as np from parameters import T_VALUES, KPT @pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )]) @pytest.mark.parametrize...
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for the model slicing functionality.""" import pytest import numpy as np from parameters import T_VALUES, KPT @pytest.mark.parametrize('slice_idx', [(0, 1)...
Fix pre-commit for slicing method.
Fix pre-commit for slicing method.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
d07e1c020185fb118b628674234c4a1ebcc11836
binder/config.py
binder/config.py
c.ServerProxy.servers = { 'lab-dev': { 'command': [ 'jupyter', 'lab', '--no-browser', '--dev-mode', '--port={port}', '--NotebookApp.token=""', ] } } c.NotebookApp.default_url = '/lab-dev'
c.ServerProxy.servers = { 'lab-dev': { 'command': [ 'jupyter', 'lab', '--no-browser', '--dev-mode', '--port={port}', '--NotebookApp.token=""', '--NotebookApp.base_url={base_url}/lab-dev' ] } } c.NotebookApp.defa...
Set base_url for dev version of lab
Set base_url for dev version of lab
Python
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
ffc4d6db188b9ad8ece655c8221f2e5a34e7c66b
main.py
main.py
""" pyMonitor first Version Written By :Ahmed Alkabir """ #!/usr/bin/python3 import main_ui as Ui import sys # Main Thread of Program def main(): app = Ui.QtWidgets.QApplication(sys.argv) main_window = Ui.QtWidgets.QMainWindow() ui = Ui.Ui_window(main_window) main_window.show() sys.exit...
""" pyMonitor first Version Written By :Ahmed Alkabir """ #!/usr/bin/python3 import main_ui as Ui import sys # Main Thread of Program def main(): if float(sys.version[:3]) >= 3.3: app = Ui.QtWidgets.QApplication(sys.argv) main_window = Ui.QtWidgets.QMainWindow() ui = Ui.Ui_windo...
Check Verison of Python Interpreter
Check Verison of Python Interpreter
Python
mit
ahmedalkabir/pyMonitor
2abb0ff8d8f57ca1ae05e0abfc17bdcbbc758e19
main.py
main.py
#!/usr/bin/env python import phiface sc = phiface.Context() yloc = 30 for weight in [1, 3, 6, 10]: xloc = 30 A = phiface.AGlyph(x=xloc, y=yloc) xloc += A.width() + 40 E = phiface.EGlyph(x=xloc, y=yloc) xloc += E.width() + 20 I = phiface.IGlyph(x=xloc, y=yloc) xloc += I.width() + 20 ...
#!/usr/bin/env python import phiface sc = phiface.Context() yloc = 30 for weight in [1, 3, 6, 10]: xloc = 30 A = phiface.AGlyph(x=xloc, y=yloc) xloc += A.width() + 40 E = phiface.EGlyph(x=xloc, y=yloc) xloc += E.width() + 20 I = phiface.IGlyph(x=xloc, y=yloc) xloc += I.width() + 20 ...
Change weight rendering based on capHeight
Change weight rendering based on capHeight
Python
bsd-2-clause
hortont424/phiface
82bfc3ad8c39ffe51677eecbdc5c6904ae1ade41
main.py
main.py
from common.bounty import * from common.peers import * from common import settings def main(): settings.setup() print "settings are:" print settings.config if __name__ == "__main__": main()
from common.bounty import * from common.peers import * from common import settings def main(): settings.setup() print "settings are:" print settings.config if settings.config.get('server') is not True: initializePeerConnections() else: listen() if __name__ == "__main__": ma...
Add primitive server option for easier debugging
Add primitive server option for easier debugging
Python
mit
gappleto97/Senior-Project
2aae7b1718bfc21267922f7fe09dcf47be69582b
blueprints/aws_rds_instance/delete_aws_rds_instance.py
blueprints/aws_rds_instance/delete_aws_rds_instance.py
import json import boto3 from infrastructure.models import Environment def run(job, logger=None, **kwargs): service = job.service_set.first() env_id = service.attributes.get(field__name__startswith='aws_environment').value env = Environment.objects.get(id=env_id) rh = env.resource_handler.cast() ...
import json import boto3 from infrastructure.models import Environment def run(job, logger=None, **kwargs): service = job.service_set.first() # The Environment ID and RDS Instance data dict were stored as attributes on # this service by a build action. env_id_cfv = service.attributes.get(field__name...
Use code consistent with other RDS actions
Use code consistent with other RDS actions [#144244831]
Python
apache-2.0
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
1c0ea1a102ed91342ce0d609733426b8a07cd67d
easy_thumbnails/tests/apps.py
easy_thumbnails/tests/apps.py
from django.apps import AppConfig class EasyThumbnailsTestConfig(AppConfig): name = 'easy_thumbnails.tests' label = 'easy_thumbnails_tests'
try: from django.apps import AppConfig except ImportError: # Early Django versions import everything in test, avoid the failure due to # AppConfig only existing in 1.7+ AppConfig = object class EasyThumbnailsTestConfig(AppConfig): name = 'easy_thumbnails.tests' label = 'easy_thumbnails_tests'
Fix an import error for old django versions
Fix an import error for old django versions Fixes #371
Python
bsd-3-clause
SmileyChris/easy-thumbnails
6e7923413bb0729a288c36f10e22ad7a777bf538
supercell/testing.py
supercell/testing.py
# vim: set fileencoding=utf-8 : # # Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com> # # 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/LICENS...
# vim: set fileencoding=utf-8 : # # Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com> # # 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/LICENS...
Add pytest to mocked sys.argv
Add pytest to mocked sys.argv If you want to use this for integration tests, the ARGV variable only has to contain the arguments. The first argument usually is the script name and is not read by tornado at all.
Python
apache-2.0
truemped/supercell,truemped/supercell
a6dc99096870b186aafe85e9777b7c29de488a51
forum/models.py
forum/models.py
from django.db import models class Thread(models.Model): """Model for representing threads.""" title = models.TextField() views = models.PositiveIntegerField(default=0) sticky = models.BooleanField() closed = models.BooleanField()
from django.db import models import django.contrib.auth.models as auth class User(auth.User): """Model for representing users. It has few fields that aren't in the standard authentication user table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length...
Create user class for forums.
Create user class for forums. Forums need to store information users that is usually not stored. This currently stores only display name, althrough it can store more in the future.
Python
mit
xfix/NextBoard
8ce6aa788573aa10758375d58881f03ff438db16
machete/base.py
machete/base.py
from datetime import datetime from thunderdome.connection import setup import thunderdome setup(["localhost"], "machete") class BaseVertex(thunderdome.Vertex): created_at = thunderdome.DateTime(default=datetime.now) class BaseEdge(thunderdome.Edge): created_at = thunderdome.DateTime(default=datetime.now) ...
from datetime import datetime from thunderdome.connection import setup import thunderdome setup(["localhost"], "machete") class BaseVertex(thunderdome.Vertex): created_at = thunderdome.DateTime(default=datetime.now) def __repr__(self): return "<{}:{}>".format(self.__class__.__name__, self.vid) clas...
Add __repr__ To BaseVertex and BaseEdge
Add __repr__ To BaseVertex and BaseEdge
Python
bsd-3-clause
rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete
ccbceb486dd4775ec6dfe3764e522a869860703b
examples/rbd_fast/rbd_fast.py
examples/rbd_fast/rbd_fast.py
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami...
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami...
Fix incorrect description of returned dict entries
Fix incorrect description of returned dict entries
Python
mit
jdherman/SALib,SALib/SALib,jdherman/SALib
4af812f9189a7bd29b9aea274eeed5cbd277dbcb
examples/widgets/actionbar.py
examples/widgets/actionbar.py
from kivy.base import runTouchApp from kivy.lang import Builder runTouchApp(Builder.load_string(''' ActionBar: pos_hint: {'top':1} ActionView: use_separator: True ActionPrevious: title: 'Action Bar' with_previous: False ActionOverflow: ActionButton: ...
from kivy.base import runTouchApp from kivy.lang import Builder runTouchApp(Builder.load_string(''' ActionBar: pos_hint: {'top':1} ActionView: use_separator: True ActionPrevious: title: 'Action Bar' with_previous: False ActionOverflow: ActionButton: ...
Remove overlapping caption in ActionBar example
Remove overlapping caption in ActionBar example
Python
mit
LogicalDash/kivy,LogicalDash/kivy,Cheaterman/kivy,Cheaterman/kivy,inclement/kivy,kivy/kivy,rnixx/kivy,bionoid/kivy,akshayaurora/kivy,bionoid/kivy,Cheaterman/kivy,LogicalDash/kivy,kivy/kivy,LogicalDash/kivy,matham/kivy,inclement/kivy,akshayaurora/kivy,inclement/kivy,matham/kivy,kivy/kivy,bionoid/kivy,akshayaurora/kivy,C...
8d73c71a0c9b8d4a226b90b9310562b490296038
gen/CSiBE-v2.1.1/preprocessed-source-compiler.py
gen/CSiBE-v2.1.1/preprocessed-source-compiler.py
#!/usr/bin/env python import argparse import os import subprocess if __name__ == "__main__": # Use wrappers for compilers (native) c_compiler_name = "gcc" if "CC" in os.environ: c_compiler_name = os.environ["CC"] preprocessed_sources = "" if "CSIBE_PREPROCESSED_SOURCES" in os.environ: ...
#!/usr/bin/env python import argparse import os import subprocess if __name__ == "__main__": # Use wrappers for compilers (native) c_compiler_name = "gcc" if "CC" in os.environ: c_compiler_name = os.environ["CC"] preprocessed_sources = "" if "CSIBE_PREPROCESSED_SOURCES" in os.environ: ...
Add requested CSiBE flags to the compilation of preprocessed files
Add requested CSiBE flags to the compilation of preprocessed files
Python
bsd-3-clause
szeged/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe
1c7487e50def0bb6bffd7af30e4f1a948197bee8
tests/settings.py
tests/settings.py
DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = ':memory:' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' INSTALLED_APPS = ( 'djmoney', 'testapp' )
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = ( 'djmoney', 'testapp' )
Switch to Django 1.2+ method of specifying databases.
Switch to Django 1.2+ method of specifying databases. At least this way the tests run. Even though they do not pass yet.
Python
bsd-3-clause
tsouvarev/django-money,recklessromeo/django-money,iXioN/django-money,pjdelport/django-money,recklessromeo/django-money,rescale/django-money,tsouvarev/django-money,iXioN/django-money,AlexRiina/django-money
a2142fb8a592a9ad9b4870d4685ec02cfa621a77
tests/settings.py
tests/settings.py
import os import urllib TRUSTED_ROOT_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer" ) SECRET_KEY = "notsecr3t" IAP_SETTINGS = { "TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE, "PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations", } if not os.path.isfile(TRU...
import os import urllib TRUSTED_ROOT_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer" ) SECRET_KEY = "notsecr3t" IAP_SETTINGS = { "TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE, "PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations", } if not os.path.isfile(TRU...
Fix cert retreival on python 3
Fix cert retreival on python 3
Python
mit
educreations/python-iap
18603df8d13cf0eff753cb713e6c52ae30179f30
experiments/camera-stdin-stdout/bg-subtract.py
experiments/camera-stdin-stdout/bg-subtract.py
#!/usr/bin/python import cv2 import ImageReader escape_key = 27 reader = ImageReader.ImageReader() fgbg = cv2.createBackgroundSubtractorMOG2() while True: imgread, img = reader.decode() if imgread: fgmask = fgbg.apply(img) cv2.imshow("frame", fgmask) key = cv2.waitKey(1) & 0xFF if k...
#!/usr/bin/python import cv2 import ImageReader import numpy as np import sys escape_key = 27 reader = ImageReader.ImageReader() fgbg = cv2.createBackgroundSubtractorMOG2() while True: imgread, img = reader.decode() if imgread: fgmask = fgbg.apply(img) retval, encodedimage = cv2.imencode("....
Print to stdout the changed video
Print to stdout the changed video
Python
mit
Mindavi/Positiebepalingssysteem
8771bbdba5b10a3b9fab2822eccdec64d221edb4
catalog/admin.py
catalog/admin.py
from django.contrib import admin from .models import Author, Book, BookInstance, Genre, Language # admin.site.register(Book) # admin.site.register(Author) admin.site.register(Genre) # admin.site.register(BookInstance) admin.site.register(Language) # Define the admin class class AuthorAdmin(admin.ModelAdmin): li...
from django.contrib import admin from .models import Author, Book, BookInstance, Genre, Language # admin.site.register(Book) # admin.site.register(Author) admin.site.register(Genre) # admin.site.register(BookInstance) admin.site.register(Language) class AuthorsInstanceInline(admin.TabularInline): model = Book ...
Configure BookInstance list view and add an inline listing
Configure BookInstance list view and add an inline listing
Python
bsd-3-clause
pavlenk0/my-catalog,pavlenk0/my-catalog
fe34a904af1d691f96b19c87ee11129eecb09dc5
byceps/blueprints/snippet_admin/service.py
byceps/blueprints/snippet_admin/service.py
# -*- coding: utf-8 -*- """ byceps.blueprints.snippet_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from difflib import HtmlDiff from ...database import db from ..party.models import Party from ..snippet.models....
# -*- coding: utf-8 -*- """ byceps.blueprints.snippet_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from difflib import HtmlDiff from ...database import db from ..party.models import Party from ..snippet.models....
Handle values to be compared being `None`.
Handle values to be compared being `None`.
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
946ef89ea55c30b9eb6684b4d73e96b05cf5d23d
aspen/server.py
aspen/server.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorit...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algor...
Fix CLI api (was missing entrypoint hook)
Fix CLI api (was missing entrypoint hook)
Python
mit
gratipay/aspen.py,gratipay/aspen.py
11f36192f1b74cd68d90a9cc0ed592c0c1b0148d
cdr_stats/mongodb_connection_middleware.py
cdr_stats/mongodb_connection_middleware.py
from django.conf import settings from django.http import HttpResponseRedirect from pymongo.connection import Connection from pymongo.errors import ConnectionFailure class MongodbConnectionMiddleware(object): def process_request(self, request): try: connection = Connection(settings.CDR_MONGO_HO...
from django.conf import settings from django import http from django.http import HttpResponseRedirect from pymongo.connection import Connection from pymongo.errors import ConnectionFailure class MongodbConnectionMiddleware(object): def process_request(self, request): try: connection = Connecti...
Add middleware check for existing data
Add middleware check for existing data
Python
mpl-2.0
Star2Billing/cdr-stats,Star2Billing/cdr-stats,cdr-stats/cdr-stats,areski/cdr-stats,areski/cdr-stats,areski/cdr-stats,cdr-stats/cdr-stats,cdr-stats/cdr-stats,cdr-stats/cdr-stats,areski/cdr-stats,Star2Billing/cdr-stats,Star2Billing/cdr-stats
6ef3e8778ad05c1dddcf6660f24f762f1725b906
features/environment.py
features/environment.py
import os import tempfile from flask import json import config def before_scenario(context, scenario): context.db_fd, context.db_url = tempfile.mkstemp() config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url import tsserver tsserver.app.config['TESTING'] = True context.app = tsserver.a...
import os import tempfile from flask import json import tsserver # If set to True, each time the test is run, new database is created as a # temporary file. If the value is equal to False, tests will be using SQLite # in-memory database. USE_DB_TEMP_FILE = False def before_scenario(context, scenario): if USE_...
Use SQLite in-memory database in tests
Use SQLite in-memory database in tests Also, probably fix temporary databases not working.
Python
mit
m4tx/techswarm-server
ec0a27694454f0765f63f9c762d42190759fd672
utils/templatetags/text_tags.py
utils/templatetags/text_tags.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Erik Stein <code@classlibrary.net>, 2015 import re from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from .. import text a...
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Erik Stein <code@classlibrary.net>, 2015 import re from django import template from django.template.defaultfilters import stringfilter from django.utils.encoding import force_text from django.utils.html import conditional_escape from django.utils.safes...
Make sure conditional_punctuation can handle all value type (using force_text).
Make sure conditional_punctuation can handle all value type (using force_text).
Python
mit
sha-red/django-shared-utils,sha-red/django-shared-utils
f410b51f850d2fb75de16d9de4e95be5eb7a4e07
python/peacock/utils/TextSubWindow.py
python/peacock/utils/TextSubWindow.py
from PyQt5 import QtCore, QtWidgets class TextSubWindow(QtWidgets.QTextEdit): """ TextEdit that saves it size when it closes and closes itself if the main widget disappears. """ def __init__(self): super(TextSubWindow, self).__init__() self.setWindowFlags(QtCore.Qt.SubWindow) sel...
from PyQt5 import QtWidgets class TextSubWindow(QtWidgets.QTextEdit): """ TextEdit that saves it size when it closes and closes itself if the main widget disappears. """ def __init__(self): super(TextSubWindow, self).__init__() self._size = None def sizeHint(self, *args): ""...
Fix problem with copying from text window.
Fix problem with copying from text window. closes #9843
Python
lgpl-2.1
harterj/moose,jessecarterMOOSE/moose,yipenggao/moose,yipenggao/moose,milljm/moose,harterj/moose,laagesen/moose,Chuban/moose,andrsd/moose,permcody/moose,dschwen/moose,milljm/moose,laagesen/moose,permcody/moose,laagesen/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,bwspenc/moose,dschwen/moose,sapitts/moose,yipenggao/...
4dfe50691b911d05be9a82946df77e234283ffe2
codejail/util.py
codejail/util.py
"""Helpers for codejail.""" import contextlib import os import shutil import tempfile class TempDirectory(object): def __init__(self): self.temp_dir = tempfile.mkdtemp(prefix="codejail-") # Make directory readable by other users ('sandbox' user needs to be # able to read it). os.c...
"""Helpers for codejail.""" import contextlib import os import shutil import tempfile @contextlib.contextmanager def temp_directory(): """ A context manager to make and use a temp directory. The directory will be removed when done. """ temp_dir = tempfile.mkdtemp(prefix="codejail-") # Make di...
Simplify these decorators, since we don't use the classes here anyway.
Simplify these decorators, since we don't use the classes here anyway.
Python
apache-2.0
edx/codejail,StepicOrg/codejail
c0808574aaf410683f9c405e98be74a3ad4f4f2c
tests/events_test.py
tests/events_test.py
from unittest import TestCase from mock import Mock from nyuki.events import EventManager, Event, on_event class Loop(Mock): STACK = list() def async(self, cb, *args): self.STACK.append(cb) class TestEventManager(TestCase): def setUp(self): loop = Mock() self.manager = EventM...
from unittest import TestCase from mock import Mock from nyuki.events import EventManager, Event, on_event class TestOnEvent(TestCase): def test_001_call(self): @on_event(Event.Connected, Event.Disconnected) def test(): pass self.assertIsInstance(test.on_event, set) class T...
Add unit tests on events.
Add unit tests on events.
Python
apache-2.0
optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki
6aa53f1fda74eb10051cb0bcc315f7db7dee1b57
tests/test_propagation.py
tests/test_propagation.py
from opentracing import Format from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.set_baggage_item("foo", "bar") opname = 'op' tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format,...
import pytest from opentracing import Format, UnsupportedFormatException from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.context.sampled = False sp.set_baggage_item("foo", "bar") opname = 'op' # Test invalid ty...
Add baggage and invalid carrier tests
Add baggage and invalid carrier tests
Python
apache-2.0
opentracing/basictracer-python
13a0c8b822582f84ff393298b13cf1e43642f825
tests/test_stacks_file.py
tests/test_stacks_file.py
import json from dmaws.stacks import Stack from dmaws.context import Context def is_true(x): assert x def is_in(a, b): assert a in b def valid_stack_json(stack): text = stack.build('stage', 'env', {}).template_body template = json.loads(text) assert 'Parameters' in template assert set(te...
import os import json from dmaws.stacks import Stack from dmaws.context import Context def is_true(x): assert x def is_in(a, b): assert a in b def valid_stack_json(ctx, stack): text = stack.build('stage', 'env', ctx.variables).template_body template = json.loads(text) assert 'Parameters' in ...
Load default var files when testing template JSON
Load default var files when testing template JSON Since template Jinja processing has access to the template variables we need to load the default files when testing the JSON output.
Python
mit
alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws
6aabf31aeb6766677f805bd4c0d5e4fc26522e53
tests/test_memory.py
tests/test_memory.py
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = f...
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = f...
Disable test_object_size under CPython 3.8
tests/memory: Disable test_object_size under CPython 3.8
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
9712183d01ef95fcd28ed1632346371127ec8a3e
tests/window_test.py
tests/window_test.py
#!/usr/bin/env python # encoding: utf-8 """Tests window.py for vimiv's test suite.""" from unittest import main from vimiv_testcase import VimivTestCase, refresh_gui class WindowTest(VimivTestCase): """Window Tests.""" @classmethod def setUpClass(cls): cls.init_test(cls, ["vimiv/testimages/"]) ...
#!/usr/bin/env python # encoding: utf-8 """Tests window.py for vimiv's test suite.""" import os from unittest import main, skipUnless from vimiv_testcase import VimivTestCase, refresh_gui class WindowTest(VimivTestCase): """Window Tests.""" @classmethod def setUpClass(cls): cls.init_test(cls, ["...
Add test for checking window resizing
Add test for checking window resizing Test if the variable vimiv["window"].winsize is adjusted when resizing the window. This is only guaranteed to work in Xvfb as e.g. tiling window managers do not react to the resize from Gtk.
Python
mit
karlch/vimiv,karlch/vimiv,karlch/vimiv
7917716ebd11770c5d4d0634b39e32e4f577ab71
tests/test_urls.py
tests/test_urls.py
from unittest import TestCase class TestURLs(TestCase): pass
from unittest import TestCase from django.contrib.auth import views from django.core.urlresolvers import resolve, reverse class URLsMixin(object): """ A TestCase Mixin with a check_url helper method for testing urls. Pirated with slight modifications from incuna_test_utils https://github.com/incuna/i...
Add lots of URL tests.
Add lots of URL tests. * The URLsMixin from incuna_test_utils/testcases/urls.py isn't quite doing what we want here, so rip it off and make a small modification (resolve(...).func.cls -> resolve(...).func). * Add lots of tests for the django.contrib.auth views that we're using (the others are more complex).
Python
bsd-2-clause
incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth,incuna/incuna-auth
322997e229457bf43ee2281993ccdc30c8455244
tests/test_util.py
tests/test_util.py
from archivebox import util def test_download_url_downloads_content(): text = util.download_url("https://example.com") assert "Example Domain" in text
from archivebox import util def test_download_url_downloads_content(): text = util.download_url("http://localhost:8080/static/example.com.html") assert "Example Domain" in text
Refactor util tests to use local webserver
test: Refactor util tests to use local webserver
Python
mit
pirate/bookmark-archiver,pirate/bookmark-archiver,pirate/bookmark-archiver
10554ed0c44f819985f9f6d1c97a265d281541a2
test/test_types.py
test/test_types.py
""" Tests for the Types module """ import unittest # pylint: disable=import-error from res import types class TestTypes(unittest.TestCase): """ Tests for the Types module """ def test_getPieceAbbreviation_empty(self): "Correctly convert a type to a character for display" self.assertEqual('.'...
""" Tests for the Types module """ import unittest # pylint: disable=import-error from res import types class TestTypes(unittest.TestCase): """ Tests for the Types module """ def test_getPieceAbbreviation_empty(self): "Correctly convert a type to a character for display" self.assertEqual('.'...
Update redundant test to check error handling
Update redundant test to check error handling
Python
mit
blairck/jaeger
d4f63a22df8bb7a866737150064d92ce7227c875
pyshould/dsl.py
pyshould/dsl.py
""" Define the names making up the domain specific language """ from .expectation import ( Expectation, ExpectationNot, ExpectationAll, ExpectationAny, ExpectationNone, OPERATOR_OR ) # Create instances to be used with the overloaded | operator should = Expectation(deferred=True) should_not = E...
""" Define the names making up the domain specific language """ from .expectation import ( Expectation, ExpectationNot, ExpectationAll, ExpectationAny, ExpectationNone, OPERATOR_OR ) # Create instances to be used with the overloaded | operator should = Expectation(deferred=True) should_not = E...
Allow multiple arguments for quantifiers
Allow multiple arguments for quantifiers
Python
mit
drslump/pyshould
3f99d7728714aed4bc19d68d2e2d410d792fe4e9
iati/core/constants.py
iati/core/constants.py
"""A module containing constants required throughout IATI library code. Warning: This contents of this module should currently be deemed private. Todo: Allow logging constants to be user-definable. """ STANDARD_VERSIONS = ['2.02'] """Define all versions of the Standard. Todo: This constant to be populate...
"""A module containing constants required throughout IATI library code. The contents of this file are not designed to be user-editable. Only edit if you know what you are doing! Warning: This contents of this module should currently be deemed private. Todo: Allow logging constants to be user-definable. """ ...
Add note that the file is not designed to be user-editable!
Add note that the file is not designed to be user-editable!
Python
mit
IATI/iati.core,IATI/iati.core
56a2848a131e411ed687eec4d6a68f1901d942dc
icforum/forum/forms.py
icforum/forum/forms.py
from django import forms from django.contrib.auth import authenticate from .models import * class SignInForm(forms.Form): username = forms.CharField(max_length=100, label='Username') password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super(Si...
from django import forms from django.contrib.auth import authenticate from .models import * class SignInForm(forms.Form): username = forms.CharField(max_length=100, label='Username') password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super(Si...
Fix label on "new message" form
Fix label on "new message" form
Python
apache-2.0
rdujardin/icforum,rdujardin/icforum,rdujardin/icforum
4bb72952c934dd6aea3db393226d37eb1b0eb72e
penelophant/models/auctions/DoubleBlindAuction.py
penelophant/models/auctions/DoubleBlindAuction.py
""" Double Blind Auction implementation """ from penelophant.models.Auction import Auction class DoubleBlindAuction(Auction): """ Double Blind Auction implementation """ __type__ = 'doubleblind' __name__ = 'Double-Blind Auction' __mapper_args__ = {'polymorphic_identity': __type__}
""" Double Blind Auction implementation """ from penelophant.models.Auction import Auction class DoubleBlindAuction(Auction): """ Double Blind Auction implementation """ __type__ = 'doubleblind' __name__ = 'Double-Blind Auction' __mapper_args__ = {'polymorphic_identity': __type__} show_highest_bid = False
Add disallowing of double blind auction highest bids being disclosed
Add disallowing of double blind auction highest bids being disclosed
Python
apache-2.0
kevinoconnor7/penelophant,kevinoconnor7/penelophant
9f43d877aed9eeca9fe1b2a8c3a19c034b5f3dfb
armstrong/apps/related_content/models.py
armstrong/apps/related_content/models.py
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from . import managers class RelatedType(models.Model): title = models.CharField(max_length=100) def __unicode__(self): return self.title class RelatedContent(mod...
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from genericm2m.models import RelatedObjectsDescriptor from . import managers class RelatedObjectsField(RelatedObjectsDescriptor): def __init__(self, model=None, from_field="sou...
Add in field for making a `related` field on objects.
Add in field for making a `related` field on objects. Big thanks to @coleifer for his [django-generic-m2m][] project, we've got a field for adding `related` to other objects with minimal new code. [django-generic-m2m]: http://github.com/coleifer/django-generic-m2m
Python
apache-2.0
texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content
5cc9d99238c417ec010db44b3919873929fd1d7f
devtools/travis-ci/update_versions_json.py
devtools/travis-ci/update_versions_json.py
import json try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from mdtraj import version if not version.release: print("This is not a release.") exit(0) URL = 'http://www.msmbuilder.org' versions = json.load(urlopen(URL + '/versions.json')) # new release so all ...
import json try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from mdtraj import version if not version.release: print("This is not a release.") exit(0) URL = 'http://www.msmbuilder.org' versions = json.load(urlopen(URL + '/versions.json')) # new release so all ...
Add 'display' key to versions.json
Add 'display' key to versions.json
Python
lgpl-2.1
mattwthompson/mdtraj,leeping/mdtraj,ctk3b/mdtraj,msultan/mdtraj,mattwthompson/mdtraj,rmcgibbo/mdtraj,dwhswenson/mdtraj,rmcgibbo/mdtraj,ctk3b/mdtraj,leeping/mdtraj,leeping/mdtraj,gph82/mdtraj,tcmoore3/mdtraj,gph82/mdtraj,ctk3b/mdtraj,msultan/mdtraj,tcmoore3/mdtraj,gph82/mdtraj,msultan/mdtraj,mdtraj/mdtraj,mattwthompson/...
8258c451de6d94936d15d772fcbf3da24f6fb4b2
byceps/services/email/transfer/models.py
byceps/services/email/transfer/models.py
""" byceps.services.email.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from dataclasses import dataclass from email.utils import formataddr from ....typing import BrandID ...
""" byceps.services.email.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from dataclasses import dataclass from email.utils import formataddr from typing import Optional fro...
Make sender address name field optional
Make sender address name field optional
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
791e03258c53379dde587a4bf0c05e0d2bc053ad
test_tbselenium.py
test_tbselenium.py
#!/usr/bin/env python2.7 import os import site import sys sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium')) # site.addsitedir(path.join(getcwd(), 'tor-browser-selenium')) from tbselenium.tbdriver import TorBrowserDriver with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver: driver.ge...
#!/usr/bin/env python # NOTICE: this is only working right now because I'm working from a dirty # submodule where I've implemented this # https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee # commit import os import site site.addsitedir(os.path.join(os.getcwd(), 'tor-brow...
Fix test to work with patched tbdriver.py (see NOTICE in diff)
Fix test to work with patched tbdriver.py (see NOTICE in diff)
Python
agpl-3.0
freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop
e525a819724f149186b5b156520afe2549e5902a
UliEngineering/Electronics/Power.py
UliEngineering/Electronics/Power.py
#!/usr/bin/env python3 """ Utilities to compute the power of a device """ from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit import numpy as np __all__ = ["current_by_power", "power_by_current_and_voltage"] def current_by_power(power="25 W", voltage="230 V") -> Unit("A"): ...
#!/usr/bin/env python3 """ Utilities to compute the power of a device """ from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit __all__ = ["current_by_power", "power_by_current_and_voltage"] def current_by_power(power="25 W", voltage="230 V") -> Unit("A"): """ Given a d...
Remove unused numpy input (codacy)
Remove unused numpy input (codacy)
Python
apache-2.0
ulikoehler/UliEngineering
79f7d8052333fcace914fa27ea2deb5f0d7cdbfc
readers/models.py
readers/models.py
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, IBOOKS), (KINDLE, KINDLE), ) ...
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, 'iBooks (.epub, .pdf)'), (KINDLE, 'K...
Make what reader can handle what clearer
Make what reader can handle what clearer
Python
mit
phildini/bockus,phildini/bockus,phildini/bockus
5834127e59b1da93bd814575cd7cbba391e253c8
run_borealis.py
run_borealis.py
from borealis import BotBorealis try: print("Welcome to BOREALIS.") print("Initializing BOREALIS and its subcomponents.") bot = BotBorealis("config.yml") print("Initialization completed. Readying subcomponents.") bot.setup() print("Subcomponents ready. All systems functional.") print("Starting BORE...
from borealis import BotBorealis import time while True: bot = None try: print("Welcome to BOREALIS.") print("Initializing BOREALIS and its subcomponents.") bot = BotBorealis("config.yml") print("Initialization completed. Readying subcomponents.") bot.setup() print("Subcomponents ready. ...
Implement recovery Bot will now automatically restart after an exception is caught.
Implement recovery Bot will now automatically restart after an exception is caught.
Python
agpl-3.0
Aurorastation/BOREALISbot2
50f3233a8560120cc0c55b02849f1b586cf1aa27
languages_plus/utils.py
languages_plus/utils.py
from django.core.exceptions import ObjectDoesNotExist from countries_plus.models import Country from .models import Language, CultureCode def associate_countries_and_languages(): for country in Country.objects.all(): langs = country.languages.strip(',') if langs: codes = langs.split("...
from django.core.exceptions import ObjectDoesNotExist from countries_plus.models import Country from .models import Language, CultureCode def associate_countries_and_languages(): for country in Country.objects.all(): langs = '' try: langs = country.languages.strip(',') if lang...
Fix a crash if a country has no languages spoken
Fix a crash if a country has no languages spoken
Python
mit
cordery/django-languages-plus
780a330e1f185d7c19953edb5bc1767582501197
tests/test_card.py
tests/test_card.py
""" Created on Dec 04, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ import unittest from cards.card import Card class Test_Card(unittest.TestCase): def setUp(self): self._suit = "clubs" self._rank = "10" self._c...
""" Created on Dec 04, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ import unittest from cards.card import Card class Test_Card(unittest.TestCase): def setUp(self): self._suit = "clubs" self._rank = "10" self._c...
Change ConcreteCard test class params.
Change ConcreteCard test class params.
Python
mit
johnpapa2/twenty-one,johnpapa2/twenty-one
e264224ee69cb37a02f28a6c78a231dd6d41db58
examples/web_rewrite_headers_middleware.py
examples/web_rewrite_headers_middleware.py
#!/usr/bin/env python3 """ Example for rewriting response headers by middleware. """ import asyncio from aiohttp.web import Application, Response @asyncio.coroutine def handler(request): return Response(text="Everything is fine") @asyncio.coroutine def middleware_factory(app, next_handler): @asyncio.corou...
#!/usr/bin/env python3 """ Example for rewriting response headers by middleware. """ import asyncio from aiohttp.web import Application, Response, HTTPException @asyncio.coroutine def handler(request): return Response(text="Everything is fine") @asyncio.coroutine def middleware_factory(app, next_handler): ...
Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found
Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found
Python
apache-2.0
alex-eri/aiohttp-1,jettify/aiohttp,hellysmile/aiohttp,z2v/aiohttp,juliatem/aiohttp,rutsky/aiohttp,AlexLisovoy/aiohttp,KeepSafe/aiohttp,mind1master/aiohttp,rutsky/aiohttp,Eyepea/aiohttp,jojurajan/aiohttp,mind1master/aiohttp,jashandeep-sohi/aiohttp,mind1master/aiohttp,alexsdutton/aiohttp,elastic-coders/aiohttp,pathcl/aio...
b75a9eab312a2ac787e4b0e44115f8bad4508418
route/__init__.py
route/__init__.py
class Route(object): def __init__(self, ip, domain): self.ip = ip self.domain = domain def __str__(self): return self.domain def query(self): """ search domain routing info """ pass def register(self): """ register domain nginx reverse proxy """ ...
from route.db import db_session from route.models import Domain import os import subprocess class Route(object): def __init__(self, ip, domain): self.ip = ip self.domain = domain def __str__(self): return self.domain def search(self, option, value): """ search domain rou...
Add register, restart, write to handle nginx
Add register, restart, write to handle nginx
Python
apache-2.0
bunseokbot/proxy_register,bunseokbot/proxy_register
90cd7a194ce1294d6b14b819b10ca62e3d058cb9
auslib/test/web/test_dockerflow.py
auslib/test/web/test_dockerflow.py
import mock from auslib.test.web.test_client import ClientTestBase class TestDockerflowEndpoints(ClientTestBase): def testVersion(self): ret = self.client.get("/__version__") self.assertEquals(ret.data, """ { "source":"https://github.com/mozilla/balrog", "version":"1.0", "commit":"abcdef12...
import mock from auslib.test.web.test_client import ClientTestBase class TestDockerflowEndpoints(ClientTestBase): def testVersion(self): ret = self.client.get("/__version__") self.assertEquals(ret.data, """ { "source":"https://github.com/mozilla/balrog", "version":"1.0", "commit":"abcdef12...
Add test to make sure public facing app raises exception when it hits an error.
Add test to make sure public facing app raises exception when it hits an error.
Python
mpl-2.0
aksareen/balrog,nurav/balrog,nurav/balrog,mozbhearsum/balrog,tieu/balrog,mozbhearsum/balrog,aksareen/balrog,testbhearsum/balrog,testbhearsum/balrog,nurav/balrog,aksareen/balrog,tieu/balrog,nurav/balrog,tieu/balrog,mozbhearsum/balrog,tieu/balrog,testbhearsum/balrog,mozbhearsum/balrog,aksareen/balrog,testbhearsum/balrog
c7daef487fee51b68d410d2f4be3fd16068c7d5a
tests/export/test_task_types_to_csv.py
tests/export/test_task_types_to_csv.py
from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_d...
from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_d...
Fix task type export test
Fix task type export test
Python
agpl-3.0
cgwire/zou
b77d4a534f5f6435f0f60c0a082b9ae02673d574
tests/twisted/connect/network-error.py
tests/twisted/connect/network-error.py
""" Connection is disconnected because server closes its TCP stream abruptly. """ from gabbletest import exec_test from servicetest import EventPattern import constants as cs import sys def test(q, bus, conn, stream): conn.Connect() q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_S...
""" Connection is disconnected because server closes its TCP stream abruptly. """ from gabbletest import exec_test from servicetest import EventPattern import constants as cs import sys def test(q, bus, conn, stream): conn.Connect() q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_S...
Make sure state change signal to 'disconnected' is also sent.
Make sure state change signal to 'disconnected' is also sent.
Python
lgpl-2.1
Ziemin/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,Ziemin/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble,mlundblad/telepathy-gabble
d1614d3747f72c1f32e74afb6e4b98eb476c7266
utils/layers_test.py
utils/layers_test.py
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs =...
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs =...
Add Second Shape Test for Layers Util
Add Second Shape Test for Layers Util
Python
apache-2.0
googleinterns/audio_synthesis
2450955e2beb14e4c6ba0394e4bcd64e2ce2e4ec
wordcloud/views.py
wordcloud/views.py
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" max_entries = int(max_entri...
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" max_entries = int(max_entri...
Add diagnostic output for when X-SendFile is misconfigured
Add diagnostic output for when X-SendFile is misconfigured
Python
agpl-3.0
mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola
4955e830d3130a6ae86d4a1c37db23777ee792d7
go_http/__init__.py
go_http/__init__.py
"""Vumi Go HTTP API client library.""" from .send import HttpApiSender, LoggingSender __version__ = "0.3.1a0" __all__ = [ 'HttpApiSender', 'LoggingSender', ]
"""Vumi Go HTTP API client library.""" from .send import HttpApiSender, LoggingSender from .account import AccountApiClient __version__ = "0.3.1a0" __all__ = [ 'HttpApiSender', 'LoggingSender', 'AccountApiClient', ]
Add AccountApiClient to top-level package.
Add AccountApiClient to top-level package.
Python
bsd-3-clause
praekelt/go-http-api,praekelt/go-http-api
e37e964bf9d2819c0234303d31ed2839c317be04
openquake/engine/tests/export/core_test.py
openquake/engine/tests/export/core_test.py
# Copyright (c) 2010-2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distr...
# Copyright (c) 2010-2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distr...
Fix a broken export test
Fix a broken export test
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
546a4681aa54ba183e956d220e98ef67ae6de691
user/decorators.py
user/decorators.py
from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect def custom_login_required(view): # view argument must be a function def new_view(request, *args, **kwargs): user = get_user(request) if user.is_authenticated(): return v...
from functools import wraps from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect from django.utils.decorators import \ available_attrs def custom_login_required(view): # view argument must be a function @wraps(view, assigned=available_attrs(view...
Use functools.wraps to copy view signature.
Ch20: Use functools.wraps to copy view signature.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
a778a41c8deb6fd9812e405143e34679122c18db
website/addons/base/utils.py
website/addons/base/utils.py
from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup return { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_s...
from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup user_addon = user.get_addon(config.short_name) ret = { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_tem...
Add user_settings to serialized addon settings
Add user_settings to serialized addon settings
Python
apache-2.0
ZobairAlijan/osf.io,leb2dg/osf.io,doublebits/osf.io,mluo613/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,mattclark/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,SSJohns/osf.io,billyhunt/osf.io,pattisdr/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,Nesiehr/osf....
13774b20f18d23dfb69c65dd151e3aed9734a88f
website/core/settings/loc.py
website/core/settings/loc.py
"""Local settings and globals.""" import sys from os.path import normpath, join from .base import * # Import secrets sys.path.append( abspath(join(PROJECT_ROOT, '../secrets/buzz/stg')) ) from secrets import * # Set static URL STATIC_URL = '/static'
"""Local settings and globals.""" import sys from os.path import normpath, join from .base import * # Import secrets -- not needed #sys.path.append( # abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg')) #) #from secrets import * # Set static URL STATIC_URL = '/static'
Comment out secrets import (not needed for this project)
Comment out secrets import (not needed for this project)
Python
mpl-2.0
stea4lth/TimelineJS,noikiy/TimelineJS,azeemmufti/TimelineJS,ryekee/TimelineJS,djaney/TimelineJS,1modm/TimelineJS,zstao/TimelineJS,wangjun/TimelineJS,1modm/TimelineJS,stea4lth/TimelineJS,matt-edgedesign/Timelinejs,LauraHilliger/TimelineJS,djaney/TimelineJS,ycaihua/TimelineJS,deenjohn/TimelineJS,ryekee/TimelineJS,deenjoh...
1cb7581f63d0d9d4e6eca69316930912c41a4fb5
Instanssi/admin_upload/models.py
Instanssi/admin_upload/models.py
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.contrib import admin class UploadedFile(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tie...
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.contrib import admin import os.path class UploadedFile(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, ...
Add helper function for getting name from UploadedFile, add model to admin.
admin_upload: Add helper function for getting name from UploadedFile, add model to admin.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
d213aa242b6293a67ba13859a81af4354d81f522
h2o-py/tests/testdir_algos/gam/pyunit_PUBDEV_7798_overlapped_knots.py
h2o-py/tests/testdir_algos/gam/pyunit_PUBDEV_7798_overlapped_knots.py
import h2o import numpy as np from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator from tests import pyunit_utils def knots_error(): # load and prepare California housing dataset np.random.seed(1234) data = h2o.H2OFrame( python_obj={'C1': list(np.random.randint(0, 9, size=1000)), ...
import h2o import numpy as np from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator from tests import pyunit_utils def knots_error(): # load and prepare California housing dataset np.random.seed(1234) data = h2o.H2OFrame( python_obj={'C1': list(np.random.randint(0, 9, size=1000)), ...
Add assert to num knots validation unit test
Add assert to num knots validation unit test
Python
apache-2.0
h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3
380baa34af7e8a704780f0ec535b626f4a286e23
deflect/admin.py
deflect/admin.py
from django.contrib import admin from .models import RedirectURL class RedirectURLAdmin(admin.ModelAdmin): list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',) list_filter = ('creator__username', 'campaign', 'medium',) ordering = ('-last_used',) readonly_fields =...
from django.contrib import admin from .models import RedirectURL class RedirectURLAdmin(admin.ModelAdmin): list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',) list_filter = ('creator__username', 'campaign', 'medium',) ordering = ('-last_used',) readonly_fields =...
Fix model creator updating on change event
Fix model creator updating on change event
Python
bsd-3-clause
jbittel/django-deflect
cc48ad87026b57b02530322b3c27f2d60e94f2e4
packages/mono_crypto.py
packages/mono_crypto.py
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): ...
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): ...
Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve
Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve
Python
mit
mono/bockbuild,mono/bockbuild
1cda84c7f23c6a5e89c9f871dba5d12c00789d1a
extract_contamination.py
extract_contamination.py
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip()....
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip()....
Handle empty fastq_screen files properly.
Handle empty fastq_screen files properly.
Python
apache-2.0
pombo-lab/gamtools,pombo-lab/gamtools
d9ab07c9c984d50ff93040d0220e4a3997e29f79
fluent_comments/email.py
fluent_comments/email.py
from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string try: from django.contrib.sites.shortcuts import get_current_site # Django 1.9+ except ImportError: from django.contrib.sites.models import get_current_site def send_comment_posted(comm...
from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.encoding import force_text try: from django.contrib.sites.shortcuts import get_current_site # Django 1.9+ except ImportError: from django.contrib.sites.models import ge...
Use force_text() to get page title
Use force_text() to get page title Some models might handle __unicode__/__str__ badly
Python
apache-2.0
edoburu/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments
815c246f1ef185e24991efc4075b2358c7955c6c
onadata/libs/utils/storage.py
onadata/libs/utils/storage.py
# coding: utf-8 import os import shutil from django.core.files.storage import get_storage_class def delete_user_storage(username): storage = get_storage_class()() def _recursive_delete(path): directories, files = storage.listdir(path) for file_ in files: storage.delete(os.path.j...
# coding: utf-8 import os import shutil from django.core.files.storage import FileSystemStorage, get_storage_class def delete_user_storage(username): storage = get_storage_class()() def _recursive_delete(path): directories, files = storage.listdir(path) for file_ in files: stora...
Use `isinstance()` at the cost of an extra import
Use `isinstance()` at the cost of an extra import
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
b242de3217ad9cf6a98ca2513ed1e4f66d2537ad
tests/NongeneratingSymbolsRemove/SimpleTest.py
tests/NongeneratingSymbolsRemove/SimpleTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy-transforms """ from unittest import TestCase, main from grammpy import * from grammpy_transforms import ContextFree class SimpleTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy-transforms """ from unittest import TestCase, main from grammpy import * from grammpy_transforms import ContextFree class A(Nonterminal): pass class B(Nonterminal): pass class C(Nonterminal): p...
Add simple test of removing nongenerating symbols
Add simple test of removing nongenerating symbols
Python
mit
PatrikValkovic/grammpy
dd8c4843b7872023e276247a4d8de052b42fa9a6
token_stream.py
token_stream.py
# '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3} class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator...
# '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3} operators = { '+': {'prec': 10, 'assoc': 'left'}, '*': {'prec': 20, 'assoc': 'left'} } class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return...
Define precedence and associativity for operators
Define precedence and associativity for operators
Python
mit
babu-thomas/calculator-parser
b834f553501d4c9ba47bcad6497555aacc06249c
gavel/controllers/api.py
gavel/controllers/api.py
from gavel import app from gavel.models import * import gavel.utils as utils from flask import Response @app.route('/api/items.csv') @utils.requires_auth def item_dump(): items = Item.query.order_by(desc(Item.mu)).all() data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']] data += [...
from gavel import app from gavel.models import * import gavel.utils as utils from flask import Response @app.route('/api/items.csv') @utils.requires_auth def item_dump(): items = Item.query.order_by(desc(Item.mu)).all() data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']] data += [...
Add API endpoint for getting decisions
Add API endpoint for getting decisions
Python
agpl-3.0
atagh/gavel-clone,anishathalye/gavel,atagh/gavel-clone,anishathalye/gavel,anishathalye/gavel
31d0af7d5f3a984d4f6c7be62d599553a3bc7c08
opps/articles/utils.py
opps/articles/utils.py
# -*- coding: utf-8 -*- from django.utils import timezone from opps.articles.models import ArticleBox, Article def set_context_data(self, SUPER, **kwargs): context = super(SUPER, self).get_context_data(**kwargs) article = Article.objects.filter( site=self.site, channel_long_slug__in=self.cha...
# -*- coding: utf-8 -*- from django.utils import timezone from opps.articles.models import ArticleBox, Article def set_context_data(self, SUPER, **kwargs): context = super(SUPER, self).get_context_data(**kwargs) article = Article.objects.filter( site=self.site, channel_long_slug__in=self.cha...
Add channel root on set context data, sent to template
Add channel root on set context data, sent to template
Python
mit
YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps
eb8884ce0c7dec3433d76c49942f0531cc96d915
plugin/main.py
plugin/main.py
#!/usr/bin/env python """ Deploy builds to a Rancher orchestrated stack using rancher-compose """ import os import drone import subprocess def main(): """The main entrypoint for the plugin.""" payload = drone.plugin.get_input() vargs = payload["vargs"] # Required fields should raise an error url...
#!/usr/bin/env python """ Deploy builds to a Rancher orchestrated stack using rancher-compose """ import os import drone import subprocess def main(): """The main entrypoint for the plugin.""" payload = drone.plugin.get_input() vargs = payload["vargs"] # Required fields should raise an error os....
Set environmental vars for rancher-compose to work
Set environmental vars for rancher-compose to work
Python
apache-2.0
dangerfarms/drone-rancher
a7028ca3d3dea5a9f8891dfd2947b671bbe02b7e
pentai/gui/my_button.py
pentai/gui/my_button.py
from kivy.uix.button import Button import audio as a_m class MyButton(Button): def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not hasattr(self, "silent"): a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs...
from kivy.uix.button import Button import audio as a_m from pentai.base.defines import * class MyButton(Button): def __init__(self, *args, **kwargs): super(MyButton, self).__init__(*args, **kwargs) self.silent = False def on_touch_up(self, touch, *args, **kwargs): if self.collide_poin...
Make "silent" an attribute from __init__
Make "silent" an attribute from __init__
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
ad07405ca877d65f30c9acd19abb4e782d854eaa
workshops/views.py
workshops/views.py
from django.views.generic import ListView, DetailView from config.utils import get_active_event from workshops.models import Workshop class WorkshopListView(ListView): template_name = 'workshops/list_workshops.html' model = Workshop context_object_name = 'workshops' def get_queryset(self): ev...
from django.views.generic import ListView, DetailView from config.utils import get_active_event from workshops.models import Workshop class WorkshopListView(ListView): template_name = 'workshops/list_workshops.html' model = Workshop context_object_name = 'workshops' def get_queryset(self): ev...
Order workshops by start date before title
Order workshops by start date before title
Python
bsd-3-clause
WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web
a39a7eb7d43282337d3e3df10921a1b0d9f0e3e4
odeintw/__init__.py
odeintw/__init__.py
# Copyright (c) 2014, Warren Weckesser # All rights reserved. # See the LICENSE file for license information. from numpy.testing import Tester as _Tester from ._odeintw import odeintw __version__ = "0.1.2.dev3" test = _Tester().test
# Copyright (c) 2014, Warren Weckesser # All rights reserved. # See the LICENSE file for license information. from ._odeintw import odeintw __version__ = "0.1.2.dev3"
Remove some unused test infrastructure
MAINT: Remove some unused test infrastructure
Python
bsd-3-clause
WarrenWeckesser/odeintw
a116b22a76b0f833aa9f7f2e2ce4b36a95bc9ba0
freight/tasks/send_pending_notifications.py
freight/tasks/send_pending_notifications.py
from __future__ import absolute_import import logging from freight import notifiers from freight.config import celery, redis from freight.models import Task from freight.notifiers import queue from freight.utils.redis import lock @celery.task(name='freight.send_pending_notifications', max_retries=None) def send_pen...
from __future__ import absolute_import import logging from freight import notifiers from freight.config import celery, redis from freight.models import Task from freight.notifiers import queue from freight.utils.redis import lock @celery.task(name='freight.send_pending_notifications', max_retries=None) def send_pen...
Add logging when no notifications due
Add logging when no notifications due
Python
apache-2.0
getsentry/freight,klynton/freight,rshk/freight,rshk/freight,rshk/freight,klynton/freight,rshk/freight,getsentry/freight,klynton/freight,klynton/freight,getsentry/freight,getsentry/freight,getsentry/freight
882fc867ab115f2b84f2f185bcebf3eb4a1d2fc8
core/forms.py
core/forms.py
from django.forms import ModelForm from django.forms.fields import CharField from models import UserProfile class UserProfileForm(ModelForm): first_name = CharField(label='First name', required=False) last_name = CharField(label='Last name', required=False) class Meta: model = UserProfile ...
from django.forms import ModelForm from django.forms.fields import CharField from models import UserProfile class UserProfileForm(ModelForm): first_name = CharField(label='First name', required=False) last_name = CharField(label='Last name', required=False) class Meta: model = UserProfile ...
Fix profile creation. (Need tests badly).
Fix profile creation. (Need tests badly).
Python
mit
kenwang76/readthedocs.org,soulshake/readthedocs.org,nyergler/pythonslides,gjtorikian/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,ojii/readthedocs.org,LukasBoersma/readthedocs.org,mhils/readthedocs.org,sid-kap/readthedocs.org,michaelmcandrew/readthedocs.org,michaelmcandrew/readthedocs.org,oji...
0874b3e5d5316c53d1d941e4e337bec45469bf6d
core/hybra.py
core/hybra.py
import data_loader import descriptives import network as module_network import timeline as module_timeline import wordclouds as module_wordclouds __sources = dir( data_loader ) __sources = filter( lambda x: x.startswith('load_') , __sources ) __sources = map( lambda x: x[5:], __sources ) def data_sources(): retur...
import data_loader import re import descriptives import network as module_network import timeline as module_timeline import wordclouds as module_wordclouds __sources = dir( data_loader ) __sources = filter( lambda x: x.startswith('load_') , __sources ) __sources = map( lambda x: x[5:], __sources ) def data_sources():...
Add method for filtering from text
Add method for filtering from text
Python
mit
HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core
28ee229284459402d73f41e756dc95fe99f0227b
pybot/resources/urls.py
pybot/resources/urls.py
FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"
FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/"
Update URL for generic graph api url
Update URL for generic graph api url
Python
mit
ben-cunningham/python-messenger-bot,ben-cunningham/pybot
ed45016c7319d2df1f894ec17971d0d1c4d8abe1
museum_site/base.py
museum_site/base.py
from django.db import models class BaseModel(models.Model): model_name = None #title #description #preview #table_fields = [] def admin_url(self): name = self.model_name.replace("-", "_").lower() return "/admin/museum_site/{}/{}/change/".format(name, self.id) def url(self)...
from django.db import models from django.utils.safestring import mark_safe class BaseModel(models.Model): model_name = None #title #description #preview #table_fields = [] def admin_url(self): name = self.model_name.replace("-", "_").lower() return "/admin/museum_site/{}/{}/cha...
Add specific error messages for mandatory subclass methods
Add specific error messages for mandatory subclass methods
Python
mit
DrDos0016/z2,DrDos0016/z2,DrDos0016/z2
149c56ba2285d42d319b525c04fea6e4a8ea0ec5
ldaptor/protocols/ldap/__init__.py
ldaptor/protocols/ldap/__init__.py
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content. git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905
Python
lgpl-2.1
antong/ldaptor,antong/ldaptor
5dcdfa510e62d754bce6270286e42a76b37c23c4
inpassing/worker/util.py
inpassing/worker/util.py
# Copyright (c) 2017 Luke San Antonio Bialecki # All rights reserved. from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s): return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
# Copyright (c) 2017 Luke San Antonio Bialecki # All rights reserved. from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s, tz=None): ret = datetime.strptime(s, DATE_FMT) if tz: return tz.localize(ret) else: ...
Support use of local timezones when parsing date strings
Support use of local timezones when parsing date strings
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
cd9048f64c6a2184e148daf0baa7bb3be51b3268
vol/__init__.py
vol/__init__.py
# coding: utf-8 from __future__ import unicode_literals, print_function from sys import platform if platform == 'darwin': from .osx import OSXVolumeController as VolumeController else: raise NotImplementedError( 'VolumeController for {} platform has not been implemented yet'.format(platform) )
# coding: utf-8 ''' A cross platform implementation of volume control ''' from __future__ import unicode_literals, print_function from sys import platform if platform == 'darwin': from .osx import OSXVolumeController as VolumeController else: raise NotImplementedError( 'VolumeController for {} platform...
Update doc for vol pkg
Update doc for vol pkg
Python
bsd-3-clause
Microcore/AGT,Microcore/YAS
6aea2f1c3a478be0c6926f442924e1f263955430
pip_run/__init__.py
pip_run/__init__.py
import sys from . import deps from . import commands from . import launch from . import scripts def run(args=None): if args is None: args = sys.argv[1:] pip_args, params = commands.parse_script_args(args) commands.intercept(pip_args) pip_args.extend(scripts.DepsReader.search(params)) with deps.load(*deps.not_...
import sys from . import deps from . import commands from . import launch from . import scripts def run(args=None): """ Main entry point for pip-run. """ if args is None: args = sys.argv[1:] pip_args, params = commands.parse_script_args(args) commands.intercept(pip_args) pip_args.extend(scripts.DepsReader.s...
Add docstring to run function.
Add docstring to run function.
Python
mit
jaraco/rwt
1e0ac4612937583dec22a81db833c7962e91edc8
registries/views.py
registries/views.py
from django.shortcuts import render from django.conf import settings from django.http import HttpResponse from rest_framework.generics import ListAPIView from registries.models import Organization from registries.serializers import DrillerListSerializer class APIDrillerListView(ListAPIView): queryset = Organizatio...
from django.shortcuts import render from django.conf import settings from django.http import HttpResponse from rest_framework.generics import ListAPIView from registries.models import Organization from registries.serializers import DrillerListSerializer class APIDrillerListView(ListAPIView): queryset = Organizatio...
Add prefetch to reduce queries on province_state
Add prefetch to reduce queries on province_state
Python
apache-2.0
rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells
d74908f5acb5c1a88965ed086d41435e0041d85b
pyluos/modules/l0_dc_motor.py
pyluos/modules/l0_dc_motor.py
from __future__ import division from .module import Module class DCMotor(object): def __init__(self, name, delegate): self._name = name self._delegate = delegate self._speed = None @property def name(self): return self._name @property def speed(self): sel...
from __future__ import division from .module import Module class DCMotor(object): def __init__(self, name, delegate): self._name = name self._delegate = delegate self._speed = None @property def name(self): return self._name @property def speed(self): sel...
Fix l0 dc field name.
Fix l0 dc field name.
Python
mit
pollen/pyrobus
7f863c30f7e49da29530d141a76c1976e0a679ee
massa/domain.py
massa/domain.py
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, create_engine, ) metadata = MetaData() measurement = Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=Fals...
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, create_engine, ) metadata = MetaData() measurement = Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=Fals...
Add a function do make db tables.
Add a function do make db tables.
Python
mit
jaapverloop/massa
e58688d87ba1c4af718ea3e427d94f68c3df3b16
qipipe/interfaces/__init__.py
qipipe/interfaces/__init__.py
from .compress import Compress from .copy import Copy from .fix_dicom import FixDicom from .group_dicom import GroupDicom from .map_ctp import MapCTP from .move import Move from .glue import Glue from .uncompress import Uncompress from .xnat_upload import XNATUpload from .xnat_download import XNATDownload
from .compress import Compress from .copy import Copy from .fix_dicom import FixDicom from .group_dicom import GroupDicom from .map_ctp import MapCTP from .move import Move from .unpack import Unpack from .uncompress import Uncompress from .xnat_upload import XNATUpload from .xnat_download import XNATDownload from .fas...
Replace Glue interface by more restrictive Unpack.
Replace Glue interface by more restrictive Unpack.
Python
bsd-2-clause
ohsu-qin/qipipe
b2e537c2d054854d0b36ccee7567c9ba9c2a5516
modulation_test.py
modulation_test.py
import pygame import random from demodulate.cfg import * from gen_tone import * if __name__ == "__main__": pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1) pygame.mixer.init() WPM = random.uniform(2,20) pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() data = gen_tone(pattern...
import pygame import random import time from demodulate.cfg import * from modulate import * from gen_tone import * if __name__ == "__main__": pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1) pygame.mixer.init() WPM = random.uniform(2,20) pattern = chars_to_elements.letters_to_sequence("NA NA NA NA...
Make modulation test wait for sound to stop playing before exiting
Make modulation test wait for sound to stop playing before exiting
Python
mit
nickodell/morse-code
e0c07b4078caaa4220040d0e8c4ed86e3a2bf087
lextoumbourou/fabfile.py
lextoumbourou/fabfile.py
import os from fabric.api import run, env, settings, cd, put, sudo from fabric.contrib import files import private def prod(): env.hosts = list(private.PROD_SERVERS) def local(): env.hosts = ['localhost'] def deploy(): """ Deploy code to production """ git_repo = 'git://github.com/lextoum...
import os from fabric.api import run, env, settings, cd, put, sudo from fabric.contrib import files import private GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git' def prod(): env.hosts = list(private.PROD_SERVERS) def local(): env.hosts = ['localhost'] def initial_build(): """ ...
Move inital_build task into own function
Move inital_build task into own function
Python
mit
lextoumbourou/lextoumbourou.com-old,lextoumbourou/lextoumbourou.com-old
70efbd90d9d5601d368ddb5ea20a3b9910539b78
members/urls.py
members/urls.py
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url...
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), url(r'^search/(?P<name>.*)/$', 'mem...
Change url and views for login/logout to django Defaults
Change url and views for login/logout to django Defaults
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
1aa050f2d50fb206ffb1a7d06e75cc2ba27cc91b
1.py
1.py
i = input() floor = 0 for x in range(0, len(i)): if i[x] == '(': floor +=1; elif i[x] == ')': floor -=1; print(floor)
i = input() floor = 0 instruction = 0 for x in range(0, len(i)): if i[x] == '(': floor +=1 elif i[x] == ')': floor -=1 if (floor < 0 and instruction == 0): instruction = x+1 print("floor: %s" % floor) print("basement entry: %s" % instruction)
Add second part of puzzle
Add second part of puzzle
Python
mit
Walther/adventofcode,Walther/adventofcode,Walther/adventofcode
6bc6a07ee60f68e2003b5afcc752c3820a176541
astropy/conftest.py
astropy/conftest.py
# this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the astropy tree. from .tests.pytest_plugins import * try: import matplotlib except ImportError: pass else: matplotlib.use...
# this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the astropy tree. from .tests.pytest_plugins import * try: import matplotlib except ImportError: pass else: matplotlib.use...
Add Cython to py.test header
Add Cython to py.test header
Python
bsd-3-clause
kelle/astropy,tbabej/astropy,lpsinger/astropy,joergdietrich/astropy,pllim/astropy,MSeifert04/astropy,AustereCuriosity/astropy,saimn/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,tbabej/astropy,mhvk/astropy,DougBurke/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,kelle/astropy,AustereCuriosi...
1056bb70699f2c480f887b13dd28b412a7aeb6c5
opps/core/admin.py
opps/core/admin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin class PublishableAdmin(admin.ModelAdmin): """ Overrides standard admin.ModelAdmin save_model method It sets user (author) based on data from requet. """ list_display = ['title', 'channel', 'date_available', 'published']...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin class PublishableAdmin(admin.ModelAdmin): """ Overrides standard admin.ModelAdmin save_model method It sets user (author) based on data from requet. """ list_display = ['title', 'date_available', 'published'] list_f...
Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core
Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core
Python
mit
YACOWS/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps
84eb438c966d5c2794a0842dccaefea726c0dbb9
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: get slug from URL pattern.
Ch05: Tag Detail: get slug from URL pattern.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
d9d0af04ea76c6c6bd346ce417e9feb61580c90e
nuitka/plugins/commercial/__init__.py
nuitka/plugins/commercial/__init__.py
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
Make it easier to integrate commercial plugins.
Plugins: Make it easier to integrate commercial plugins.
Python
apache-2.0
kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka
badda02f6cc81a8c5670b6f53e67009a3cb8b66f
rmake/core/constants.py
rmake/core/constants.py
# # Copyright (c) 2010 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/...
# # Copyright (c) 2010 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/...
Relocate core status codes to the 450-499 range
Relocate core status codes to the 450-499 range
Python
apache-2.0
sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake3