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 |
|---|---|---|---|---|---|---|---|---|---|
89c005e2fd7d7f7727ba225cc20789fea992b1d4 | backend/scripts/mktemplate.py | backend/scripts/mktemplate.py | #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
... | #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
... | Update script to show which file it is loading. | Update script to show which file it is loading.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
6ac4764790526f435ffc6337145439d710dd455f | virtualenv/__init__.py | virtualenv/__init__.py | from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from virtualenv.core import create
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__aut... | from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from virtualenv.core import create
def create_environment(
home_dir,
site_packages=False, clear=False,
... | Add a backwards compatible create_environment. | Add a backwards compatible create_environment.
| Python | mit | ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv |
7822687bb78cbe422af0d707a1ed7fc94011628d | castor/tasks.py | castor/tasks.py | from celery import Celery
from settings import SETTINGS
import requests
HOOKS = SETTINGS.get('hooks', [])
CELERY_SETTINGS = SETTINGS.get('celery', {})
app = Celery()
app.conf.update(**CELERY_SETTINGS)
@app.task
def dispatch_event(event):
event_repr = '%s:%s' % (event['id'][:10], event['status'])
for url in... | from celery import Celery
from settings import SETTINGS
import requests
HOOKS = SETTINGS.get('hooks', [])
CELERY_SETTINGS = SETTINGS.get('celery', {})
app = Celery()
app.conf.update(**CELERY_SETTINGS)
@app.task
def dispatch_event(event):
event_repr = '%s:%s' % (event['id'][:10], event['status'])
for url in... | Return event dictionary at the end of the task. | Return event dictionary at the end of the task.
| Python | mit | sourcelair/castor |
84d743476261d30b352e3bfc103d76e7e8350b4c | tests/test_urls.py | tests/test_urls.py | """
Testing of project level URLs.
"""
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from urltools import compare
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify tha... | """
Testing of project level URLs.
"""
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
import ssl
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protec... | Disable SSL validation for a test which uses urltools | Disable SSL validation for a test which uses urltools
This is currently a common problem with python >= 2.7.9:
http://stackoverflow.com/questions/27835619/ssl-certificate-verify-failed-error
| Python | agpl-3.0 | mitodl/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,mitodl/lore,mitodl/lore,mitodl/lore,amir-qayyum-khan/lore,mitodl/lore |
a17d3fbf19b25e1da568266b17abe575071e3f80 | server/lib/utils.py | server/lib/utils.py | import yaml
import json
import os
import uuid
def loadFromFile(path, bytes=False):
from config import PATH
if not os.path.isabs(path):
path = os.path.join(PATH, path)
readType = 'r' if not bytes else 'rb'
with open(path, readType) as file:
fileContents = file.read()
file.close()
... | import yaml
import json
import os
import uuid
def loadFromFile(path, bytes=False):
from config import PATH
if not os.path.isabs(path):
path = os.path.join(PATH, path)
readType = 'r' if not bytes else 'rb'
with open(path, readType, encoding='utf-8') as file:
fileContents = file.read()
... | Fix not being able to parse diacritics | Fix not being able to parse diacritics
| Python | agpl-3.0 | MakersLab/custom-print |
57b1dbc45e7b78f7aa272fd5b7d4bd022850beb9 | lametro/migrations/0007_update_packet_links.py | lametro/migrations/0007_update_packet_links.py | # Generated by Django 2.2.24 on 2021-10-22 19:54
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
for packet in ('BillPacket', 'EventPacket'):
packet_model = apps.get_m... | # Generated by Django 2.2.24 on 2021-10-22 19:54
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
# for packet in ('BillPacket', 'EventPacket'):
# packet_model = apps.get... | Disable data migration for deployment | Disable data migration for deployment
| Python | mit | datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic |
ce36dd825635c8487fcd9f83bd686a2dce7c318c | hello.py | hello.py | from flask import Flask
from flask import request
import os
from dogapi import dog_http_api as api
app = Flask(__name__)
api.api_key = os.environ.get('DD_API_KEY')
action_url = "/" + os.environ.get('BASE_URL') + "/"
@app.route(action_url, methods=['POST', 'GET'])
def hello():
api.metric('mailgun.event', (reques... | from flask import Flask
from flask import request
import os
from dogapi import dog_http_api as api
app = Flask(__name__)
api.api_key = os.environ.get('DD_API_KEY')
action_url = "/" + os.environ.get('BASE_URL') + "/"
@app.route(action_url, methods=['POST', 'GET'])
def hello():
api.metric('mailgun.event', (reques... | Use the right style of request. | Use the right style of request.
| Python | apache-2.0 | darron/mailgun_datadog |
c711d5e2dbca4b95bebc0eed4d48a35eb3c7a998 | website/addons/dropbox/settings/local-dist.py | website/addons/dropbox/settings/local-dist.py | # -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
| # -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'jnpncg5s2fc7cj8'
DROPBOX_SECRET = 'sjqv1hrk7sonhu1' | Add dropbox credentials for testing. | Add dropbox credentials for testing.
| Python | apache-2.0 | crcresearch/osf.io,acshi/osf.io,felliott/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,jnayak1/osf.io,baylee-d/osf.io,TomBaxter/osf.io,mluke93/osf.io,mluo613/osf.io,pattisdr/osf.io,samchrisinger/osf.io,wearpants/osf.io,mfraezz/osf.io,kch8qx/osf.io,Nesiehr/osf.io,adlius/osf.io,RomanZWang/osf.io,abought/osf.io,felliott/osf... |
df3bbdcf08dafbf2fd6997638a575fb4e47ac61f | factory/tools/cat_StarterLog.py | factory/tools/cat_StarterLog.py | #!/bin/env python
#
# cat_StarterLog.py
#
# Print out the StarterLog for a glidein output file
#
# Usage: cat_StarterLog.py logname
#
import os.path
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StarterLog.py [-monitor] <logname>"
def main(... | #!/bin/env python
#
# cat_StarterLog.py
#
# Print out the StarterLog for a glidein output file
#
# Usage: cat_StarterLog.py logname
#
import os.path
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StarterLog.py [-monitor] <logname>"
def main(... | Add support for monitor starterlog | Add support for monitor starterlog
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS |
dd6c3abcfc01b22528440e5dd62a1d3d3453b8b3 | djangopress/templatetags/djangopress_tags.py | djangopress/templatetags/djangopress_tags.py | """Templatetags for djangopress."""
from datetime import date
from collections import defaultdict
from django import template
from djangopress.models import Post, Category
register = template.Library()
@register.inclusion_tag('djangopress/tags/archive_list.html')
def archive_list():
"""List post by date"""
... | """Templatetags for djangopress."""
from datetime import date
from collections import defaultdict
from django import template
from djangopress.models import Post, Category
register = template.Library()
@register.inclusion_tag('djangopress/tags/archive_list.html')
def archive_list():
"""List post by date"""
... | Sort the months in archive_templatetag | Sort the months in archive_templatetag
| Python | mit | gilmrjc/djangopress,gilmrjc/djangopress,gilmrjc/djangopress |
226cb45ba39d13c4bf2b40f3998b2631f9f461a6 | Lib/cluster/__init__.py | Lib/cluster/__init__.py | #
# cluster - Vector Quantization / Kmeans
#
from info import __doc__
__all__ = ['vq']
import vq
| #
# cluster - Vector Quantization / Kmeans
#
from info import __doc__
__all__ = ['vq']
import vq
from numpy.testing import NumpyTest
test = NumpyTest().test
| Add missing test definition in scipy.cluster | Add missing test definition in scipy.cluster
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@2941 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor |
1317d645092d94c95bcaf7a0341ac18208f9df0d | patient/admin.py | patient/admin.py | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Patient
from django import forms
class CustomPatientForm(forms.ModelForm):
class Meta:
model = Patient
def __init__(self, *args, **kwargs):
super(CustomPatientForm, self).__init__(*args, **kwargs)... | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Patient
from django import forms
class CustomPatientForm(forms.ModelForm):
class Meta:
model = Patient
exclude = []
def __init__(self, *args, **kwargs):
super(CustomPatientForm, self).__in... | Fix deprecated warning in CustomPatientForm | Fix deprecated warning in CustomPatientForm
| Python | mit | sigurdsa/angelika-api |
39461a97ef6e6b988466f41ddfee17687dd59ee1 | notifications/match_score.py | notifications/match_score.py | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
sel... | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
sel... | Add event key to match score notification | Add event key to match score notification | Python | mit | bdaroz/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-allianc... |
6623d5679eef2c3db70edce7334582b5d524786d | micro.py | micro.py | #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def evaluate(tokens):
name = tokens[0]
tokens = tokens[1:]
if ... | #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def parse_function(tokens):
return 'test', (23, None), tokens[-1... | Add a detection of a function definition. | Add a detection of a function definition.
| Python | mit | thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro |
46afcd0e5e958e22647ef9c708918489027277e2 | modeltranslation/tests/settings.py | modeltranslation/tests/settings.py | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INS... | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INS... | Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled. | Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled.
| Python | bsd-3-clause | extertioner/django-modeltranslation,marctc/django-modeltranslation,yoza/django-modeltranslation,nanuxbe/django-modeltranslation,akheron/django-modeltranslation,vstoykov/django-modeltranslation,SideStudios/django-modeltranslation,yoza/django-modeltranslation,marctc/django-modeltranslation,deschler/django-modeltranslatio... |
9e27c8f803c42e65ec333ed1679ea70a5618f3c6 | dunya/test_settings.py | dunya/test_settings.py | from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
| from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
from xmlrunner.extra.djangotestrunner import XMLTestRunner
from django.test.runner import DiscoverRunner
from django.db import connections, DEFAULT_DB_ALIAS
# We use the XMLTestRunner on CI
class DunyaTestRunner(XMLTestRunner):
#class DunyaTe... | Update test settings to create the unaccent ext if needed | Update test settings to create the unaccent ext if needed
| Python | agpl-3.0 | MTG/dunya,MTG/dunya,MTG/dunya,MTG/dunya |
ad415f26eec5c6a20c26123ccb6ce3e320ea9a69 | zou/app/blueprints/crud/asset_instance.py | zou/app/blueprints/crud/asset_instance.py | from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init... | from zou.app.models.asset_instance import AssetInstance
from zou.app.services import assets_service, user_service
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class AssetInstancesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init... | Change asset instance update permissions | Change asset instance update permissions
* Do not allow to change instance number
* Allow to change instance name by a CG artist
| Python | agpl-3.0 | cgwire/zou |
2afe09bcbcc728e98ec8da39b68ea65f4c270fdb | html5lib/trie/_base.py | html5lib/trie/_base.py | from __future__ import absolute_import, division, unicode_literals
from collections import Mapping
class Trie(Mapping):
"""Abstract base class for tries"""
def keys(self, prefix=None):
keys = super().keys()
if prefix is None:
return set(keys)
# Python 2.6: no set compre... | from __future__ import absolute_import, division, unicode_literals
from collections import Mapping
class Trie(Mapping):
"""Abstract base class for tries"""
def keys(self, prefix=None):
keys = super(Trie, self).keys()
if prefix is None:
return set(keys)
# Python 2.6: no ... | Make this in practice unreachable code work on Py2 | Make this in practice unreachable code work on Py2
| Python | mit | html5lib/html5lib-python,html5lib/html5lib-python,html5lib/html5lib-python |
5c5b81312317c1750ea320666b2adc4f74d13366 | f8a_jobs/graph_sync.py | f8a_jobs/graph_sync.py | """Functions to retrieve pending list and invoke Graph Sync."""
import f8a_jobs.defaults as configuration
import requests
import traceback
import logging
from urllib.parse import urljoin
logger = logging.getLogger(__name__)
def _api_call(url, params=None):
params = params or {}
try:
logger.info("AP... | """Functions to retrieve pending list and invoke Graph Sync."""
import f8a_jobs.defaults as configuration
import requests
import traceback
import logging
from urllib.parse import urljoin
logger = logging.getLogger(__name__)
def _api_call(url, params=None):
params = params or {}
try:
logger.info("AP... | Fix code for review comments | Fix code for review comments
| Python | apache-2.0 | fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs |
270a03dc78838137051fec49050f550c44be2359 | facebook_auth/views.py | facebook_auth/views.py | import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
next_url =... | import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
... | Add facebook error handler in view. | Add facebook error handler in view.
This assumes that there is no other backend which
can authenticate user with facebook credentials.
| Python | mit | jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth |
088d76bbe01a9a6dd0a246be8ce703d5b64c540e | Lib/hotshot/__init__.py | Lib/hotshot/__init__.py | """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._... | """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._... | Allow user code to call the addinfo() method on the profiler object. | Allow user code to call the addinfo() method on the profiler object.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
d89715196ba79da02a997688414dfa283bee5aeb | profiles/tests/test_views.py | profiles/tests/test_views.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from utils.factories import UserFactory
from profiles.views import ProfileView
class ProfileViewTests(TestCase):
def setUp(self):
request_factory = RequestFactory()
request... | from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from utils.factories import UserFactory
from profiles.views import (
ProfileView,
ReviewUserView,
)
class ProfileViewTests(TestCase):
def setUp(self):
request_factory = Req... | Add tests for user review view | Add tests for user review view
| Python | mit | phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts |
f2a46687e24d82060b687922de3495111f82e558 | geist/backends/fake.py | geist/backends/fake.py | import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, w=800, h=600):
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
def create_process(self, command):
pass
def actions_transaction(self):
... | import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, image=None, w=800, h=600):
if image is None:
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
else:
if isinstance(imag... | Allow Fake Backend to take an image as the screen | Allow Fake Backend to take an image as the screen
| Python | mit | kebarr/Geist,thetestpeople/Geist |
aded1c825385817dc39d8ff99c169e6620008abf | blivet/populator/helpers/__init__.py | blivet/populator/helpers/__init__.py | from .btrfs import BTRFSFormatPopulator
from .boot import AppleBootFormatPopulator, EFIFormatPopulator, MacEFIFormatPopulator
from .disk import DiskDevicePopulator
from .disklabel import DiskLabelFormatPopulator
from .dm import DMDevicePopulator
from .dmraid import DMRaidFormatPopulator
from .loop import LoopDevicePopu... | import inspect as _inspect
from .devicepopulator import DevicePopulator
from .formatpopulator import FormatPopulator
from .btrfs import BTRFSFormatPopulator
from .boot import AppleBootFormatPopulator, EFIFormatPopulator, MacEFIFormatPopulator
from .disk import DiskDevicePopulator
from .disklabel import DiskLabelForma... | Add functions to return a helper class based on device data. | Add functions to return a helper class based on device data.
This is intended to be the complete API of populator.helpers.
| Python | lgpl-2.1 | vojtechtrefny/blivet,jkonecny12/blivet,vojtechtrefny/blivet,rhinstaller/blivet,rhinstaller/blivet,rvykydal/blivet,AdamWill/blivet,rvykydal/blivet,vpodzime/blivet,AdamWill/blivet,jkonecny12/blivet,vpodzime/blivet |
d6759d0abec637753d93cd407fad5e7abc6ec86d | astropy/tests/plugins/display.py | astropy/tests/plugins/display.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This plugin now lives in pytest-astropy, but we keep the code below during
# a deprecation phase.
import warnings
from astropy.utils.exceptions import AstropyDeprecationWarning
try:
from pytest_astropy_header.display import PYTEST_HEADER_MODULES, ... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This plugin now lives in pytest-astropy, but we keep the code below during
# a deprecation phase.
import warnings
from astropy.utils.exceptions import AstropyDeprecationWarning
try:
from pytest_astropy_header.display import (PYTEST_HEADER_MODULES,... | Fix typo in deprecation warning | TST: Fix typo in deprecation warning [ci skip]
| Python | bsd-3-clause | stargaser/astropy,dhomeier/astropy,saimn/astropy,saimn/astropy,larrybradley/astropy,astropy/astropy,StuartLittlefair/astropy,lpsinger/astropy,dhomeier/astropy,lpsinger/astropy,StuartLittlefair/astropy,larrybradley/astropy,lpsinger/astropy,MSeifert04/astropy,astropy/astropy,astropy/astropy,MSeifert04/astropy,larrybradle... |
e3bac9c0a655ae49d6e15b16894712f4edbc994b | campus02/web/views/primarykey.py | campus02/web/views/primarykey.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from rest_framework import viewsets
from rest_framework.filters import DjangoObjectPermissionsFilter
from .. import (
models,
permissions,
)
from ..serializers import (
primarykey as serializers
)
class MovieViewSet(viewsets.ReadOnlyModelViewSet):
queryset =... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from rest_framework import viewsets, filters
from .. import (
models,
permissions,
)
from ..serializers import (
primarykey as serializers
)
class MovieViewSet(viewsets.ReadOnlyModelViewSet):
queryset = models.Movie.objects.all()
serializer_class = seria... | Add ordering filters for primary key based api. | Add ordering filters for primary key based api.
| Python | mit | fladi/django-campus02,fladi/django-campus02 |
06645a637c0d34270f88f9a6b96133da5c415dd7 | froide/publicbody/admin.py | froide/publicbody/admin.py | from django.contrib import admin
from froide.publicbody.models import PublicBody, FoiLaw
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("geography", "name",)}
list_display = ('name', 'classification', 'geography')
list_filter = ('classification',)
search_fields = ['name', "des... | from django.contrib import admin
from froide.publicbody.models import PublicBody, FoiLaw
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("geography", "name",)}
list_display = ('name', 'classification', 'topic', 'geography')
list_filter = ('classification', 'topic',)
search_fiel... | Add topic to PublicBodyAdmin list_filter and list_display | Add topic to PublicBodyAdmin list_filter and list_display | Python | mit | catcosmo/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,fin/froide,CodeforHawaii/froide,fin/froide,okfse/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,ryankanno/froide,LilithWittmann/froide,LilithWittmann/froide,CodeforHawaii/froide,fin/froide,catcosmo/froide,catcosmo/froide,okfse/froide,ryankanno/fr... |
621d285c05ce3a6257edcffec03c8a96507b6179 | name/feeds.py | name/feeds.py | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse_lazy
from django.utils.feedgenerator import Atom1Feed
from . import app_settings
from .models import Name, Location
class NameAtomFeedType(Atom1Feed):
"""Create an Atom feed that sets the Content-Type response
head... | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse_lazy
from django.utils.feedgenerator import Atom1Feed
from . import app_settings
from .models import Name
class NameAtomFeedType(Atom1Feed):
"""Create an Atom feed that sets the Content-Type response
header to appl... | Change the formating of item_description. Remove item_location because it was not used. | Change the formating of item_description. Remove item_location because it was not used.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name,damonkelley/django-name |
002dd6fa4af36bd722b3f194c93f1e2e628ad561 | inboxen/app/model/email.py | inboxen/app/model/email.py | from inboxen.models import Alias, Attachment, Email, Header
from config.settings import datetime_format, recieved_header_name
from datetime import datetime
def make_email(message, alias, domain):
inbox = Alias.objects.filter(alias=alias, domain__domain=domain)[0]
user = inbox.user
body = message.base.body
... | from inboxen.models import Alias, Attachment, Email, Header
from config.settings import datetime_format, recieved_header_name
from datetime import datetime
def make_email(message, alias, domain):
inbox = Alias.objects.filter(alias=alias, domain__domain=domain)[0]
user = inbox.user
body = message.base.body
... | Reduce number of queries to DB | Reduce number of queries to DB
| Python | agpl-3.0 | Inboxen/router,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen |
1ecd6cacac15bff631b958ee6773b2ad8659df50 | opps/images/widgets.py | opps/images/widgets.py | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rend... | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rend... | Create widget CropExample on images | Create widget CropExample on images
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps |
1a03fbbb612d8faa5a6733fe7d4920f3ca158a69 | acme/utils/observers.py | acme/utils/observers.py | # Copyright 2018 DeepMind Technologies Limited. 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 ... | # Copyright 2018 DeepMind Technologies Limited. 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 ... | Add a missing @abc.abstractmethod declaration | Add a missing @abc.abstractmethod declaration
PiperOrigin-RevId: 424036906
Change-Id: I3979c35ec30caa4b684d43376b2a36d21f7e79df
| Python | apache-2.0 | deepmind/acme,deepmind/acme |
018d062f2ed9ca9acd3d555d439dd81b89c88a6f | parse_push/managers.py | parse_push/managers.py |
from django.db import models
class DeviceManager(models.Manager):
def latest(self):
""" Returns latest Device instance """
return self.latest('created_at')
|
from django.db import models
class DeviceManager(models.Manager):
def get_latest(self):
""" Returns latest Device instance """
return self.get_queryset().latest('created_at')
| Use .get_latest() instead so that we do not override built-in .latest() | Use .get_latest() instead so that we do not override built-in .latest()
| Python | bsd-3-clause | willandskill/django-parse-push |
ab2f4aaf9546787a269a3d0ec5b3b83c86a43bde | Languages.py | Languages.py | #!/usr/bin/env python3
import requests
import re
def findAllLanguages():
"Find a list of Crowdin language codes to which KA is translated to"
response = requests.get("https://crowdin.com/project/khanacademy")
txt = response.text
for match in re.findall(r"https?://[a-z0-9]*\.cloudfront\.net/images/flags... | #!/usr/bin/env python3
import requests
import re
def findAllLanguages():
"Find a list of Crowdin language codes to which KA is translated to"
response = requests.get("https://crowdin.com/project/khanacademy")
txt = response.text
langs = set()
for match in re.findall(r"https?://[a-z0-9]*\.cloudfront... | Return language set instead of language generator | Return language set instead of language generator
| Python | apache-2.0 | ulikoehler/KATranslationCheck,ulikoehler/KATranslationCheck,KA-Advocates/KATranslationCheck,KA-Advocates/KATranslationCheck,ulikoehler/KATranslationCheck,KA-Advocates/KATranslationCheck,ulikoehler/KATranslationCheck,ulikoehler/KATranslationCheck,KA-Advocates/KATranslationCheck |
8d313884a52b06e2fdf9a3c0d152b9e711ff02c2 | kkbox/trac/secretticket.py | kkbox/trac/secretticket.py | from trac.core import Component, implements
from trac.perm import IPermissionRequestor
class KKBOXSecretTicketsPolicy(Component):
implements(IPermissionRequestor)
def get_permission_actions(self):
return ['SECRET_VIEW']
| from trac.ticket.model import Ticket
from trac.core import Component, implements, TracError
from trac.perm import IPermissionPolicy
class KKBOXSecretTicketsPolicy(Component):
implements(IPermissionPolicy)
def __init__(self):
config = self.env.config
self.sensitive_keyword = config.get('kkbox',... | Mark ticket as sensitive by keyword | Mark ticket as sensitive by keyword
Set sensitive_keyword in trac.ini as following example, These ticket has
"secret" keyword are viewable by reporter, owner and cc.
[kkbox]
sensitive_keyword = secret
| Python | bsd-3-clause | KKBOX/trac-keyword-secret-ticket-plugin |
01516489dbf9ee78128d653b3ebc46730d466425 | apps/api/serializers.py | apps/api/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game, Platform
from apps.subscribers.models import Ticket
class HostSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'timestamp... | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game, Platform
from apps.subscribers.models import Ticket
class HostSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'timestamp... | Add appearance count to the API. | Add appearance count to the API.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv |
8ee38953a9f8bdbd95ace4ea45e3673cc260bb4b | scripts/cronRefreshEdxQualtrics.py | scripts/cronRefreshEdxQualtrics.py | import getopt
import sys
import os
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
# sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
source_dir = [os.path.join(os.path.dir... | #!/usr/bin/env python
import getopt
import sys
import os
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
# sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
source_dir = [o... | Add python environment to cron qualtrics script | Add python environment to cron qualtrics script
| Python | bsd-3-clause | paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation |
ff0468f51b6a5cebd00f2cea8d2abd5f74e925d6 | ometa/tube.py | ometa/tube.py | from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incomin... | from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incomin... | Update TrampolinedParser a little for my purposes. | Update TrampolinedParser a little for my purposes.
| Python | mit | rbtcollins/parsley,python-parsley/parsley,python-parsley/parsley,rbtcollins/parsley |
3263a691db55ed72c4f98096748ad930c7ecdd68 | setup.py | setup.py | #!/usr/bin/env python
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Py... | #!/usr/bin/env python
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Py... | Update repository addresses and emails | Update repository addresses and emails
| Python | mit | jleclanche/python-ptch |
2fa8b2f4a63579633272b1cc8d972baf27c661f2 | pmg/models/__init__.py | pmg/models/__init__.py | from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import *
| from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import SoundcloudTrack
| Fix error on admin user_report view | Fix error on admin user_report view
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 |
678e872de192b09c1bafc7a26dc67d7737a14e20 | altair/examples/us_population_over_time.py | altair/examples/us_population_over_time.py | """
US Population Over Time
=======================
This chart visualizes the age distribution of the US population over time.
It uses a slider widget that is bound to the year to visualize the age
distribution over time.
"""
# category: case studies
import altair as alt
from vega_datasets import data
source = data.po... | """
US Population by Age and Sex
============================
This chart visualizes the age distribution of the US population over time.
It uses a slider widget that is bound to the year to visualize the age
distribution over time.
"""
# category: case studies
import altair as alt
from vega_datasets import data
source... | Tidy up U.S. Population by Age and Sex | Tidy up U.S. Population by Age and Sex | Python | bsd-3-clause | altair-viz/altair |
15e66e00be22d7177fcba292720f55f548839469 | packages/dependencies/intel_quicksync_mfx.py | packages/dependencies/intel_quicksync_mfx.py | {
'repo_type' : 'git',
'url' : 'https://github.com/lu-zero/mfx_dispatch.git',
'conf_system' : 'cmake',
'source_subfolder' : '_build',
'configure_options' : '.. {cmake_prefix_options} -DCMAKE_INSTALL_PREFIX={target_prefix} -DBUILD_SHARED_LIBS=0 -DCMAKE_BUILD_TYPE=Release',
'_info' : { 'version' : None, 'fancy_name... | {
'repo_type' : 'git',
'do_not_bootstrap' : True,
'run_post_patch' : [
'autoreconf -fiv',
],
'patches' : [
( 'mfx/mfx-0001-mingwcompat-disable-va.patch', '-p1' ),
],
'url' : 'https://github.com/lu-zero/mfx_dispatch.git',
'configure_options' : '{autoconf_prefix_options} --without-libva_drm --without-libva_x1... | Revert "packages/quicksync-mfx: switch to cmake" | Revert "packages/quicksync-mfx: switch to cmake"
This reverts commit b3db211b42f26480fe817d26d7515ec8bd6e5c9e.
| Python | mpl-2.0 | DeadSix27/python_cross_compile_script |
5ffdfd7eb103d6974c3fb782eecaf457f53c972f | setup.py | setup.py | import os
from distutils.core import setup
version = '0.9.3'
def read_file(name):
return open(os.path.join(os.path.dirname(__file__),
name)).read()
readme = read_file('README.rst')
changes = read_file('CHANGES')
setup(
name='django-maintenancemode',
version=version,
des... | import os
from distutils.core import setup
version = '0.9.3'
here = os.path.abspath(os.path.dirname(__file__))
def read_file(name):
return open(os.path.join(here, name)).read()
readme = read_file('README.rst')
changes = read_file('CHANGES')
setup(
name='django-maintenancemode',
version=version,
des... | Use the absolute path for the long description to work around CI issues. | Use the absolute path for the long description to work around CI issues. | Python | bsd-3-clause | aarsan/django-maintenancemode,shanx/django-maintenancemode,aarsan/django-maintenancemode,21strun/django-maintenancemode,shanx/django-maintenancemode,21strun/django-maintenancemode |
1224552892d1d459864d5ab2dada328a20cc66e7 | jobs/spiders/tvinna.py | jobs/spiders/tvinna.py | import dateutil.parser
import scrapy.spiders
from jobs.items import JobsItem
class TvinnaSpider(scrapy.spiders.XMLFeedSpider):
name = "tvinna"
start_urls = ['http://www.tvinna.is/feed/?post_type=job_listing']
itertag = 'item'
namespaces = [
('atom', 'http://www.w3.org/2005/Atom'),
('c... | import dateutil.parser
import scrapy
import scrapy.spiders
from jobs.items import JobsItem
class TvinnaSpider(scrapy.spiders.XMLFeedSpider):
name = "tvinna"
start_urls = ['http://www.tvinna.is/feed/?post_type=job_listing']
itertag = 'item'
namespaces = [
('atom', 'http://www.w3.org/2005/Atom'... | Fix the extraction of the company name. | Fix the extraction of the company name.
There's an apparent bug in the Tvinna rss feed, such that the username of the person creating the listing is used in place of a company name in the `<cd:creator>` field. As a work around, we need to visit the job listing page, and extract it from that instead. It requires more r... | Python | apache-2.0 | multiplechoice/workplace |
2800e2cf0a7a998a5081929e6750265f30b09130 | tests/test_bql.py | tests/test_bql.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | Add some more trivial bql2sql tests. | Add some more trivial bql2sql tests.
| Python | apache-2.0 | probcomp/bayeslite,probcomp/bayeslite |
2d6e0710dbc781f54295e18299be6f4c1bb0ec43 | jsonmerge/jsonvalue.py | jsonmerge/jsonvalue.py | # vim:ts=4 sw=4 expandtab softtabstop=4
class JSONValue(object):
def __init__(self, val=None, ref='#', undef=False):
assert not isinstance(val, JSONValue)
self.val = val
self.ref = ref
self.undef = undef
def is_undef(self):
return self.undef
def _subval(self, key, ... | # vim:ts=4 sw=4 expandtab softtabstop=4
class JSONValue(object):
def __init__(self, val=None, ref='#', undef=False):
assert not isinstance(val, JSONValue)
self.val = val
self.ref = ref
self.undef = undef
def is_undef(self):
return self.undef
def _subval(self, key, ... | Fix Python3 support: remove iteritems | Fix Python3 support: remove iteritems
| Python | mit | avian2/jsonmerge |
bc0895f318a9297144e31da3647d6fc5716aafc4 | setup.py | setup.py | '''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))... | '''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))... | Make sure this works the first time you run it | Make sure this works the first time you run it
| Python | mit | skggm/skggm,skggm/skggm |
7e341014059c98bdd91a1c876982b8caa47a5586 | setup.py | setup.py | from __future__ import with_statement
from distutils.core import setup
def readme():
try:
with open('README.rst') as f:
return f.read()
except IOError:
return
setup(
name='encodingcontext',
version='0.9.0',
description='A bad idea about the default encoding',
lon... | from __future__ import with_statement
from distutils.core import setup
import re
def readme():
try:
with open('README.rst') as f:
readme = f.read()
except IOError:
return
return re.sub(
r'''
(?P<colon> : \n{2,})?
\.\. [ ] code-block:: \s+ [^\n]+ \n
... | Transform readme into PyPI compliant reST | Transform readme into PyPI compliant reST
| Python | mit | dahlia/encodingcontext |
ae280f4f837a23608749e8a8de1cbba98bafc621 | examples/mhs_atmosphere/mhs_atmosphere_plot.py | examples/mhs_atmosphere/mhs_atmosphere_plot.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, fields='density... | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# Axes flip for normal='y'
#ds.coordin... | Add x-y flipping code for SlicePlot | Add x-y flipping code for SlicePlot
| Python | bsd-2-clause | SWAT-Sheffield/pysac,Cadair/pysac |
64d4bcf0862e2715dc0de92a0621adf23dff5818 | source/harmony/schema/collector.py | source/harmony/schema/collector.py | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
from abc import ABCMeta, abstractmethod
class Collector(object):
'''Collect and return schemas.'''
__metaclass__ = ABCMeta
@abstractmethod
def collect(self):
'''Yield collected schemas.
... | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import os
from abc import ABCMeta, abstractmethod
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
raise ImportError('Could not import json or simp... | Support collecting schemas from filesystem. | Support collecting schemas from filesystem.
| Python | apache-2.0 | 4degrees/harmony |
3e403ed0962b62b19247dd1021f672507d003f07 | labware/microplates.py | labware/microplates.py | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
class Microplate(GridContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = 7.15
depth ... | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
class Microplate(GridContainer, LiquidContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = ... | Refactor of LiquidContainer vs. GridContainer to support grids which don't contain liquids. | Refactor of LiquidContainer vs. GridContainer to support grids which don't contain liquids.
| Python | apache-2.0 | OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons_sdk,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,Opentrons/labware |
451951b311ef6e2bb76348a116dc0465f735348e | pytest_watch/config.py | pytest_watch/config.py | try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import pytest
CLI_OPTION_PREFIX = '--'
class CollectConfig(object):
"""
A pytest plugin to gets the configuration file.
"""
def __init__(self):
self.path = None
def pytest_cmdli... | try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import pytest
CLI_OPTION_PREFIX = '--'
class CollectConfig(object):
"""
A pytest plugin to gets the configuration file.
"""
def __init__(self):
self.path = None
def pytest_cmdli... | Fix running when pytest.ini is not present. | Fix running when pytest.ini is not present.
| Python | mit | joeyespo/pytest-watch |
0f40869157ef56df0ff306fb510be4401b5cbe5d | test/low_level/test_frame_identifiers.py | test/low_level/test_frame_identifiers.py | import inspect
from pyinstrument.low_level import stat_profile as stat_profile_c
from pyinstrument.low_level import stat_profile_python
class AClass:
def get_frame_identfier_for_a_method(self, getter_function):
frame = inspect.currentframe()
assert frame
return getter_function(frame)
... | import inspect
from pyinstrument.low_level import stat_profile as stat_profile_c
from pyinstrument.low_level import stat_profile_python
class AClass:
def get_frame_identifier_for_a_method(self, getter_function):
frame = inspect.currentframe()
assert frame
return getter_function(frame)
... | Add test for a cell variable | Add test for a cell variable
| Python | bsd-3-clause | joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument |
d1da03b40e9a10a07b67eeb76a0bef8cc704a40c | utils/exporter.py | utils/exporter.py | import plotly as py
from os import makedirs
from utils.names import output_file_name
_out_dir = 'graphs/'
def export(fig, module, dates):
graph_dir = '{}{}/'.format(_out_dir, str(module))
makedirs(graph_dir, exist_ok=True)
py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates))
| import plotly as py
from os import makedirs
from utils.names import output_file_name
_out_dir = 'graphs/'
def export(fig, module, dates):
graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names
makedirs(graph_dir, exist_ok=True)
py.offline.plot(fig, filename=graph_di... | Remove .py extension from graph dir names | Remove .py extension from graph dir names
| Python | mit | f-jiang/sleep-pattern-grapher |
8f753ba1bc3f17146841d1f83f493adb8ea480e1 | voteit/stancer.py | voteit/stancer.py |
def generate_stances(blocs=[], filters={}):
return "banana!"
| from bson.code import Code
from voteit.core import votes
REDUCE = Code("""
function(obj, prev) {
if (!prev.votes.hasOwnProperty(obj.option)) {
prev.votes[obj.option] = 1;
} else {
prev.votes[obj.option]++;
}
//prev.count++;
};
""")
def generate_stances(blocs=[], filters={}):
data... | Replace “banana” with business logic (kind of). | Replace “banana” with business logic (kind of). | Python | mit | tmtmtmtm/voteit-api,pudo/voteit-server,pudo-attic/voteit-server |
6e8e7a067419166afd632aa63ecb743dd6c3a162 | geokey_dataimports/tests/test_model_helpers.py | geokey_dataimports/tests/test_model_helpers.py | # coding=utf-8
from io import BytesIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant un... | # coding=utf-8
from cStringIO import StringIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or rel... | Simplify test data for easier comparison. | Simplify test data for easier comparison.
| Python | mit | ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports |
b8e23194ff0c24bd9460629aff18f69d7a868f6d | likelihood.py | likelihood.py | import math
#Log-likelihood
def ll(ciphertext,perm,mat,k):
s=0.0
for i in range(len(ciphertext)-(k-1)):
kmer = tuple([perm[c] for c in ciphertext[i:i+k]])
s = s + math.log(mat[kmer])
return s
| import math
#Log-likelihood
def ll(ciphertext,perm,mat,k):
if k==1:
return ll_k1(ciphertext,perm,mat)
if k==2:
return ll_k2(ciphertext,perm,mat)
if k==3:
return ll_k3(ciphertext,perm,mat)
s=0.0
for i in range(len(ciphertext)-(k-1)):
kmer = tuple([perm[c] for c in ciph... | Add hard-coded versions of ll function for k=1,2,3 for speed | Add hard-coded versions of ll function for k=1,2,3 for speed
| Python | mit | gputzel/decode |
50596484c1214a73d3722af116ccea7fa258fb11 | direnaj/direnaj_api/celery_app/server_endpoint.py | direnaj/direnaj_api/celery_app/server_endpoint.py | __author__ = 'onur'
from celery import Celery
import direnaj_api.config.server_celeryconfig as celeryconfig
app_object = Celery()
app_object.config_from_object(celeryconfig)
@app_object.task
def deneme(x, seconds):
print "Sleeping for printing %s for %s seconds.." % (x, seconds)
import time
time.sleep(... | __author__ = 'onur'
from celery import Celery
import direnaj_api.config.server_celeryconfig as celeryconfig
app_object = Celery()
app_object.config_from_object(celeryconfig)
@app_object.task
def deneme(x, seconds):
print "Sleeping for printing %s for %s seconds.." % (x, seconds)
import time
time.sleep(... | Fix for periodic task scheduler (4) | Fix for periodic task scheduler (4)
| Python | mit | boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj |
6d2118a87dfb811015727970b1eda74c15769e06 | distutilazy/__init__.py | distutilazy/__init__.py | """
distutilazy
-----------
Extra distutils command classes.
:license: MIT, see LICENSE for more details.
"""
from os.path import dirname, abspath
import sys
__version__ = '0.4.0'
__all__ = ['clean', 'pyinstaller', 'command']
base_dir = abspath(dirname(dirname(__file__)))
if base_dir not in sys.path:
if len(sy... | """
distutilazy
-----------
Extra distutils command classes.
:license: MIT, see LICENSE for more details.
"""
from os.path import dirname, abspath
import sys
__version__ = "0.4.0"
__all__ = ("clean", "pyinstaller", "command")
base_dir = abspath(dirname(dirname(__file__)))
if base_dir not in sys.path:
if len(sy... | Replace ' with " to keep it consistant with other modules | Replace ' with " to keep it consistant with other modules
| Python | mit | farzadghanei/distutilazy |
8ffe217fe512296d41ae474c9d145ee2de599eac | src/constants.py | src/constants.py | class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?ut... | class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?ut... | Include all but have a supported set | Include all but have a supported set
Rather than commenting out the values, this seems more sensible. And pretty.. of
course.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in>
| Python | mit | venkateshshukla/th-editorials-server |
03cb3e001a25467319d0d82a5fc95e1c07ea3dd4 | setup.py | setup.py | from distutils.core import setup
import multi_schema
setup(
name = "django-multi-schema",
version = multi_schema.__version__,
description = "Postgres schema support in django.",
url = "http://hg.schinckel.net/django-multi-schema",
author = "Matthew Schinckel",
author_email = "matt@schinckel.net... | from distutils.core import setup
import multi_schema
setup(
name = "django-multi-schema",
version = multi_schema.__version__,
description = "Postgres schema support in django.",
url = "http://hg.schinckel.net/django-multi-schema",
author = "Matthew Schinckel",
author_email = "matt@schinckel.net... | Add south as a dependency, so we can apply a version. Does not need to be installed in INSTALLED_APPS. | Add south as a dependency, so we can apply a version.
Does not need to be installed in INSTALLED_APPS.
| Python | bsd-3-clause | luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse |
669280351b04d61df1de5ff03c4c7a258b37ad32 | sell/views.py | sell/views.py | from decimal import Decimal
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard
class SellWizard(BookChooserWizard):
@property
def page_title(self):
return _("Sell b... | from decimal import Decimal
import re
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard
class SellWizard(BookChooserWizard):
@property
def page_title(self):
return... | Delete non-digit characters in ISBN in server side | Delete non-digit characters in ISBN in server side
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda |
eeecf68d2d59bc2233478b01748cbf88bab85722 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
execfile('facebook/version.py')
setup(
name = 'Facebook',
version = __version__,
description = 'Facebook makes it even easier to interact with Facebook\'s Graph API',
long_description = open('README.rst').read() + '\n\n' + open('HISTORY.rst').rea... | #!/usr/bin/env python
from distutils.core import setup
execfile('facebook/version.py')
setup(
name='Facebook',
version=__version__,
description='Facebook makes it even easier to interact "+\
"with Facebook\'s Graph API',
long_description=open('README.rst').read() + '\n\n' +
open('... | Add missing requires and PEP8ize. | Add missing requires and PEP8ize.
| Python | mit | jgorset/facebook,vyyvyyv/facebook,jgorset/facebook,vyyvyyv/facebook |
51d0498f1c444f00ce982a93d8c9fdfb72a196b4 | setup.py | setup.py | #! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, 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
Unl... | #! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, 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
Unl... | Replace execfile() with exec() since it does not work with Python 3 | Replace execfile() with exec() since it does not work with Python 3
Signed-off-by: Christophe Vu-Brugier <1930e27f67e1e10d51770b88cb06d386f1aa46ae@yahoo.fr>
| Python | apache-2.0 | agrover/targetcli-fb,cloud4life/targetcli-fb,cvubrugier/targetcli-fb |
99b79326fa18f46fe449e11fd0bfa17814d7a148 | setup.py | setup.py | from distutils.core import setup
setup(
name='resync',
version='0.6.1',
packages=['resync'],
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Environment ... | from distutils.core import setup
setup(
name='resync',
version='0.6.1',
packages=['resync'],
scripts=['bin/resync'],
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
... | Add config to install resync script | Add config to install resync script
| Python | apache-2.0 | resync/resync,dans-er/resync,lindareijnhoudt/resync,lindareijnhoudt/resync,dans-er/resync |
13ef6879aeca9881483bd9f575d66377f1dde0c1 | tests/test_io.py | tests/test_io.py | import numpy as np
from tempfile import NamedTemporaryFile
from microscopium import io as mio
def test_imsave_tif_compress():
im = np.random.randint(0, 256, size=(1024, 1024, 3)).astype(np.uint8)
with NamedTemporaryFile(suffix='.tif') as fout:
fname = fout.name
fout.close()
mio.imsave(i... | import os
import numpy as np
from tempfile import NamedTemporaryFile
from microscopium import io as mio
from microscopium import pathutils as pth
def test_recursive_glob():
abspath = os.path.dirname(__file__)
tiffs0 = pth.all_matching_files(abspath, '*.tif')
assert len(tiffs0) == 8
assert tiffs0[0].st... | Improve test coverage by testing recursive glob | Improve test coverage by testing recursive glob
| Python | bsd-3-clause | jni/microscopium,microscopium/microscopium,Don86/microscopium,microscopium/microscopium,jni/microscopium,Don86/microscopium |
97edbee5813b8a87606b8fb3d09b4f116cdaf025 | mordecai/tests/conftest.py | mordecai/tests/conftest.py | from ..geoparse import Geoparser
import pytest
import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger'])
@pytest.fixture(scope='session', autouse=True)
def geo():
return Geoparser(nlp=nlp, threads=False, models_path = "/Users/ahalterman/MIT/Geolocation/mordecai_new/mordecai/mordecai/models/")
... | from ..geoparse import Geoparser
import pytest
import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger'])
@pytest.fixture(scope='session', autouse=True)
def geo():
return Geoparser(nlp=nlp, threads=False)
@pytest.fixture(scope='session', autouse=True)
def geo_thread():
return Geoparser(nlp... | Remove hardcoded paths from testing | Remove hardcoded paths from testing
| Python | mit | openeventdata/mordecai |
37aa1c9f8faeefe7305cca526a7424a349939add | tests/smoke_test.py | tests/smoke_test.py | # -*- coding: utf-8 -*-
import unittest
import sys
sys.path.insert(0, '../mafia')
from game import Game
from game import Player
from testclient.testmessenger import TestMessenger
class SmokeTest(unittest.TestCase):
def setUp(self):
self.messenger = TestMessenger()
def test_smoke_test(self):... | # -*- coding: utf-8 -*-
import unittest
import sys
sys.path.insert(0, '../')
from mafia.game import Game
from mafia.game import Player
from testclient.testmessenger import TestMessenger
class SmokeTest(unittest.TestCase):
def setUp(self):
self.messenger = TestMessenger()
def test_smoke_test... | Change the smoke test imports to a relative import for consistency. | Change the smoke test imports to a relative import for consistency.
| Python | mit | BitokuOokami/PloungeMafiaToolkit |
11d19d1756f6227db894aabcf4bd02e327e292c7 | tests/test_basic.py | tests/test_basic.py | from hello_world import hello_world
from unittest import TestCase
class BasicTest(TestCase):
def test_basic_hello_world(self):
"""
Test basic hello world messaging
"""
False
| from hello_world import hello_world
from unittest import TestCase
class BasicTest(TestCase):
def test_basic_hello_world(self):
"""
Test basic hello world messaging
"""
self.assertTrue(callable(hello_world))
| Make things a little better | Make things a little better
| Python | mit | jeansaad/hello_world |
acd92d6a9e8c710657a4bcf1c46076f9d06f3d46 | test_results/plot_all.py | test_results/plot_all.py | import glob
import csv
import numpy as np
import matplotlib.pyplot as plt
for file in glob.glob("*.csv"):
data = np.genfromtxt(file, delimiter = ',', names = True)
plt.figure(figsize=(10,20))
plt.suptitle(file)
num_plots = len(data.dtype.names)
count = 1
for col_name in data.dtype.names:
... | import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("test-results-plots.pdf")
for file in glob.glob("*.csv"):
data = np.genfromtxt(file, delimiter = ',', names = True)
plt.figure(figsize=(10,20))
plt.suptitle(... | Save all simulation plots to one PDF instead of multiple | Save all simulation plots to one PDF instead of multiple
| Python | agpl-3.0 | BrewPi/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,glibersat/firmware,etk29321/firmware,etk29321/firmware,etk29321/firmware,etk29321/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,etk29321/firmware,BrewPi/firmware,etk2932... |
cc8f5b35d4c227f82b2872d5bfad24bef37209e5 | overtime_calculator/__main__.py | overtime_calculator/__main__.py | import hug
from overtime_calculator import auth, api
@hug.get("/", output=hug.output_format.html)
def base():
return "<h1>Hello, world</h1>"
@hug.extend_api()
def with_other_apis():
return [
auth,
api
]
| import sys
import pathlib
import hug
from overtime_calculator import auth, api
@hug.get("/", output=hug.output_format.html)
def base():
return "<h1>Hello, world</h1>"
@hug.extend_api()
def with_other_apis():
return [
auth,
api
]
if __name__ == '__main__':
_file = pathlib.Path(sys.... | Improve UX for those who use CLI | Enhancement: Improve UX for those who use CLI
| Python | mit | x10an14/overtime-calculator |
b0b232297f55cd38db85bb2ec5b30a6022a3f4d1 | tweepy/asynchronous/__init__.py | tweepy/asynchronous/__init__.py | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy.asynchronoous
Asynchronous interfaces with the Twitter API
"""
try:
import aiohttp
except ModuleNotFoundError:
from tweepy.errors import TweepyException
raise TweepyException("tweepy.asynchronous requires aiohttp to be ... | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy.asynchronoous
Asynchronous interfaces with the Twitter API
"""
try:
import aiohttp
import oauthlib
except ModuleNotFoundError:
from tweepy.errors import TweepyException
raise TweepyException(
"tweepy.asynchr... | Check oauthlib installation when importing asynchronous subpackage | Check oauthlib installation when importing asynchronous subpackage
| Python | mit | svven/tweepy,tweepy/tweepy |
f5f850e53a889a5afe483ae2ca07e147d4a94c08 | tests.py | tests.py | #!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal, assert_is_instance
from pandas_finance import get_stock
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stock_called_correctly(se... | #!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal, assert_is_instance
from pandas_finance import get_stock, get_required_tickers
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stoc... | Add test for parsing tickers. | Add test for parsing tickers.
| Python | agpl-3.0 | scraperwiki/stock-tool,scraperwiki/stock-tool |
019f259ae42a95802dce644511399332506ad1cc | tracing/tracing/metrics/metric_runner.py | tracing/tracing/metrics/metric_runner.py | # Copyright 2016 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.
import os
from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.m... | # Copyright 2016 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.
import os
from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.m... | Support relative paths in bin/run_metric | Support relative paths in bin/run_metric
As a result of this patch, it will be possible to run:
bin/run_metric MemoryMetric test_data/memory_dumps.json
^^^^^^^^^^^^^^^^^^^^^^^^^^^
instead of:
bin/run_metric MemoryMetric $PWD/test_data/memory_dumps.json
... | Python | bsd-3-clause | catapult-project/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sa... |
611aee2e704ffbad8579e5005ca36232097f96c5 | bot/utils.py | bot/utils.py | from enum import IntEnum
from discord import Embed
class OpStatus(IntEnum):
SUCCESS = 0x2ECC71,
FAILURE = 0xc0392B,
WARNING = 0xf39C12,
NONE = None
def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed:
name = ctx.message.server.me.nick if ctx.message.server.me.nick is ... | from enum import IntEnum
from discord import Embed
class OpStatus(IntEnum):
SUCCESS = 0x2ECC71,
FAILURE = 0xc0392B,
WARNING = 0xf39C12,
NONE = -1
def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed:
name = ctx.message.server.me.nick if ctx.message.server.me.nick is no... | Fix issue with enum not accepting null | Fix issue with enum not accepting null
| Python | apache-2.0 | HellPie/discord-reply-bot |
b3466fc14e9616c620258eea382b644ac2585845 | rest/urls.py | rest/urls.py | # Author: Braedy Kuzma
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.Com... | # Author: Braedy Kuzma
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.Com... | Add extra endpoint for posts? | Add extra endpoint for posts?
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project |
ab7ce76c47ea99080c105feb1a4f8aed39554597 | doc/examples/example_world.py | doc/examples/example_world.py |
from __future__ import unicode_literals
from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer
from examplegame.squeaky import Squeaker
def world(store):
... |
from __future__ import unicode_literals
from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer
from examplegame.squeaky import Squeaker
def world(store):
... | Make rooms in the example game (grammatically) "proper" (nouns) | Make rooms in the example game (grammatically) "proper" (nouns)
| Python | mit | twisted/imaginary |
94e8b7bf8b24dfa36f240e601cb0894b10cab21a | tools/examples/geturl.py | tools/examples/geturl.py | #!/usr/bin/env python2
#
# USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import svn._wc
import svn.util
def main(pool, files):
for f in files:
entry = svn._wc.svn_wc_entry(f, 0, pool)
print svn._wc.svn_wc_entry_t_url_get(entry)
if __name__ == '... | #!/usr/bin/env python2
#
# USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import os
import sys
import svn.wc
import svn.util
def main(pool, files):
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.pa... | Update the example to use the new access baton stuff. | Update the example to use the new access baton stuff.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@844036 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion |
68b1c3804504ecc14f7c23465ca11db31489e1cd | mozcal/events/views.py | mozcal/events/views.py | from django.shortcuts import render, get_object_or_404
from mozcal.events.models import Event, Space, FunctionalArea
def one(request, slug):
event = get_object_or_404(Event, slug=slug)
return render(request, 'event.html', { 'event': event })
def all(request):
events = Event.objects.all()
spaces = Space.obj... | from django.shortcuts import render, get_object_or_404
from mozcal.events.models import Event, Space, FunctionalArea
def one(request, slug):
event = get_object_or_404(Event, slug=slug)
return render(request, 'event.html', { 'event': event })
def all(request):
search_string = request.GET.get('search', '')
... | Allow filtering of events by title | Allow filtering of events by title
| Python | bsd-3-clause | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents |
ce191a9ea7bad7493560a7bdd7f7de2e56f94612 | fuse_util.py | fuse_util.py | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
if os.path.isfile("/usr/bin/fuse"):
return "/usr/bin/fuse"
else:
... | Make Sublime plugin work with new Fuse install location | Make Sublime plugin work with new Fuse install location
We changed the location of fuse from /usr/bin to /usr/local/bin to be
compatible with El Capitan. The latter is not on path in Sublime, so use
absolute paths for fuse.
| Python | mit | fusetools/Fuse.SublimePlugin,fusetools/Fuse.SublimePlugin |
d0908d1e4e5279579a93772210b001c19fae9b10 | cogs/misc.py | cogs/misc.py | import discord
from discord.ext import commands
class Misc:
@commands.command()
async def highfive(self, ctx):
"""
Give Yutu a high-five
"""
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@commands.command()
async def cute(self, ctx, user: d... | import discord
from discord.ext import commands
class Misc:
@commands.command()
async def highfive(self, ctx: commands.Context):
"""
Give Yutu a high-five
"""
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@commands.command()
async def cute(... | Add type markers for ctx objects | Add type markers for ctx objects
| Python | mit | HarkonenBade/yutu |
2263d180184c908b0e96d53f43f6c81aa23a3c92 | push/urls.py | push/urls.py | from django.conf.urls import url
from push import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
url(r'^sender', views.sender, name = 'sender'),
url(r'^notification_list', views.notification_list, name = 'notification_list'),
url(r'^settings', views.settings, name = 'settings'),
url... | from django.conf.urls import url
from push import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
url(r'^sender', views.sender, name = 'sender'),
url(r'^notification_list', views.notification_list, name = 'notification_list'),
url(r'^settings', views.settings, name = 'settings'),
url... | Modify device_token register URL dispatcher | Modify device_token register URL dispatcher
| Python | apache-2.0 | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas |
d5f0b698831e4bfb35b74ef0d8c7af75c91e67d3 | dadd/worker/handlers.py | dadd/worker/handlers.py | import os
import json
import socket
import requests
from flask import request, jsonify, Response, abort
from dadd.worker import app
from dadd.worker.proc import ChildProcess
@app.route('/run/', methods=['POST'])
def run_process():
proc = ChildProcess(request.json)
proc.run()
return jsonify(proc.info())... | import os
import json
import socket
import requests
from flask import request, jsonify, Response, abort
from dadd.worker import app
from dadd.worker.proc import ChildProcess
@app.route('/run/', methods=['POST'])
def run_process():
proc = ChildProcess(request.json)
proc.run()
return jsonify(proc.info())... | Fix up the manual register URL in the worker and fix the initial log tail. | Fix up the manual register URL in the worker and fix the initial log tail.
| Python | bsd-3-clause | ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd |
fb1d39ed30e73bef49be7a71945d5dfd67af28e3 | scripting.py | scripting.py | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, ... | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, ... | Add a friendly mkdir() function. | Add a friendly mkdir() function.
| Python | mit | Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab |
0216bfd48fddb9bb7bda611ec5bdfe368bdee55f | layout/tests.py | layout/tests.py | from django.test import TestCase
# Create your tests here.
| from django.core.urlresolvers import resolve
from django.test import TestCase
from layout.views import home
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page(self):
found = resolve('/')
self.assertEqual(found.func, home)
| Add home page resolve test to layout | Add home page resolve test to layout
| Python | mit | jvanbrug/scout,jvanbrug/scout |
9debed5d1d83bdf2098a7a3841ae4ff272e7ea8e | lib/__init__.py | lib/__init__.py | from client import WebHDFSClient
__version__ = '1.0'
| from errors import WebHDFSError
from client import WebHDFSClient
from attrib import WebHDFSObject
__version__ = '1.0'
| Make other API classes available from base module. | Make other API classes available from base module.
| Python | mit | mk23/webhdfs,mk23/webhdfs |
2cb2779bfe1ddfcd6651665276ed0a1d513c57de | fireplace/cards/wog/shaman.py | fireplace/cards/wog/shaman.py | from ..utils import *
##
# Minions
class OG_023:
"Primal Fusion"
play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM)
OG_023t = buff(+1, +1)
class OG_209:
"Hallazeal the Ascended"
events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT))
| from ..utils import *
##
# Minions
class OG_023:
"Primal Fusion"
play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM)
OG_023t = buff(+1, +1)
class OG_026:
"Eternal Sentinel"
play = UnlockOverload(CONTROLLER)
class OG_209:
"Hallazeal the Ascended"
events = Damage(source=SPELL + FRIENDLY).on(Hea... | Implement Eternal Sentinel, Stormcrack and Hammer of Twilight | Implement Eternal Sentinel, Stormcrack and Hammer of Twilight
| Python | agpl-3.0 | NightKev/fireplace,beheh/fireplace,jleclanche/fireplace |
562b56d67d7d292d7c63ec8c3f453bae92a3b073 | tests/test_wysiwyg_editor.py | tests/test_wysiwyg_editor.py | from . import TheInternetTestCase
from helium.api import click, Text, press, CONTROL, COMMAND, write
from sys import platform
class WYSIWYGEditorTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/tinymce"
def test_use_wysiwyg_editor(self):
self.assertTrue(Text("Your content ... | from . import TheInternetTestCase
from helium.api import click, Text, write
class WYSIWYGEditorTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/tinymce"
def test_use_wysiwyg_editor(self):
self.assertTrue(Text("Your content goes here.").exists())
click("File")
click("Ne... | Simplify the WYSIWYG editor test case. | Simplify the WYSIWYG editor test case.
| Python | mit | bugfree-software/the-internet-solution-python |
47b3d205931d6ee7fa8062b3e2f01d1ea07df11a | pathvalidate/_error.py | pathvalidate/_error.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
class NullNameError(ValueError):
"""
Raised when a name is empty.
"""
class InvalidCharError(ValueError):
"""
Raised when includes in... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
class InvalidNameError(ValueError):
"""
Base class of invalid name error.
"""
class NullNameError(InvalidNameError):
"""
Raised when ... | Add base class of invalid name error | Add base class of invalid name error
| Python | mit | thombashi/pathvalidate |
752e6cef31ea124f00eced5699fb225501258148 | reversible.py | reversible.py | #!/usr/bin/env python
""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
https://projecteuler.net/problem=145
"""
def is_odd(num):
""" Check if an integer is odd. """
if num % 2 != 0:
return True
else:
return False
def is_reversible(num):
""" ... | #!/usr/bin/env python
""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
https://projecteuler.net/problem=145
"""
def is_odd(num):
""" Check if an integer is odd. """
if num % 2 != 0:
return True
else:
return False
def is_reversible(num):
""" ... | Add check for leading zeroes. | Add check for leading zeroes.
| Python | mit | smillet15/project-euler |
3ffc101a1a8b1ec17e5f2e509a1e5182a1f6f4b9 | fzn/utils.py | fzn/utils.py | import subprocess as sp
import signal
import threading
import os
SIGTERM_TIMEOUT = 1.0
class Command(object):
def __init__(self, cmd, memlimit=None):
self.cmd = cmd
self.memlimit = memlimit
self.process = None
self.stdout = None
self.stderr = None
self.exitcode = ... | import subprocess as sp
import signal
import threading
import os
SIGTERM_TIMEOUT = 1.0
class Command(object):
def __init__(self, cmd, memlimit=None):
self.cmd = cmd
self.memlimit = memlimit
self.process = None
self.stdout = None
self.stderr = None
self.exitcode = ... | Enable Command to support memory limiting. | Enable Command to support memory limiting.
| Python | lgpl-2.1 | eomahony/Numberjack,eomahony/Numberjack,eomahony/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,eomahony/Numberjack,eomahony/Numberjack |
a89a61620306d3cc38062cf69c56db64aadf0a8d | pokedex/db/__init__.py | pokedex/db/__init__.py | import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, **kwargs):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contained within the package d... | import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, session_args={}, engine_args={}):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contain... | Allow passing engine arguments to connect(). | Allow passing engine arguments to connect().
| Python | mit | mschex1/pokedex,RK905/pokedex-1,xfix/pokedex,veekun/pokedex,DaMouse404/pokedex,veekun/pokedex |
9d5abdaefa483574cdd81da8d8d4e63ef68f5ab8 | crossfolium/__init__.py | crossfolium/__init__.py | # -*- coding: utf-8 -*-
"""
Crossfolium
-----------
"""
import crossfolium.marker_function as marker_function
from crossfolium.crossfolium import (
Crossfilter,
PieFilter,
RowBarFilter,
BarFilter,
TableFilter,
CountFilter,
ResetFilter,
GeoChoroplethFilter,
)
from .map import (
... | # -*- coding: utf-8 -*-
"""
Crossfolium
-----------
"""
from __future__ import absolute_import
from crossfolium import marker_function
from crossfolium.crossfolium import (
Crossfilter,
PieFilter,
RowBarFilter,
BarFilter,
TableFilter,
CountFilter,
ResetFilter,
GeoChoroplethFilter,
... | Handle absolute import for py27 | Handle absolute import for py27
| Python | mit | BibMartin/crossfolium,BibMartin/crossfolium |
e325c603e972e6e7cd50eefae23b94594b6c9751 | Tables/build_db.py | Tables/build_db.py | import sqlite3
import os
import pandas as pd
TABLES = [['Natures', 'nature'],
['Experience'],
]
PATH = os.path.dirname(__file__)+"/"
CONNECTION = sqlite3.connect(PATH + 'serpyrior.db')
# insert a little jimmy drop tables here
for table in TABLES:
table_name = table[0]
print(table_name)
... | import sqlite3
import os
import pandas as pd
TABLES = [['Natures', 'nature'],
['Experience'],
]
PATH = os.path.dirname(__file__)+"/"
try: # Little Bobby Tables
os.remove(PATH + 'serpyrior.db')
except FileNotFoundError:
pass
CONNECTION = sqlite3.connect(PATH + 'serpyrior.db')
for table i... | Remove db if it already exists | Remove db if it already exists
| Python | mit | Ditoeight/Pyranitar |
80fb36f2e8754a07ae2f6f4b454862a8b1852763 | dadd/worker/handlers.py | dadd/worker/handlers.py | import json
import requests
from flask import request, jsonify
from dadd.worker import app
from dadd.worker.proc import ChildProcess
@app.route('/run/', methods=['POST'])
def run_process():
proc = ChildProcess(request.json)
proc.run()
return jsonify(proc.info())
@app.route('/register/', methods=['POS... | import json
import socket
import requests
from flask import request, jsonify
from dadd.worker import app
from dadd.worker.proc import ChildProcess
@app.route('/run/', methods=['POST'])
def run_process():
proc = ChildProcess(request.json)
proc.run()
return jsonify(proc.info())
@app.route('/register/',... | Use the fqdn when registering with the master. | Use the fqdn when registering with the master.
Not all deployment systems will provide a specific hostname via an env
var so we'll avoid relying on it by asking the machine.
| Python | bsd-3-clause | ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd |
2a76368054599006c8f7833cda1ec20f85bfcb28 | hash_table.py | hash_table.py | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024... | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024... | Build out hash function of hash table class | Build out hash function of hash table class
| Python | mit | jwarren116/data-structures-deux |
b0824da73317bae42cb39fad5cfc95574548594a | accounts/models.py | accounts/models.py | # coding: utf-8
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
fro... | # coding: utf-8
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
fro... | Change l'ordre d'insertion des utilisateurs. | Change l'ordre d'insertion des utilisateurs.
| Python | bsd-3-clause | dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede |
9ffc56e947dea40cd49c76beada2ec469a01f8f8 | __init__.py | __init__.py | import base64
import json
from os import path
import sys
sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__))))
api_file = 'my_api.json'
_api_file = '{}\{}'.format(path.dirname(path.abspath(__file__)), api_file)
with open(_api_file) as fin:
cw_api_settings = json.load(fin)
API_URL = c... | import base64
import json
from os import path
import sys
sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__))))
api_file = 'my_api.json'
_api_file = path.join(path.dirname(path.abspath(__file__)), api_file)
with open(_api_file) as fin:
cw_api_settings = json.load(fin)
API_URL = cw_api... | Make api file path OS safe | Make api file path OS safe
| Python | mit | joshuamsmith/ConnectPyse |
f99847f363eed36713f657a4cb15a103ffcc6623 | web/server.py | web/server.py | import http.client
import os
from flask import Flask
from pymongo import MongoClient
MONGO_URL = os.environ.get('MONGO_URL', 'mongodb://mongo:27017/')
MONGO_DATABASE = os.environ.get('MONGO_DATABASE', 'whistleblower')
DATABASE = MongoClient(MONGO_URL)[MONGO_DATABASE]
app = Flask(__name__)
@app.route('/')
def hello_... | import http.client
import os
from flask import Flask
from pymongo import MongoClient
MONGO_URL = os.environ.get('MONGO_URL', 'mongodb://mongo:27017/')
MONGO_DATABASE = os.environ.get('MONGO_DATABASE', 'whistleblower')
DATABASE = MongoClient(MONGO_URL)[MONGO_DATABASE]
app = Flask(__name__)
@app.route('/')
def hello_... | Save every request coming in the facebook webroot endpoint | Save every request coming in the facebook webroot endpoint
| Python | unlicense | datasciencebr/whistleblower |
483cf7f91a89e040184bd71a0a1c59c0e0926e34 | elasticmapping/types.py | elasticmapping/types.py | # ElasticMapping
# File: types.py
# Desc: base Elasticsearch types
class CallableDict(dict):
BASE = None
OVERRIDES = None
def __call__(self, overrides):
new_dict = CallableDict(self)
new_dict.OVERRIDES = overrides
new_dict.BASE = self
return new_dict
BASE_TYPE = {
's... | # ElasticMapping
# File: types.py
# Desc: base Elasticsearch types
class CallableDict(dict):
BASE = None
OVERRIDES = None
def __call__(self, overrides):
new_dict = CallableDict(self)
new_dict.OVERRIDES = overrides
new_dict.BASE = self
return new_dict
BASE_TYPE = {
's... | Switch default to actual ES default (date_optional_time) and add TIME type | Switch default to actual ES default (date_optional_time) and add TIME type
| Python | mit | Fizzadar/ElasticMapping,Fizzadar/ElasticMapping |
b3bae8e48618e487ce9c8a90a555d5c6d6664872 | app/management/commands/cleanapptables.py | app/management/commands/cleanapptables.py | from django.core.management.base import BaseCommand, CommandError
from app.models import Author, Location, AutoComment, Comment, Idea, Vote
class Command(BaseCommand):
def handle(self, *args, **options):
self.stdout.write('Starting to clean app tables...')
try:
Idea.objects.all().delet... | from django.core.management.base import BaseCommand, CommandError
from app.models import Author, Location, AutoComment, Comment, Idea, Vote, SocialNetworkAppUser
class Command(BaseCommand):
def handle(self, *args, **options):
self.stdout.write('Starting to clean app tables...')
try:
Id... | Add the deletion of the app users | Add the deletion of the app users
| Python | mit | joausaga/social-ideation,joausaga/social-ideation,rebearteta/social-ideation,rebearteta/social-ideation,rebearteta/social-ideation,joausaga/social-ideation,joausaga/social-ideation,rebearteta/social-ideation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.