commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
1e8fd33ef4e8b75632d8a4fe4d86944fdfc5a649 | beetle/__init__.py | beetle/__init__.py | name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'
class BeetleError(Exception):
pass
| name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'
class BeetleError(Exception):
def __init__(self, page=None):
self.page = page
| Allow the BeetleError class to take a page object as an argument | Allow the BeetleError class to take a page object as an argument
| Python | mit | cknv/beetle | name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'
class BeetleError(Exception):
def __init__(self, page=None):
self.page = page
| Allow the BeetleError class to take a page object as an argument
name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'
class BeetleError(Exception):
pass
|
2d534b7be13bda60646815e16a91e778da71c3f8 | auditlog/__manifest__.py | auditlog/__manifest__.py | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | Remove pre_init_hook reference from openerp, no pre_init hook exists any more | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
| Python | agpl-3.0 | Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Associ... |
926ddeb63f0366a59f14adbab5421ccb7f78f144 | exercises/book-store/example.py | exercises/book-store/example.py | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return 8 * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_far
gr... | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return BOOK_PRICE * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_fa... | Use book price constant in calculation | book-store: Use book price constant in calculation
| Python | mit | N-Parsons/exercism-python,pheanex/xpython,jmluy/xpython,behrtam/xpython,exercism/xpython,smalley/python,exercism/xpython,exercism/python,N-Parsons/exercism-python,smalley/python,pheanex/xpython,jmluy/xpython,exercism/python,behrtam/xpython | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return BOOK_PRICE * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_fa... | book-store: Use book price constant in calculation
BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return 8 * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
... |
dd19012ed8bb6ec702d84abe400bc3dec47044f3 | sortedm2m_tests/__init__.py | sortedm2m_tests/__init__.py | # Python
import os
# django-setuptest
import setuptest
TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']
class TestSuite(setuptest.SetupTestSuite):
def resolve_packages(self):
packages = super(TestSuite, self).resolve_packages()
for test_app in TEST_APPS:
... | # Python
import os
# django-setuptest
import setuptest
TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']
class TestSuite(setuptest.SetupTestSuite):
def __init__(self, *args, **kwargs):
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from south.managemen... | Fix to allow tests with South migrations to run. | Fix to allow tests with South migrations to run.
| Python | bsd-3-clause | gregmuellegger/django-sortedm2m,fabrique/django-sortedm2m,gradel/django-sortedm2m,MathieuDuponchelle/django-sortedm2m,fabrique/django-sortedm2m,gradel/django-sortedm2m,fabrique/django-sortedm2m,gradel/django-sortedm2m,gregmuellegger/django-sortedm2m,MathieuDuponchelle/django-sortedm2m,gregmuellegger/django-sortedm2m | # Python
import os
# django-setuptest
import setuptest
TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']
class TestSuite(setuptest.SetupTestSuite):
def __init__(self, *args, **kwargs):
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from south.managemen... | Fix to allow tests with South migrations to run.
# Python
import os
# django-setuptest
import setuptest
TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']
class TestSuite(setuptest.SetupTestSuite):
def resolve_packages(self):
packages = super(TestSuite, self).reso... |
9ad55a4d532dc98f257206ae82b5d06f4203a4d4 | server/lib/python/cartodb_services/setup.py | server/lib/python/cartodb_services/setup.py | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/geocoder-api',
author='Data Serv... | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data ... | Update url of pip package | Update url of pip package
| Python | bsd-3-clause | CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data ... | Update url of pip package
"""
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/geocoder-a... |
25db9110d34760118b47b2bdf637cf6947154c2c | tests/unit/distributed/test_objectstore.py | tests/unit/distributed/test_objectstore.py | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | Test json file with api key is in API service class | Test json file with api key is in API service class
| Python | mit | a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,vladsaveliev/bcbio-nextgen,cha... | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | Test json file with api key is in API service class
import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.obje... |
3fb0f567dcaf69e4fa9872702ffbfa8ab0e69eaf | lib/utilities/key_exists.py | lib/utilities/key_exists.py |
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
... |
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
... | Add more error handling to key exists | Add more error handling to key exists
| Python | mpl-2.0 | mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mozilla/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,mpurzynski/MozDe... |
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
... | Add more error handling to key exists
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_di... |
f9ebca863ff2fd1a0ea160047cd70c59b4663b9d | test_bert_trainer.py | test_bert_trainer.py | import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(out... | import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(out... | Print eval results in test | Print eval results in test
| Python | apache-2.0 | googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings | import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(out... | Print eval results in test
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
... |
d1b7753fd29cb5c1f68b5ee121a511e43c99b5de | pmix/ppp/odkcalculate.py | pmix/ppp/odkcalculate.py | class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self):
return ""
def to_text(self):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
| class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self, *args, **kwargs):
return ""
def to_text(self, *args, **kwargs):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
| Update signature of to_text and to_html | Update signature of to_text and to_html
| Python | mit | jkpr/pmix | class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self, *args, **kwargs):
return ""
def to_text(self, *args, **kwargs):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
| Update signature of to_text and to_html
class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self):
return ""
def to_text(self):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
|
186a2c3f235264c3c71396efcbb8a33924758db9 | scrape.py | scrape.py | import discord
import asyncio
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.',... | import discord
import asyncio
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.',... | Update to use token instead of email+pass | Update to use token instead of email+pass
| Python | mit | suclearnub/discordgrapher | import discord
import asyncio
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.',... | Update to use token instead of email+pass
import discord
import asyncio
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Ch... |
7f5d6e4386e3a80db5cfcbf961c7603b0c78cc52 | openxc/sources/serial.py | openxc/sources/serial.py | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
class Serial... | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
class Serial... | Make sure LOG is defined before using it. | Make sure LOG is defined before using it.
| Python | bsd-3-clause | openxc/openxc-python,openxc/openxc-python,openxc/openxc-python | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
class Serial... | Make sure LOG is defined before using it.
"""A virtual serial port data source."""
from __future__ import absolute_import
import logging
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
from .base import BytestreamDataSource, DataSourceError
LOG =... |
ca11355cb4ece27ffb9fee8e9df304b43dd6b6b8 | server/proposal/migrations/0034_fix_updated.py | server/proposal/migrations/0034_fix_updated.py | import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max
def fix_updated(apps, _):
Proposal = apps.get_model("proposal", "Proposal")
proposals = Proposal.objects.annotate(published=Max("documents__published"))
for proposal in proposals:
... | Set proposal updated date to the mod date of most recent Document | Set proposal updated date to the mod date of most recent Document
| Python | mit | cityofsomerville/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise | import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max
def fix_updated(apps, _):
Proposal = apps.get_model("proposal", "Proposal")
proposals = Proposal.objects.annotate(published=Max("documents__published"))
for proposal in proposals:
... | Set proposal updated date to the mod date of most recent Document
| |
bcf4f87e3690986827d8d34eea5e7edfc03485e2 | cassandra_migrate/test/test_cql.py | cassandra_migrate/test/test_cql.py | from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
['CREATE TABLE hello', 'CREATE TABLE world']),
# Two st... | from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
['CREATE TABLE hello', 'CREATE TABLE world']),
# Two st... | Add CQL-splitting test case for double-dollar-sign strings | Add CQL-splitting test case for double-dollar-sign strings
| Python | mit | Cobliteam/cassandra-migrate,Cobliteam/cassandra-migrate | from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
['CREATE TABLE hello', 'CREATE TABLE world']),
# Two st... | Add CQL-splitting test case for double-dollar-sign strings
from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
... |
5bf040c84bb5fddceba0324b409514e8c80e19eb | conda/python-scons/conda.py | conda/python-scons/conda.py | from distutils.version import StrictVersion
from distutils.msvccompiler import get_build_version
from sys import maxsize
from SCons.Script import AddOption, GetOption
from path import path
import subprocess
def generate(env):
"""Add Builders and construction variables to the Environment."""
if not 'conda' in e... | Add Conda Tool for SCons | Add Conda Tool for SCons
| Python | apache-2.0 | StatisKit/StatisKit,StatisKit/StatisKit | from distutils.version import StrictVersion
from distutils.msvccompiler import get_build_version
from sys import maxsize
from SCons.Script import AddOption, GetOption
from path import path
import subprocess
def generate(env):
"""Add Builders and construction variables to the Environment."""
if not 'conda' in e... | Add Conda Tool for SCons
| |
edab1cbfb3aada1378e1b248075909a2ba717efa | rtei/migrations/0003_rteidocument_file_size.py | rtei/migrations/0003_rteidocument_file_size.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-11 08:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rtei', '0002_auto_20190109_1413'),
]
operations = [
migrations.AddField(
... | Add rteidocument file size migration | Add rteidocument file size migration
(apply 3rd)
| Python | agpl-3.0 | okfn/rtei,okfn/rtei,okfn/rtei,okfn/rtei | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-11 08:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rtei', '0002_auto_20190109_1413'),
]
operations = [
migrations.AddField(
... | Add rteidocument file size migration
(apply 3rd)
| |
94cd1300a4ccf66488120092dfe880eabc7f06df | tests/test_dump.py | tests/test_dump.py | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpat... | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TM... | TEST - setup teardown for test | TEST - setup teardown for test
| Python | bsd-2-clause | QuLogic/gitwash,QuLogic/gitwash | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TM... | TEST - setup teardown for test
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file... |
a035798ed00df2483a32e76a913cbc4cc8bf8df2 | api/middleware.py | api/middleware.py | class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
| class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [A... | Fix API access control headers | Fix API access control headers
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline | class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [A... | Fix API access control headers
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
|
29b1c862f603f3399ebe1e3acb7e14e776e2102f | performance_testing/result.py | performance_testing/result.py | import os
from datetime import datetime
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
name = '%d-%d-%d_%d-%d-%d' % (datetime.year,
datetime.month,
datetime.day,
... | Create Result class with file | Create Result class with file
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | import os
from datetime import datetime
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
name = '%d-%d-%d_%d-%d-%d' % (datetime.year,
datetime.month,
datetime.day,
... | Create Result class with file
| |
d676065cb9f137c5feb18b125d0d30dfae4e0b65 | Dice.py | Dice.py | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
... | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
... | Add get dice roll function | Add get dice roll function
| Python | mit | achyutreddy24/DiceGame | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
... | Add get dice roll function
import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = ra... |
c4f0f13892f1a1af73a94e6cbea95d30e676203c | xorgauth/accounts/views.py | xorgauth/accounts/views.py | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_conse... | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_conse... | Fix access restriction to /accounts/profile/ | Fix access restriction to /accounts/profile/
LoginRequiredMixin needs to come first for it to be applied. Otherwise,
/accounts/profile/ is accessible even when the user is not
authenticated.
| Python | agpl-3.0 | Polytechnique-org/xorgauth,Polytechnique-org/xorgauth | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_conse... | Fix access restriction to /accounts/profile/
LoginRequiredMixin needs to come first for it to be applied. Otherwise,
/accounts/profile/ is accessible even when the user is not
authenticated.
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins i... |
ab3e5d78f883561d45ac6074f27c97eefa4c1540 | test_bst.py | test_bst.py | from bst import BinarySearchTree
nodes = [5, 4, 8, 3, 43, 22, 7, 74, 2]
def test_insert_nodes():
"""size of tree equal to number of values inserted"""
b = BinarySearchTree()
for n in nodes:
b.insert(n)
assert b.size() == 9
def test_contains_node():
"""expected nodes in tree"""
b = ... | Add tests for binary search tree | Add tests for binary search tree
| Python | mit | nbeck90/data_structures_2 | from bst import BinarySearchTree
nodes = [5, 4, 8, 3, 43, 22, 7, 74, 2]
def test_insert_nodes():
"""size of tree equal to number of values inserted"""
b = BinarySearchTree()
for n in nodes:
b.insert(n)
assert b.size() == 9
def test_contains_node():
"""expected nodes in tree"""
b = ... | Add tests for binary search tree
| |
2e92550dd52d8a084b01a6e4b8a429e50f11cf36 | scripts/compact_seriesly.py | scripts/compact_seriesly.py | from logger import logger
from seriesly import Seriesly
from perfrunner.settings import StatsSettings
def main():
s = Seriesly(StatsSettings.SERIESLY['host'])
for db in s.list_dbs():
logger.info('Compacting {}'.format(db))
result = s[db].compact()
logger.info('Compaction finished: {}'... | from logger import logger
from seriesly import Seriesly
from perfrunner.settings import StatsSettings
def main():
s = Seriesly(StatsSettings.SERIESLY)
for db in s.list_dbs():
logger.info('Compacting {}'.format(db))
result = s[db].compact()
logger.info('Compaction finished: {}'.format(... | Update reference to Seriesly hostname | Update reference to Seriesly hostname
Change-Id: I03eb6b3551e21d6987f15ec236c40546b312e663
Reviewed-on: http://review.couchbase.org/71447
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
| Python | apache-2.0 | pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner | from logger import logger
from seriesly import Seriesly
from perfrunner.settings import StatsSettings
def main():
s = Seriesly(StatsSettings.SERIESLY)
for db in s.list_dbs():
logger.info('Compacting {}'.format(db))
result = s[db].compact()
logger.info('Compaction finished: {}'.format(... | Update reference to Seriesly hostname
Change-Id: I03eb6b3551e21d6987f15ec236c40546b312e663
Reviewed-on: http://review.couchbase.org/71447
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
from logger import logge... |
aae0e295ef1c020371831aa9145820d8678670f7 | axes/apps.py | axes/apps.py | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | Add QA skip for import ordering | Add QA skip for import ordering | Python | mit | jazzband/django-axes | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | Add QA skip for import ordering
from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging... |
bd99d5fe158d911e08b329c05fc8ba46c909d7b4 | scripts/ua/mine_mtarchive.py | scripts/ua/mine_mtarchive.py | import subprocess
import datetime
import pytz
import urllib2
from ingest_from_rucsoundings import RAOB
import psycopg2
POSTGIS = psycopg2.connect(database='postgis', host='iemdb')
def conv( raw):
if float(raw) < -9998:
return None
return float(raw)
sts = datetime.datetime(1946,1,1)
ets = datetime.da... | Add script to process mtarchive's sounding archive | Add script to process mtarchive's sounding archive | Python | mit | akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem | import subprocess
import datetime
import pytz
import urllib2
from ingest_from_rucsoundings import RAOB
import psycopg2
POSTGIS = psycopg2.connect(database='postgis', host='iemdb')
def conv( raw):
if float(raw) < -9998:
return None
return float(raw)
sts = datetime.datetime(1946,1,1)
ets = datetime.da... | Add script to process mtarchive's sounding archive
| |
9d78a7be6ea922844bc9c6a0795af8d7b7a247a3 | bl/text.py | bl/text.py |
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn ... |
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn ... | Revert "allow to write Text with raw data" | Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
| Python | mpl-2.0 | BlackEarth/bl,BlackEarth/bl |
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn ... | Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=f... |
083d71834e82815dd338a873090df4cda64d74f4 | test/test_logger.py | test/test_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test... | Update skip condition for tests | Update skip condition for tests
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test... | Update skip condition for tests
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import lo... |
996611b4ec0f0e13769d40122f21b6a6362783a5 | app.tmpl/models.py | app.tmpl/models.py | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
os.path.join(app.root_path, app... | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
o... | Use newer package import syntax for Flask | Use newer package import syntax for Flask
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
o... | Use newer package import syntax for Flask
# Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.... |
dbdf844f97feb69d405618271af943d17c4363cb | setup.py | setup.py | # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.j... | # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.j... | Rename the DB initialization script | scripts: Rename the DB initialization script
We'll have other scripts, prefixing them all by the app name will be
nicer to admins.
| Python | agpl-3.0 | network-box/uptrack,network-box/uptrack | # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.j... | scripts: Rename the DB initialization script
We'll have other scripts, prefixing them all by the app name will be
nicer to admins.
# There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_pa... |
71eeb919373787569034225e8047079075df5569 | Challenges/chall_06.py | Challenges/chall_06.py | #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt:
welcome to my zipped list.
... | #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt:
welcome to my zipped list.
... | Add print statements for clarity | Add print statements for clarity
| Python | mit | HKuz/PythonChallenge | #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt:
welcome to my zipped list.
... | Add print statements for clarity
#!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt... |
77c69f592fe35ac4e3087366da084b7a73f21ee6 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... | Update pyyaml requirement from <5.2,>=5.1 to >=5.1,<5.3 | Update pyyaml requirement from <5.2,>=5.1 to >=5.1,<5.3
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyy... | Python | apache-2.0 | zooniverse/panoptes-cli | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... | Update pyyaml requirement from <5.2,>=5.1 to >=5.1,<5.3
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyy... |
9942b7b6e550ec6f76def44a7470f747c47b13a8 | utils/00-cinspect.py | utils/00-cinspect.py | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | Patch the colorized formatter to not break for C modules. | Patch the colorized formatter to not break for C modules.
| Python | bsd-3-clause | punchagan/cinspect,punchagan/cinspect | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | Patch the colorized formatter to not break for C modules.
""" A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
impor... |
ab32e80f7d5bb92c969a0f0926a120325fad438b | peekaboo.py | peekaboo.py | import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r... | import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r... | Use the list item, not the list. | Use the list item, not the list.
Otherwise you get urls with `[u'1234']` in.
| Python | mit | ghickman/peekaboo | import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r... | Use the list item, not the list.
Otherwise you get urls with `[u'1234']` in.
import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications... |
61cf4e2feb3d8920179e28719822c7fb34ea6550 | 3/ibm_rng.py | 3/ibm_rng.py | def ibm_rng(x1, a, c, m):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
| def ibm_rng(x1, a=65539, c=0, m=2**31):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
| Add defaults to the ibm RNG | Add defaults to the ibm RNG
| Python | mit | JelteF/statistics | def ibm_rng(x1, a=65539, c=0, m=2**31):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
| Add defaults to the ibm RNG
def ibm_rng(x1, a, c, m):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
|
991b0da117956e4d523732edc03bc287edf6a680 | identity/app.py | identity/app.py | from __future__ import unicode_literals, absolute_import
import os
from identity import app
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0',
port=port,
debug=os.environ.get('DEBUG', False))
| from __future__ import unicode_literals, absolute_import
import os
if os.environ.get('ENV') and os.path.exists(os.environ['ENV']):
for line in open(os.environ['ENV']):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from identity import app
if __name__ == ... | Load env-vars from a .env file | Load env-vars from a .env file
| Python | mit | ErinCall/identity,ErinCall/identity | from __future__ import unicode_literals, absolute_import
import os
if os.environ.get('ENV') and os.path.exists(os.environ['ENV']):
for line in open(os.environ['ENV']):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from identity import app
if __name__ == ... | Load env-vars from a .env file
from __future__ import unicode_literals, absolute_import
import os
from identity import app
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0',
port=port,
debug=os.environ.get('DEBUG', False))
|
f98a20977c359189b506f765d6c2493fda7718a9 | scripts/tests/off-center-rotation.py | scripts/tests/off-center-rotation.py | from paraview.simple import *
import tonic
from tonic import paraview as pv
dataset_destination_path = '/Users/seb/spherical'
# Initial ParaView scene setup
Cone(Center=[2,4,8])
Show()
view = Render()
view.CameraFocalPoint = [2,4,8]
view.CameraPosition = [2,4,0]
view.CenterOfRotation = [2,4,8]
view.CameraViewUp = [0... | Add a test for spherical camera with off center object | test(CenterOfRotation): Add a test for spherical camera with off center object
| Python | bsd-3-clause | Kitware/tonic-data-generator,Kitware/tonic-data-generator | from paraview.simple import *
import tonic
from tonic import paraview as pv
dataset_destination_path = '/Users/seb/spherical'
# Initial ParaView scene setup
Cone(Center=[2,4,8])
Show()
view = Render()
view.CameraFocalPoint = [2,4,8]
view.CameraPosition = [2,4,0]
view.CenterOfRotation = [2,4,8]
view.CameraViewUp = [0... | test(CenterOfRotation): Add a test for spherical camera with off center object
| |
8c2996b94cdc3210b24ebeaeb957c625629f68a5 | hunting/level/encoder.py | hunting/level/encoder.py | import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif is... | import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif is... | Add log to encoding output (still fails due to objects) | Add log to encoding output (still fails due to objects)
| Python | mit | MoyTW/RL_Arena_Experiment | import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif is... | Add log to encoding output (still fails due to objects)
import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
... |
597000dac85ef0760e04f3c6d885bde531fa86a2 | Lib/test/crashers/decref_before_assignment.py | Lib/test/crashers/decref_before_assignment.py | """
General example for an attack against code like this:
Py_DECREF(obj->attr); obj->attr = ...;
here in Module/_json.c:scanner_init().
Explanation: if the first Py_DECREF() calls either a __del__ or a
weakref callback, it will run while the 'obj' appears to have in
'obj->attr' still the old reference to the obj... | Add a crasher for the documented issue of calling "Py_DECREF(self->xxx)"; | Add a crasher for the documented issue of calling "Py_DECREF(self->xxx)";
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | """
General example for an attack against code like this:
Py_DECREF(obj->attr); obj->attr = ...;
here in Module/_json.c:scanner_init().
Explanation: if the first Py_DECREF() calls either a __del__ or a
weakref callback, it will run while the 'obj' appears to have in
'obj->attr' still the old reference to the obj... | Add a crasher for the documented issue of calling "Py_DECREF(self->xxx)";
| |
413c0b7f2df43543fd360bca1a9a6b9de4f6f5e8 | integration-tests/features/steps/user_intent.py | integration-tests/features/steps/user_intent.py | """Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
"""Post data into the REST API endpoin... | """Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
"""Post data into the REST API endpoin... | Fix - send JSON to the API, not raw data | Fix - send JSON to the API, not raw data
| Python | apache-2.0 | tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common | """Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
"""Post data into the REST API endpoin... | Fix - send JSON to the API, not raw data
"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin
import requests
from src.authorization_tokens import authorization
from src.parsing import parse_token_clause
def post_data_to_user_intent_endpoint(context, payload=None):
... |
d5a3b6e1eb37883a16c7e98d2a1b7c98d8d67051 | layout/tests.py | layout/tests.py | 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)
| from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from layout.views import home
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page(self):
found = resolve('/')
se... | Add test for home page html content | Add test for home page html content
| Python | mit | jvanbrug/scout,jvanbrug/scout | from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from layout.views import home
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page(self):
found = resolve('/')
se... | Add test for home page html content
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)
|
7f48dde064acbf1c192ab0bf303ac8e80e56e947 | wafer/kv/models.py | wafer/kv/models.py | from django.contrib.auth.models import Group
from django.db import models
from jsonfield import JSONField
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=True)
value = JSONField()
def __unicode__(self):
r... | from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField
@python_2_unicode_compatible
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(... | Use @python_2_unicode_compatible rather than repeating methods | Use @python_2_unicode_compatible rather than repeating methods
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField
@python_2_unicode_compatible
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(... | Use @python_2_unicode_compatible rather than repeating methods
from django.contrib.auth.models import Group
from django.db import models
from jsonfield import JSONField
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=Tru... |
806e3b4f92fdc72a83cac18d338d7293673f9650 | yolk/__init__.py | yolk/__init__.py | """yolk
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.1'
| """yolk
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.2'
| Increment patch version to 0.6.2 | Increment patch version to 0.6.2
| Python | bsd-3-clause | myint/yolk,myint/yolk | """yolk
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.2'
| Increment patch version to 0.6.2
"""yolk
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.1'
|
ba3c7e6e2c7fff7ed0c2b51a129b9d7c85eefc6f | helios/__init__.py | helios/__init__.py |
from django.conf import settings
from django.core.urlresolvers import reverse
from helios.views import election_shortcut
TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"
# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY
# allow upload ... | from django.conf import settings
from django.core.urlresolvers import reverse
TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"
# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY
# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.... | Remove unused import causing deprecation warning | Remove unused import causing deprecation warning
Warning in the form:
RemovedInDjango19Warning: "ModelXYZ" doesn't declare an explicit app_label
Apparently this happens because it tries to import models before app
configuration runs
| Python | apache-2.0 | shirlei/helios-server,benadida/helios-server,shirlei/helios-server,benadida/helios-server,shirlei/helios-server,benadida/helios-server,benadida/helios-server,benadida/helios-server,shirlei/helios-server,shirlei/helios-server | from django.conf import settings
from django.core.urlresolvers import reverse
TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"
# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY
# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.... | Remove unused import causing deprecation warning
Warning in the form:
RemovedInDjango19Warning: "ModelXYZ" doesn't declare an explicit app_label
Apparently this happens because it tries to import models before app
configuration runs
from django.conf import settings
from django.core.urlresolvers import reverse
from h... |
fb5612d641296a022a869bd0a4b9a0aed9255e51 | _pytest/test_formatting.py | _pytest/test_formatting.py | import pytest
import wee_slack
@pytest.mark.parametrize("text", [
"""
* an item
* another item
""",
"* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
assert wee_slack.render_formatting(text) == text
| Add tests for no formatting cases | Add tests for no formatting cases
| Python | mit | wee-slack/wee-slack,rawdigits/wee-slack,trygveaa/wee-slack | import pytest
import wee_slack
@pytest.mark.parametrize("text", [
"""
* an item
* another item
""",
"* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
assert wee_slack.render_formatting(text) == text
| Add tests for no formatting cases
| |
0325d4d55e9f42d031edc66fe4dedfefea4c66e2 | src/scripts/Main.py | src/scripts/Main.py | """The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
# Read the path for the configuration file we use for this ... | """The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
# Read the path for the configuration file we use for this ... | Enable inhomogeneous packets in the main simulation runner | Enable inhomogeneous packets in the main simulation runner
| Python | bsd-3-clause | WaveBlocks/WaveBlocksND,WaveBlocks/WaveBlocksND | """The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
# Read the path for the configuration file we use for this ... | Enable inhomogeneous packets in the main simulation runner
"""The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
... |
c9e2c70e05ade220e5aa6a4790ee2a9b720cc46e | sorting_test.py | sorting_test.py | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesor... | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(me... | Allow comparison within a fixed time period | Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many... | Python | mit | timpel/stanford-algs,timpel/stanford-algs | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(me... | Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many... |
acf2729f368ad4eabc0219d1a191089e8d5f740f | dmz/geolocate.py | dmz/geolocate.py | #Using MaxMind, so import pygeoip
import pygeoip
def geolocate(ip_addresses):
#Read in files, storing in memory for speed
ip4_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", flags = 1)
#Check type
if not(isinstan... | """
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip
class GeoLocator(object):
"""Geo locate IP addresses using the MaxMind database"""
def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
ipv6_geo_path='/usr/sh... | Move the Geo Location stuff into a class | Move the Geo Location stuff into a class
| Python | mit | yuvipanda/edit-stats | """
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip
class GeoLocator(object):
"""Geo locate IP addresses using the MaxMind database"""
def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
ipv6_geo_path='/usr/sh... | Move the Geo Location stuff into a class
#Using MaxMind, so import pygeoip
import pygeoip
def geolocate(ip_addresses):
#Read in files, storing in memory for speed
ip4_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", fla... |
cf6034fc62cc97a5655b371fdef4a4728707fdea | changes/utils/locking.py | changes/utils/locking.py | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}'.format(
func.__name__,
md5(
'&'.... | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}:{2}'.format(
func.__module__,
func.__name__,
... | Use __module__ to make @lock unique | Use __module__ to make @lock unique
Summary: Fixes T49428.
Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...
Reviewers: armooo, kylec
Reviewed By: kylec
Subscribers: changesbot, mkedia, jukka, vishal
Maniphest Tasks: T494... | Python | apache-2.0 | bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}:{2}'.format(
func.__module__,
func.__name__,
... | Use __module__ to make @lock unique
Summary: Fixes T49428.
Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...
Reviewers: armooo, kylec
Reviewed By: kylec
Subscribers: changesbot, mkedia, jukka, vishal
Maniphest Tasks: T494... |
98fe5bbe14ef47006ca45b82b681abc5b54be5cd | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_descri... | from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_descri... | Remove kws: does not exist | Remove kws: does not exist
| Python | bsd-3-clause | funkybob/django-flatblocks,funkybob/django-flatblocks | from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_descri... | Remove kws: does not exist
from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the mai... |
5dd07cdc94a479b5c274a2335a50815b957cffe6 | zoe_web/web/__init__.py | zoe_web/web/__init__.py | # Copyright (c) 2015, Daniele Venzano
#
# 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 w... | # Copyright (c) 2015, Daniele Venzano
#
# 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 w... | Fix version in web pages | Fix version in web pages
| Python | apache-2.0 | DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe | # Copyright (c) 2015, Daniele Venzano
#
# 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 w... | Fix version in web pages
# Copyright (c) 2015, Daniele Venzano
#
# 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 applic... |
34d94f771b61a73ee484fc576f8e5dd2d0b14a0f | softwareindex/handlers/coreapi.py | softwareindex/handlers/coreapi.py | import requests, json, urllib
SEARCH_URL = 'http://core.ac.uk:80/api-v2/articles/search/'
API_KEY = 'FILL THIS IN'
def getCOREMentions(identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/reg... | import requests, json, urllib
SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'
def getCOREMentions(identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"... | Switch to using the v1 API to get total hits. | Switch to using the v1 API to get total hits.
| Python | bsd-3-clause | softwaresaved/softwareindex,softwaresaved/softwareindex | import requests, json, urllib
SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'
def getCOREMentions(identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"... | Switch to using the v1 API to get total hits.
import requests, json, urllib
SEARCH_URL = 'http://core.ac.uk:80/api-v2/articles/search/'
API_KEY = 'FILL THIS IN'
def getCOREMentions(identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can b... |
03b4e218e796bf2cc42015f70195fb4a5e13f33b | decision/__init__.py | decision/__init__.py | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.info("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY... | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTR... | Set config logging in init to debug | Set config logging in init to debug
| Python | mit | LandRegistry/decision-alpha,LandRegistry/decision-alpha | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTR... | Set config logging in init to debug
import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.info("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry... |
e0adf4df50dcb366e7977f46e1f09ca04dd48cf2 | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotat... | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotat... | Update log output so that it works more nicely with ELK | Update log output so that it works more nicely with ELK
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotat... | Update log output so that it works more nicely with ELK
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which l... |
ff664b9731d6fdcbbd3eadf02595a35ccac402f6 | markups/common.py | markups/common.py | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Update MathJax URL to 2.7.1 | Update MathJax URL to 2.7.1
| Python | bsd-3-clause | retext-project/pymarkups,mitya57/pymarkups | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Update MathJax URL to 2.7.1
# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.gete... |
1e2822bb71c123993419479c2d4f5fc3e80e35bb | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
adzerk_srs = g.live_config.get("adzerk_srs")
in_adzerk_sr = a... | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
adzerk_srs = g.live_config.get("adzerk_srs")
in_adzerk_sr = a... | Use analytics name for subreddits if available. | Use analytics name for subreddits if available.
This allows a catch-all for multis to be used.
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
adzerk_srs = g.live_config.get("adzerk_srs")
in_adzerk_sr = a... | Use analytics name for subreddits if available.
This allows a catch-all for multis to be used.
from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adze... |
06c8c91b05e0bf5f15271560df4101d90adfeb39 | Lib/test/test_capi.py | Lib/test/test_capi.py | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _test exports whose name begins with 'test_'.
import sys
import test_support
import _testcapi
for name in dir(_testcapi):
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_support.... | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
import sys
import test_support
import _testcapi
for name in dir(_testcapi):
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_supp... | Fix typo in comment (the module is now called _testcapi, not _test). | Fix typo in comment (the module is now called _testcapi, not _test).
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
import sys
import test_support
import _testcapi
for name in dir(_testcapi):
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_supp... | Fix typo in comment (the module is now called _testcapi, not _test).
# Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _test exports whose name begins with 'test_'.
import sys
import test_support
import _testcapi
for name in dir(_testcapi):
if name.startswith('tes... |
d3fd59325f592bd3409d8466ba288e0c377c7440 | mklocale/cmd.py | mklocale/cmd.py | import argparse
import logging
import yaml
from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify
log = logging.getLogger("mklocale")
def cmdline(argv):
logging.basicConfig(level=logging.INFO)
ap = argparse.ArgumentParser()
ap.add_ar... | import argparse
import hashlib
import logging
import os
import yaml
from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify
log = logging.getLogger("mklocale")
def cmdline(argv):
logging.basicConfig(level=logging.INFO)
ap = argparse.Argum... | Add optional use of requests_cache | Add optional use of requests_cache
| Python | mit | akx/mklocale | import argparse
import hashlib
import logging
import os
import yaml
from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify
log = logging.getLogger("mklocale")
def cmdline(argv):
logging.basicConfig(level=logging.INFO)
ap = argparse.Argum... | Add optional use of requests_cache
import argparse
import logging
import yaml
from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify
log = logging.getLogger("mklocale")
def cmdline(argv):
logging.basicConfig(level=logging.INFO)
ap = arg... |
0668a4bba21e44a028cb008b03165f63eba5b457 | acute/models.py | acute/models.py | """
acute models.
"""
from django.db.models import fields
from opal import models
class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatmen... | """
acute models.
"""
from django.db.models import fields
from opal import models
class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatmen... | Rename Clerking -> Seen by | Rename Clerking -> Seen by
closes #1
| Python | agpl-3.0 | openhealthcare/acute,openhealthcare/acute,openhealthcare/acute | """
acute models.
"""
from django.db.models import fields
from opal import models
class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatmen... | Rename Clerking -> Seen by
closes #1
"""
acute models.
"""
from django.db.models import fields
from opal import models
class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.P... |
145b40c1b855b9f40eddf4682f4361112e459323 | lcddaemon.py | lcddaemon.py | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue im... | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue im... | Update to load dynamically the module selected by user. | Update to load dynamically the module selected by user.
| Python | mit | juliendelplanque/lcddaemon | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue im... | Update to load dynamically the module selected by user.
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from co... |
4ae27811595ce3c53670df441429bcf4cace4e15 | StockIndicators/StockIndicators.py | StockIndicators/StockIndicators.py | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username": "bob", "user_id": 2}
])
| Implement blueprints on stock indicators | Implement blueprints on stock indicators | Python | mit | z0rkuM/stockbros,z0rkuM/stockbros,z0rkuM/stockbros,z0rkuM/stockbros | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username": "bob", "user_id": 2}
])
| Implement blueprints on stock indicators
| |
2a0c9cc447e1dffe2eb03c49c0c6801f4303a620 | plugins/imagetypes.py | plugins/imagetypes.py | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Swap order of name and description when listing image types | Swap order of name and description when listing image types
Uses the same order as target types, which puts the most important information,
the name, in front.
Refs APPENG-3419
| Python | apache-2.0 | sassoftware/rbuild,sassoftware/rbuild | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Swap order of name and description when listing image types
Uses the same order as target types, which puts the most important information,
the name, in front.
Refs APPENG-3419
#
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except ... |
55a17865393f8c4d489f41dccbcc656670c81f2b | bika/lims/fields.py | bika/lims/fields.py | """Generic field extensions
"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import Implicit
from Acquisition import ImplicitAcquisitionWrapper
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.field import ExtensionField
from archetypes.sch... | Move schemaextender automatic getter and setter methods | Move schemaextender automatic getter and setter methods
| Python | agpl-3.0 | anneline/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS | """Generic field extensions
"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import Implicit
from Acquisition import ImplicitAcquisitionWrapper
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.field import ExtensionField
from archetypes.sch... | Move schemaextender automatic getter and setter methods
| |
096c8165ec2beacbc4897285b8fed439765d3e01 | test/integration/ggrc/models/test_document.py | test/integration/ggrc/models/test_document.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Integration tests for Document"""
from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories
clas... | Add test on update document title | Add test on update document title
| Python | apache-2.0 | AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Integration tests for Document"""
from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories
clas... | Add test on update document title
| |
3d385898592b07249b478b37854d179d27a27bbb | OmniMarkupLib/Renderers/MarkdownRenderer.py | OmniMarkupLib/Renderers/MarkdownRenderer.py | from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self).load_settings(renderer_options, globa... | from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self).load_settings(renderer_opti... | Add litcoffee to Markdown extensions | Add litcoffee to Markdown extensions
| Python | mit | timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer | from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self).load_settings(renderer_opti... | Add litcoffee to Markdown extensions
from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self)... |
9f8db061956fc73a197d9c5eb1b045a6e0655dc0 | fc2json.py | fc2json.py | #!/usr/bin/env python
import sys, json
file = sys.argv[1]
subject = file.split('.')[0]
data = {
"subject": subject,
"cards": {}
}
fc = [line.split(':') for line in open(file, 'r').read().splitlines()]
js = open(subject + ".json", 'w')
for line in fc:
data["cards"][line[0]] = line[1]
js.write(json.dum... | #!/usr/bin/env python
'''
File: fc2json.py
Author: Kristoffer Dalby
Description: Tiny script for converting flashcard format to json.
'''
import sys, json
file = sys.argv[1]
subject = file.split('.')[0]
data = {
"subject": subject,
"cards": {}
}
fc = [line.split(':') for line in open(file, 'r').read().spli... | Use a real JS construct, WTF knows why this works in chromium. | Use a real JS construct, WTF knows why this works in chromium.
| Python | mit | kradalby/flashcards,kradalby/flashcards | #!/usr/bin/env python
'''
File: fc2json.py
Author: Kristoffer Dalby
Description: Tiny script for converting flashcard format to json.
'''
import sys, json
file = sys.argv[1]
subject = file.split('.')[0]
data = {
"subject": subject,
"cards": {}
}
fc = [line.split(':') for line in open(file, 'r').read().spli... | Use a real JS construct, WTF knows why this works in chromium.
#!/usr/bin/env python
import sys, json
file = sys.argv[1]
subject = file.split('.')[0]
data = {
"subject": subject,
"cards": {}
}
fc = [line.split(':') for line in open(file, 'r').read().splitlines()]
js = open(subject + ".json", 'w')
for lin... |
b4aae8d7f87bd3f1bb27610440c20ab1110d2b3a | dbaas/util/update_instances_with_offering.py | dbaas/util/update_instances_with_offering.py | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | Fix script to update offering on instances | Fix script to update offering on instances
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | Fix script to update offering on instances
# coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for... |
ec59ed5c360d0d455c4623425271df3fffecbf82 | test/test_cs.py | test/test_cs.py | import pytest
from pml import cs
class InvalidControlSystem(cs.ControlSystem):
"""
Extends ControlSystem without implementing required methods.
"""
def __init__(self):
pass
def test_ControlSystem_throws_NotImplememtedError():
with pytest.raises(NotImplementedError):
cs.ControlSys... | Add simple tests for pml/cs.py. | Add simple tests for pml/cs.py.
| Python | apache-2.0 | willrogers/pml,willrogers/pml | import pytest
from pml import cs
class InvalidControlSystem(cs.ControlSystem):
"""
Extends ControlSystem without implementing required methods.
"""
def __init__(self):
pass
def test_ControlSystem_throws_NotImplememtedError():
with pytest.raises(NotImplementedError):
cs.ControlSys... | Add simple tests for pml/cs.py.
| |
3a3c1491cf185899a5e5b6288ae0a3542b536dee | setup.py | setup.py | from distutils.core import setup
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.7",
maintainer="Curtis C. Hovey",
maintainer_email="sinzui.is@verizon.net",
url="https://launchpad.net/pocket-lint",
packages=[
'pocketlint', 'poc... | from distutils.core import setup
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.8",
maintainer="Curtis C. Hovey",
maintainer_email="sinzui.is@verizon.net",
url="https://launchpad.net/pocket-lint",
packages=[
'pocketlint', 'poc... | Increment version to suport Python 2.6. | Increment version to suport Python 2.6. | Python | mit | chevah/pocket-lint,chevah/pocket-lint | from distutils.core import setup
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.8",
maintainer="Curtis C. Hovey",
maintainer_email="sinzui.is@verizon.net",
url="https://launchpad.net/pocket-lint",
packages=[
'pocketlint', 'poc... | Increment version to suport Python 2.6.
from distutils.core import setup
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.7",
maintainer="Curtis C. Hovey",
maintainer_email="sinzui.is@verizon.net",
url="https://launchpad.net/pocket-lint",
... |
c062ae638a4c864e978a4adfcd7d8d830b99abc2 | opentreemap/treemap/lib/dates.py | opentreemap/treemap/lib/dates.py | from datetime import datetime
from django.utils import timezone
import calendar
import pytz
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'
def parse_date_string_with_or_without_time(date_string):
try:
return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
except ValueError... | from datetime import datetime
from django.utils import timezone
import calendar
import pytz
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'
def parse_date_string_with_or_without_time(date_string):
try:
return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
except ValueError... | Add function for nullsafe, tzsafe comparison | Add function for nullsafe, tzsafe comparison
| Python | agpl-3.0 | clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-... | from datetime import datetime
from django.utils import timezone
import calendar
import pytz
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'
def parse_date_string_with_or_without_time(date_string):
try:
return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
except ValueError... | Add function for nullsafe, tzsafe comparison
from datetime import datetime
from django.utils import timezone
import calendar
import pytz
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'
def parse_date_string_with_or_without_time(date_string):
try:
return datetime.strptime(date_string.strip... |
ff23ae7705aa2841ff92d273d4e4851e3b7411c5 | ws-tests/test_invalid_study_put.py | ws-tests/test_invalid_study_put.py | #!/usr/bin/env python
from opentreetesting import test_http_json_method, config
import datetime
import codecs
import json
import sys
import os
# this makes it easier to test concurrent pushes to different branches
if len(sys.argv) > 1:
study_id = sys.argv[1]
else:
study_id = 1003
DOMAIN = config('host', 'apih... | Add a test for invalid PUTs which do not have a valid auth_token | Add a test for invalid PUTs which do not have a valid auth_token
| Python | bsd-2-clause | OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api | #!/usr/bin/env python
from opentreetesting import test_http_json_method, config
import datetime
import codecs
import json
import sys
import os
# this makes it easier to test concurrent pushes to different branches
if len(sys.argv) > 1:
study_id = sys.argv[1]
else:
study_id = 1003
DOMAIN = config('host', 'apih... | Add a test for invalid PUTs which do not have a valid auth_token
| |
d4b32d8f1beb16f9f7309d1cceb16b37e491bea3 | controllers/event_wizard_controller.py | controllers/event_wizard_controller.py | import os
from google.appengine.ext.webapp import template
from base_controller import CacheableHandler
class EventWizardHandler(CacheableHandler):
CACHE_VERSION = 1
CACHE_KEY_FORMAT = "event_wizard"
def __init__(self, *args, **kw):
super(EventWizardHandler, self).__init__(*args, **kw)
s... | import os
from google.appengine.ext.webapp import template
from base_controller import CacheableHandler
class EventWizardHandler(CacheableHandler):
CACHE_VERSION = 1
CACHE_KEY_FORMAT = "event_wizard"
def __init__(self, *args, **kw):
super(EventWizardHandler, self).__init__(*args, **kw)
s... | Fix event wizard cache keys | Fix event wizard cache keys
| Python | mit | fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredha... | import os
from google.appengine.ext.webapp import template
from base_controller import CacheableHandler
class EventWizardHandler(CacheableHandler):
CACHE_VERSION = 1
CACHE_KEY_FORMAT = "event_wizard"
def __init__(self, *args, **kw):
super(EventWizardHandler, self).__init__(*args, **kw)
s... | Fix event wizard cache keys
import os
from google.appengine.ext.webapp import template
from base_controller import CacheableHandler
class EventWizardHandler(CacheableHandler):
CACHE_VERSION = 1
CACHE_KEY_FORMAT = "event_wizard"
def __init__(self, *args, **kw):
super(EventWizardHandler, self).__... |
6144ac22f7b07cb1bd322bb05391a530f128768f | tests/integration/fileserver/fileclient_test.py | tests/integration/fileserver/fileclient_test.py | # -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting.helpers import (ensure_in_syspath, destructiveTest)
from salttesting.mock import MagicMock, patch
ensure_in_syspath('../')
# Import salt libs
import integration
from salt import fileclien... | # -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting.unit import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../')
# Import salt libs
imp... | Remove unused imports & Skip if no mock available | Remove unused imports & Skip if no mock available
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | # -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting.unit import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../')
# Import salt libs
imp... | Remove unused imports & Skip if no mock available
# -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting.helpers import (ensure_in_syspath, destructiveTest)
from salttesting.mock import MagicMock, patch
ensure_in_syspath('../')
# Import salt... |
f762c4e129db71ef7cfccba9b8e60582a3358617 | octane_fuelclient/octaneclient/commands.py | octane_fuelclient/octaneclient/commands.py | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | Call fuelclient directly passing over the object | Call fuelclient directly passing over the object
| Python | apache-2.0 | Mirantis/octane,stackforge/fuel-octane,Mirantis/octane,stackforge/fuel-octane | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | Call fuelclient directly passing over the object
from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release.... |
a0791aeead7eb77ddf1553a3392f1302a1a5acbb | Instanssi/ext_blog/views.py | Instanssi/ext_blog/views.py | # -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event
class blog_feed(Feed):
title = "Instanssi.org Blogi"
link = "http://instanss... | # -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event
class blog_feed(Feed):
title = "Instanssi.org Blogi"
link = "http://instanss... | Sort by date, remove post limit. | ext_blog: Sort by date, remove post limit.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | # -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event
class blog_feed(Feed):
title = "Instanssi.org Blogi"
link = "http://instanss... | ext_blog: Sort by date, remove post limit.
# -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event
class blog_feed(Feed):
title = "Inst... |
eee7ee47f0a6e2be31c74f9967fa1b2f1a8b3b01 | experiments/example-fsrcnn/run.py | experiments/example-fsrcnn/run.py | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3))
model.summary()
# Data
train_set = '91-i... | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale))
model.summary()
# Data
train_set = '... | Set the stride to scale | Set the stride to scale
| Python | mit | qobilidop/srcnn,qobilidop/srcnn | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale))
model.summary()
# Data
train_set = '... | Set the stride to scale
"""Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3))
model.summary()
... |
44f92d7c96b074054b11876d208494da1acef7e7 | Lib/tempfile.py | Lib/tempfile.py | # Temporary file name allocation
import posix
import path
# Changeable parameters (by clients!)...
# XXX Should the environment variable $TMPDIR override tempdir?
tempdir = '/usr/tmp'
template = '@'
# Kludge to hold mutable state
class Struct: pass
G = Struct()
G.i = 0
# User-callable function
# XXX Should thi... | # Temporary file name allocation
import posix
import path
# Changeable parameters (by clients!)...
# XXX Should the environment variable $TMPDIR override tempdir?
tempdir = '/usr/tmp'
template = '@'
# Counter for generating unique names
counter = 0
# User-callable function
# XXX Should this have a parameter, l... | Use 'global' instead of struct kludge. | Use 'global' instead of struct kludge.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | # Temporary file name allocation
import posix
import path
# Changeable parameters (by clients!)...
# XXX Should the environment variable $TMPDIR override tempdir?
tempdir = '/usr/tmp'
template = '@'
# Counter for generating unique names
counter = 0
# User-callable function
# XXX Should this have a parameter, l... | Use 'global' instead of struct kludge.
# Temporary file name allocation
import posix
import path
# Changeable parameters (by clients!)...
# XXX Should the environment variable $TMPDIR override tempdir?
tempdir = '/usr/tmp'
template = '@'
# Kludge to hold mutable state
class Struct: pass
G = Struct()
G.i = 0
#... |
1ecbd06083ac65a9520bcf0f87c5f5f1b4a4e532 | helloworld.py | helloworld.py |
#This is my hello world program
str1='Hello'
str2='Tarun'
print str1 +' '+ str2
# this is my hello world program
print 'Hello World!'
#This is my Hello world program
str1='Hello'
str2='Akash'
print str1 + ' ' + str2 + '!'
#this is a comment
str1='Hello'
str2='Priyanka'
print str1+' '+str2 |
print "helloworld" | Add strings to print hello world | Add strings to print hello world
| Python | apache-2.0 | ctsit/J.O.B-Training-Repo-1 |
print "helloworld" | Add strings to print hello world
#This is my hello world program
str1='Hello'
str2='Tarun'
print str1 +' '+ str2
# this is my hello world program
print 'Hello World!'
#This is my Hello world program
str1='Hello'
str2='Akash'
print str1 + ' ' + str2 + '!'
#this is a comment
str1='Hello'
str2='Priyanka'
print str1+... |
2e6e7d8ec05f2a760f12f2547730c4707a07ebfa | utils/swift_build_support/tests/test_xcrun.py | utils/swift_build_support/tests/test_xcrun.py | # test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for ... | # test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for ... | Fix typo XCRun -> xcrun | [gardening][build-script] Fix typo XCRun -> xcrun | Python | apache-2.0 | nathawes/swift,xedin/swift,apple/swift,aschwaighofer/swift,practicalswift/swift,glessard/swift,uasys/swift,rudkx/swift,huonw/swift,roambotics/swift,Jnosh/swift,bitjammer/swift,shahmishal/swift,lorentey/swift,modocache/swift,manavgabhawala/swift,KrishMunot/swift,devincoughlin/swift,nathawes/swift,atrick/swift,zisko/swif... | # test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for ... | [gardening][build-script] Fix typo XCRun -> xcrun
# test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library E... |
a4f24c4224f19ee47c201d1497e770db8fda7128 | project/settings/dev.py | project/settings/dev.py | from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = ['*']
try:
import dj_database_url
DATABASES = {'default': dj_database_url.config(
default='postgres://postgres:postgres@db:5432/postgres')}
except ImportError:
pass
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Disab... | from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = ['*']
try:
import dj_database_url
DATABASES = {'default': dj_database_url.config(
default='postgres://postgres:postgres@db:5432/postgres')}
except ImportError:
pass
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Disab... | Make debug toolbar use local jquery | Make debug toolbar use local jquery
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web | from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = ['*']
try:
import dj_database_url
DATABASES = {'default': dj_database_url.config(
default='postgres://postgres:postgres@db:5432/postgres')}
except ImportError:
pass
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Disab... | Make debug toolbar use local jquery
from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = ['*']
try:
import dj_database_url
DATABASES = {'default': dj_database_url.config(
default='postgres://postgres:postgres@db:5432/postgres')}
except ImportError:
pass
EMAIL_BACKEND = 'django.core.mail.bac... |
5c806fbd52da5ddb006c24b922967e6468e73221 | zerver/tornado/application.py | zerver/tornado/application.py | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from ra... | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from ra... | Remove a misleading comment and reformat. | tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.
| Python | apache-2.0 | zulip/zulip,rht/zulip,kou/zulip,zulip/zulip,kou/zulip,rht/zulip,rht/zulip,eeshangarg/zulip,andersk/zulip,showell/zulip,hackerkid/zulip,punchagan/zulip,showell/zulip,rht/zulip,rht/zulip,zulip/zulip,zulip/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,eeshangarg/zulip,kou/zulip,eeshangarg/zulip,hackerkid/zulip,anders... | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from ra... | tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.
import atexit
import tornado.web
from django.conf ... |
730b5acb9c715a0b7e2f70d4ee3d26cd2a8a03ca | wordcloud/views.py | wordcloud/views.py | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cache_path = settings.WORDCL... | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cache_path = settings.WORDCL... | Fix a deprecation warning; content_type replaces mimetype | Fix a deprecation warning; content_type replaces mimetype
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cache_path = settings.WORDCL... | Fix a deprecation warning; content_type replaces mimetype
import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return... |
30bfe04e0fa1386e263cbd0e8dbc6f3689f9cb21 | connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py | connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def migrate(cr, version):
cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
'RENAME TO carepoint_rx_ord_ln')
cr.execute('ALTER TABLE carepoint_carepoint_organ... | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
_logger = logging.getLogger(__name__)
def migrate(cr, version):
try:
cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
'RENAME TO care... | Fix prescription migration * Add try/catch & rollback to db alterations in case server re-upgrades | [FIX] connector_carepoint: Fix prescription migration
* Add try/catch & rollback to db alterations in case server re-upgrades
| Python | agpl-3.0 | laslabs/odoo-connector-carepoint | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
_logger = logging.getLogger(__name__)
def migrate(cr, version):
try:
cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
'RENAME TO care... | [FIX] connector_carepoint: Fix prescription migration
* Add try/catch & rollback to db alterations in case server re-upgrades
# -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def migrate(cr, version):
cr.execute('ALTER TABLE carepoint_medical_p... |
1e1ee9998a5e1461b1688d55218d793402fbb4d7 | setup.py | setup.py | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description =... | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description =... | Use the official notation of the Django package | Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible. | Python | bsd-3-clause | tubaman/django-macaddress | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description =... | Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible.
import os
from setuptools im... |
2a17b9fdb55806d6397f506066a2a7e8c480020b | pylinks/main/tests.py | pylinks/main/tests.py | from django.test import TestCase
from analytics.models import GoogleAnalytics
class GoogleAnalyticsTests(TestCase):
def test_ga_tracking(self):
GoogleAnalytics(site_id=1, web_property_id='12345').save()
response = self.client.get('/')
self.assertContains(response, "_gaq.push(['_setAccount'... | from django.test import TestCase
from analytics.models import GoogleAnalytics
class GoogleAnalyticsTests(TestCase):
def test_ga_tracking(self):
GoogleAnalytics(site_id=1, web_property_id='12345').save()
response = self.client.get('/')
self.assertContains(response, "_gaq.push(['_setAccount'... | Add simple admin test just so we catch breakage early | Add simple admin test just so we catch breakage early
| Python | mit | michaelmior/pylinks,michaelmior/pylinks,michaelmior/pylinks | from django.test import TestCase
from analytics.models import GoogleAnalytics
class GoogleAnalyticsTests(TestCase):
def test_ga_tracking(self):
GoogleAnalytics(site_id=1, web_property_id='12345').save()
response = self.client.get('/')
self.assertContains(response, "_gaq.push(['_setAccount'... | Add simple admin test just so we catch breakage early
from django.test import TestCase
from analytics.models import GoogleAnalytics
class GoogleAnalyticsTests(TestCase):
def test_ga_tracking(self):
GoogleAnalytics(site_id=1, web_property_id='12345').save()
response = self.client.get('/')
... |
48cd23e15cad7ce6a3db916d2287df7dcd98b482 | setup.py | setup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.in... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.in... | Set the version from gocd_cli instead of gocd | Set the version from gocd_cli instead of gocd
| Python | mit | gaqzi/py-gocd-cli,gaqzi/gocd-cli | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.in... | Set the version from gocd_cli instead of gocd
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def i... |
1927c503fda892490fb7262ba480e429a0f416fb | intermol/orderedset.py | intermol/orderedset.py | import collections
from copy import deepcopy
class OrderedSet(collections.Set):
def __init__(self, iterable=()):
self.d = collections.OrderedDict.fromkeys(iterable)
def add(self, key):
self.d[key] = None
def discard(self, key):
del self.d[key]
def difference_update(self, *a... | from collections.abc import Set
from collections import OrderedDict
from copy import deepcopy
class OrderedSet(Set):
def __init__(self, iterable=()):
self.d = OrderedDict.fromkeys(iterable)
def add(self, key):
self.d[key] = None
def discard(self, key):
del self.d[key]
def d... | Update collections imports for deprecations | Update collections imports for deprecations
| Python | mit | shirtsgroup/InterMol,shirtsgroup/InterMol | from collections.abc import Set
from collections import OrderedDict
from copy import deepcopy
class OrderedSet(Set):
def __init__(self, iterable=()):
self.d = OrderedDict.fromkeys(iterable)
def add(self, key):
self.d[key] = None
def discard(self, key):
del self.d[key]
def d... | Update collections imports for deprecations
import collections
from copy import deepcopy
class OrderedSet(collections.Set):
def __init__(self, iterable=()):
self.d = collections.OrderedDict.fromkeys(iterable)
def add(self, key):
self.d[key] = None
def discard(self, key):
del se... |
847682bfe21eeb9475f96cdbacc5bd873af095d3 | src/locations/migrations/0005_auto_20161024_2257.py | src/locations/migrations/0005_auto_20161024_2257.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-10-24 19:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('locations', '0004_auto_20160828_2114'),
]
operations = [
migrations.AlterModelOption... | Add migrations for location and district ordering | Add migrations for location and district ordering
| Python | mit | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign | # -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-10-24 19:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('locations', '0004_auto_20160828_2114'),
]
operations = [
migrations.AlterModelOption... | Add migrations for location and district ordering
| |
3028e6de1c0367939028d9b21bd48468c01096ce | fabfile.py | fabfile.py | # -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.utils as utils
import oinspect.sphinxify as spxy
def _show_page(content, fname):
with open(fname, 'wb') as f:
f.write(utils.to_binary_string(content, encodin... | # -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.utils as utils
import oinspect.sphinxify as spxy
def _show_page(content, fname):
with open(fname, 'wb') as f:
f.write(utils.to_binary_string(content, encodi... | Add empty line for pep8 | Add empty line for pep8
| Python | bsd-3-clause | techtonik/docrepr,techtonik/docrepr,spyder-ide/docrepr,spyder-ide/docrepr,spyder-ide/docrepr,techtonik/docrepr | # -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.utils as utils
import oinspect.sphinxify as spxy
def _show_page(content, fname):
with open(fname, 'wb') as f:
f.write(utils.to_binary_string(content, encodi... | Add empty line for pep8
# -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.utils as utils
import oinspect.sphinxify as spxy
def _show_page(content, fname):
with open(fname, 'wb') as f:
f.write(utils.to_binar... |
e994aa4c4389177aedca8192a41d27bdbb81458e | tests/conftest.py | tests/conftest.py | from distutils import dir_util
import pytest
import os
@pytest.fixture(scope="class")
def datadir(tmpdir_factory, request):
"""
Fixture responsible for searching a folder with the same name of test
module and, if available, moving all contents to a temporary directory so
tests can use them freely.
... | from distutils import dir_util
import pytest
import os
@pytest.fixture(scope="function")
def datadir(tmpdir_factory, request):
"""
Fixture responsible for searching a folder with the same name of test
module and, if available, moving all contents to a temporary directory so
tests can use them freely.
... | Change scope of datadir fixture to function-level | Change scope of datadir fixture to function-level
| Python | mit | ZedThree/fort_depend.py,ZedThree/fort_depend.py | from distutils import dir_util
import pytest
import os
@pytest.fixture(scope="function")
def datadir(tmpdir_factory, request):
"""
Fixture responsible for searching a folder with the same name of test
module and, if available, moving all contents to a temporary directory so
tests can use them freely.
... | Change scope of datadir fixture to function-level
from distutils import dir_util
import pytest
import os
@pytest.fixture(scope="class")
def datadir(tmpdir_factory, request):
"""
Fixture responsible for searching a folder with the same name of test
module and, if available, moving all contents to a tempor... |
815a9c802440375cc283179c15d3b1a371863418 | tests/test_class_based.py | tests/test_class_based.py | """tests/test_decorators.py.
Tests that class based hug routes interact as expected
Copyright (C) 2015 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction,... | Add test for desired support of class based routers | Add test for desired support of class based routers
| Python | mit | timothycrosley/hug,timothycrosley/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,timothycrosley/hug | """tests/test_decorators.py.
Tests that class based hug routes interact as expected
Copyright (C) 2015 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction,... | Add test for desired support of class based routers
| |
f0c2494aeec0040fab6276ba0ddbb0812d27e09a | scripts/plots.py | scripts/plots.py | """
Plot user tweet activity.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import twitterproj
def plot_counts(collection, ax=None):
if ax is None:
ax = plt.gca()
tweets, db, conn = twitterproj.connect()
counts = []
for doc in collection.find():
counts... | Add simple scripts to plot frequencies. | Add simple scripts to plot frequencies.
| Python | unlicense | chebee7i/twitter,chebee7i/twitter,chebee7i/twitter | """
Plot user tweet activity.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import twitterproj
def plot_counts(collection, ax=None):
if ax is None:
ax = plt.gca()
tweets, db, conn = twitterproj.connect()
counts = []
for doc in collection.find():
counts... | Add simple scripts to plot frequencies.
| |
c78e7d4ca37936fd1e539bf83bb9bfdc24d2568f | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.6'
REQUIREMENTS = ['requests']
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.6.1'
REQUIREMENTS = ['requests']
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System... | Adjust Setup: using Python 3.4, not Python 2 supported (currently). | Adjust Setup: using Python 3.4, not Python 2 supported (currently).
| Python | unlicense | BigFlySports/python-amazon-mws | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.6.1'
REQUIREMENTS = ['requests']
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System... | Adjust Setup: using Python 3.4, not Python 2 supported (currently).
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.6'
REQUIREMENTS = ['requests']
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
... |
8629221d23cf4fe8a447b12930fdee4801cd82f9 | setup.py | setup.py | #! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
setup(name='demandlib',
versio... | #! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
... | Fix data availability when installed via pip | Fix data availability when installed via pip
| Python | mit | oemof/demandlib | #! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
... | Fix data availability when installed via pip
#! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools impo... |
e6d4ca44f3f71468c40842c53e3963b425ac2527 | mss/factory.py | mss/factory.py | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -... | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -... | Fix pylint: Import outside toplevel (%s) (import-outside-toplevel) | MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
| Python | mit | BoboTiG/python-mss | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -... | MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
fr... |
c5296f0246c3e2cbf50ca7cad0c7f1130b0dd611 | analysis_10x10.py | analysis_10x10.py | # -*- coding:utf-8 -*-
from pylab import *
import tables
"""
TODO
- Faire tous les MPS
- Faire tous les STS
- Faire le déphasage
"""
DB = tables.openFile('db.h5')
# Get data
DATA = []
for g in DB.walkGroups():
try:
pset = g.paramset._v_attrs
res = g.results._v_attrs
except tables.NoSuchNode... | Add an analysis file for 10x10 simulations | Add an analysis file for 10x10 simulations
Not finished, MPS Whole figure is quite ok.
| Python | mit | neuro-lyon/multiglom-model,neuro-lyon/multiglom-model | # -*- coding:utf-8 -*-
from pylab import *
import tables
"""
TODO
- Faire tous les MPS
- Faire tous les STS
- Faire le déphasage
"""
DB = tables.openFile('db.h5')
# Get data
DATA = []
for g in DB.walkGroups():
try:
pset = g.paramset._v_attrs
res = g.results._v_attrs
except tables.NoSuchNode... | Add an analysis file for 10x10 simulations
Not finished, MPS Whole figure is quite ok.
| |
ddbd66713fd8f146509413772f4a4e3801f5fbf8 | ynr/apps/sopn_parsing/models.py | ynr/apps/sopn_parsing/models.py | import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_delete=models.CASCADE
)
raw_da... | import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_delete=models.CASCADE
)
raw_da... | Use None rather than -1 for Pandas | Use None rather than -1 for Pandas
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_delete=models.CASCADE
)
raw_da... | Use None rather than -1 for Pandas
import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_de... |
79d3f7476ef35ce120190badad63d460d7fa092b | rootio/telephony/forms.py | rootio/telephony/forms.py | # from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_TYPE
from .models import Phone... | # from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_TYPE
from .models import Phone... | Fix inline phone number form | Fix inline phone number form
| Python | agpl-3.0 | rootio/rootio_web,rootio/rootio_web,rootio/rootio_web,rootio/rootio_web | # from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_TYPE
from .models import Phone... | Fix inline phone number form
# from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_... |
db1af67bab58b831dcf63f63bfefc0e28e4ced55 | congress_tempest_tests/config.py | congress_tempest_tests/config.py | # Copyright 2015 Intel Corp
# 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 ap... | # Copyright 2015 Intel Corp
# 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 ap... | Add congress to service_available group | Add congress to service_available group
Add congress to service_available group. used in tempest plugin
to check if service is available or not
Change-Id: Ia3edbb545819d76a6563ee50c2dcdad6013f90e9
| Python | apache-2.0 | ramineni/my_congress,ramineni/my_congress,ramineni/my_congress,ramineni/my_congress,openstack/congress,openstack/congress | # Copyright 2015 Intel Corp
# 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 ap... | Add congress to service_available group
Add congress to service_available group. used in tempest plugin
to check if service is available or not
Change-Id: Ia3edbb545819d76a6563ee50c2dcdad6013f90e9
# Copyright 2015 Intel Corp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License")... |
b2593ea8f4a8e98b2a92ccebae69376516fb860c | setup.py | setup.py | from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
with open('README') as f:
readme = f.read()
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
author_email='plummer574@gmail.com',
url='https://github.com/plumd... | import os
from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
if os.path.exists('README'):
with open('README') as f:
readme = f.read()
else:
readme = None
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
... | Fix for non-existent rst README | Fix for non-existent rst README
| Python | bsd-3-clause | plumdog/flask_table,plumdog/flask_table,plumdog/flask_table | import os
from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
if os.path.exists('README'):
with open('README') as f:
readme = f.read()
else:
readme = None
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
... | Fix for non-existent rst README
from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
with open('README') as f:
readme = f.read()
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
author_email='plummer574@gmail.com',
... |
2198ae847cb257d210c043bb08d52206df749a24 | Jeeves/jeeves.py | Jeeves/jeeves.py | import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def on_ready():
print('------')
print('Logged in as %s (%s)' % (client.u... | import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def on_ready():
print('------')
print('Logged in as %s (%s)' % (client.u... | Change knugen command to use array in config/data.json instead of hardcoded array. | Change knugen command to use array in config/data.json instead of hardcoded array.
| Python | mit | havokoc/MyManJeeves | import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def on_ready():
print('------')
print('Logged in as %s (%s)' % (client.u... | Change knugen command to use array in config/data.json instead of hardcoded array.
import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def ... |
d7c4f0471271d104c0ff3500033e425547ca6c27 | notification/context_processors.py | notification/context_processors.py | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
}
else:
return {} | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
"notifications": Notice.objects.filter(user=request.user.id)
}
else:
... | Add user notifications to context processor | Add user notifications to context processor
| Python | mit | affan2/django-notification,affan2/django-notification | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
"notifications": Notice.objects.filter(user=request.user.id)
}
else:
... | Add user notifications to context processor
from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
}
else:
return {} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.