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 |
|---|---|---|---|---|---|---|---|---|---|
55c60d059a4f6a6ae6633318420a7c0cd22c2513 | product/models.py | product/models.py | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('... | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('... | Fix in string representation of product model. | Fix in string representation of product model.
| Python | mit | borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa |
df5040b728ec59f9f548c7bd032d9e8b7ab0c2e0 | database/queries/update_queries.py | database/queries/update_queries.py | UPDATE_MOVIE = '''
UPDATE MOVIE
SET column1=?, RATING=?
WHERE MOVIE.ID=?;
'''
UPDATE_PROJECTION = '''
UPDATE PROJECTION
SET MOVIE_ID=?, TYPE=?, DATE=?
WHERE PROJECTION.ID=?;
'''
| UPDATE_MOVIE = '''
UPDATE MOVIE
SET column1=?, RATING=?
WHERE MOVIE.ID=?;
'''
UPDATE_PROJECTION = '''
UPDATE PROJECTION
SET MOVIE_ID=?, TYPE=?, DATE=?
WHERE PROJECTION.ID=?;
'''
DELETE_RESERVATION = '''
UPDATE RESERVATION
SET USER_ID=?, PROJECTION_ID=?, ROW=?, COL=?
WHERE RESERVATI... | Add update queries for reservation | Add update queries for reservation
| Python | mit | BrickText/JHROM |
1d355a2143daf438b5a2f5185a7f60268ad7c686 | tests/local_test.py | tests/local_test.py | from nose.tools import istest, assert_equal
from spur import LocalShell
shell = LocalShell()
@istest
def output_of_run_is_stored():
result = shell.run(["echo", "hello"])
assert_equal("hello\n", result.output)
| from nose.tools import istest, assert_equal
from spur import LocalShell
shell = LocalShell()
@istest
def output_of_run_is_stored():
result = shell.run(["echo", "hello"])
assert_equal("hello\n", result.output)
@istest
def cwd_of_run_can_be_set():
result = shell.run(["pwd"], cwd="/")
assert_equal("/\n... | Add test for setting cwd in LocalShell.run | Add test for setting cwd in LocalShell.run
| Python | bsd-2-clause | mwilliamson/spur.py |
2f02960607b75e74a757ded1e2472a5fb8585d4f | tests/pyb/extint.py | tests/pyb/extint.py | import pyb
ext = pyb.ExtInt('X1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l))
ext.disable()
ext.enable()
print(ext.line())
ext.swint()
ext.disable()
| import pyb
# test basic functionality
ext = pyb.ExtInt('X1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l))
ext.disable()
ext.enable()
print(ext.line())
ext.swint()
# test swint while disabled, then again after re-enabled
ext.disable()
ext.swint()
ext.enable()
ext.swint()
# disable now that th... | Add test for ExtInt when doing swint while disabled. | tests/pyb: Add test for ExtInt when doing swint while disabled.
| Python | mit | infinnovation/micropython,adafruit/circuitpython,turbinenreiter/micropython,dxxb/micropython,pfalcon/micropython,infinnovation/micropython,Timmenem/micropython,oopy/micropython,mhoffma/micropython,pfalcon/micropython,selste/micropython,adafruit/circuitpython,Peetz0r/micropython-esp32,oopy/micropython,torwag/micropython... |
74010276715e3570ad6f66144f2c2e31aff8948a | tests/test_local.py | tests/test_local.py | import cachelper
class TestMemorize:
def test_should_cache_return_value(self, mocker):
func = mocker.Mock()
func.side_effect = lambda i: i * 2
func.__name__ = 'double'
cached = cachelper.memoize()(func)
assert cached(2) == 4
assert cached(2) == 4
assert fu... | import cachelper
class TestMemorize:
def test_should_cache_return_value(self, mocker):
func = mocker.Mock()
func.side_effect = lambda i: i * 2
func.__name__ = 'double'
cached = cachelper.memoize()(func)
assert cached(2) == 4
assert cached(2) == 4
assert fu... | Add test to make sure memoize works for methods | Add test to make sure memoize works for methods
| Python | mit | suzaku/cachelper |
5f3491b583599148dba71dac5279f4ef6eb77c10 | tests/test_suite.py | tests/test_suite.py | #! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest
from . import downloader_test
def suite()... | #! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest
from . import downloader_test
from . impor... | Update test suite generator to import tests in source_test. | Update test suite generator to import tests in source_test.
| Python | mit | jkawamoto/roadie-gcp,jkawamoto/roadie-gcp |
a10ffe519c50bd248bd9bfcde648f66e15fb6fd3 | node_bridge.py | node_bridge.py | import os
import platform
import subprocess
IS_OSX = platform.system() == 'Darwin'
IS_WINDOWS = platform.system() == 'Windows'
def node_bridge(data, bin, args=[]):
env = None
startupinfo = None
if IS_OSX:
# GUI apps in OS X doesn't contain .bashrc/.zshrc set paths
env = os.environ.copy()
env['PATH'] += ':/us... | import os
import platform
import subprocess
IS_OSX = platform.system() == 'Darwin'
IS_WINDOWS = platform.system() == 'Windows'
def node_bridge(data, bin, args=[]):
env = None
startupinfo = None
if IS_OSX:
# GUI apps in OS X doesn't contain .bashrc/.zshrc set paths
env = os.environ.copy()
env['PATH'] += os.pa... | Add support for `n` Node.js version manager | Add support for `n` Node.js version manager
| Python | mit | hudochenkov/sublime-postcss-sorting,hudochenkov/sublime-postcss-sorting |
744d4a34fa3f5f514f3f1e525822360dd97e28e2 | astroquery/ogle/tests/test_ogle_remote.py | astroquery/ogle/tests/test_ogle_remote.py |
import pytest
import astropy.units as u
from astropy.coordinates import SkyCoord
from .. import Ogle
@pytest.mark.remote_data
def test_ogle_single():
co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic')
response = Ogle.query_region(coord=co)
assert len(response) == 1
@pytest.mark.remote_da... |
import pytest
import astropy.units as u
from astropy.coordinates import SkyCoord
from .. import Ogle
@pytest.mark.remote_data
def test_ogle_single():
co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic')
response = Ogle.query_region(coord=co)
assert len(response) == 1
@pytest.mark.remote_da... | Fix column name in tests | Fix column name in tests
| Python | bsd-3-clause | imbasimba/astroquery,imbasimba/astroquery |
315aedbfff9e345b1e4a4ffab999741bb9a802da | oopconcepts.py | oopconcepts.py | class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, ", self.name)
p1 = Person("Allan")
p1.say_hello()
p2 = Person("John")
p2.say_hello()
| class Classroom:
def __init__(self):
self._people = []
def add_person(self, person):
self._people.append(person)
def remove_person(self, person):
self._people.remove(person)
def greet(self):
for person in self._people:
person.say_hello()
class Person:
... | Create classroom and some encapsulation | Create classroom and some encapsulation
| Python | mit | cunctat0r/pythonstudy |
3e37a216f532382e9a730a41677859f64b521574 | thunder/utils/common.py | thunder/utils/common.py | def check_spark():
SparkContext = False
try:
from pyspark import SparkContext
finally:
return SparkContext
def check_path(path, credentials=None):
"""
Check that specified output path does not already exist
The ValueError message will suggest calling with overwrite=True; this f... | def notsupported(mode):
raise NotImplementedError("Operation not supported for mode '%s'" % mode)
def check_spark():
SparkContext = False
try:
from pyspark import SparkContext
finally:
return SparkContext
def check_path(path, credentials=None):
"""
Check that specified output ... | Add method for raising not supported error | Add method for raising not supported error
| Python | apache-2.0 | thunder-project/thunder,jwittenbach/thunder,j-friedrich/thunder,j-friedrich/thunder |
e30d433153d9ad2f1d931f7f48b0ebbe9ba6763c | modules/new_module/new_module.py | modules/new_module/new_module.py |
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewUR... |
import logging
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
def on_module_enabled():
logging.info('Module new_module.py was just enabled')
def on_module_disabled():
logging.info('Module new_module.py was j... | Add enable and dissable hooks | Add enable and dissable hooks
| Python | apache-2.0 | UniMOOC/gcb-new-module,UniMOOC/gcb-new-module,UniMOOC/gcb-new-module,UniMOOC/gcb-new-module |
314f387e3a227181926531f5230f21887d35038b | uploader/uploader.py | uploader/uploader.py | import os
import glob
import logging
import dropbox
from dropbox.client import DropboxClient, ErrorResponse
import settings
from settings import DROPBOX_TOKEN_FILE
def load_dropbox_token():
with open(DROPBOX_TOKEN_FILE, 'r') as f:
dropbox_token = f.read()
return dropbox_token
def has_valid_dropbox_t... | import os
import glob
import logging
import subprocess
import dropbox
from dropbox.client import DropboxClient, ErrorResponse
import settings
from settings import DROPBOX_TOKEN_FILE
def load_dropbox_token():
with open(DROPBOX_TOKEN_FILE, 'r') as f:
dropbox_token = f.read()
return dropbox_token
def h... | Add util to test network connection | Add util to test network connection
| Python | mit | projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse |
59fd414849907f73d5904f46139127ae3638c9bd | ankieta/petition_custom/forms.py | ankieta/petition_custom/forms.py | from petition.forms import SignatureForm
from crispy_forms.layout import Layout, Submit
from crispy_forms.bootstrap import PrependedText
from crispy_forms.helper import FormHelper
from django.utils.translation import ugettext as _
import swapper
Signature = swapper.load_model("petition", "Signature")
class CustomSig... | from petition.forms import SignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper
Signature = swapper.load_model("petition", "Signature")
class CustomSignatureForm(SignatureForm):
def __init__(self, *args, **kwargs):
super(CustomSignatureForm,... | Fix typo in CustomSignatureForm fields definition | Fix typo in CustomSignatureForm fields definition
| Python | bsd-3-clause | ad-m/petycja-faoo,ad-m/petycja-faoo,ad-m/petycja-faoo |
80a9019cb24ea581a9cef0344caaf4cec4a95a94 | testproject/chtest/consumers.py | testproject/chtest/consumers.py | from channels.sessions import enforce_ordering
#@enforce_ordering(slight=True)
def ws_connect(message):
pass
#@enforce_ordering(slight=True)
def ws_message(message):
"Echoes messages back to the client"
message.reply_channel.send(message.content)
| from channels.sessions import enforce_ordering
#@enforce_ordering(slight=True)
def ws_connect(message):
pass
#@enforce_ordering(slight=True)
def ws_message(message):
"Echoes messages back to the client"
message.reply_channel.send({
"text": message['text'],
})
| Fix echo endpoint in testproject | Fix echo endpoint in testproject
| Python | bsd-3-clause | Krukov/channels,Coread/channels,django/channels,andrewgodwin/channels,linuxlewis/channels,Krukov/channels,raphael-boucher/channels,andrewgodwin/django-channels,raiderrobert/channels,Coread/channels |
824c8cd3eb563de60ddf13fac1f7ca1341aa01f1 | astral/api/tests/test_streams.py | astral/api/tests/test_streams.py | from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory(... | from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory(... | Update tests for new redirect-after-create stream. | Update tests for new redirect-after-create stream.
| Python | mit | peplin/astral |
e6a251da6d6902d2633afab7c4e9ecaf366f964c | tools/build_modref_templates.py | tools/build_modref_templates.py | #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from apigen import ApiDocWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(... | #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from apigen import ApiDocWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(... | Remove gorlin_glue from generated docs for now. It produces about 100 warnings during doc build. | Remove gorlin_glue from generated docs for now. It produces about 100 warnings during doc build.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@926 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| Python | bsd-3-clause | glatard/nipype,grlee77/nipype,glatard/nipype,arokem/nipype,wanderine/nipype,FCP-INDI/nipype,arokem/nipype,mick-d/nipype_source,sgiavasis/nipype,FredLoney/nipype,carolFrohlich/nipype,mick-d/nipype,gerddie/nipype,Leoniela/nipype,wanderine/nipype,gerddie/nipype,dgellis90/nipype,Leoniela/nipype,FCP-INDI/nipype,FredLoney/ni... |
97cfc12433b32997bf7345512326d160ea4e48fa | systemd/install.py | systemd/install.py | """
Install Wabbit Systemd service.
"""
from glob import glob
from shutil import copy
from os import chdir
from os.path import dirname, realpath
from subprocess import call
import sys
import coils
# Load configuration file.
CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.conf'
config = coils.Config(CONFIG)
pr... | """
Install Wabbit Systemd service.
"""
from glob import glob
from shutil import copy
from os import chdir
from os.path import dirname, realpath
from subprocess import call
import sys
import coils
# Load configuration file.
CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.conf'
config = coils.Config(CONFIG)
# ... | Remove creation of service files. | Remove creation of service files.
| Python | mit | vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit |
d2032ed28e97b8a23c4eec95fcadfaa80e944f01 | conman/pages/tests/test_views.py | conman/pages/tests/test_views.py | from django.test import TestCase
from conman.tests.utils import RequestTestCase
from . import factories
from .. import views
class TestPageDetail(RequestTestCase):
def test_get_object(self):
"""PageDetail displays the page instance passed in the node kwarg."""
request = self.create_request()
... | from django.test import TestCase
from conman.tests.utils import RequestTestCase
from . import factories
from .. import views
class TestPageDetail(RequestTestCase):
def test_get_object(self):
"""PageDetail displays the page instance passed in the node kwarg."""
request = self.create_request()
... | Remove unused test class attr | Remove unused test class attr
| Python | bsd-2-clause | meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman |
b83958697004d7203fed20a3024efe3c653f9535 | tiddlywebconfig.py | tiddlywebconfig.py | config = {
'wikitext.default_renderer': 'twikified',
'wikitext.type_render_map': {
'text/x-tiddlywiki': 'twikified'
}
}
| config = {
'wikitext.default_renderer': 'tiddlywebplugins.twikified',
'wikitext.type_render_map': {
'text/x-tiddlywiki': 'tiddlywebplugins.twikified'
}
}
| Use fully qualified module names | Use fully qualified module names
This is so that the tiddlyweb instance used in the tests can find the renderer
| Python | bsd-3-clause | TiddlySpace/tiddlywebplugins.twikified |
fab0855e7076d7cfcfe2d65a820ed5099084f543 | privileges/views.py | privileges/views.py | import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wrap... | import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wrap... | Add mixin to put the username in context | Add mixin to put the username in context | Python | bsd-3-clause | eldarion/privileges,jacobwegner/privileges,jacobwegner/privileges |
f3eb94bbe10160a4337c5eb9241166f60b9724a8 | pyvideo/settings.py | pyvideo/settings.py | # Django settings for pyvideo project.
from richard.settings import *
ALLOWED_HOSTS = ['pyvideo.ru']
TIME_ZONE = 'Europe/Moscow'
LANGUAGE_CODE = 'ru'
SECRET_KEY = 'this_is_not_production_so_who_cares'
ROOT_URLCONF = 'pyvideo.urls'
WSGI_APPLICATION = 'pyvideo.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(ROOT... | # Django settings for pyvideo project.
from richard.settings import *
ALLOWED_HOSTS = ['pyvideo.ru', 'pyvideoru.herokuapp.com']
TIME_ZONE = 'Europe/Moscow'
LANGUAGE_CODE = 'ru'
SECRET_KEY = 'this_is_not_production_so_who_cares'
ROOT_URLCONF = 'pyvideo.urls'
WSGI_APPLICATION = 'pyvideo.wsgi.application'
TEMPLATE_DIR... | Add heroku host to ALLOWED_HOSTS | Add heroku host to ALLOWED_HOSTS
| Python | bsd-3-clause | WarmongeR1/pyvideo.ru,WarmongeR1/pyvideo.ru,WarmongeR1/pyvideo.ru,coagulant/pyvideo.ru,coagulant/pyvideo.ru,coagulant/pyvideo.ru |
722e975e8819b59d9d2f53627a5d37550ea09c55 | tests/test_clean.py | tests/test_clean.py | from mergepurge import clean
import pandas as pd
import numpy as np
t_data = pd.Series({'name': 'Timothy Testerosa III'})
t_parsed = (np.nan, 'Timothy', 'Testerosa', 'Timothy Testerosa')
# FIXME - load a csv file with a name column and the 4 correctly parsed name parts as 4 other cols
# Then, iterate over the names
... | from mergepurge import clean
import pandas as pd
import numpy as np
complete = pd.read_csv('complete_parsed.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
COMP_LOC_COLS = ['address', 'city', 'state', 'zipcode']
COMP_CONTACT_... | Add tests for most functions in clean module | Add tests for most functions in clean module
Iterate over the complete and parsed test data and confirm we can still
produce the excepted output for most functions in clean.py.
| Python | mit | mikecunha/mergepurge |
59b59e75f87942dfd54f8542b04e4185a871cf4b | utils/messaging.py | utils/messaging.py | """
Contains utilities regarding messages
"""
def paginate(string, pref='```\n', aff='```', max_length=2000, sep='\n'):
'Chop a string into even chunks of max_length around the given separator'
max_size = max_length - len(pref) - len(aff)
str_length = len(string)
if str_length <= max_size:
re... | """
Contains utilities regarding messages
"""
def paginate(string, pref='```\n', aff='```', max_length=2000, sep='\n'):
'Chop a string into even chunks of max_length around the given separator'
max_size = max_length - len(pref) - len(aff)
str_length = len(string)
if str_length <= max_size:
re... | Add util function for accepting input by PM | Add util function for accepting input by PM
| Python | mit | randomic/antinub-gregbot |
0947643977b989ca924bcf932a5153472e362108 | plata/utils.py | plata/utils.py | from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache... | from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_... | Use DjangoJSONEncoder, it knows how to handle dates and decimals | JSONFieldDescriptor: Use DjangoJSONEncoder, it knows how to handle dates and decimals
| Python | bsd-3-clause | armicron/plata,stefanklug/plata,allink/plata,armicron/plata,armicron/plata |
d81c64f68aa47581aa8207f858aec8af1bb805d9 | wallace/sources.py | wallace/sources.py | from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self, w... | from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self):
... | Fix bug that arose through grammar tweaking | Fix bug that arose through grammar tweaking
| Python | mit | jcpeterson/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wal... |
8f0502d618a35b2b63ee280caee91c508482dbf4 | services/api/app.py | services/api/app.py | import json
import itertools
import logging
__author__ = 'patrickwalsh'
from flask import Flask
from redis import Redis
app = Flask(__name__)
logger = logging.getLogger(__name__)
redis = Redis()
IID_INDEX = 'index'
@app.route('/intersections')
def get_all_intersections():
try:
nodes = redis.smembers(... | import json
import itertools
import logging
__author__ = 'patrickwalsh'
from flask import Flask
from redis import Redis
app = Flask(__name__)
logger = logging.getLogger(__name__)
redis = Redis()
IID_INDEX = 'index'
@app.route('/intersections')
def get_all_intersections():
try:
# nodes = redis.smember... | Update fetching nodes to manually get all keys with iid prefix instead of using an index | Update fetching nodes to manually get all keys with iid prefix instead of using an index
| Python | mit | pnw/Chch-openhack,pnw/Chch-openhack |
10ef76977e724cff86361db07a7fcb844d8376e7 | scrapi/util.py | scrapi/util.py | from datetime import datetime
import pytz
def timestamp():
return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8')
def copy_to_unicode(element):
""" used to transform the lxml version of unicode to a
standard version of unicode that can be pickalable -
necessary for linting """
... | from datetime import datetime
import pytz
def timestamp():
return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8')
def copy_to_unicode(element):
""" used to transform the lxml version of unicode to a
standard version of unicode that can be pickalable -
necessary for linting """
... | Add scrapi create rename iterable if we want to move to chunks in the fuure | Add scrapi create rename iterable if we want to move to chunks in the fuure
| Python | apache-2.0 | mehanig/scrapi,fabianvf/scrapi,fabianvf/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,felliott/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,mehanig/scrapi,erinspace/scrapi,ostwald/scrapi |
bab5ed65fb9530b9cd3e9bfabc1e2632da31d106 | knowledge_repo/app/auth_providers/ldap.py | knowledge_repo/app/auth_providers/ldap.py | from ..auth_provider import KnowledgeAuthProvider
from ..models import User
from flask import (
redirect,
render_template,
request,
url_for,
)
from ldap3 import Server, Connection, ALL
from knowledge_repo.constants import AUTH_LOGIN_FORM, LDAP, USERNAME
class LdapAuthProvider(KnowledgeAuthProvider):
... | from ..auth_provider import KnowledgeAuthProvider
from ..models import User
from flask import (
redirect,
render_template,
request,
url_for,
)
from ldap3 import Connection, Server, ALL
from knowledge_repo.constants import AUTH_LOGIN_FORM, LDAP, USERNAME
class LdapAuthProvider(KnowledgeAuthProvider):
... | Fix a lint indent issue | Fix a lint indent issue
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo |
c47f93796bfc4f9026e5451121de7a419ed88e96 | lobster/cmssw/data/merge_cfg.py | lobster/cmssw/data/merge_cfg.py | import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys
options = VarParsing('analysis')
options.register('output', mytype=VarParsing.varType.string)
options.parseArguments()
process = cms.Process("PickEvent")
process.source = cms.Source ("... | import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys
options = VarParsing('analysis')
options.register('output', mytype=VarParsing.varType.string)
options.register('loginterval', 1000, mytype=VarParsing.varType.int)
options.parseArguments... | Trim down merge verbosity to avoid overly large log files. | Trim down merge verbosity to avoid overly large log files.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
a63d37f6817098c75d0863ab5513e9de8369f6ff | apps/curia_vista/management/commands/update_all.py | apps/curia_vista/management/commands/update_all.py | from timeit import default_timer as timer
from django.core.management.base import BaseCommand
from apps.curia_vista.management.commands.update_affair_summaries import Command as ImportCommandAffairSummaries
from apps.curia_vista.management.commands.update_affairs import Command as ImportCommandAffairs
from apps.curia... | from timeit import default_timer as timer
from django.core.management.base import BaseCommand
from apps.curia_vista.management.commands.update_affair_summaries import Command as ImportCommandAffairSummaries
from apps.curia_vista.management.commands.update_committee import Command as ImportCommandCommittee
from apps.... | Remove reference to no longer existing command update_affairs | Remove reference to no longer existing command update_affairs
| Python | agpl-3.0 | rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma |
4bd16d369cc9c89973247afee6ee5ab28eeee014 | tests/providers/test_dnsimple.py | tests/providers/test_dnsimple.py | # Test for one implementation of the interface
from lexicon.providers.dnsimple import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# p... | # Test for one implementation of the interface
from lexicon.providers.dnsimple import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# p... | Add OTP to test filters | Add OTP to test filters
| Python | mit | AnalogJ/lexicon,tnwhitwell/lexicon,tnwhitwell/lexicon,AnalogJ/lexicon |
b1a28600e6b97ab020c69ff410aebd962b4e1e93 | testproject/tablib_test/tests.py | testproject/tablib_test/tests.py | from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
f... | from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
f... | Test that specifying fields and exclude in ModelDataset.Meta works. | Test that specifying fields and exclude in ModelDataset.Meta works.
| Python | mit | joshourisman/django-tablib,ebrelsford/django-tablib,joshourisman/django-tablib,ebrelsford/django-tablib |
95d3401b29d2cba2d282256cdd2513c67e3df858 | ipython_notebook_config.py | ipython_notebook_config.py | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | Set the content security policy | Set the content security policy
| Python | bsd-3-clause | jupyter/nature-demo,jupyter/nature-demo,jupyter/nature-demo |
fe41ecce4b840374a561bbef0bbf4ad465e66180 | tests/ml/test_fasttext_helpers.py | tests/ml/test_fasttext_helpers.py | import pandas
import unittest
import cocoscore.ml.fasttext_helpers as fth
class CVTest(unittest.TestCase):
train_path = 'ft_simple_test.txt'
ft_path = '/home/lib/fastText'
model_path = 'testmodel'
def test_train_call_parameters(self):
train_call, compress_call = fth.get_fasttext_train_calls(... | import pandas
import unittest
import cocoscore.ml.fasttext_helpers as fth
class CVTest(unittest.TestCase):
train_path = 'ft_simple_test.txt'
ft_path = '/home/lib/fastText'
model_path = 'testmodel'
test_path = 'ft_simple_test.txt'
probability_path = 'ft_simple_prob.txt'
def test_train_call_pa... | Add unittest for testing file path | Add unittest for testing file path
| Python | mit | JungeAlexander/cocoscore |
fd1590ad0ceab26e281c58aefeac1365a3f332d5 | tests/test_lib_tokens_webauthn.py | tests/test_lib_tokens_webauthn.py | """
This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn.
This depends on lib.tokenclass
"""
from .base import MyTestCase
from privacyidea.lib.tokens.webauthntoken import WebAuthnTokenClass, WEBAUTHNACTION
from privacyidea.lib.token import init_token
from privacyidea.lib.policy import set_... | """
This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn.
This depends on lib.tokenclass
"""
import unittest
from copy import copy
from privacyidea.lib.tokens import webauthn
from privacyidea.lib.tokens.webauthn import COSEALGORITHM
from .base import MyTestCase
from privacyidea.lib.tokens... | Add testing for the WebAuthn implementation | Add testing for the WebAuthn implementation
| Python | agpl-3.0 | privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea |
7c16ad1dbe97a2f06968f508e605485e86751a5b | tests/utils.py | tests/utils.py | import unittest
from knights import compiler
class Mock(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class TemplateTestCase(unittest.TestCase):
def assertRendered(self, source, expected, context=None, debug=False):
try:
tmpl... | import unittest
from knights import compiler
class Mock(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class TemplateTestCase(unittest.TestCase):
def assertRendered(self, source, expected, context=None):
try:
tmpl = compiler.k... | Remove debug flag from tests | Remove debug flag from tests
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
7e7b0ce7c31c50bdcfaf80d950206e58401c5a8c | workshopvenues/venues/models.py | workshopvenues/venues/models.py | from django.db import models
class Facility(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Address(models.Model):
street = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10... | from django.db import models
class Facility(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Address(models.Model):
street = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10... | Add country field to Address model | Add country field to Address model
| Python | bsd-3-clause | andreagrandi/workshopvenues |
e20d0725e47ea6fe671f7889c02f212962963083 | pyinstaller/hook-googleapiclient.model.py | pyinstaller/hook-googleapiclient.model.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Fix pyinstall-build by including discovery cache documents. | Fix pyinstall-build by including discovery cache documents.
Produced an error related to serviceusage API.
Change-Id: Idf6b83912c3e71e7081ef1b6b0a2836a18723542
GitOrigin-RevId: e38c69cfc7269177570a8aa8c23f8eaa2d32ddd2
| Python | apache-2.0 | GoogleCloudPlatform/gcpdiag,GoogleCloudPlatform/gcpdiag,GoogleCloudPlatform/gcpdiag |
97b2e90f4f9a4f3c08f4556856aec1d31b44749a | flocker/control/_clusterstate.py | flocker/control/_clusterstate.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | Address review comment: Link to issue. | Address review comment: Link to issue.
| Python | apache-2.0 | achanda/flocker,runcom/flocker,Azulinho/flocker,mbrukman/flocker,jml/flocker,moypray/flocker,AndyHuu/flocker,agonzalezro/flocker,Azulinho/flocker,moypray/flocker,w4ngyi/flocker,moypray/flocker,jml/flocker,LaynePeng/flocker,hackday-profilers/flocker,adamtheturtle/flocker,LaynePeng/flocker,1d4Nf6/flocker,w4ngyi/flocker,a... |
9044f377d3018e7589f16126e65bcea173576918 | joby/tests/test_data_science_jobs.py | joby/tests/test_data_science_jobs.py | """ Test the data_science_jobs spider. """
from joby.items import JobLoader, Job
from joby.tests.utilities import make_offline_parser
from datetime import date
TEST_URL = 'http://www.data-science-jobs.com/detail/20'
# noinspection PyShadowingNames
def test_parse_overview_table():
expected_fields = {
'... | """ Test the data_science_jobs spider. """
from joby.spiders.data_science_jobs import DataScienceJobsSpider
from joby.items import JobLoader, Job
from joby.tests.utilities import make_offline_parser
from datetime import date
TEST_URL = 'http://www.data-science-jobs.com/detail/20'
# noinspection PyShadowingNames
d... | Add new Parser class argument (spider) and fix test parameters. | Add new Parser class argument (spider) and fix test parameters.
| Python | mit | cyberbikepunk/job-spiders |
9ec8d2b01e0f8aefc9d4c2c82c22af6f8c48a75b | usingnamespace/api/interfaces.py | usingnamespace/api/interfaces.py | from zope.interface import Interface
class ISerializer(Interface):
"""Marker Interface"""
| from zope.interface import Interface
class ISerializer(Interface):
"""Marker Interface"""
class IDigestMethod(Interface):
"""Marker Interface"""
| Add new marker interface for a digest method | Add new marker interface for a digest method
| Python | isc | usingnamespace/usingnamespace |
343c5eb47510f784588e425619c43df916a40fe7 | delivery/services/external_program_service.py | delivery/services/external_program_service.py |
import subprocess
import atexit
from delivery.models.execution import ExecutionResult, Execution
class ExternalProgramService():
@staticmethod
def run(cmd):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... |
import subprocess
from delivery.models.execution import ExecutionResult, Execution
class ExternalProgramService():
@staticmethod
def run(cmd):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... | Remove at exit handler it doesnt work... | Remove at exit handler it doesnt work...
| Python | mit | arteria-project/arteria-delivery |
64d2a7a7e4cd0375efaddc8ef20889755d691b7e | simplenote-backup.py | simplenote-backup.py | import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not o... | import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not o... | Set the modification dates of the created files to that of the notes | Set the modification dates of the created files to that of the notes
| Python | mit | hiroshi/simplenote-backup |
476754a381fe38a0bbe6e3c7892c59a6cfa47db1 | openedx/features/job_board/models.py | openedx/features/job_board/models.py | from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
po... | from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
po... | Add support for countries with accented characters | Add support for countries with accented characters
| Python | agpl-3.0 | philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform |
d0c82bdd2d7e801c5bebc8ef0d87ed436e29fb82 | wiblog/formatting.py | wiblog/formatting.py | from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of... | from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
return mark_safe(CommonMark.commonmark(value))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firstNewline >... | Remove full CommonMark syntax for a simplified version | Remove full CommonMark syntax for a simplified version
| Python | agpl-3.0 | lo-windigo/fragdev,lo-windigo/fragdev |
2fcf9131bca907d79d96c622d015ba99de038e8d | zou/app/stores/publisher_store.py | zou/app/stores/publisher_store.py | from flask_socketio import SocketIO
from flask import current_app
from zou.app import config
host = config.KEY_VALUE_STORE["host"]
port = config.KEY_VALUE_STORE["port"]
redis_db = config.KV_EVENTS_DB_INDEX
redis_url = "redis://%s:%s/%s" % (host, port, redis_db)
socketio = None
def publish(event, data):
data = ... | from flask_socketio import SocketIO
from flask import current_app
from zou.app import config
host = config.KEY_VALUE_STORE["host"]
port = config.KEY_VALUE_STORE["port"]
redis_db = config.KV_EVENTS_DB_INDEX
redis_url = "redis://%s:%s/%s" % (host, port, redis_db)
socketio = None
def publish(event, data):
if sock... | Make publisher store emit the right event name | Make publisher store emit the right event name
| Python | agpl-3.0 | cgwire/zou |
24e6d37108bc01b69d2f64014862bebd1e980fee | olim/olim/apps/storage/models.py | olim/olim/apps/storage/models.py | from django.db import models
# Create your models here.
| from django.db import models
class Filesys(models.Model):
name = models.CharField(max_length=100)
url = models.URLField()
date = models.DateField(auto_now=True)
#uploader = models.ForeignKey('account.User')
thumbnail = models.FileField(upload_to='thumb')
parent_dir = models.CharField(max_lengt... | Make a model 'Filesys'. (not yet, because of uploader field) | Make a model 'Filesys'. (not yet, because of uploader field)
| Python | apache-2.0 | sparcs-kaist/olim,sparcs-kaist/olim |
d10656527cf3a0fe3d47827d8d2f27fda4cb2a5c | zseqfile/__init__.py | zseqfile/__init__.py | """
zseqfile - transparently handle compressed files
"""
# Expose the public API.
from .zseqfile import ( # noqa
open,
open_gzip,
open_bzip2,
open_lzma,
)
| """
zseqfile - transparently handle compressed files
"""
from .zseqfile import ( # noqa
open,
open_gzip,
open_bzip2,
open_lzma,
)
open_gz = open_gzip
open_bz2 = open_bzip2
open_xz = open_lzma
| Define a few convenience aliases in the public API | Define a few convenience aliases in the public API
| Python | bsd-3-clause | wbolster/zseqfile |
ff153f141eb67f124520c51de69e161436ff0666 | GreyMatter/business_news_reader.py | GreyMatter/business_news_reader.py | import json
import requests
from bs4 import BeautifulSoup
from SenseCells.tts import tts
# NDTV News
fixed_url = 'http://profit.ndtv.com/news/latest/'
news_headlines_list = []
news_details_list = []
for i in range(1, 2):
changing_slug = '/page-' + str(i)
url = fixed_url + changing_slug
r = requests.get... | import requests
from bs4 import BeautifulSoup
from SenseCells.tts import tts
# NDTV News
fixed_url = 'http://profit.ndtv.com/news/latest/'
news_headlines_list = []
news_details_list = []
for i in range(1, 2):
changing_slug = '/page-' + str(i)
url = fixed_url + changing_slug
r = requests.get(url)
dat... | Fix errors due to quotes and parenthesis in reading | Fix errors due to quotes and parenthesis in reading
| Python | mit | anurag-ks/Melissa-Core,Melissa-AI/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core |
5bfc42e4f7c948b1cb895ebec523426be6908829 | dockorm/tests/utils.py | dockorm/tests/utils.py | """
Utilities for dockorm tests.
"""
# encoding: utf-8
from __future__ import unicode_literals
from os.path import (
dirname,
join,
)
from six import iteritems
from ..container import (
Container,
scalar,
)
TEST_ORG = 'dockorm_testing'
TEST_TAG = 'test'
def assert_in_logs(container, line):
"""... | """
Utilities for dockorm tests.
"""
# encoding: utf-8
from __future__ import unicode_literals
from os import getenv
from os.path import (
dirname,
join,
)
from six import iteritems
from ..container import (
Container,
scalar,
)
TEST_ORG = 'dockorm_testing'
TEST_TAG = 'test'
def assert_in_logs(con... | Enable running tests from inside a container | TST: Enable running tests from inside a container
by setting an env var for the path to the test volume data on the host
| Python | apache-2.0 | quantopian/DockORM |
ed3906b295669b1c0e38d88a7eb19cdde324042b | pybuild/packages/libzmq.py | pybuild/packages/libzmq.py | from ..source import GitSource
from ..package import Package
from ..patch import LocalPatch
from ..util import target_arch
class LibZMQ(Package):
source = GitSource('https://github.com/AIPYX/zeromq3-x.git', alias='libzmq', branch='qpyc/3.2.5')
patches = [
LocalPatch('0001-Fix-libtoolize-s-issue-in-auto... | from ..source import GitSource
from ..package import Package
from ..patch import LocalPatch
from ..util import target_arch
class LibZMQ(Package):
source = GitSource('https://github.com/AIPYX/zeromq3-x.git', alias='libzmq', branch='qpyc/3.2.5')
patches = [
LocalPatch('0001-Fix-libtoolize-s-issue-in-auto... | Fix issue for building PyZMQ | Fix issue for building PyZMQ
| Python | apache-2.0 | qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core,qpython-android/QPython3-core |
960520b723d1af1999c647ebea8969b4837aa458 | blister/xmp.py | blister/xmp.py | # Copyright (c) 2016 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class VanillaXMP:
pass
| # Copyright (c) 2016 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from collections.abc import MutableMapping
class VanillaXMP (MutableMapping):
def __delitem__ (self, key):
pass
def __getite... | Write minimal code to implement MutableMapping | Write minimal code to implement MutableMapping
| Python | bsd-3-clause | daaang/blister |
ba23f58f7359b943d8d8ae7f05e15419c6918c6f | test/blacklist.py | test/blacklist.py | """
'blacklist' is a Python dictionary, it stores the mapping of a string describing
either a testclass or a testcase, i.e, testclass.testmethod, to the reason (a
string) it is blacklisted.
Following is an example which states that test class IntegerTypesExprTestCase
should be skipped because 'This test class crashed'... | """
'blacklist' is a Python dictionary, it stores the mapping of a string describing
either a testclass or a testcase, i.e, testclass.testmethod, to the reason (a
string) it is blacklisted.
Following is an example which states that test class IntegerTypesExprTestCase
should be skipped because 'This test class crashed'... | Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python, due to crashes while running the entire test suite with clang-126. | Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python,
due to crashes while running the entire test suite with clang-126.
To reproduce:
CC=clang ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
To skip this test case:
CC=clang ./dotest.py -b blacklist.py -v -w 2> ~/Developer/Log/lldb... | Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb |
8c26cb08dd08b7e34352e51b06ecb9129ac201a1 | stagecraft/libs/schemas/schemas.py | stagecraft/libs/schemas/schemas.py | from django.conf import settings
from json import loads as json_loads
from os import path
def get_schema():
schema_root = path.join(
settings.BASE_DIR,
'stagecraft/apps/datasets/schemas/timestamp.json'
)
with open(schema_root) as f:
json_f = json_loads(f.read())
return json_f
| from django.conf import settings
from json import loads as json_loads
from os import path
def get_schema():
schema_root = path.join(
settings.BASE_DIR,
'stagecraft/apps/datasets/schemas/timestamp.json'
)
with open(schema_root) as f:
schema = json_loads(f.read())
return schema
| Make the schema return object a bit more obvious and descriptive | Make the schema return object a bit more obvious and descriptive
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft |
e3f55180bba935f09355b73049c3729c797c9e9f | lc0266_palindrome_permutation.py | lc0266_palindrome_permutation.py | """Leetcode 266. Palindrome Permutation (Premium)
Easy
URL: https://leetcode.com/problems/palindrome-permutation
Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
"""... | """Leetcode 266. Palindrome Permutation (Premium)
Easy
URL: https://leetcode.com/problems/palindrome-permutation
Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
"""... | Complete one odd char count sol | Complete one odd char count sol
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
b6d61fef0fe372c7149fa52e2ab1acff144d0118 | tests/fixtures/dummy/facilities.py | tests/fixtures/dummy/facilities.py | # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet
from .address import AddressData
class SiteData(DataSet):
class dummy:
... | # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet
from .address import AddressData
from .finance import AccountData
class SiteData(... | Add fee_account to BuildingData of legacy test base | Add fee_account to BuildingData of legacy test base
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
5f27e570a369fbb408a48a567064a96f1ceac277 | tests/commands/project/utils.py | tests/commands/project/utils.py | from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
m = requests_mock.mock()
if isinstance(existing_projects, int):... | from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
project_id = uuid4()
m = requests_mock.mock()
if isinstance... | Add a mock API path for project details, used in e.g. test_init | Add a mock API path for project details, used in e.g. test_init
| Python | mit | valohai/valohai-cli |
bbd8b027eecc48266dfeee12419a6bcd807bdf65 | tests/__init__.py | tests/__init__.py | import os
import unittest
import pytest
class ScraperTest(unittest.TestCase):
online = False
test_file_name = None
def setUp(self):
os.environ[
"RECIPE_SCRAPERS_SETTINGS"
] = "tests.test_data.test_settings_module.test_settings"
test_file_name = (
self.te... | import os
import unittest
import pytest
class ScraperTest(unittest.TestCase):
maxDiff = None
online = False
test_file_name = None
def setUp(self):
os.environ[
"RECIPE_SCRAPERS_SETTINGS"
] = "tests.test_data.test_settings_module.test_settings"
test_file_name = (
... | Set maxDiff to 'None' on the base ScraperTest class | Set maxDiff to 'None' on the base ScraperTest class
| Python | mit | hhursev/recipe-scraper |
181d3b06bf985d0ccec156363ecd4fe3792ddf1a | scripts/assignment_test.py | scripts/assignment_test.py | # -*- coding: utf-8 -*-
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments ... | # -*- coding: utf-8 -*-
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments... | Refactor of one assignment test | Refactor of one assignment test
| Python | agpl-3.0 | Som-Energia/somenergia-generationkwh,Som-Energia/somenergia-generationkwh |
120bff1f3bdf347351c6903dc3df0cd51f1837c6 | tools/clean_output_directory.py | tools/clean_output_directory.py | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import utils
def Main():
build_root = utils.GetBuild... | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import utils
def Main():
build_root = utils.GetBuild... | Fix build directory cleaner, to not follow links on Windows. | Fix build directory cleaner, to not follow links on Windows.
BUG=
R=ricow@google.com
Review URL: https://codereview.chromium.org//1219833003.
| Python | bsd-3-clause | dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/... |
a0605e1be5980f9c2f80fe0e751e736a3f4b48ef | fiji_skeleton_macro.py | fiji_skeleton_macro.py | import sys
from ij import IJ
def ij_binary_skeletonize(impath_in, impath_out):
"""Load image `impath`, skeletonize it, and save it to the same file.
Parameters
----------
impath_in : string
Path to a 3D image file.
impath_out : string
Path to which to write the skeleton image fil... | import sys
from ij import IJ
def ij_binary_skeletonize(impath_in, impath_out):
"""Load image `impath`, skeletonize it, and save it to the same file.
Parameters
----------
impath_in : string
Path to a 3D image file.
impath_out : string
Path to which to write the skeleton image fil... | Add pruning step to skeletonization | Add pruning step to skeletonization
This requires an updated Fiji, as detailed in this mailing list thread:
https://list.nih.gov/cgi-bin/wa.exe?A1=ind1308&L=IMAGEJ#41
https://list.nih.gov/cgi-bin/wa.exe?A2=ind1308&L=IMAGEJ&F=&S=&P=36891
| Python | bsd-3-clause | jni/skeletons |
327ddb6db4009cf329ac0f8fb22b56b002e7ef96 | server/adventures/tests.py | server/adventures/tests.py | from django.test import TestCase
from .models import Author, Publisher, Edition, Setting, Adventure
class AuthorTests(TestCase):
def test_create_author(self):
gygax = Author.objects.create(name='Gary Gygax')
self.assertEqual(Author.objects.first(), gygax)
self.assertEqual(Author.objects.co... | from django.test import TestCase
from .models import Author, Publisher, Edition, Setting, Adventure
class AuthorTests(TestCase):
def test_create_author(self):
gygax = Author.objects.create(name='Gary Gygax')
self.assertEqual(Author.objects.first(), gygax)
self.assertEqual(Author.objects.co... | Add Setting model creation test | Add Setting model creation test
| Python | mit | petertrotman/adventurelookup,petertrotman/adventurelookup,petertrotman/adventurelookup,petertrotman/adventurelookup |
a3187d16a70966c84a4f4977768fcfefc93b5a6d | this_app/forms.py | this_app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | Add form to create a bucketlist item | Add form to create a bucketlist item
| Python | mit | borenho/flask-bucketlist,borenho/flask-bucketlist |
73c842af63a09add43c0e33336dd4eb21153fda1 | bin/database.py | bin/database.py | #!/usr/bin/env python
import json
from api import config
CURRENT_DATABASE_VERSION = 1 # An int that is bumped when a new
def confirm_schema_match():
"""
Checks version of database schema
Returns (0) if DB schema version matches requirements.
Returns (42) if DB schema version does not match
requi... | #!/usr/bin/env python
import json
from api import config
CURRENT_DATABASE_VERSION = 1 # An int that is bumped when a new schema change is made
def confirm_schema_match():
"""
Checks version of database schema
Returns (0) if DB schema version matches requirements.
Returns (42) if DB schema version d... | Fix tab vs spaces issue | Fix tab vs spaces issue
| Python | mit | scitran/api,scitran/api,scitran/core,scitran/core,scitran/core,scitran/core |
a5200bf744b819deff5f2301f5affdc524754a9a | code/png/__init__.py | code/png/__init__.py | from png import *
# Following methods are not parts of API and imports only for unittest
from png import _main
from png import strtobytes | try:
from png import *
# Following methods are not parts of API and imports only for unittest
from png import _main
from png import strtobytes
except ImportError:
_png = __import__(__name__ + '.png')
_to_import = _png.png.__all__
_to_import.extend(('_main', 'strtobytes'))
for it in _to_... | Fix compatibility with absolute import of Py3 | Fix compatibility with absolute import of Py3
| Python | mit | Scondo/purepng,Scondo/purepng |
73c84754699a6f0803d0ceb3081988b45c9c76e7 | contours/__init__.py | contours/__init__.py | # -* coding: utf-8 -*-
"""Contour calculations."""
# Python 2 support
# pylint: disable=redefined-builtin,unused-wildcard-import,wildcard-import
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from .core import numpy_formatter, matlab... | # -* coding: utf-8 -*-
"""Contour calculations."""
# Python 2 support
from __future__ import absolute_import
from .core import numpy_formatter, matlab_formatter, shapely_formatter
from .quad import QuadContourGenerator
__version__ = '0.0.2.dev0'
| Remove unneeded Python 2.7 compatibility imports. | Remove unneeded Python 2.7 compatibility imports.
| Python | mit | ccarocean/python-contours |
2ad9cf280ee1743f1ad542d3c0c8d8365caea11e | condatestall.py | condatestall.py | """
Uses conda to run and test all supported python + numpy versions.
"""
from __future__ import print_function
import itertools
import subprocess
import os
import sys
NPY = '16', '17'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def main():
failfast = '-v' in sys.argv[1:]
args = "... | """
Uses conda to run and test all supported python + numpy versions.
"""
from __future__ import print_function
import itertools
import subprocess
import os
import sys
if '-q' in sys.argv[1:]:
NPY = '18',
else:
NPY = '16', '17', '18'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def ... | Add option for quick test on all python version | Add option for quick test on all python version
| Python | bsd-2-clause | pitrou/numba,GaZ3ll3/numba,pombredanne/numba,GaZ3ll3/numba,stuartarchibald/numba,numba/numba,cpcloud/numba,gmarkall/numba,cpcloud/numba,gdementen/numba,ssarangi/numba,seibert/numba,sklam/numba,gdementen/numba,jriehl/numba,gmarkall/numba,IntelLabs/numba,pombredanne/numba,stuartarchibald/numba,jriehl/numba,stuartarchibal... |
a3e537dc7e91785bb45bfe4d5a788c26d52653b1 | command_line/make_sphinx_html.py | command_line/make_sphinx_html.py | # LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html
from __future__ import division
from libtbx import easy_run
import libtbx.load_env
import os.path as op
import shutil
import os
import sys
if (__name__ == "__main__") :
xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
assert (xia2_dir is not... | # LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html
from __future__ import division
import libtbx.load_env
from dials.util.procrunner import run_process
import shutil
import os
if (__name__ == "__main__") :
xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
assert (xia2_dir is not None)
dest_... | Check make exit codes and stop on error | Check make exit codes and stop on error
| Python | bsd-3-clause | xia2/xia2,xia2/xia2 |
72d45d64cace23950ef32e670e074ab45ec4d25b | designatedashboard/enabled/_1720_project_dns_panel.py | designatedashboard/enabled/_1720_project_dns_panel.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | Add ADD_INSTALLED_APPS to 'enabled' file | Add ADD_INSTALLED_APPS to 'enabled' file
Django looks for translation catalogs from directories in
INSTALLED_APPS. To display translations for designate-dashboard,
'designatedashboard' needs to be registered to INSTALLED_APPS.
(cherry picked from commit 1ed7893eb2ae10172a2f664fc05428c28c29099e)
Change-Id: Id5f0f0cb9c... | Python | apache-2.0 | openstack/designate-dashboard,openstack/designate-dashboard,openstack/designate-dashboard |
14b0ddc6fccf54a430caffdb10bad3a8cbbd2bc1 | ereuse_devicehub/scripts/updates/snapshot_software.py | ereuse_devicehub/scripts/updates/snapshot_software.py | from pydash import find
from ereuse_devicehub.resources.device.domain import DeviceDomain
from ereuse_devicehub.resources.event.device import DeviceEventDomain
from ereuse_devicehub.scripts.updates.update import Update
class SnapshotSoftware(Update):
"""
Changes the values of SnapshotSoftware and adds it to ... | from contextlib import suppress
from pydash import find
from ereuse_devicehub.resources.device.domain import DeviceDomain
from ereuse_devicehub.resources.event.device import DeviceEventDomain
from ereuse_devicehub.scripts.updates.update import Update
class SnapshotSoftware(Update):
"""
Changes the values of... | Fix getting snapshotsoftware on old snapshots | Fix getting snapshotsoftware on old snapshots
| Python | agpl-3.0 | eReuse/DeviceHub,eReuse/DeviceHub |
35325168839234efe98a927fda76548de553d666 | test/test_pipeline.py | test/test_pipeline.py | from pype.lexer import lexer
from pype.pipeline import Pipeline
example_error_ppl='test/samples/example_error.ppl'
example0_ppl='test/samples/example0.ppl'
example0_token='test/samples/example0.tokens'
example1_ppl='test/samples/example1.ppl'
example1_token='test/samples/example1.tokens'
def test_lexer():
lexer.i... | from pytest import raises
from pype.lexer import lexer
from pype.pipeline import Pipeline
example_error_ppl='test/samples/example_error.ppl'
example0_ppl='test/samples/example0.ppl'
example0_token='test/samples/example0.tokens'
example1_ppl='test/samples/example1.ppl'
example1_token='test/samples/example1.tokens'
def... | Raise pypeSyntaxError in pype test | Raise pypeSyntaxError in pype test
| Python | mit | cs207-project/TimeSeries,cs207-project/TimeSeries,cs207-project/TimeSeries,cs207-project/TimeSeries |
d84a47b875af42da3491c771e461b0a8ca5556db | tests/test_models.py | tests/test_models.py | import pytest
@pytest.mark.django_db
def test_tinycontent_str(simple_content):
assert "foobar" == str(simple_content)
@pytest.mark.django_db
def test_tinycontentfile_str(file_upload):
assert "Foobar" == str(file_upload)
| import pytest
@pytest.mark.django_db
def test_tinycontent_str(simple_content):
assert "foobar" == str(simple_content)
@pytest.mark.django_db
def test_tinycontentfile_str(file_upload):
assert "Foobar" == str(file_upload)
@pytest.mark.django_db
def test_tinycontentfile_slug(file_upload):
assert "foobar"... | Test the slug field is generated correctly | Test the slug field is generated correctly
| Python | bsd-3-clause | dominicrodger/django-tinycontent,ad-m/django-tinycontent,watchdogpolska/django-tinycontent,ad-m/django-tinycontent,dominicrodger/django-tinycontent,watchdogpolska/django-tinycontent |
ea2383175456257384e625bb1113d98536b78a92 | tests/test_shutil.py | tests/test_shutil.py | #!/usr/bin/env python
__author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2014, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '1/24/14'
import unittest
import os
import shutil
from monty.shutil import copy_r
class CopyRTest(unittest.T... | #!/usr/bin/env python
__author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2014, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '1/24/14'
import unittest
import os
import shutil
from monty.shutil import copy_r
# class CopyRTest(unittest... | Comment out CopyR test for now. | Comment out CopyR test for now.
| Python | mit | yanikou19/monty,davidwaroquiers/monty,materialsvirtuallab/monty,davidwaroquiers/monty,materialsvirtuallab/monty,gpetretto/monty,gmatteo/monty,gmatteo/monty |
0cc408e04c0f321bf486d6063b11e9b0762ef8fc | tests/test_tokens.py | tests/test_tokens.py | """
NOTE: There are no tests that check for data validation at this point since
the interpreter doesn't have any data validation as a feature.
"""
import pytest
from calc import INTEGER, Token
def test_no_defaults():
# There's no valid defaults at the moment.
with pytest.raises(TypeError):
Token()
... | """
NOTE: There are no tests that check for data validation at this point since
the interpreter doesn't have any data validation as a feature.
"""
import pytest
from calc import INTEGER, Token
def test_no_defaults():
# There's no valid defaults at the moment.
with pytest.raises(TypeError):
Token()
... | Use str and repr functions instead of magic methods | Use str and repr functions instead of magic methods
| Python | isc | bike-barn/red-green-refactor |
6c4883d6e4e65c9d6618244d821ca44c59ca5d58 | tests/test_prepare.py | tests/test_prepare.py | from asyncpg import _testbase as tb
class TestPrepare(tb.ConnectedTestCase):
async def test_prepare_1(self):
st = await self.con.prepare('SELECT 1 = $1 AS test')
rec = (await st.execute(1))[0]
self.assertTrue(rec['test'])
self.assertEqual(len(rec), 1)
self.assertEqual(tup... | from asyncpg import _testbase as tb
class TestPrepare(tb.ConnectedTestCase):
async def test_prepare_1(self):
st = await self.con.prepare('SELECT 1 = $1 AS test')
rec = (await st.execute(1))[0]
self.assertTrue(rec['test'])
self.assertEqual(len(rec), 1)
self.assertEqual(tup... | Test that we handle None->NULL conversion for TEXT and BINARY | tests: Test that we handle None->NULL conversion for TEXT and BINARY
| Python | apache-2.0 | MagicStack/asyncpg,MagicStack/asyncpg |
37eb125c2b68c0c0c271325aab9cb4863dc6ea55 | cte-collation-poc/extractmath.py | cte-collation-poc/extractmath.py | #!/usr/bin/env python
from __future__ import print_function
import sys
import argparse
from lxml import etree
NS = {'x': 'http://www.w3.org/1999/xhtml',
'mml':'http://www.w3.org/1998/Math/MathML'}
body_xpath = etree.XPath('//x:body', namespaces=NS)
math_xpath = etree.XPath("//mml:math", namespaces=NS)
def ... | #!/usr/bin/env python
from __future__ import print_function
import sys
import argparse
from lxml import etree
NS = {'x': 'http://www.w3.org/1999/xhtml',
'mml':'http://www.w3.org/1998/Math/MathML'}
body_xpath = etree.XPath('//x:body', namespaces=NS)
math_xpath = etree.XPath("//mml:math", namespaces=NS)
def ... | Use clear() instead of manually deleting all elements in the body | Use clear() instead of manually deleting all elements in the body
| Python | lgpl-2.1 | Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-rulesets,Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cte,Connexions/cte |
52e12dac4a341ddb7bbbf8bcbf5ee8a0d9dc5ec4 | treq/test/test_api.py | treq/test/test_api.py | import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
client_patcher = mock.patch('treq.api.HTTPClient')
self.HTTPClient = client_patcher.start()
self.addCleanup(cl... | import mock
from treq.test.util import TestCase
import treq
from treq._utils import set_global_pool
class TreqAPITests(TestCase):
def setUp(self):
set_global_pool(None)
agent_patcher = mock.patch('treq.api.Agent')
self.Agent = agent_patcher.start()
self.addCleanup(agent_patcher.... | Update default_pool tests for new call tree (mocks are fragile). | Update default_pool tests for new call tree (mocks are fragile).
| Python | mit | hawkowl/treq,hawkowl/treq,habnabit/treq,glyph/treq,cyli/treq,mithrandi/treq,ldanielburr/treq,FxIII/treq,inspectlabs/treq |
69924be13f6b4303304c86fa56a802b6d358e7b2 | instance/configuration_example.py | instance/configuration_example.py | # -*- coding: utf-8 -*-
"""
Instance configuration, possibly overwriting default values.
"""
class Configuration:
"""
Instance specific configurations for |projectname| that should not be shared with anyone
else (e.g. because of passwords).
You can overwrite any of the values from :m... | # -*- coding: utf-8 -*-
"""
Instance configuration, possibly overwriting default values.
"""
class Configuration:
"""
Instance specific configurations for |projectname| that should not be shared with anyone
else (e.g. because of passwords).
You can overwrite any of the values from :m... | Add admin email list to instance configuration. | Add admin email list to instance configuration.
| Python | mit | BMeu/Orchard,BMeu/Orchard |
36df0d8f2878a1b51b4d9461f1ee64ef90a826a3 | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | Implement UpperCamelCase name check for enum case | Implement UpperCamelCase name check for enum case
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
ab7eb6891ff0f6a574708267f166bc27c7b7e95b | orderedmodel/models.py | orderedmodel/models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, default=1)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not se... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, default=1, db_index=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
... | Enable index for order column | Enable index for order column
Ordering will be faster
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel |
817b597f3a45a8b16de84d480458a66499604f5a | owned_models/models.py | owned_models/models.py | from django.conf import settings
from django.db import models
class UserOwnedModelManager(models.Manager):
def filter_for_user(self, user, *args, **kwargs):
return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs)
def get_for_user(self, user, *args, **kwargs):
... | from django.conf import settings
from django.db import models
class UserOwnedModelManager(models.Manager):
def filter_for_user(self, user, *args, **kwargs):
return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs)
def get_for_user(self, user, *args, **kwargs):
... | Add `get_or_create_for_user` method to default Manager. | Add `get_or_create_for_user` method to default Manager. | Python | mit | discolabs/django-owned-models |
10f48f8a8d71a237b97f7952cf8164d0c5138886 | budget_proj/budget_app/urls.py | budget_proj/budget_app/urls.py | from django.conf.urls import url
from . import views
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='hackoregon_budget')
# Listed in alphabetical order.
urlpatterns = [
url(r'^$', schema_view),
url(r'^kpm/$', views.ListKpm.as_view()),
url(r'^ocrb/$', views.List... | from django.conf.urls import url
from . import views
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='hackoregon_budget')
# Listed in alphabetical order.
urlpatterns = [
url(r'^$', schema_view),
url(r'^kpm/$', views.ListKpm.as_view()),
url(r'^ocrb/$', views.List... | Add endpoints for AWS production feeds | Add endpoints for AWS production feeds
Added endpoints for pulling the data from AWS (vs pulling from CSV)
| Python | mit | hackoregon/team-budget,jimtyhurst/team-budget,hackoregon/team-budget,hackoregon/team-budget,jimtyhurst/team-budget,jimtyhurst/team-budget |
ea87538d29e4d6e9d3904e6ead86ebe4eb958aff | lib/reinteract/about_dialog.py | lib/reinteract/about_dialog.py | import gtk
import os
def _find_program_in_path(progname):
try:
path = os.environ['PATH']
except KeyError:
path = os.defpath
for dir in path.split(os.pathsep):
p = os.path.join(dir, progname)
if os.path.exists(p):
return p
return None
def _find_url_open_pr... | import gtk
import os
import sys
def _find_program_in_path(progname):
try:
path = os.environ['PATH']
except KeyError:
path = os.defpath
for dir in path.split(os.pathsep):
p = os.path.join(dir, progname)
if os.path.exists(p):
return p
return None
def _find_... | Use 'open' to open about dialog URLs on OS X | Use 'open' to open about dialog URLs on OS X
| Python | bsd-2-clause | johnrizzo1/reinteract,alexey4petrov/reinteract,alexey4petrov/reinteract,rschroll/reinteract,johnrizzo1/reinteract,rschroll/reinteract,jbaayen/reinteract,alexey4petrov/reinteract,jbaayen/reinteract,jbaayen/reinteract,johnrizzo1/reinteract,rschroll/reinteract |
95508fca6683220b52fb4853c3073b054775a377 | activities/models.py | activities/models.py | from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
... | from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
... | Change to_user to CharField for message model | Change to_user to CharField for message model
| Python | apache-2.0 | belatrix/BackendAllStars |
e21693f8c08e805421cc9b207dd901ed0fcd85a7 | tuskar_ui/infrastructure/history/views.py | tuskar_ui/infrastructure/history/views.py | # -*- coding: utf8 -*-
#
# 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... | # -*- coding: utf8 -*-
#
# 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... | Fix error in History table if stack does not exist | Fix error in History table if stack does not exist
Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba
| Python | apache-2.0 | rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui |
09bc3137328fbefe41044b5124f3c6a7abaa8982 | wqflask/tests/base/test_general_object.py | wqflask/tests/base/test_general_object.py | import unittest
from base.GeneralObject import GeneralObject
class TestGeneralObjectTests(unittest.TestCase):
"""
Test the GeneralObject base class
"""
def test_object_contents(self):
"""Test whether base contents are stored properly"""
test_obj = GeneralObject("a", "b", "c")
... | import unittest
from base.GeneralObject import GeneralObject
class TestGeneralObjectTests(unittest.TestCase):
"""
Test the GeneralObject base class
"""
def test_object_contents(self):
"""Test whether base contents are stored properly"""
test_obj = GeneralObject("a", "b", "c")
... | Add more tests for general_object | Add more tests for general_object
* wqflask/tests/base/test_general_object.py: test getattr() and `==`
| Python | agpl-3.0 | genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2 |
36916009198abca34c4457d93bc65abea6193d75 | yunity/tests/unit/test__utils__session.py | yunity/tests/unit/test__utils__session.py | from django.test import TestCase
from yunity.utils.session import RealtimeClientData
class TestSharedSession(TestCase):
def test_session_key(self):
self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123')
def test_set_get_django_redis(self):
RealtimeClientData.set_user_s... | from django.test import TestCase
from yunity.utils.session import RealtimeClientData
class TestSharedSession(TestCase):
def test_session_key(self):
self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123')
def test_set_get_django_redis(self):
RealtimeClientData.set_user_s... | Fix missing refactorization in unit test | Fix missing refactorization in unit test
send_to_users unit test was not modified after parameter change.
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core |
a52bd5acd50d37314247e4ffaed501ba08e0eca3 | tests/test_simple_model.py | tests/test_simple_model.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for creating a simple tight-binding model."""
import pytest
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('t1', T_VALUES)
@pytest.mark.para... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for creating a simple tight-binding model."""
import pytest
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('t1', T_VALUES)
@pytest.mark.para... | Fix test broken by previous commit. | Fix test broken by previous commit.
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
941ccc65bd14e65f7e877d107f67ee3bfe8e68a3 | thecure/sprites/enemies.py | thecure/sprites/enemies.py | from pygame.locals import *
from thecure import get_engine
from thecure.sprites.base import WalkingSprite
class Enemy(WalkingSprite):
DEFAULT_HEALTH = 10
class InfectedHuman(Enemy):
MOVE_SPEED = 2
def tick(self):
super(InfectedHuman, self).tick()
if self.started:
# Figure ... | from pygame.locals import *
from thecure import get_engine
from thecure.sprites.base import Direction, WalkingSprite
class Enemy(WalkingSprite):
DEFAULT_HEALTH = 10
class InfectedHuman(Enemy):
MOVE_SPEED = 2
APPROACH_DISTANCE = 400
def tick(self):
super(InfectedHuman, self).tick()
... | Improve infected human approach AI. | Improve infected human approach AI.
The approach AI now only kicks in when the player is within 400 pixels
of the enemy.
The direction it chooses to look in is a bit more sane now. It will
figure out whether the distance is greater in the X or Y location, and
pick a direction based on that. Now they actually appear t... | Python | mit | chipx86/the-cure |
6af918668cddf30c12a10fe46bc174e110bf04c3 | red_api.py | red_api.py | import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mo... | import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo on... | Use bson's JSON util to handle ObjectIds in a JSON context | Use bson's JSON util to handle ObjectIds in a JSON context
| Python | mit | AnSavvides/redjohn,AnSavvides/redjohn |
8f70981f93da9648a618fb529629e5bdd88a1f7d | tests/test_command_line_tool.py | tests/test_command_line_tool.py | import unittest
import os
from performance_testing.command_line import Tool
from performance_testing.result import Result
from performance_testing.config import Config
class CommandLineToolTest(unittest.TestCase):
def setUp(self):
self.current_directory = os.path.dirname(os.path.abspath(__file__))
... | import unittest
import os
from performance_testing.command_line import Tool
from performance_testing.result import Result
from performance_testing.config import Config
import config
class CommandLineToolTest(unittest.TestCase):
def setUp(self):
self.current_directory = os.path.dirname(os.path.abspath(__fi... | Remove yaml config and use config object | Remove yaml config and use config object
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing |
25f69d929af9ef600f067343524272bcaef54a6b | KerbalStuff/celery.py | KerbalStuff/celery.py | import smtplib
from celery import Celery
from email.mime.text import MIMEText
from KerbalStuff.config import _cfg, _cfgi, _cfgb
app = Celery("tasks", broker="redis://localhost:6379/0")
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i+n]
@... | import smtplib
from celery import Celery
from email.mime.text import MIMEText
from KerbalStuff.config import _cfg, _cfgi, _cfgb
app = Celery("tasks", broker="redis://localhost:6379/0")
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i+n]
@... | Remove addresses from "To" field, BCC instead. | [proposal] Remove addresses from "To" field, BCC instead.
Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68 | Python | mit | EIREXE/SpaceDock,EIREXE/SpaceDock,EIREXE/SpaceDock,EIREXE/SpaceDock |
2d8a3b8c9ca6196317758e58cefc76163b88607f | falcom/table.py | falcom/table.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | Move assignments in Table.__init__ around | Move assignments in Table.__init__ around
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
016cb79166bfaeb28f5d1a0c540f7e0632d485a1 | setup.py | setup.py | from distutils.core import setup
VERSION = '0.0.2.8'
setup(
name='jpp',
version=VERSION,
packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'],
url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION),
license='MIT',
author='asherbar',
author_em... | from distutils.core import setup
VERSION = '0.0.2.8'
setup(
name='jpp',
version=VERSION,
packages=['jpp', 'jpp.parser', 'jpp.cli_test'],
url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION),
license='MIT',
author='asherbar',
author_email='asherbare@gmail.com'... | Fix error due to missing package in packages list | Fix error due to missing package in packages list
| Python | mit | asherbar/json-plus-plus |
cb6d0ea6c05eb62fafe97ac13d5665cb00b2db3c | setup.py | setup.py | #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from distutils.core import setup
setup(name='spherical_functions',
version='1.0',
description='Python/numba implementation of Wigner D Matrices, spi... | #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from distutils.core import setup
setup(name='spherical_functions',
version='1.0',
description='Python/numba implementation of Wigner D Matrices, spi... | Copy data files for numpy | Copy data files for numpy
| Python | mit | moble/spherical_functions |
dcdaef9fb950a8082dcd46fc6a43c965b09f43b5 | places/views.py | places/views.py | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.list im... | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.list im... | Order restaurants by name in ListView | Order restaurants by name in ListView
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist |
08e84dcc0bce7a1914bc7fa734ca51c0dde362d1 | lab/monitors/nova_service_list.py | lab/monitors/nova_service_list.py | def start(lab, log, args):
import time
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
duration = args['duration']
period = args['period']
statuses = {'up': 1, 'down': 0}
server = lab.director()
start_time = time.time()
while start_tim... | def start(lab, log, args):
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
statuses = {'up': 1, 'down': 0}
server = lab.director()
with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_N... | Verify services status if FI is rebooted | Verify services status if FI is rebooted
Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
| Python | apache-2.0 | CiscoSystems/os-sqe,CiscoSystems/os-sqe,CiscoSystems/os-sqe |
84953a5595598f08741d49da22b01aaca2459bc2 | server/bottle_drone.py | server/bottle_drone.py | """Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run, hook, response, get, abort
from venthur_api import libardrone
drone = libardrone.ARDrone()
@hook('after_request')
def enable_cors():
"""Allow control headers."""
response.headers['Access-Control-Allow-O... | """Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run, hook, response, get, abort
from venthur_api import libardrone
drone = libardrone.ARDrone()
@hook('after_request')
def enable_cors():
"""Allow control headers."""
response.headers['Access-Control-Allow-O... | Set up a imgdata route to fetch latest image. | Set up a imgdata route to fetch latest image.
| Python | mit | DroneQuest/drone-quest,DroneQuest/drone-quest |
0449b604691b78d41ba588c43fe6f9646ebfc2e4 | OIPA/api/permissions/serializers.py | OIPA/api/permissions/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import Group
from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup
from api.publisher.serializers import PublisherSerializer
class OrganisationUserSerializer(serializers.ModelSerializer):
admin_groups ... | from rest_framework import serializers
from django.contrib.auth.models import Group
from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup
from api.publisher.serializers import PublisherSerializer
class OrganisationUserSerializer(serializers.ModelSerializer):
admin_groups ... | Add an is_validated key t OrganisationUserSerializer. | Add an is_validated key t OrganisationUserSerializer.
| Python | agpl-3.0 | zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA |
a6e6c32fc8455303c44cebdfa7507300d298aa24 | mediacrush/mcmanage/files.py | mediacrush/mcmanage/files.py | from ..objects import File, Album, Feedback, RedisObject, FailedFile
from ..files import delete_file
def files_delete(arguments):
hash = arguments['<hash>']
f = File.from_hash(hash)
if not f:
print("%r is not a valid file." % arguments["<hash>"])
return
delete_file(f)
print("Done, ... | from ..objects import File, Album, Feedback, RedisObject, FailedFile
from ..files import delete_file
def files_delete(arguments):
hash = arguments['<hash>']
if hash.startswith("./"):
hash = hash[2:]
f = File.from_hash(hash)
if not f:
print("%r is not a valid file." % hash)
retu... | Add support for ./hash to mcmanage | Add support for ./hash to mcmanage
| Python | mit | roderickm/MediaCrush,roderickm/MediaCrush,nerdzeu/NERDZCrush,roderickm/MediaCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.