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
c80424ca0dd8d748f7da167a588582ee94986da0
polling_stations/apps/data_importers/management/commands/import_highland.py
polling_stations/apps/data_importers/management/commands/import_highland.py
from data_importers.management.commands import BaseDemocracyCountsCsvImporter class Command(BaseDemocracyCountsCsvImporter): council_id = "HLD" addresses_name = ( "2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Districts.csv" ) stations_name = ( "2022-05-05/2022-03-24...
from data_importers.management.commands import BaseDemocracyCountsCsvImporter class Command(BaseDemocracyCountsCsvImporter): council_id = "HLD" addresses_name = ( "2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Districts.csv" ) stations_name = ( "2022-05-05/2022-03-24...
Set don't use station coords for geocoding
Set don't use station coords for geocoding
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
9ef92435a94d01d963b25e10bfb681daf04df193
dbaas/integrations/iaas/manager.py
dbaas/integrations/iaas/manager.py
from dbaas_cloudstack.provider import CloudStackProvider from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider from integrations.monitoring.manager import MonitoringManager import logging LOG = logging.getLogger(__name__) class IaaSManager(): @classmethod def destroy_instance(cls, ...
from dbaas_cloudstack.provider import CloudStackProvider from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider from integrations.monitoring.manager import MonitoringManager import logging LOG = logging.getLogger(__name__) class IaaSManager(): @classmethod def destroy_instance(cls, ...
Remove monitoring only after database quarantine
Remove monitoring only after database quarantine
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
9c4ecf0b72d86ae113fa13f210c543120635b73e
board.py
board.py
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.ze...
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init__(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy....
Fix init method, self.rows and capital booleans.
Fix init method, self.rows and capital booleans.
Python
mit
isaacarvestad/four-in-a-row
73f7f64ff5a29d5fa007ad44f2d68c6dc2ae65d7
sql/src/test/BugTracker/Tests/connect_crash.SF-1436626.py
sql/src/test/BugTracker/Tests/connect_crash.SF-1436626.py
import os, time def main(): srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB')) srv = os.popen(srvcmd, 'w') time.sleep(10) # give server time to start cltcmd = os.getenv('SQL_CLIENT') clt = os.popen(cltcmd, 'w') clt.write('select ...
import subprocess, os, time def main(): srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB')) srv = subprocess.Popen(srvcmd, shell = True, stdin = subprocess.PIPE) time.sleep(10) # give server time to start cltcmd = os.getenv('SQL_CLIENT') ...
Use the subprocess module to start processes with pipes. This seems to fix the lack of output on Windows.
Use the subprocess module to start processes with pipes. This seems to fix the lack of output on Windows.
Python
mpl-2.0
zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb
db0921e0242d478d29115179b9da2ffcd3fa35fb
micromanager/resources/__init__.py
micromanager/resources/__init__.py
from .base import ResourceBase # noqa F401 from .bucket import Bucket # noqa F401 from .sql import SQLInstance # noqa F401 from .bigquery import BQDataset # noqa F401 class Resource(): @staticmethod def factory(resource_data): resource_kind_map = { 'storage#bucket': Bucket, ...
from .base import ResourceBase # noqa F401 from .bucket import Bucket # noqa F401 from .sql import SQLInstance # noqa F401 from .bigquery import BQDataset # noqa F401 class Resource(): @staticmethod def factory(resource_data, **kargs): resource_kind_map = { 'storage#bucket': ...
Allow kargs in resource factory
Allow kargs in resource factory
Python
apache-2.0
forseti-security/resource-policy-evaluation-library
6e40897f935f504bb0bf3e60fbf9d1ef54786d2e
smoked/test/url.py
smoked/test/url.py
# coding: utf-8 from __future__ import unicode_literals from django.utils.six.moves.urllib.request import urlopen def url_available(url=None, expected_code=200): """ Check availability (HTTP response code) of single resource """ assert urlopen(url).getcode() == expected_code
# coding: utf-8 from __future__ import unicode_literals from django.utils.six.moves.urllib.request import urlopen from django.utils.six.moves.urllib.error import HTTPError def url_available(url=None, expected_code=200): """ Check availability (HTTP response code) of single resource """ try: assert ur...
Fix for testing error pages
Fix for testing error pages calling url_available(url='http://doesnotexist.com', expected_code=404) # raise exception
Python
mit
djentlemen/django-smoked
120a93a867fcad7228a4befbf16a371f2210a852
djangoautoconf/cmd_handler_base/database_connection_maintainer.py
djangoautoconf/cmd_handler_base/database_connection_maintainer.py
import thread import time from django.db import close_old_connections class DatabaseConnectionMaintainer(object): DB_TIMEOUT_SECONDS = 60*60 def __init__(self, db_timeout=None): self.clients = set() # self.device_to_protocol = {} self.is_recent_db_change_occurred = False if d...
import thread import time from datetime import datetime # from django.db import close_old_connections from django.db import connection class DatabaseConnectionMaintainer(object): DB_TIMEOUT_SECONDS = 60*60 def __init__(self, db_timeout=None): self.clients = set() # self.device_to_protocol =...
Use connection.close to close database connections.
Use connection.close to close database connections.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
23f2be0d47c5bf8de48e614be6927dcbb5df06fc
cmsplugin_filer_file/cms_plugins.py
cmsplugin_filer_file/cms_plugins.py
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext_lazy as _ import models class FilerFilePlugin(CMSPluginBase): module = 'Filer' model = models.FilerFile name = _("File") render_template = "cmsplugin_filer_file/file.html" ...
from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from django.utils.translation import ugettext_lazy as _ import models from django.conf import settings class FilerFilePlugin(CMSPluginBase): module = 'Filer' model = models.FilerFile name = _("File") render_template = "cm...
Revert "FilerFilePlugin.icon_src is also obsolete"
Revert "FilerFilePlugin.icon_src is also obsolete" This reverts commit 6f9609a350fcac101eb28c08f8499f11d753f292.
Python
bsd-3-clause
pbs/cmsplugin-filer,skirsdeda/cmsplugin-filer,wlanslovenija/cmsplugin-filer,divio/cmsplugin-filer,isotoma/cmsplugin-filer,eliasp/cmsplugin-filer,brightinteractive/cmsplugin-filer,brightinteractive/cmsplugin-filer,grigoryk/cmsplugin-filer,pbs/cmsplugin-filer,skirsdeda/cmsplugin-filer,dreipol/cmsplugin-filer,dreipol/cmsp...
29c20b0a55b0f003a5a5dd83d5d0f177eca6a5c6
valuenetwork/valueaccounting/migrations/0013_auto_20180530_2053.py
valuenetwork/valueaccounting/migrations/0013_auto_20180530_2053.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-30 20:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('valueaccounting', '0012_auto_20170717_1841'), ] op...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-30 20:53 # and then modified by fosterlynn to remove the migration that duplicates a previous migration, and change the dependency to that migration from __future__ import unicode_literals from django.db import migrations, models import django.db.models.d...
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
Python
agpl-3.0
FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork
a7340268cd5bf19d81668595c2cec5e707873737
tests/test_objects.py
tests/test_objects.py
import sys from funcy.objects import * ### @cached_property def test_set_cached_property(): class A(object): @cached_property def prop(self): return 7 a = A() assert a.prop == 7 a.prop = 42 assert a.prop == 42 ### Monkey tests def test_monkey(): class A(object...
import sys from funcy.objects import * ### @cached_property def test_set_cached_property(): calls = [0] class A(object): @cached_property def prop(self): calls[0] += 1 return 7 a = A() assert a.prop == 7 assert a.prop == 7 assert calls == [1] a.p...
Test that @cached_property really caches
Test that @cached_property really caches
Python
bsd-3-clause
musicpax/funcy,ma-ric/funcy,Suor/funcy
587f6c77153235e3defcc6b0b6598634e1ee2828
lib/sqlalchemy/dialects/__init__.py
lib/sqlalchemy/dialects/__init__.py
# dialects/__init__.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php __all__ = ( "firebird", "mssql", "mysql", "oracle", "postgr...
# dialects/__init__.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php __all__ = ( "firebird", "mssql", "mysql", "oracle", "postgr...
Load external firebird or sybase dialect if available
Load external firebird or sybase dialect if available Fixes: #5318 Extension of I1660abb11c02656fbf388f2f9c4257075111be58 Change-Id: I32b678430497327f9b08f821bd345a2557e34b1f
Python
mit
monetate/sqlalchemy,j5int/sqlalchemy,j5int/sqlalchemy,zzzeek/sqlalchemy,sqlalchemy/sqlalchemy,monetate/sqlalchemy
f4c01d85eb5a3873ea80e24b3dae50bd3ab87f4a
llvmlite/binding/linker.py
llvmlite/binding/linker.py
from __future__ import print_function, absolute_import from ctypes import c_int, c_char_p, POINTER from . import ffi def link_modules(dst, src): dst.verify() src.verify() with ffi.OutputString() as outerr: err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) # The underlying module was destr...
from __future__ import print_function, absolute_import from ctypes import c_int, c_char_p, POINTER from . import ffi def link_modules(dst, src): with ffi.OutputString() as outerr: err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) # The underlying module was destroyed src.detach() ...
Remove unnecessary verify. We should let user run the verification instead of doing it in linkage.
Remove unnecessary verify. We should let user run the verification instead of doing it in linkage.
Python
bsd-2-clause
numba/llvmlite,numba/llvmlite,numba/llvmlite,numba/llvmlite
60b039aabb94c1e5a50bb19bb7267a0fd3ceaa86
mollie/api/objects/list.py
mollie/api/objects/list.py
from .base import Base class List(Base): current = None def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __len__(self): """Return the count field.""" return int(self['count']) def get_object_name(self): r...
from .base import Base class List(Base): current = None def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __len__(self): """Return the count field.""" return int(self['count']) def get_object_name(self): r...
Drop obsoleted support for offset.
Drop obsoleted support for offset.
Python
bsd-2-clause
mollie/mollie-api-python
ba211a0037aa26d5d1fc9cb7a0de55a46b481a82
prometapi/bicikeljproxy/management/commands/bicikelj_fetch_citybikes.py
prometapi/bicikeljproxy/management/commands/bicikelj_fetch_citybikes.py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option import os import sys class Command(BaseCommand): help = 'Fetch bicikelj XMLs and store them in order not to storm on official servers' def handle(self, *args, **options): from prometapi.bicikeljproxy.models import ...
from django.core.management.base import BaseCommand, CommandError from optparse import make_option import os import sys class Command(BaseCommand): help = 'Fetch bicikelj XMLs and store them in order not to storm on official servers' def handle(self, *args, **options): from prometapi.bicikeljproxy.models import ...
Print data when citybikes throws error.
Print data when citybikes throws error.
Python
agpl-3.0
zejn/prometapi,izacus/prometapi,zejn/prometapi,izacus/prometapi
fbbee24a71f840131748bc8ca1cadc7759c58d52
molo/core/content_import/api/urls.py
molo/core/content_import/api/urls.py
from django.conf.urls import url from molo.core.content_import.api import admin_views urlpatterns = [ url(r"^import-articles/$", admin_views.ArticleImportView.as_view(), name="article-import"), url(r"^parent/$", admin_views.ChooseParentView.as_view(model_admin=admin_views.ArticleModelAdmin()), name="test-par...
from django.conf.urls import url from molo.core.content_import.api import admin_views urlpatterns = [ url(r"^import-articles/$", admin_views.ArticleImportView.as_view(), name="article-import"), url(r"^parent/$", admin_views.ArticleChooserView.as_view(model_admin=admin_views.ArticleModelAdmin()), name="test-p...
Fix name of Aritlce Parent Chooser view as used by the URLs
Fix name of Aritlce Parent Chooser view as used by the URLs
Python
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
ce97f7677a84db351e3d2cadf01691fc879a8fbe
profile/files/applications/report/fedora/check_updates.py
profile/files/applications/report/fedora/check_updates.py
dnf_failure = False base = dnf.Base() try: base.read_all_repos() base.fill_sack() upgrades = base.sack.query().upgrades().run() except: dnf_failure = True if dnf_failure: pkg_output = -1 else: pkg_output = len(upgrades)
dnf_failure = False base = dnf.Base() base.conf.substitutions.update_from_etc("/") try: base.read_all_repos() base.fill_sack() upgrades = base.sack.query().upgrades().run() except: dnf_failure = True if dnf_failure: pkg_output = -1 else: pkg_output = len(upgrades)
Read custom variables (Required to support CentOS Stream)
Read custom variables (Required to support CentOS Stream)
Python
apache-2.0
norcams/himlar,tanzr/himlar,raykrist/himlar,norcams/himlar,norcams/himlar,TorLdre/himlar,tanzr/himlar,tanzr/himlar,raykrist/himlar,TorLdre/himlar,norcams/himlar,TorLdre/himlar,raykrist/himlar,mikaeld66/himlar,mikaeld66/himlar,mikaeld66/himlar,tanzr/himlar,TorLdre/himlar,raykrist/himlar,tanzr/himlar,norcams/himlar,raykr...
5085e2f8c97ecab6617b4f7b0c8250095d47b22d
boardinghouse/templatetags/boardinghouse.py
boardinghouse/templatetags/boardinghouse.py
from django import template from ..schema import is_shared_model as _is_shared_model from ..schema import get_schema_model Schema = get_schema_model() register = template.Library() @register.filter def is_schema_aware(obj): return obj and not _is_shared_model(obj) @register.filter def is_shared_model(obj): ...
from django import template from ..schema import is_shared_model as _is_shared_model from ..schema import _get_schema register = template.Library() @register.filter def is_schema_aware(obj): return obj and not _is_shared_model(obj) @register.filter def is_shared_model(obj): return obj and _is_shared_model(o...
Remove a database access from the template tag.
Remove a database access from the template tag. --HG-- branch : schema-invitations
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
538ae3b96399e207e38bdf53bdd1c8f738b82e33
tests/test_pagination.py
tests/test_pagination.py
from hn import HN hn = HN() def test_pagination_top(): """ This test checks if the pagination works for the front page by comparing number of stories in 2 pages. """ assert len(hn.get_stories(page_limit=2)) == 2 * 30 def test_pagination_newest(): """ This test checks if the pagination wo...
from hn import HN hn = HN() def test_pagination_top_for_2_pages(): """ This test checks if the pagination works for the front page by comparing number of stories in 2 page. """ stories = hn.get_stories(page_limit=2) assert len(stories) == 2 * 30 def test_pagination_newest_for_3_pages(): ...
Add test cases for unexpected page_limit
Add test cases for unexpected page_limit
Python
mit
brunocappelli/HackerNewsAPI,karan/HackerNewsAPI,brunocappelli/HackerNewsAPI,karan/HackerNewsAPI,brunocappelli/HackerNewsAPI
7d894c2faa2d9dfac8eec5389ecb500a8f5f8e63
bin/pymodules/apitest/jscomponent.py
bin/pymodules/apitest/jscomponent.py
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChang...
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChang...
Add placeable to javascript context
Add placeable to javascript context
Python
apache-2.0
realXtend/tundra,antont/tundra,realXtend/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,BogusCurry/tundra,AlphaStaxLLC/tundra,jesterKing/naali,pharos3d/tundra,antont/tundra,BogusCurry/tundra,BogusCurry/tundra,realXtend/tundra,jesterKing/naali,antont/tundra,antont/tund...
c80fc3c31003e6ecec049ac2e1ca370e58ab2b3c
mediasync/processors/yuicompressor.py
mediasync/processors/yuicompressor.py
from django.conf import settings from mediasync import JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.ex...
from django.conf import settings from mediasync import CSS_MIMETYPES, JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.real...
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
Python
bsd-3-clause
sunlightlabs/django-mediasync,mntan/django-mediasync,mntan/django-mediasync,sunlightlabs/django-mediasync,sunlightlabs/django-mediasync,mntan/django-mediasync
2745423ce5a7e9963038a529337a1d71d4465cba
core/views.py
core/views.py
from django.conf import settings from django.views.static import serve from django.http import HttpResponse from django.views.decorators.csrf import csrf_view_exempt import json import os from projects.models import Project from projects.tasks import update_docs from projects.utils import get_project_path, find_file ...
from django.conf import settings from django.views.static import serve from django.http import HttpResponse from django.views.decorators.csrf import csrf_view_exempt import json import os from projects.models import Project from projects.tasks import update_docs from projects.utils import get_project_path, find_file ...
Fix empty file names messin stuff up.
Fix empty file names messin stuff up.
Python
mit
clarkperkins/readthedocs.org,kenwang76/readthedocs.org,pombredanne/readthedocs.org,LukasBoersma/readthedocs.org,davidfischer/readthedocs.org,raven47git/readthedocs.org,royalwang/readthedocs.org,mhils/readthedocs.org,sils1297/readthedocs.org,gjtorikian/readthedocs.org,nyergler/pythonslides,nyergler/pythonslides,fujita-s...
2327eb0c4db7d6b771777e8d73ec99a8e324391a
printzone.py
printzone.py
#!/usr/bin/env python import dns.query import dns.zone import sys from optparse import OptionParser parser = OptionParser() parser.add_option("--server", dest="dns_server", help="DNS server to query.", type="string") parser.add_option("--zone", dest="dns_zone", h...
#!/usr/bin/env python import dns.query import dns.zone import sys from optparse import OptionParser parser = OptionParser() parser.add_option("--server", dest="dns_server", help="DNS server to query.", type="string") parser.add_option("--zone", dest="dns_zone", h...
Split the XFR output into an array of values.
Split the XFR output into an array of values. Had to split on \n. Need to go through the code more and figure out why it doesn't actually present itself upon printing
Python
bsd-3-clause
jforman/python-ddns
3577007a2b48ca410a0a34a10f64adcdb3537912
setup.py
setup.py
# -*- coding: utf-8 -*- import os from distutils.core import setup here = os.path.dirname(__file__) def get_long_desc(): return open(os.path.join(here, 'README.rst')).read() # Function borrowed from carljm. def get_version(): fh = open(os.path.join(here, "gcframe", "__init__.py")) try: for lin...
# -*- coding: utf-8 -*- import os from distutils.core import setup here = os.path.dirname(__file__) def get_long_desc(): return open(os.path.join(here, 'README.rst')).read() # Function borrowed from carljm. def get_version(): fh = open(os.path.join(here, "gcframe", "__init__.py")) try: for lin...
Update the classification to production/stable.
Update the classification to production/stable.
Python
bsd-3-clause
benspaulding/django-gcframe
3c94fc8a784420740caa8831363b6ebb8b1d6095
django_archive/archivers/__init__.py
django_archive/archivers/__init__.py
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' def get_archiver(fmt): """ Return the class corresponding with the provided archival form...
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( (TARBALL, "Tarball (.tar)"), (TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)")...
Add tuple containing all supported archive formats and their human-readable description.
Add tuple containing all supported archive formats and their human-readable description.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
ee494fd205c58029960d4a5702f59418c8110eb3
django_iceberg/context_processors.py
django_iceberg/context_processors.py
# -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) from django_iceberg.auth_utils import init_iceberg, get_conf_class def iceberg_settings(request): """ Defines some template variables in context """ conf = get_conf_class(request) if not conf: ICEBERG_API_URL_FUL...
# -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) from django_iceberg.auth_utils import init_iceberg, get_conf_class def iceberg_settings(request): """ Defines some template variables in context """ conf = get_conf_class(request) if not conf: ICEBERG_API_URL_FUL...
Add username to context in iceberg_settings context processor
Add username to context in iceberg_settings context processor
Python
mit
izberg-marketplace/django-izberg,izberg-marketplace/django-izberg,Iceberg-Marketplace/django-iceberg,Iceberg-Marketplace/django-iceberg
cd27849acae57a0382f66116771491576177a39e
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup __VERSION__ = '0.2.4' long_description = "See https://furtive.readthedocs.org" setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='dbryant4@gmail.com', ...
#!/usr/bin/env python from distutils.core import setup __VERSION__ = '0.2.4' long_description = """ Github: https://github.com/dbryant4/furtive """ setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='dbryant4@gma...
Add links to github project page
Add links to github project page
Python
mit
dbryant4/furtive
1cbf66453e2808e8c15628b41e37e96c93cc77db
great_expectations_airflow/hooks/db_hook.py
great_expectations_airflow/hooks/db_hook.py
from airflow.hooks.dbapi_hook import DbApiHook import great_expectations as ge class ExpectationMySQLHook(DbApiHook): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_ge_df(self, dataset_name, **kwargs): self.log.info("Connecting to dataset {dataset} on {uri}".f...
import great_expectations as ge from airflow.hooks.mysql_hook import MySqlHook class ExpectationMySQLHook(MySqlHook): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_ge_df(self, dataset_name, **kwargs): self.log.info("Connecting to dataset {dataset} on {uri}".f...
Make sure hook can actually be instantiated (generic DbApiHook cannot)
Make sure hook can actually be instantiated (generic DbApiHook cannot)
Python
apache-2.0
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
e68aaef747f5a2ced06f74249d49d0ed81551d23
test/test_functionality.py
test/test_functionality.py
""" Tests of overall functionality """ import pytest import toolaudit import yaml def test_simple_audit(capsys): """ Check simple audit gives the expected output """ app = toolaudit.application.ToolauditApp() try: app.run(kitlist_file='test/example.yaml') except SystemExit: pa...
""" Tests of overall functionality """ import pytest import toolaudit import yaml def test_simple_audit(capsys, monkeypatch): """ Check simple audit gives the expected output """ def mockreturn(path): return '9c3bb3efa8095f36aafd9bf3a698efe439505021' monkeypatch.setattr(toolaudit.readers,...
Use mocking to fix the result of hashing files
Use mocking to fix the result of hashing files
Python
mit
jstutters/toolaudit
6de9b3215ac9d3a2b5dc97af5e5fe02886d4bfe1
pywikibot/families/wikitech_family.py
pywikibot/families/wikitech_family.py
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikitech family class Family(family.Family): def __init__(self): super(Family, self).__init__() self.name = 'wikitech' self.langs = { 'en': 'wikitech.wikimedia.org', } def version(s...
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikitech family class Family(family.Family): def __init__(self): super(Family, self).__init__() self.name = 'wikitech' self.langs = { 'en': 'wikitech.wikimedia.org', } def version(s...
Remove overide of default scriptpath
Remove overide of default scriptpath
Python
mit
pywikibot/core-migration-example
4a032ece106d4b3b3764420197453afd33475bf6
donut/modules/permissions/helpers.py
donut/modules/permissions/helpers.py
import flask from donut.modules.groups import helpers as groups def has_permission(user_id, permission_id): ''' Returns True if [user_id] holds a position that directly or indirectly (through a position relation) grants them [permission_id]. Otherwise returns False. ''' if not (isinstance(u...
import flask from donut.modules.groups import helpers as groups def has_permission(user_id, permission_id): ''' Returns True if [user_id] holds a position that directly or indirectly (through a position relation) grants them [permission_id]. Otherwise returns False. ''' if not (isinstance(u...
Fix failing test and make lint
Fix failing test and make lint
Python
mit
ASCIT/donut-python,ASCIT/donut,ASCIT/donut,ASCIT/donut-python,ASCIT/donut
30ffff16e5dd4eec6e5128a277a677834470be73
scikits/learn/tests/test_cross_val.py
scikits/learn/tests/test_cross_val.py
""" Test the cross_val module """ import numpy as np import nose from .. import cross_val def test_kfold(): # Check that errors are raise if there is not enough samples nose.tools.assert_raises(AssertionError, cross_val.KFold, 3, 3) y = [0, 0, 1, 1, 2] nose.tools.assert_raises(AssertionError, cross_...
""" Test the cross_val module """ import numpy as np import nose from ..base import BaseEstimator from .. import cross_val class MockClassifier(BaseEstimator): """Dummy classifier to test the cross-validation """ def __init__(self, a=0): self.a = a def fit(self, X, Y, **params): ...
Add a smoke test for cross_val_score
TEST: Add a smoke test for cross_val_score
Python
bsd-3-clause
mjgrav2001/scikit-learn,marcocaccin/scikit-learn,jmschrei/scikit-learn,ycaihua/scikit-learn,sarahgrogan/scikit-learn,xubenben/scikit-learn,appapantula/scikit-learn,mehdidc/scikit-learn,bikong2/scikit-learn,cainiaocome/scikit-learn,hsiaoyi0504/scikit-learn,Titan-C/scikit-learn,hsuantien/scikit-learn,kmike/scikit-learn,V...
106833059bc2dad8a284de50e153bf673d2e3b4b
premis_event_service/urls.py
premis_event_service/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (r'^APP/node/(?P<identifier>.+?)/$', 'node'), # event urls (r'^APP/event/$', 'app_event'), ...
try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import * # In case of Django<=1.3 urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (...
Support new and old Django urlconf imports
Support new and old Django urlconf imports
Python
bsd-3-clause
unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service
d902045e991cc778dabe31e34a6dcd119e19ccd0
attributes/license/main.py
attributes/license/main.py
from utilities import url_to_json def run(project_id, repo_path, cursor, **options): query = 'SELECT url FROM projects WHERE id = ' + str(project_id) cursor.execute(query) record = cursor.fetchone() full_url = record[0].rstrip() json_response = url_to_json(full_url, headers={ 'Accept'...
from core import tokenize from utilities import url_to_json def run(project_id, repo_path, cursor, **options): query = 'SELECT url FROM projects WHERE id = ' + str(project_id) cursor.execute(query) record = cursor.fetchone() full_url = tokenize(record[0].rstrip()) json_response = url_to_json(full...
Update license attribute to return binary and raw result
Update license attribute to return binary and raw result
Python
apache-2.0
RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper
61cce2cd23c798a8604274335d9637e8ebce1385
api/v2/views/image.py
api/v2/views/image.py
from core.models import Application as Image from api import permissions from api.v2.serializers.details import ImageSerializer from api.v2.views.base import AuthOptionalViewSet from api.v2.views.mixins import MultipleFieldLookup class ImageViewSet(MultipleFieldLookup, AuthOptionalViewSet): """ API endpoint...
from core.models import Application as Image from api import permissions from api.v2.serializers.details import ImageSerializer from api.v2.views.base import AuthOptionalViewSet from api.v2.views.mixins import MultipleFieldLookup class ImageViewSet(MultipleFieldLookup, AuthOptionalViewSet): """ API endpoint...
Add 'Machine Identifier' for easy support lookups in Troposphere
Add 'Machine Identifier' for easy support lookups in Troposphere
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
358f244b397f11cdf9f89304356ac45b4c6621b5
__init__.py
__init__.py
#! /usr/bin/env python # coding=utf-8 import os.path import subprocess class SubTask(): def __init__(self, output_dir, log): self.__output_dir = output_dir self.__log = log self.__wd = os.path.dirname(os.path.realpath(__file__)) self.__init_done = False print "__init__" ...
#! /usr/bin/env python # coding=utf-8 import os.path import subprocess class SubTask(): def __init__(self, output_dir, log): self.__output_dir = output_dir self.__log = log self.__wd = os.path.dirname(os.path.realpath(__file__)) self.__init_done = False print "__init__" ...
Add return value: tcc path.
Add return value: tcc path.
Python
apache-2.0
lugovskoy/dts-sample-compile
61ca14440f39106b6109b96919b520e40170b1f3
examples/tour_examples/xkcd_tour.py
examples/tour_examples/xkcd_tour.py
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_basic(self): self.open('https://xkcd.com/1117/') self.assert_element('img[alt="My Sky"]') self.create_shepherd_tour() self.add_tour_step("Welcome to XKCD!") self.add_tour_step("This is the XKCD logo.",...
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_basic(self): self.open('https://xkcd.com/1117/') self.assert_element('img[alt="My Sky"]') self.create_shepherd_tour() self.add_tour_step("Welcome to XKCD!") self.add_tour_step("This is the XKCD logo.",...
Update a SeleniumBase tour example
Update a SeleniumBase tour example
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
671cd368c9730e7c15005df4e476e86d80bf0b8e
array/rotate-image.py
array/rotate-image.py
# You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees clockwise # solve with O(1) additional memory def rotate_image(a): n = len(a) if a is None or n < 1: return a else: for i in range(n/2): for j in range(i, n-i-1): temp = a[i][j] a[i][j] = a[n-1-j][i] a[n-...
# You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees clockwise # solve with O(1) additional memory def rotate_image(a): n = len(a) if a is None or n < 1: return a else: for i in range(n/2): # loop through all squares one by one for j in range(i, n-i-1): # loop through ...
Add test cases and comments
Add test cases and comments
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
d68f391d15927db65ea4e62d67bd9faf37b5deaf
file_process/utils/get_reference.py
file_process/utils/get_reference.py
from __future__ import absolute_import from .twobit import TwoBitFile def get_reference_allele(chrom, start, hg19_path): twobit_file = TwoBitFile(hg19_path) end = start + 1 refallele = twobit_file[chrom][start:end] return refallele
from __future__ import absolute_import from .twobit import TwoBitFile def get_reference_allele(chrom, start, hg19_path): twobit_file = TwoBitFile(hg19_path) end = start + 1 try: refallele = twobit_file[chrom][start:end] except TypeError: refallele = 'N' return refallele
Return N for ref allele in pos uncovered by ref
Return N for ref allele in pos uncovered by ref This arose during processing of a CGI var file originating from LFR data (not sure, but LFR is an advanced technique, so it's possible CGI is calling some positions that aren't called in reference).
Python
mit
PersonalGenomesOrg/archive-genevieve-201505,PersonalGenomesOrg/archive-genevieve-201505,PersonalGenomesOrg/archive-genevieve-201505
461522c3b79202c915544466272d3bb2a3d0ecbe
api/radar_api/serializers/meta.py
api/radar_api/serializers/meta.py
from radar.models.users import User from radar.serializers.fields import StringField, IntegerField from radar.serializers.models import ModelSerializer class TinyUserSerializer(ModelSerializer): id = IntegerField() username = StringField() email = StringField() first_name = StringField() last_name...
from radar.models.users import User from radar.serializers.fields import StringField, IntegerField, DateTimeField from radar.serializers.models import ModelSerializer class TinyUserSerializer(ModelSerializer): id = IntegerField() username = StringField() email = StringField() first_name = StringField(...
Add created and modified date mixins
Add created and modified date mixins
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
71d6176b1468a5bf9aef1ced5214c32b69efaf50
apps/countdown/views.py
apps/countdown/views.py
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, 'month': int(month) - 1, #JS takes month...
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.http import urlencode import json import urllib2 def index(request, year, month, day, hour, text): params = { 'year': year, 'month': int(month) - 1, #JS takes month...
Fix bug in countdonw hours calculation
Fix bug in countdonw hours calculation
Python
bsd-3-clause
Teknologforeningen/tf-info,Teknologforeningen/tf-info,Teknologforeningen/tf-info
bde0363b51bfa7bb6facac1185c9a687ff952e36
artifacts/exceptions.py
artifacts/exceptions.py
# -*- coding: utf-8 -*- # # Artifacts - Artifactory Search Client # # Copyright 2015 Smarter Travel # # Available under the MIT license. See LICENSE for details. # """ artifacts.exceptions ~~~~~~~~~~~~~~~~~~~~ Exceptions raised by the Artifacts library. """ from __future__ import print_function, division class Art...
# -*- coding: utf-8 -*- # # Artifacts - Artifactory Search Client # # Copyright 2015 Smarter Travel # # Available under the MIT license. See LICENSE for details. # """ artifacts.exceptions ~~~~~~~~~~~~~~~~~~~~ Exceptions raised by the Artifacts library. """ from __future__ import print_function, division __all__ = ...
Add __all__ variable to enforce ordering in docs
Add __all__ variable to enforce ordering in docs
Python
mit
smarter-travel-media/stac
c1ed5eb96b04ca0af2ad8f26023d8cbaa4a75eda
rx/concurrency/threadpoolscheduler.py
rx/concurrency/threadpoolscheduler.py
import logging from concurrent.futures import ThreadPoolExecutor from rx.core import Scheduler, Disposable from rx.disposables import SingleAssignmentDisposable, CompositeDisposable from .timeoutscheduler import TimeoutScheduler log = logging.getLogger("Rx") class ThreadPoolScheduler(TimeoutScheduler): """A sc...
from concurrent.futures import ThreadPoolExecutor from rx.core import Scheduler from .newthreadscheduler import NewThreadScheduler class ThreadPoolScheduler(NewThreadScheduler): """A scheduler that schedules work via the thread pool.""" class ThreadPoolThread: """Wraps a concurrent future as a thre...
Make thread pool scheduler behave as a pooled new thread scheduler
Make thread pool scheduler behave as a pooled new thread scheduler
Python
mit
ReactiveX/RxPY,ReactiveX/RxPY
358fcbf44903d817f115d4df1074a89a9f151c9c
pythonforandroid/recipes/pymunk/__init__.py
pythonforandroid/recipes/pymunk/__init__.py
from os.path import join from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = '5.5.0' url = 'https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip' depends = ['cffi', 'setuptools'] call_host...
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython =...
Update Pymunk recipe to 6.0.0
Update Pymunk recipe to 6.0.0
Python
mit
PKRoma/python-for-android,kronenpj/python-for-android,kronenpj/python-for-android,PKRoma/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kivy/python-for-android,kivy/p...
a9fb5d3899e5f7f9c0b964a2eaa0f74df33dc52f
scrapple/utils/exceptions.py
scrapple/utils/exceptions.py
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None ...
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands....
Add custom error class 'InvalidType'
Add custom error class 'InvalidType'
Python
mit
AlexMathew/scrapple,scrappleapp/scrapple,AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple
0757efde915acdf651231bc345c4c1f3ca67d921
work/print-traceback.py
work/print-traceback.py
#!/usr/bin/python3 from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None if __name__ == '__main__': if len(sys.argv) >= 2: paths = [sys.argv[1].split('.')] else: ...
#!/usr/bin/python3 from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None def display(obj): for path in paths: subobj = get(obj, path) if subobj is not None: ...
Allow multiple lines of traceback.
Allow multiple lines of traceback.
Python
mit
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
b56c1cb1185c8d20276688f29509947cb46a26d4
test/test_compiled.py
test/test_compiled.py
""" Test compiled module """ import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os...
""" Test compiled module """ import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os...
Add test with standard lib
Add test with standard lib math.cos( should return <Param: x @0,0>
Python
mit
WoLpH/jedi,WoLpH/jedi,dwillmer/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,mfussenegger/jedi,dwillmer/jedi,jonashaag/jedi,tjwei/jedi,tjwei/jedi,flurischt/jedi
85d0bc9fbb20daeff9aa48a83be1823fa346cb9c
tests/test_helpers.py
tests/test_helpers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.base import RakutenAPIResponse @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.sea...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.base import RakutenAPIResponse @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.sea...
Fix tests for Python 3
Fix tests for Python 3
Python
mit
alexandriagroup/rakuten-ws
f18957ca1986317e8987183633c39f1987e316c4
pgcontents/__init__.py
pgcontents/__init__.py
from .checkpoints import PostgresCheckpoints from .pgmanager import PostgresContentsManager __all__ = [ 'PostgresCheckpoints', 'PostgresContentsManager', ]
# Do this first so that we bail early with a useful message if the user didn't # specify [ipy3] or [ipy4]. try: import IPython # noqa except ImportError: raise ImportError( "No IPython installation found.\n" "To install pgcontents with the latest Jupyter Notebook" " run 'pip install pgc...
Add warning if IPython isn't installed.
DOC: Add warning if IPython isn't installed.
Python
apache-2.0
quantopian/pgcontents
cc44afdca3ebcdaeed3555f161d3e0a1992c19eb
planet/api/__init__.py
planet/api/__init__.py
# Copyright 2017 Planet Labs, 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 writ...
# Copyright 2017 Planet Labs, 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 writ...
Put api.__version__ back in after version shuffle
Put api.__version__ back in after version shuffle
Python
apache-2.0
planetlabs/planet-client-python,planetlabs/planet-client-python
268c4dce6cfa59e10cff7f4bf8456276c2e11f7d
main.py
main.py
#!/usr/bin/env python2.7 #coding: utf8 """ KSP Add-on Version Checker. """ # Copyright 2014 Dimitri "Tyrope" Molenaars # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use self file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache....
#!/usr/bin/env python2.7 #coding: utf8 """ KSP Add-on Version Checker. """ # Copyright 2014 Dimitri "Tyrope" Molenaars # 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....
Create config paths if needed, find files and (for now) report remotes.
Create config paths if needed, find files and (for now) report remotes.
Python
apache-2.0
tyrope/KSP-addon-version-checker
9fe11538a9d74ff235b530a71d2399fe6c03a88a
tests/rules_tests/FromRulesComputeTest.py
tests/rules_tests/FromRulesComputeTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule class FromRulesComputeTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions.NotASingleSymbolException import NotASingleSymbolException from grammpy.exceptions.CantCreateSingleRuleExcepti...
Add tests to compute from rules property
Add tests to compute from rules property
Python
mit
PatrikValkovic/grammpy
fbfae080cc59e2faae4c8ece21e4aa2970efee1e
encmass.py
encmass.py
#!/usr/bin/env python # ----------------------------------------------------------------------------- # GENHERNQUIST.ENCMASS # Laura L Watkins [lauralwatkins@gmail.com] # ----------------------------------------------------------------------------- import numpy as np from astropy import units as u from scipy import sp...
#!/usr/bin/env python # ----------------------------------------------------------------------------- # GENHERNQUIST.ENCMASS # Laura L Watkins [lauralwatkins@gmail.com] # ----------------------------------------------------------------------------- import numpy as np from astropy import units as u from scipy import sp...
Fix error in enclosed mass calculation and fix unit handling.
Fix error in enclosed mass calculation and fix unit handling.
Python
bsd-2-clause
lauralwatkins/genhernquist
5ee3eb2f68e4af8e70ea383b067fe67ffd4800bf
loadsbroker/webapp/__init__.py
loadsbroker/webapp/__init__.py
import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/da...
import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/da...
Set the `default_filename` for `GrafanaHandler`.
Set the `default_filename` for `GrafanaHandler`.
Python
apache-2.0
loads/loads-broker,loads/loads-broker,loads/loads-broker,loads/loads-broker
ddd8f1a8fab0f77943d7a47e1d154d1104add26e
ievv_opensource/ievv_batchframework/rq_tasks.py
ievv_opensource/ievv_batchframework/rq_tasks.py
from __future__ import absolute_import import django_rq from ievv_opensource.ievv_batchframework.models import BatchOperation from ievv_opensource.ievv_batchframework import batchregistry import logging class BatchActionGroupTask(object): abstract = True def run_actiongroup(self, actiongroup_name, batchop...
import django_rq from ievv_opensource.ievv_batchframework.models import BatchOperation from ievv_opensource.ievv_batchframework import batchregistry import logging class BatchActionGroupTask(object): abstract = True def run_actiongroup(self, actiongroup_name, batchoperation_id, **kwargs): try: ...
Remove dependency on the future lib.
Remove dependency on the future lib.
Python
bsd-3-clause
appressoas/ievv_opensource,appressoas/ievv_opensource,appressoas/ievv_opensource,appressoas/ievv_opensource,appressoas/ievv_opensource
dd739126181b29493c9d1d90a7e40eac09c23666
app/models.py
app/models.py
# -*- coding: utf-8 -*- """ app.models ~~~~~~~~~~ Provides the SQLAlchemy models """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import savalidation.validators as val from datetime import datetime as dt from app import db from savalidation...
# -*- coding: utf-8 -*- """ app.models ~~~~~~~~~~ Provides the SQLAlchemy models """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import savalidation.validators as val from datetime import datetime as dt from app import db from savalidation...
Add unique constraint to rid
Add unique constraint to rid
Python
mit
reubano/hdxscraper-hdro,reubano/hdxscraper-hdro,reubano/hdxscraper-hdro
4ac335e2ac69f634d51ab8b84805947fe2b87fc5
app.py
app.py
#!notify/bin/python3 import os import sys from pushbullet import Pushbullet def create_note(title, content): api_key = os.environ["PB_API_KEY"] pb = Pushbullet(api_key) pb.push_note(title, content) if len(sys.argv) >= 3: title = sys.argv[1] body = sys.argv[2] create_note(title, body) else: ...
#!notify/bin/python3 import hug import os from pushbullet import Pushbullet @hug.cli() def create_note(title: hug.types.text, content: hug.types.text): api_key = os.environ["PB_API_KEY"] pb = Pushbullet(api_key) pb.push_note(title, content) if __name__ == '__main__': create_note.interface.cli()
Migrate command line interface to hug
Migrate command line interface to hug
Python
isc
tildecross/tildex-notify
fe768f5d8c1081f69acd8cf656aa618da7caf93b
cbpos/mod/currency/views/config.py
cbpos/mod/currency/views/config.py
from PySide import QtGui import cbpos from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() ...
from PySide import QtGui import cbpos import cbpos.mod.currency.controllers as currency from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() ...
Handle unset default currency better
Handle unset default currency better
Python
mit
coinbox/coinbox-mod-currency
85faea2a9185924d1255e84aad1489f7e3627d13
django_lightweight_queue/utils.py
django_lightweight_queue/utils.py
from django.db import models from django.conf import settings from django.utils.importlib import import_module from django.core.exceptions import MiddlewareNotUsed from django.utils.functional import memoize from django.utils.module_loading import module_has_submodule from . import app_settings def get_path(path): ...
from django.db import models from django.conf import settings from django.utils.importlib import import_module from django.core.exceptions import MiddlewareNotUsed from django.utils.functional import memoize from django.utils.module_loading import module_has_submodule from . import app_settings def get_path(path): ...
Add setproctitle wrapper so it's optional.
Add setproctitle wrapper so it's optional. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
Python
bsd-3-clause
prophile/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,thread/django-lightweight-queue
694079aa480072e97043f968547941404f303c75
array/quick-sort.py
array/quick-sort.py
# Sort list using recursion def quick_sort(lst): if len(lst) == 0: print [] left = [] right = [] pivot = lst[0] # compare first element in list to the rest for i in range(1, len(lst)): if lst[i] < pivot: left.append(lst[i]) else: right.append(lst[i])
# Sort list using recursion def quick_sort(lst): if len(lst) == 0: print [] left = [] right = [] pivot = lst[0] # compare first element in list to the rest for i in range(1, len(lst)): if lst[i] < pivot: left.append(lst[i]) else: right.append(lst[i]) # recursion print quick_sort(left) + pivot + ...
Apply recursion to quick sort
Apply recursion to quick sort
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
5345cfddc24303a7d27b61865306775f93bb908c
django_lightweight_queue/utils.py
django_lightweight_queue/utils.py
from django.utils.importlib import import_module from django.core.exceptions import MiddlewareNotUsed from django.utils.functional import memoize from . import app_settings def get_path(path): module_name, attr = path.rsplit('.', 1) module = import_module(module_name) return getattr(module, attr) def g...
from django.db.models import get_apps from django.core.exceptions import MiddlewareNotUsed from django.utils.importlib import import_module from django.utils.functional import memoize from django.utils.module_loading import module_has_submodule from . import app_settings def get_path(path): module_name, attr = pa...
Add utility to import all submodules of all apps.
Add utility to import all submodules of all apps. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
Python
bsd-3-clause
thread/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue,prophile/django-lightweight-queue,lamby/django-lightweight-queue
f225ffecf061470b877388d26c1605248b9611da
ygorcam.py
ygorcam.py
#!/usr/bin/env python import tempfile import subprocess import web urls = ("/camera", "Camera") app = web.application(urls, globals()) class Camera(object): def GET(self): with tempfile.NamedTemporaryFile(suffix=".jpg") as tfp: process = subprocess.Popen(["picamera", "-o", tfp.name]) ...
#!/usr/bin/env python import tempfile import subprocess import web urls = ("/camera", "Camera") app = web.application(urls, globals()) class Camera(object): def GET(self): with tempfile.NamedTemporaryFile(suffix=".jpg") as tfp: process = subprocess.Popen(["raspistill", "-o", tfp.name]) ...
Use raspistill and provide some additional error info
Use raspistill and provide some additional error info
Python
mit
f0rk/ygorcam
cc62a1eea746a7191b4a07a48dcf55f4c76787ee
asyncpg/__init__.py
asyncpg/__init__.py
import asyncio from .protocol import Protocol __all__ = ('connect',) class Connection: def __init__(self, protocol, transport, loop): self._protocol = protocol self._transport = transport self._loop = loop def get_settings(self): return self._protocol.get_settings() as...
import asyncio from .protocol import Protocol __all__ = ('connect',) class Connection: def __init__(self, protocol, transport, loop): self._protocol = protocol self._transport = transport self._loop = loop def get_settings(self): return self._protocol.get_settings() as...
Use loop.create_future if it exists
Use loop.create_future if it exists
Python
apache-2.0
MagicStack/asyncpg,MagicStack/asyncpg
64b4c9e44c5305801f45e23efd2bc0843588afef
src/sentry/api/endpoints/organization_projects.py
src/sentry/api/endpoints/organization_projects.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Project, Team class OrganizationProjectsEndpoint(Or...
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Project, Team ...
Add organization projects to docs
Add organization projects to docs
Python
bsd-3-clause
ngonzalvez/sentry,argonemyth/sentry,imankulov/sentry,wujuguang/sentry,JackDanger/sentry,llonchj/sentry,BayanGroup/sentry,felixbuenemann/sentry,ifduyue/sentry,gencer/sentry,jean/sentry,gencer/sentry,gencer/sentry,jean/sentry,1tush/sentry,wujuguang/sentry,BuildingLink/sentry,imankulov/sentry,kevinastone/sentry,looker/sen...
1596e1cdd1a9907c6efa29e89b68f57e21b2fc01
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
: Create documentation of DataSource Settings Task-Url:
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
44297159b6539987ed8fcdb50cd5b3e367a9cdc2
db/sql_server/pyodbc.py
db/sql_server/pyodbc.py
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff a...
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_ta...
Add column support for sql server
Add column support for sql server
Python
apache-2.0
smartfile/django-south,smartfile/django-south
a0d0d1312d95e1d6df2b8463b9df3ff4178c2802
setup.py
setup.py
from distutils.core import setup import glob,re config_files = glob.glob('config/*.ini') def get_version(): """ Gets version from osg-configure script file """ buffer = open('scripts/osg-configure').read() match = re.search("VERSION\s+=\s+'(.*)'", buffer) return match.group(1) setup(name='osg-configur...
from distutils.core import setup import glob,re, os config_files = glob.glob('config/*.ini') def get_version(): """ Gets version from osg-configure script file """ buffer = open('scripts/osg-configure').read() match = re.search("VERSION\s+=\s+'(.*)'", buffer) return match.group(1) def get_test_files()...
Include test files when packaging osg-configure
Include test files when packaging osg-configure git-svn-id: 8e6470fdf0410dbd375d7ca1c7e7b1f4e5857e13@14556 4e558342-562e-0410-864c-e07659590f8c
Python
apache-2.0
opensciencegrid/osg-configure,opensciencegrid/osg-configure,matyasselmeci/osg-configure,matyasselmeci/osg-configure
dc6d56b7997a9c15419fb66cd724ae3fc1a011a0
rdrf/rdrf/initial_data/iprestrict_permissive.py
rdrf/rdrf/initial_data/iprestrict_permissive.py
"""Disable iprestriction completely.""" from iprestrict.models import IPGroup, IPRange, Rule def load_data(**kwargs): allow_all() def allow_all(): all_group = get_or_create_all_group() Rule.objects.all().delete() Rule.objects.create( ip_group=all_group, action='A', url_patt...
"""Disable iprestriction completely.""" from iprestrict.models import RangeBasedIPGroup, IPRange, Rule def load_data(**kwargs): allow_all() def allow_all(): all_group = get_or_create_all_group() Rule.objects.all().delete() Rule.objects.create( ip_group=all_group, action='A', ...
Update iprestrict models in initial data
Update iprestrict models in initial data
Python
agpl-3.0
muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf
a20a63415bf1343ab826d1155c1004e84b14077e
massa/validation.py
massa/validation.py
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(val...
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError from .errors import InvalidInputError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=...
Fix bug, InvalidInputError not defined.
Fix bug, InvalidInputError not defined.
Python
mit
jaapverloop/massa
a2b418c89e6ad3f85c88b7dfcc2238d62cb2e36e
karanja_me/polls/tests.py
karanja_me/polls/tests.py
from django.test import TestCase # Create your tests here.
import datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionMethodTest(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recenlty() should return False for questions that the pub_date is in the fut...
Test case for Question method added
Test case for Question method added A test case to avoid future published questions read as recently added
Python
mit
yoda-yoda/django-dive-in,yoda-yoda/django-dive-in,denisKaranja/django-dive-in,denisKaranja/django-dive-in
1a1f0a9bca7458153ef84316fd84dfbe56be08ef
dolo/config.py
dolo/config.py
#from __future__ import print_function # This module is supposed to be imported first # it contains global variables used for configuration # try to register printing methods if IPython is running save_plots = False try: import dolo.misc.printing as printing from numpy import ndarray from dolo.symbolic...
#from __future__ import print_function # This module is supposed to be imported first # it contains global variables used for configuration # try to register printing methods if IPython is running save_plots = False try: import dolo.misc.printing as printing from numpy import ndarray from dolo.symbolic...
Remove print("failing back on pretty_print") when using dolo-recs
Remove print("failing back on pretty_print") when using dolo-recs
Python
bsd-2-clause
EconForge/dolo
bf69962ab7cb730c270ba31508af8af270c912a6
examples/generate-manager-file.py
examples/generate-manager-file.py
#!/usr/bin/python import sys import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE if len(sys.argv) >= 2: manager_name = sys.argv[1] else: manager_name = "haze" service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name object_path = "/org/freedesktop/Telepathy/ConnectionMana...
#!/usr/bin/python import sys import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \ CONN_MGR_PARAM_FLAG_REGISTER if len(sys.argv) >= 2: manager_name = sys.argv[1] else: manager_name = "haze" service_na...
Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L
Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L 20070911135601-4210b-dec39420c4af7a81bd9b6060cb81d787ebb707fc.gz
Python
lgpl-2.1
detrout/telepathy-python,max-posedon/telepathy-python,PabloCastellano/telepathy-python,epage/telepathy-python,PabloCastellano/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,epage/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,max-posedon/telepathy-python,detrout/t...
5af9796dc0fcc425efd6b0283f2e4a79dec31d5f
server/liveblog/blogs/blogs_test.py
server/liveblog/blogs/blogs_test.py
import unittest from liveblog.blogs.blogs import BlogService from superdesk.errors import SuperdeskApiError class BlogsTestCase(unittest.TestCase): def setUp(self): pass def test_if_check_max_active(self): increment = 10 """so if check "subscription in SUBSCRIPTION_MAX_ACTIVE_BLOGS" p...
from liveblog.blogs import init_app from superdesk.tests import TestCase from superdesk import get_resource_service from superdesk.errors import SuperdeskApiError class BlogsTestCase(TestCase): def setUp(self): # from nose.tools import set_trace; set_trace() init_app(self.app) def test_if_no...
Test case: _check_max_active method to check both scenarios
Test case: _check_max_active method to check both scenarios
Python
agpl-3.0
liveblog/liveblog,superdesk/liveblog,hlmnrmr/liveblog,superdesk/liveblog,superdesk/liveblog,liveblog/liveblog,hlmnrmr/liveblog,liveblog/liveblog,liveblog/liveblog,liveblog/liveblog,hlmnrmr/liveblog,hlmnrmr/liveblog,superdesk/liveblog
fd7f413925491f305a30a73f0c6eb6306a9ebf19
tests/test_member_access.py
tests/test_member_access.py
import pytest # type: ignore from ppb_vector import Vector @pytest.fixture() def vector(): return Vector(10, 20) def test_class_member_access(vector): assert vector.x == 10 assert vector.y == 20 def test_index_access(vector): assert vector[0] == 10 assert vector[1] == 20 def test_key_acces...
from hypothesis import given import pytest # type: ignore from ppb_vector import Vector from utils import vectors @pytest.fixture() def vector(): return Vector(10, 20) def test_class_member_access(vector): assert vector.x == 10 assert vector.y == 20 @given(v=vectors()) def test_index_access(v: Vecto...
Make {index.key}_access into Hypothesis tests
tests/member_access: Make {index.key}_access into Hypothesis tests
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
7f99ba5d06d646eef03bd3848fae579d0f51e2f6
alembic/testing/__init__.py
alembic/testing/__init__.py
from sqlalchemy.testing import config from sqlalchemy.testing import emits_warning from sqlalchemy.testing import engines from sqlalchemy.testing import exclusions from sqlalchemy.testing import mock from sqlalchemy.testing import provide_metadata from sqlalchemy.testing import skip_if from sqlalchemy.testing import us...
from sqlalchemy.testing import config from sqlalchemy.testing import emits_warning from sqlalchemy.testing import engines from sqlalchemy.testing import exclusions from sqlalchemy.testing import mock from sqlalchemy.testing import provide_metadata from sqlalchemy.testing import skip_if from sqlalchemy.testing import us...
Remove code to force ENABLE_ASYNCIO to False
Remove code to force ENABLE_ASYNCIO to False Forcing ENABLE_ASYNCIO to False was interfering with testing under async drivers when the (third-party dialect) test suite included both SQLAlchemy and Alembic tests. Change-Id: I2fe40049c24ba8eba0a10011849a912c03aa381e
Python
mit
zzzeek/alembic,sqlalchemy/alembic
9ed6833c88e2718e54cb25b6c1837ff4868c81c9
emote/emote.py
emote/emote.py
""" A simple CLI tool for quickly copying common emoticon/emoji to your clipboard. """ import pyperclip import json import sys import argparse with open("mapping.json") as f: emotes = json.load(f) def main(): parser = argparse.ArgumentParser( description=sys.modules[__name__].__doc__, ...
""" A simple CLI tool for quickly copying common emoticon/emoji to your clipboard. """ import pyperclip import json import sys import argparse with open("mapping.json") as f: emotes = json.load(f) def main(): parser = argparse.ArgumentParser( description=sys.modules[__name__].__doc__, ...
Add logic for displaying help if no args are specified.
Add logic for displaying help if no args are specified.
Python
mit
d6e/emotion
df045cb2e5e53c497aa101719c528b1f17c03a1f
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) from app import views, models
from werkzeug.contrib.fixers import ProxyFix from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') app.wsgi_app = ProxyFix(app.wsgi_app) login_manager = LoginManager() login_manager.init_app(app) db = SQLAlch...
Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17
Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17
Python
mit
ngoduykhanh/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,0x97/PowerDNS-Admin,ngoduykhanh/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,0x97/PowerDNS-Admin,0x97/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilipp...
19b15df8b2d92b3a00f94f53b684f9422d570c13
vumi/middleware/__init__.py
vumi/middleware/__init__.py
"""Middleware classes to process messages on their way in and out of workers. """ from vumi.middleware.base import ( TransportMiddleware, ApplicationMiddleware, MiddlewareStack, create_middlewares_from_config, setup_middlewares_from_config) __all__ = [ 'TransportMiddleware', 'ApplicationMiddleware', 'Midd...
"""Middleware classes to process messages on their way in and out of workers. """ from vumi.middleware.base import ( BaseMiddleware, TransportMiddleware, ApplicationMiddleware, MiddlewareStack, create_middlewares_from_config, setup_middlewares_from_config) __all__ = [ 'BaseMiddleware', 'TransportMiddl...
Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications.
Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications.
Python
bsd-3-clause
harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi
22772750d7bee9e9f1f8ac28068d1865e8f0ec32
fuf/interop.py
fuf/interop.py
import sys # Used to get rid of py2/3 differences # Blatantly stolen from the excellent `six` library # Allows the same calls between python2 and python3 if sys.version_info[0] == 3: exec_ = getattr(__builtins__, "exec") raw_input = input else: def exec_(_code_, _globs_=None, _locs_=None): """Execu...
import sys # Used to get rid of py2/3 differences # Blatantly stolen from the excellent `six` library # Allows the same calls between python2 and python3 if sys.version_info[0] == 3: exec_ = __builtins__["exec"] raw_input = input else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code i...
Fix python 3 support for exec
Fix python 3 support for exec
Python
mit
msoucy/fuf
ca8aca917234bdc10a47091ee83be8eed4845b5f
applications/decorators.py
applications/decorators.py
from functools import wraps from django.http import HttpResponseNotFound from django.shortcuts import redirect from core.utils import get_event_page def organiser_only(function): """ Decorator for views that checks that the user is logged in and that they are a team member for a particular page. Returns...
from functools import wraps from django.http import HttpResponseNotFound from django.shortcuts import redirect from core.utils import get_event_page def organiser_only(function): """ Decorator for views that checks that the user is logged in and that they are a team member for a particular page. Returns...
Define 'city' at top decorator
Define 'city' at top decorator
Python
bsd-3-clause
patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls
6761d8230d59031ad5183615f68a71e51f5f0309
elasticmock/__init__.py
elasticmock/__init__.py
# -*- coding: utf-8 -*- from functools import wraps from mock import patch from elasticmock.fake_elasticsearch import FakeElasticsearch ELASTIC_INSTANCES = {} def _get_elasticmock(hosts=None): elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0].get('port')) ...
# -*- coding: utf-8 -*- from functools import wraps from mock import patch from elasticmock.fake_elasticsearch import FakeElasticsearch ELASTIC_INSTANCES = {} def _get_elasticmock(hosts=None, *args, **kwargs): elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0]...
Allow ignored params to Elasticsearch
Allow ignored params to Elasticsearch
Python
mit
vrcmarcos/elasticmock
c21c53a625b2ca1e2f704286bfa99e61bbed0619
takeyourmeds/reminders/reminders_calls/tests.py
takeyourmeds/reminders/reminders_calls/tests.py
from takeyourmeds.utils.test import TestCase from ..enums import TypeEnum, SourceEnum from .enums import StateEnum class TwimlCallbackTest(TestCase): def setUp(self): super(TwimlCallbackTest, self).setUp() self.call = self.user.reminders.create( type=TypeEnum.call, ).instance...
from django.conf import settings from takeyourmeds.utils.test import TestCase from ..enums import TypeEnum, SourceEnum from .enums import StateEnum class TwimlCallbackTest(TestCase): def setUp(self): super(TwimlCallbackTest, self).setUp() self.reminder = self.user.reminders.create( ...
Check we get some sane XML back
Check we get some sane XML back Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
5f77be6bc80b9ed653f85f4b8c0c60ccb520f2f8
saleor/payment/gateways/utils.py
saleor/payment/gateways/utils.py
import warnings from typing import TYPE_CHECKING, List from django.conf import settings if TYPE_CHECKING: from ..interface import GatewayConfig def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]: supp_currencies = config.supported_currencies if not supp_currencies: ...
import re import warnings from typing import TYPE_CHECKING, List from django.conf import settings if TYPE_CHECKING: from ..interface import GatewayConfig def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]: supp_currencies = config.supported_currencies if not supp_curre...
Update supported currencies in gateways, set default currency for dummy gateway
Update supported currencies in gateways, set default currency for dummy gateway
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
ea5499d36ef84e879737fd8c6d6148dd8305c356
bookshelf/search_indexes.py
bookshelf/search_indexes.py
# Imports ##################################################################### from haystack import indexes from .models import Book # Classes ##################################################################### class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True,...
# Imports ##################################################################### from haystack import indexes from .models import Book # Classes ##################################################################### class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True,...
Allow some blank fields in Booki model from search
Allow some blank fields in Booki model from search
Python
agpl-3.0
antoviaque/plin,antoviaque/plin,antoviaque/plin
03d8b2ca0b070f9247376c40e1f3a4655e579dd0
kibitzr/notifier/telegram-split.py
kibitzr/notifier/telegram-split.py
from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) ...
from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) ...
Use parent 'post' function to actually send message
Use parent 'post' function to actually send message
Python
mit
kibitzr/kibitzr,kibitzr/kibitzr
0b7cdb4b5a6dab5f2983313d745bea84ff302e01
Machines/wxMachines.py
Machines/wxMachines.py
# -*- coding: utf-8 -*- # Import # Import for changing the Python Path for importing Gestalt import sys import os # Change the Python Path base_dir = os.path.dirname(__file__) or '.' appdir = os.path.abspath(os.path.join(base_dir, os.pardir)) sys.path.insert(0, appdir) # Import Gestalt from gestalt import nodes fro...
# -*- coding: utf-8 -*- # Import # Import for changing the Python Path for importing Gestalt import sys import os # Change the Python Path base_dir = os.path.dirname(__file__) or '.' appdir = os.path.abspath(os.path.join(base_dir, os.pardir)) sys.path.insert(0, appdir) # Import Gestalt from gestalt import nodes fro...
Improve general classes with input from Ilan Ellison Moyer's thesis
Improve general classes with input from Ilan Ellison Moyer's thesis
Python
mit
openp2pdesign/wxGestalt
610d9a3c58f70d8b2002403003b705dd57513d92
manage.py
manage.py
#!/usr/bin/env python import os import sys from django.core.management import execute_from_command_line from wger.main import get_user_config_path, setup_django_environment if __name__ == "__main__": setup_django_environment( get_user_config_path('wger', 'settings.py')) #os.environ.setdefaul...
#!/usr/bin/env python import sys from django.core.management import execute_from_command_line from wger.utils.main import ( setup_django_environment, get_user_config_path ) if __name__ == "__main__": setup_django_environment( get_user_config_path('wger', 'settings.py')) #os.environ.s...
Change imports of helper functions
Change imports of helper functions These are now in the utils app
Python
agpl-3.0
rolandgeider/wger,kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,wger-project/wger,wger-project/wger,rolandgeider/wger,DeveloperMal/wger,DeveloperMal/wger,wger-project/wger,peter...
8ae1a0793e1938cf845b249d0133e7fc352cda5b
django/website/logframe/tests/test_period_utils.py
django/website/logframe/tests/test_period_utils.py
from datetime import date from ..period_utils import get_month_shift, get_periods def test_get_month_shift_handles_december(): new_month, _ = get_month_shift(12, 1) assert 12 == new_month def test_get_periods_when_end_date_before_period_end(): # This should produce eight periods, 2 for each of the year...
from datetime import date, timedelta from ..period_utils import get_month_shift, get_periods, periods_intersect def test_get_month_shift_handles_december(): new_month, _ = get_month_shift(12, 1) assert 12 == new_month def test_get_periods_when_end_date_before_period_end(): # This should produce eight p...
Add tests for period_intersect logic
Add tests for period_intersect logic
Python
agpl-3.0
aptivate/alfie,daniell/kashana,aptivate/alfie,daniell/kashana,aptivate/kashana,aptivate/kashana,daniell/kashana,daniell/kashana,aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana
74ededafa70c7ec5548d86289c6dbfc5e4cff6f2
tests/integration/ssh/test_deploy.py
tests/integration/ssh/test_deploy.py
# -*- coding: utf-8 -*- ''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple pin...
# -*- coding: utf-8 -*- ''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import import os import shutil # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' ...
Add ssh thin_dir integration test
Add ssh thin_dir integration test
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
1ef311a2bef956acf09c8aae21f2e1e27c02e511
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Update dsub version to 0.1.3.dev0
Update dsub version to 0.1.3.dev0 PiperOrigin-RevId: 173965107
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
7a732c70fb5e07181aeb8f2386230fbecf0667e9
test/test_historynode.py
test/test_historynode.py
""" Tests for the HistoryNode module """ pass
""" Tests for the HistoryNode module """ from contextlib import contextmanager from io import StringIO import sys import unittest from src import historynode @contextmanager def captured_output(): """ Redirects stdout to StringIO so we can inspect Print statements """ new_out = StringIO() old_out = sys.s...
Add unit test for print_board()
Add unit test for print_board()
Python
mit
blairck/jaeger
b5ca3dd7b5c743987223b42e302a4044367d4dc9
opps/core/admin/article.py
opps/core/admin/article.py
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from opps.core.models import Post, PostImage from redactor.widgets import RedactorEditor class PostImageInline(admin.TabularInline): model = PostImage fk_name = 'post' raw_id_fields = ['image'] actions = None extr...
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from opps.core.models import Post, PostImage, PostSource from redactor.widgets import RedactorEditor class PostImageInline(admin.TabularInline): model = PostImage fk_name = 'post' raw_id_fields = ['image'] actions = N...
Create post source inline (admin Tabular Inline) on core post
Create post source inline (admin Tabular Inline) on core post
Python
mit
YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps
f627a76e8dac96282b0a9f76eeda8c7db70cc030
telemetry/telemetry/internal/actions/javascript_click.py
telemetry/telemetry/internal/actions/javascript_click.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.internal.actions import page_action class ClickElementAction(page_action.ElementPageAction): def RunAction(self, tab): code = ''' ...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.internal.actions import page_action class ClickElementAction(page_action.ElementPageAction): def RunAction(self, tab): code = ''' ...
Fix a regression where the user_gesture bit isn't set for ClickElement.
Fix a regression where the user_gesture bit isn't set for ClickElement. The regrssion was introduced in https://chromium-review.googlesource.com/c/catapult/+/1335627 Once this rolls into Chromium, I'll add a chromium side test to prevent it from regress again in the future. Bug: chromium:885912 TEST=manual R=58bdb62...
Python
bsd-3-clause
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
9e7dc537d09555d9c77ff5e1f16f5577721910f9
runtests.py
runtests.py
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'consol...
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'consol...
Fix issue with old wagtail core paths
Fix issue with old wagtail core paths
Python
mit
Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget
145158b5a1693a831d2d198473d24b9d4ef6e24e
sherlock.py
sherlock.py
# -*- coding: utf-8 -*- import sys, datetime, getopt from reddit_user import RedditUser longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="]) args = dict(longopts) file_mode = "" if len(sys.argv) < 2: sys.exit("Usage: python sherlock.py <username> --file=(read|write)") if args.has_ke...
# -*- coding: utf-8 -*- import sys, datetime, getopt from reddit_user import RedditUser longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="]) args = dict(longopts) file_mode = "" if len(sys.argv) < 2: sys.exit("Usage: python sherlock.py <username> --file=(read|write)") if args.has_ke...
Write output to text file
Write output to text file
Python
mit
orionmelt/sherlock
4c6784bd17113261b95178deadd037ef3c8ea830
normandy/recipes/tests/__init__.py
normandy/recipes/tests/__init__.py
import factory from normandy.base.tests import FuzzyUnicode from normandy.recipes.models import Action, Recipe, RecipeAction class RecipeFactory(factory.DjangoModelFactory): class Meta: model = Recipe name = FuzzyUnicode() enabled = True class ActionFactory(factory.DjangoModelFactory): cla...
import factory from normandy.base.tests import FuzzyUnicode from normandy.recipes.models import Action, Locale, Recipe, RecipeAction class RecipeFactory(factory.DjangoModelFactory): class Meta: model = Recipe name = FuzzyUnicode() enabled = True @factory.post_generation def locale(self,...
Fix tests to handle Locale as a foreign key.
Fix tests to handle Locale as a foreign key.
Python
mpl-2.0
mozilla/normandy,Osmose/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy
618dcb272a2b19e0cd3b973e65d74085775cf4dd
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_fr...
Change key and value to more descriptive names
Change key and value to more descriptive names
Python
apache-2.0
billyhunt/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,jnayak1/osf.io,alexschiller/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,Ghalko/osf.io,doublebits/osf.io,leb2dg/osf.io,TomHeatwole/osf.io,laurenrevere/osf.io,adlius/osf.io,cosenal/osf.io,samanehs...
a1e1f0661331f5bf8faa81210eae2cad0c2ad7b3
calico_containers/tests/st/__init__.py
calico_containers/tests/st/__init__.py
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/ca...
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/ca...
Fix bug in file path.
Fix bug in file path.
Python
apache-2.0
dalanlan/calico-docker,projectcalico/calico-docker,L-MA/calico-docker,robbrockbank/calicoctl,insequent/calico-docker,TeaBough/calico-docker,Metaswitch/calico-docker,CiscoCloud/calico-docker,frostynova/calico-docker,L-MA/calico-docker,insequent/calico-docker,webwurst/calico-docker,Symmetric/calico-docker,TrimBiggs/calic...
4aeb2496eb02e130b7dbc37baef787669f8dd1e7
typesetter/typesetter.py
typesetter/typesetter.py
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] with open('typesetter/data/words...
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().spli...
Reduce search response time by keeping wordlist in memory
Reduce search response time by keeping wordlist in memory
Python
mit
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
dac4ef0e30fb5dd26ef41eb74854919cf5295450
subprocrunner/error.py
subprocrunner/error.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals class CommandError(Exception): @property def errno(self): return self.__errno def __init__(self, *args, **kwargs): self.__errno = kwargs.pop...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals class CommandError(Exception): @property def cmd(self): return self.__cmd @property def errno(self): return self.__errno def __init...
Add a property to an exception class
Add a property to an exception class
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
c17b8e6141d2832b9920eb143de2937993fb8865
linguist/models/base.py
linguist/models/base.py
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.C...
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.C...
Rename locale field to language.
Rename locale field to language.
Python
mit
ulule/django-linguist