commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
4eae42a542c67e4b47e4b7fffc0b746fdb934f51 | librarypaste/mongostore.py | librarypaste/mongostore.py | import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid, data=bson.Binary(data))
doc.update(content)
se... | import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
doc.update(data=bson.Binary(... | Allow data=None, even though the spec doesn't allow it | Allow data=None, even though the spec doesn't allow it
| Python | mit | yougov/librarypaste,yougov/librarypaste |
7dd8e3339d5e29f5be4e84f949ac607c9ebddb97 | main.py | main.py |
import time
import os
from tweepy import API
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from credentials import *
class listener(StreamListener):
def __init__(self, api, start_time, time_limit=60):
self.time = start_time
self.limit = time... |
from time import ctime
from tweepy import API
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from credentials import *
from tweepy.utils import import_simplejson
json = import_simplejson()
class listener(StreamListener):
def __init__(self, api, followed_user... | Remove unused code + follow only specific user status | Remove unused code + follow only specific user status
| Python | mit | vishoo7/TwitterAutoReply |
cd174416301e03c0beea260925d6227c38444c73 | shapely/geometry/__init__.py | shapely/geometry/__init__.py | """Geometry classes and factories
"""
from geo import box, shape, asShape, mapping
from point import Point, asPoint
from linestring import LineString, asLineString
from polygon import Polygon, asPolygon
from multipoint import MultiPoint, asMultiPoint
from multilinestring import MultiLineString, asMultiLineString
from ... | """Geometry classes and factories
"""
from base import CAP_STYLE, JOIN_STYLE
from geo import box, shape, asShape, mapping
from point import Point, asPoint
from linestring import LineString, asLineString
from polygon import Polygon, asPolygon
from multipoint import MultiPoint, asMultiPoint
from multilinestring import M... | Add missing cap and join style imports | Add missing cap and join style imports
| Python | bsd-3-clause | jdmcbr/Shapely,jdmcbr/Shapely,mouadino/Shapely,abali96/Shapely,mindw/shapely,mindw/shapely,mouadino/Shapely,abali96/Shapely |
29e01ab226f5451e22ba3291e81bbaff13ce1867 | greenmine/settings/__init__.py | greenmine/settings/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
try:
print "Trying import local.py settings..."
from .local import *
except ImportError:
print "Trying import development.py settings..."
from .development import *
| # -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
print_function
)
import os, sys
try:
print("Trying import local.py settings...", file=sys.stderr)
from .local import *
except ImportError:
print("Trying import development.py settings...", file=sys.stderr)
from .development impor... | Send more print message to sys.stderr | Smallfix: Send more print message to sys.stderr
| Python | agpl-3.0 | Zaneh-/bearded-tribble-back,astagi/taiga-back,astronaut1712/taiga-back,dayatz/taiga-back,bdang2012/taiga-back-casting,jeffdwyatt/taiga-back,crr0004/taiga-back,seanchen/taiga-back,coopsource/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,Rademade/taiga-back,obimod/taiga-back,dycodedev/taiga-back,Tigerwhit4/taiga-... |
a993ec7f6af7bd543c1084084117042e8a10be51 | reports/tests.py | reports/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | from datetime import time
from django.test import client, TestCase
from members.models import User
from .models import Report
from protocols.models import Topic
client = client.Client()
class ReportTest(TestCase):
def setUp(self):
self.kril = User.objects.create(
username='Kril',
... | Add test for adding report | Add test for adding report
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
0566fc979f582341f968b5fb17b064a41619e6f3 | bifrost/tests/unit/test_inventory.py | bifrost/tests/unit/test_inventory.py | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | Replace assertEqual(None, *) with assertIsNone | Replace assertEqual(None, *) with assertIsNone
Replace assertEqual(None, *) with assertIsNone in tests
Change-Id: I257c479b7a23e39178d292c347d04ad979c48f0f
Closes-bug: #1280522
| Python | apache-2.0 | bcornec/bifrost,openstack/bifrost,openstack/bifrost,EntropyWorks/bifrost,bcornec/bifrost,EntropyWorks/bifrost |
74c7f22cfdd14761932fb9c138435671d1490dfa | partner_industry_secondary/models/res_partner.py | partner_industry_secondary/models/res_partner.py | # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models... | # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models... | Make api constrains multi to avoid error when create a company with 2 contacts | partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts
| Python | agpl-3.0 | syci/partner-contact,syci/partner-contact |
eed276146fe06e5d8191462cc7ef81a65c4bbdbb | pdf_generator/styles.py | pdf_generator/styles.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from reportlab.platypus import (
Paragraph as BaseParagraph,
Image as BaseImage,
Spacer,
)
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
styles = getSampleStyleSheet()
snormal = ParagraphStyle('no... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from reportlab.platypus import (
Paragraph as BaseParagraph,
Image as BaseImage,
Spacer,
)
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
styles = getSampleStyleSheet()
snormal = ParagraphStyle('no... | Add bold and italic helpers | Add bold and italic helpers
| Python | mit | cecedille1/PDF_generator |
ee7147e6d781a92d0ded0e094cc01a187fcb64ae | openstates/people.py | openstates/people.py | from pupa.scrape import Legislator
from .base import OpenstatesBaseScraper
class OpenstatesPersonScraper(OpenstatesBaseScraper):
def scrape_legislator(self, legislator_id):
old = self.api('legislators/' + legislator_id + '?')
old.pop('country', None)
old.pop('level', None)
new = L... | from pupa.scrape import Legislator
from .base import OpenstatesBaseScraper
class OpenstatesPersonScraper(OpenstatesBaseScraper):
def scrape_legislator(self, legislator_id):
old = self.api('legislators/' + legislator_id + '?')
old.pop('country', None)
old.pop('level', None)
new = L... | Move the APIKey bits out to the init | Move the APIKey bits out to the init
| Python | bsd-3-clause | openstates/billy,openstates/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,sunlightlabs/billy |
76ceb2f7c39d6cd82710e8e02df7a7a4b7d6360a | spitfire/runtime/repeater.py | spitfire/runtime/repeater.py | class RepeatTracker(object):
def __init__(self):
self.repeater_map = {}
def __setitem__(self, key, value):
try:
self.repeater_map[key].index = value
except KeyError, e:
self.repeater_map[key] = Repeater(value)
def __getitem__(self, key):
return self.repeater_map[key]
class Repeater(... | class RepeatTracker(object):
def __init__(self):
self.repeater_map = {}
def __setitem__(self, key, value):
try:
self.repeater_map[key].index = value
except KeyError, e:
self.repeater_map[key] = Repeater(value)
def __getitem__(self, key):
return self.repeater_map[key]
class Repeater(... | Revert last change (breaks XSPT) | Revert last change (breaks XSPT) | Python | bsd-3-clause | ahmedissa/spitfire,tkisme/spitfire,infin8/spitfire,infin8/spitfire,funic/spitfire,ahmedissa/spitfire,YifanCao/spitfire,YifanCao/spitfire,infin8/spitfire,TheProjecter/spitfire,YifanCao/spitfire,ahmedissa/spitfire,lefay1982/spitfire,funic/spitfire,tkisme/spitfire,coverband/spitfire,ahmedissa/spitfire,tkisme/spitfire,cove... |
11f5b2a82da1fad974c4ed505b9cd4938414b859 | sponsorship_compassion/model/project_compassion.py | sponsorship_compassion/model/project_compassion.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file _... | Remove children of a suspended project from internet. | Remove children of a suspended project from internet.
| Python | agpl-3.0 | eicher31/compassion-modules,Secheron/compassion-modules,ndtran/compassion-accounting,emgirardin/compassion-modules,CompassionCH/compassion-modules,MickSandoz/compassion-modules,maxime-beck/compassion-modules,maxime-beck/compassion-modules,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion... |
29b5337132373d624f291af3f64bb3b05fd48e77 | tests/test_list.py | tests/test_list.py | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
exp... | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
exp... | Make sure we're sorting results | Make sure we're sorting results
| Python | mit | skbkontur/carbonate,unbrice/carbonate,skbkontur/carbonate,ross/carbonate,ross/carbonate,graphite-project/carbonate,deniszh/carbonate,unbrice/carbonate,jssjr/carbonate,criteo-forks/carbonate,criteo-forks/carbonate,ross/carbonate,jssjr/carbonate,unbrice/carbonate,skbkontur/carbonate,jssjr/carbonate,graphite-project/carbo... |
bf383d4425510a17bed0780fd80d2e3b1c741aa8 | run-preglyphs.py | run-preglyphs.py | #MenuTitle: Run preglyphs
# -*- coding: utf-8 -*-
__doc__="""
Runs preglyphs from your chosen project folder then open the generated file
"""
__copyright__ = 'Copyright (c) 2019, SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = 'N... | #MenuTitle: Run preglyphs
# -*- coding: utf-8 -*-
__doc__="""
Runs preglyphs from your chosen project folder then open the generated file
"""
__copyright__ = 'Copyright (c) 2019, SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = 'N... | Expand path for other folder structures. | Expand path for other folder structures.
| Python | mit | n7s/scripts-for-glyphs,n7s/scripts-for-glyphs |
5cd6ed09511fdd40714ebe647577cb77fd366f7f | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, WARNING
class PugLint(NodeLinter):
"""Provides an ... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, WARNING
class PugLint(NodeLinter):
"""Provides an ... | Remove `error_stream`; Add `on_stderr` to make it works | Remove `error_stream`; Add `on_stderr` to make it works
| Python | mit | benedfit/SublimeLinter-contrib-pug-lint,benedfit/SublimeLinter-contrib-jade-lint |
7bb5329abb41c16bb59b03cf467b4abec4d948bf | my_test_suite/test_case.py | my_test_suite/test_case.py | class TestResult(object):
def __init__(self):
self.runCount = 0
self.errorCount = 0
def summary(self):
return "{} run, {} failed".format(self.runCount, self.errorCount)
def testStarted(self):
self.runCount += 1
def testFailed(self):
self.errorCount += 1
class... | class TestResult(object):
def __init__(self):
self.runCount = 0
self.errorCount = 0
self.setUpErrorCount = 0
def summary(self):
return "{} run, {} failed, {} setups failed".format(self.runCount,
self.errorCount,
... | Add handling for failed setup | Add handling for failed setup
| Python | mit | stephtzhang/tdd |
e28ba167fe0fafd9db5f2e582520b3237d1be36f | Python/Mac/sample_python_mac.py | Python/Mac/sample_python_mac.py | #using the pymssql driver
import pymssql
#Connect to your database.
#Replace server name, username, password, and database name with your credentials
conn = pymssql.connect(server='yourserver.database.windows.net',
user='yourusername@yourserver', password='yourpassword',
database='AdventureWorks')
cursor = conn.... | #using the pymssql driver
import pymssql
#Connect to your database.
#Replace server name, username, password, and database name with your credentials
conn = pymssql.connect(server='yourserver.database.windows.net',
user='yourusername@yourserver', password='yourpassword',
database='AdventureWorks')
cursor = conn.cur... | Fix white space in python example. | Fix white space in python example.
| Python | mit | Azure/azure-sql-database-samples,Azure/azure-sql-database-samples,Azure/azure-sql-database-samples,Azure/azure-sql-database-samples,Azure/azure-sql-database-samples,Azure/azure-sql-database-samples,Azure/azure-sql-database-samples |
0ac444affdff8db699684aa4cf04c2cb0daf0286 | rplugin/python3/denite/source/workspaceSymbol.py | rplugin/python3/denite/source/workspaceSymbol.py | from os import path
import sys
from .base import Base
sys.path.insert(0, path.dirname(path.dirname(__file__)))
from common import ( # isort:skip # noqa: I100
convert_symbols_to_candidates,
SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX,
highlight_setup,
)
class Source(Base):
def __init__(self, vim):
s... | from os import path
import sys
from .base import Base
sys.path.insert(0, path.dirname(path.dirname(__file__)))
from common import ( # isort:skip # noqa: I100
convert_symbols_to_candidates,
SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX,
highlight_setup,
)
class Source(Base):
def __init__(self, vim):
s... | Make workspace symbols interactive in denite | Make workspace symbols interactive in denite
Some servers limit the amount of symbols they return.
Having an interactive implementation allows us to use the server instead
of the client which means we allways get the best results of the query.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... |
831e09baadf3e7c426bc5558c04dae234b2902d2 | account_companyweb/tests/__init__.py | account_companyweb/tests/__init__.py | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera... | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera... | Add checks on init file | [ADD] Add checks on init file
| Python | agpl-3.0 | QANSEE/l10n-belgium,Niboo/l10n-belgium,QANSEE/l10n-belgium,Noviat/l10n-belgium,acsone/l10n-belgium,akretion/l10n-belgium,Noviat/l10n-belgium,Niboo/l10n-belgium,acsone/l10n-belgium,akretion/l10n-belgium,yvaucher/l10n-belgium |
be8ac3ac13fee7db684c931cdc15be98ca6a283c | ample/util/tests/test_mrbump_util.py | ample/util/tests/test_mrbump_util.py | """Test functions for util.mrbump_util"""
import cPickle
import os
import unittest
from ample.constants import AMPLE_PKL, SHARE_DIR
from ample.util import mrbump_util
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thisd = os.path.abspath( os.path.dirname( __file__ ) )
... | """Test functions for util.mrbump_util"""
import cPickle
import os
import unittest
from ample.constants import AMPLE_PKL, SHARE_DIR
from ample.util import mrbump_util
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thisd = os.path.abspath( os.path.dirname( __file__ ) )
... | Update unit test for changes to topf | Update unit test for changes to topf
| Python | bsd-3-clause | rigdenlab/ample,rigdenlab/ample,linucks/ample,linucks/ample |
701a6b4a4ed8a4db9f1b961cf8d5a1a6ef5c48a1 | gratipay/renderers/csv_dump.py | gratipay/renderers/csv_dump.py | from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from io import BytesIO
from aspen import renderers
class Renderer(renderers.Renderer):
def render_content(self, context):
context['response'].headers['Content-Type'] = 'text/plain'
rows = eval(self.com... | from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from io import BytesIO
from aspen import renderers
class Renderer(renderers.Renderer):
def render_content(self, context):
rows = eval(self.compiled, globals(), context)
if not rows:
return ... | Remove line that sets content type text/plain | Remove line that sets content type text/plain
| Python | mit | studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,gratipay/g... |
2bf8888b3c39b8d044b1bc7bd196e0bbe275c583 | konstrukteur/HtmlParser.py | konstrukteur/HtmlParser.py | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filenam... | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filenam... | Add summary to html parser | Add summary to html parser
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur |
2806517a37791b2b72e534a037bbc914cf33ba7c | fabfile.py | fabfile.py | from fabric.api import *
def update():
require('code_root')
git_pull()
restart_web_server()
def git_pull():
run('cd %s; git stash; git pull' % (env.code_root))
def restart_web_server():
"Restart the web server"
run('%s/apache2/bin/restart' % env.code_root_parent)
def migrate():
run... | from fabric.api import *
def update():
"""Requires code_root env variable. Does a git pull and restarts the web server"""
require('code_root')
git_pull()
restart_web_server()
def git_pull():
"""Does a git stash then a git pull on the project"""
run('cd %s; git stash; git pull' % (env.code_... | Add some info in the fab tasks | Add some info in the fab tasks
| Python | mit | leominov/fabric-bolt,madazone/fabric-bolt,maximon93/fabric-bolt,fabric-bolt/fabric-bolt,paperreduction/fabric-bolt,naphthalene/fabric-bolt,yourilima/fabric-bolt,damoguyan8844/fabric-bolt,brajput24/fabric-bolt,brajput24/fabric-bolt,Hedde/fabric-bolt,paperreduction/fabric-bolt,jproffitt/fabric-bolt,leominov/fabric-bolt,m... |
332a73c1d7f50cb336577921f0af218dc39d40e1 | raiden/tests/unit/transfer/test_utils.py | raiden/tests/unit/transfer/test_utils.py | import pytest
from eth_utils import decode_hex
from raiden.constants import EMPTY_HASH, EMPTY_MERKLE_ROOT
from raiden.transfer.utils import hash_balance_data
@pytest.mark.parametrize(
"values,expected",
(
((0, 0, EMPTY_HASH), bytes(32)),
(
(1, 5, EMPTY_MERKLE_ROOT),
de... | import pytest
from eth_utils import decode_hex
from raiden.constants import EMPTY_HASH, EMPTY_MERKLE_ROOT
from raiden.tests.utils import factories
from raiden.transfer.secret_registry import events_for_onchain_secretreveal
from raiden.transfer.state import TransactionExecutionStatus
from raiden.transfer.utils import h... | Add unit tests for transfer/secret_registry | Add unit tests for transfer/secret_registry
| Python | mit | hackaugusto/raiden,hackaugusto/raiden |
f8ac907837e198ddac3d4ce9c5f72243c89b5ca1 | config.py | config.py | host = 'http://mech-ai.appspot.com'
try:
from local_config import * # Override with config-local if exists
except ImportError:
pass
| import os
host_envs = {
'prod': 'http://mech-ai.appspot.com',
'dev': 'http://127.0.0.1:8080',
}
environment = os.getenv('ENV', 'dev')
host = host_env.get('environment')
username = os.getenv('USER')
access_token = os.getenv('TOKEN')
try:
from local_config import * # Override with local settings if exist... | Enable environment variables for settings | Enable environment variables for settings
| Python | mit | supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai |
bc411a7069386196abc6de6ae2314182efbda048 | avalonstar/apps/subscribers/admin.py | avalonstar/apps/subscribers/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'is_active', 'is_paid', 'twid']
list_editable = ['created', 'updated', 'is_active', 'is_paid']
ordering = ['-updated']
adm... | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid']
list_editable = ['is_active', 'is_paid']
ordering = ['-updated']
admin.site.regi... | Add streak to list_display, remove created and updated from list_editable. | Add streak to list_display, remove created and updated from list_editable.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv |
1bbe01fb9cafcb2effd6e95f40ae5c9872469f08 | exporter/mailer.py | exporter/mailer.py | import sendgrid
import config as config
from sendgrid.helpers.mail import Mail, Content
sg = sendgrid.SendGridAPIClient(apikey=config.SENDGRID_API_KEY)
from_mail = sendgrid.Email(config.SENDGRID_FROM_MAIL)
def send_download_link(to, link):
to_mail = sendgrid.Email(to)
content = Content("text/html", "<html> Y... | import sendgrid
import config as config
from sendgrid.helpers.mail import Mail, Content
sg = sendgrid.SendGridAPIClient(apikey=config.SENDGRID_API_KEY)
from_mail = sendgrid.Email(config.SENDGRID_FROM_MAIL)
def send_download_link(to, link):
to_mail = sendgrid.Email(to)
content = Content("text/html", "<html> <... | Add heading to export mail | Add heading to export mail
| Python | mit | melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter |
b0aa167c0d16b5262eceed9ff2af43643a987d47 | learning_journal/models.py | learning_journal/models.py | import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqla... | import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
... | Add bridge between Entry and User(which will be created on the next commit) | Add bridge between Entry and User(which will be created on the next commit)
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal |
35bb090dd926d4327fa046ee2da64c4cb5b38a47 | app/notify_client/email_branding_client.py | app/notify_client/email_branding_client.py | from app.notify_client import NotifyAdminAPIClient, cache
class EmailBrandingClient(NotifyAdminAPIClient):
@cache.set("email_branding-{branding_id}")
def get_email_branding(self, branding_id):
return self.get(url="/email-branding/{}".format(branding_id))
@cache.set("email_branding")
def get_a... | from app.notify_client import NotifyAdminAPIClient, cache
class EmailBrandingClient(NotifyAdminAPIClient):
@cache.set("email_branding-{branding_id}")
def get_email_branding(self, branding_id):
return self.get(url="/email-branding/{}".format(branding_id))
@cache.set("email_branding")
def get_a... | Remove old way of sorting | Remove old way of sorting
This is redundant since the model layer has built-in sorting.
It’s also not a good separation of concerns for something presentational
(sort order) to be in the API client layer.
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
6c3a1d011ff51b99a7975ef186cff042aea086d4 | poller.py | poller.py | #!/usr/bin/env python
import urllib2
import ssl
# Define the sites we want to poll and the timeout.
SITES = (
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
)
TIMEOUT = 5
try:
import gntp.notifier
notification = gntp.notifier.mini
except ImportError:
try:
... | #!/usr/bin/env python
import urllib2
import ssl
# Define the sites we want to poll and the timeout.
SITES = (
'https://redmine.codegrove.org',
'http://koodilehto.fi',
'http://vakiopaine.net',
)
TIMEOUT = 5
try:
import gntp.notifier
notification = gntp.notifier.mini
except ImportError:
try:
... | Add call to show at pynotify | Add call to show at pynotify
| Python | mit | koodilehto/website-poller,koodilehto/website-poller |
7f24d458d4953542ad481920642016f482978009 | pyautoupdate/_file_glob.py | pyautoupdate/_file_glob.py | import glob
import shutil
import os
if os.name == "nt": # pragma: no branch
from .ntcommonpath import commonpath
else:
from .posixcommonpath import commonpath
# def move_glob(src,dst):
# """Moves files from src to dest.
# src may be any glob to recognize files. dst must be a folder.
# """
# f... | import glob
import shutil
import os
if os.name == "nt": # pragma: no branch
from .ntcommonpath import commonpath
else: # pragma: no branch
from .posixcommonpath import commonpath
# def move_glob(src,dst):
# """Moves files from src to dest.
# src may be any glob to recognize files. dst must be a folde... | Fix whitespace in file_glob and attempt coverage modification | Fix whitespace in file_glob and attempt coverage modification
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
eb674c9bd91ff1c8baf95ad440d4a3897b2a030d | magpie/main.py | magpie/main.py | # -*- coding: utf-8 -*-
import nltk
from hazm import word_tokenize
from hazm.HamshahriReader import HamshahriReader
import config
def doc_features(doc, dist_words):
words_set = set(word_tokenize(doc['text']))
features = {}
for word in dist_words:
features['contains(%s)' % word] = (word in words_... | # -*- coding: utf-8 -*-
import nltk
from hazm import Normalizer, Stemmer, word_tokenize
from hazm.HamshahriReader import HamshahriReader
import config
def doc_features(doc, dist_words):
words_set = set(doc['words'])
features = {}
for word in dist_words:
features['contains(%s)' % word] = (word in... | Add normalization and stemming, use fine grained selection of words. | Add normalization and stemming, use fine grained selection of words.
| Python | mit | s1na/magpie |
90633f6aa401b40c6d94e623bac4268f752db430 | flask_dynstatic.py | flask_dynstatic.py | __author__ = 'mkaplenko'
views = []
def to_static_html(func):
def wrapper(*args, **kwargs):
if func not in views:
views.append(func)
print views
return func(*args, **kwargs)
return wrapper
| from functools import wraps
import os
static_root = os.path.join(os.path.dirname(__file__), 'static')
views = []
def to_static_html(path):
def decorator(func):
if func not in views:
views.append((path, func))
@wraps(func)
def wrapper(*args, **kwargs):
return ... | Add to static_html decorator code | Add to static_html decorator code
| Python | bsd-3-clause | mkaplenko/flask-dynstatic |
eec8f84aa12d692c8e042ac00eaca39faefb96f6 | armstrong/core/arm_sections/backends.py | armstrong/core/arm_sections/backends.py | from django.db.models import Q
from .utils import get_section_relations, get_item_model_class
class ItemFilter(object):
manager_attr = 'objects'
def get_manager(self, model):
"""Return the desired manager for the item model."""
return getattr(model, self.manager_attr)
def get_section_re... | from django.db.models import Q
from .utils import get_section_relations, get_item_model_class
class ItemFilter(object):
manager_attr = 'objects'
def get_manager(self, model):
"""Return the desired manager for the item model."""
return getattr(model, self.manager_attr)
def get_section_re... | Use distinct() when getting section items | Use distinct() when getting section items
| Python | apache-2.0 | texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections |
12519845ea1e74276261a5fb4f6b07fe3fb2f82c | exploratory_analysis/console.py | exploratory_analysis/console.py | import os
from utils import Reader
import code
if __name__ == '__main__':
working_directory = os.getcwd()
files = Reader.read_directory(working_directory)
print '{} available data files'.format(len(files))
code.interact(local=dict(globals(), **locals()))
| import os
from utils import Reader
import code
import sys
if __name__ == '__main__':
# coding=utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
working_directory = os.getcwd()
files = Reader.read_directory(working_directory)
print '{} available data files'.format(len(files))
code.interact(... | Set default encoding to utf-8 | Set default encoding to utf-8
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis |
c06ab929e1f7a55ddc0ed978939ea604cad003cb | hamper/plugins/roulette.py | hamper/plugins/roulette.py | import random, datetime
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'ro... | import random
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
... | Revert "This should break the flakes8 check on Travis" | Revert "This should break the flakes8 check on Travis"
This reverts commit 91c3d6c30d75ce66228d52c74bf8a4d8e7628670.
| Python | mit | hamperbot/hamper,maxking/hamper,iankronquist/hamper |
c2782795dc679897b333138482b99b21b4c60349 | salt/modules/test.py | salt/modules/test.py | '''
Module for running arbitrairy tests
'''
import time
def echo(text):
'''
Return a string - used for testing the connection
CLI Example:
salt '*' test.echo 'foo bar baz quo qux'
'''
print 'Echo got called!'
return text
def ping():
'''
Just used to make sure the minion is up and... | '''
Module for running arbitrairy tests
'''
import time
def echo(text):
'''
Return a string - used for testing the connection
CLI Example:
salt '*' test.echo 'foo bar baz quo qux'
'''
print 'Echo got called!'
return text
def ping():
'''
Just used to make sure the minion is up and... | Fix assignment issue in coallatz | Fix assignment issue in coallatz
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
5796093cecbe9e671dfe3b056f6e907a452694e5 | autodbperftool/ADT/tpccmysql.py | autodbperftool/ADT/tpccmysql.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Created on 2015-06-19
@author: mizhon
'''
#from common import CommonActions
from Logs import logger
log = logger.Log()
class TpccmysqlActions(object):
@classmethod
def ta_get_cmds(cls, cmd_action):
try:
cmds = None
if cmd_ac... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Created on 2015-06-19
@author: mizhon
'''
#from common import CommonActions
from Logs import logger
log = logger.Log()
class TpccmysqlActions(object):
@classmethod
def ta_get_cmds(cls, cmd_action):
try:
cmds = None
if cmd_ac... | Add function to save tpcc-mysql results | Add function to save tpcc-mysql results | Python | apache-2.0 | mizhon/tools |
f7a420fa865ea2fcd871ad20800c2e21112ce2ec | examples/map/plot_frameless_image.py | examples/map/plot_frameless_image.py | """
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary m... | """
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary m... | Add a clip to the frameless example | Add a clip to the frameless example
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy |
b1963f00e5290c11654eefbd24fbce185bbcd8b4 | packages/Preferences/define.py | packages/Preferences/define.py | import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
| import os
_CURRENTPATH = os.path.dirname(os.path.realpath(__file__))
config_name = 'mantle_config.ini'
preferencesIconPath = os.path.join(_CURRENTPATH, 'static', 'gear.svg')
preferencesUIPath = os.path.join(_CURRENTPATH, 'ui', 'preferences.ui')
version = '0.1.0'
| Add config ini file name. | Add config ini file name.
| Python | mit | takavfx/Mantle |
15964c974220c88a1b2fbca353d4a11b180e2bd8 | _launch.py | _launch.py | from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'... | from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command, Command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolo... | Refactor Command action to dragonglue.command | Refactor Command action to dragonglue.command
| Python | mit | drocco007/vox_commands |
18fa2a02b073ec0cf7fb82152389c312844b5fda | wsgi.py | wsgi.py | """
WSGI script run on Heroku using gunicorn.
Exposes the app and configures it to use Heroku environment vars.
"""
from suddendev import create_app, socketio
app = create_app()
socketio.run(app)
| """
WSGI script run on Heroku using gunicorn.
Exposes the app and configures it to use Heroku environment vars.
"""
import os
from suddendev import create_app, socketio
app = create_app()
port = int(os.environ.get("PORT", 5000))
socketio.run(app, host='0.0.0.0', port=port)
| Read Heroku port envvar and use if given. | [NG] Read Heroku port envvar and use if given.
| Python | mit | SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev |
8c1fa5b134bf6f64dca258c087dc01f9e19e6ca4 | tests/__init__.py | tests/__init__.py | """
distutilazy.tests
-----------------
Tests for distutilazy
:license: MIT, see LICENSE for more details.
"""
import os
__all__ = ["test_util", "test_clean"]
for file_ in os.listdir(os.path.dirname(__file__)):
if file_.startswith('test_') and file_.endswith('.py'):
__all__.append(file_... | """
distutilazy.tests
-----------------
Tests for distutilazy
:license: MIT, see LICENSE for more details.
"""
from os import path
import glob
test_modules = [path.splitext(path.basename(filename))[0] for filename in glob.glob(path.join(path.dirname(__file__), 'test*.py'))]
__all__ = test_modules
| Improve detecting available test modules in test package | Improve detecting available test modules in test package
By using glob and path.splitext instead of manually iterating over files
in the directory and filtering out files based on their names.
| Python | mit | farzadghanei/distutilazy |
76e1565200dda04e4091be761c737042f9a15e67 | synapse/media/v1/__init__.py | synapse/media/v1/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... | Change error message for missing pillow libs. | Change error message for missing pillow libs.
| Python | apache-2.0 | illicitonion/synapse,howethomas/synapse,iot-factory/synapse,TribeMedia/synapse,matrix-org/synapse,iot-factory/synapse,illicitonion/synapse,matrix-org/synapse,matrix-org/synapse,rzr/synapse,howethomas/synapse,rzr/synapse,howethomas/synapse,howethomas/synapse,illicitonion/synapse,illicitonion/synapse,rzr/synapse,matrix-o... |
e8bcd56727199de75a0dcefe7590d3866a14f39d | django_mailbox/tests/test_mailbox.py | django_mailbox/tests/test_mailbox.py | from django.test import TestCase
from django_mailbox.models import Mailbox
__all__ = ['TestMailbox']
class TestMailbox(TestCase):
def test_protocol_info(self):
mailbox = Mailbox()
mailbox.uri = 'alpha://test.com'
expected_protocol = 'alpha'
actual_protocol = mailbox._protocol_i... | import os
from django.test import TestCase
from django_mailbox.models import Mailbox
__all__ = ['TestMailbox']
class TestMailbox(TestCase):
def test_protocol_info(self):
mailbox = Mailbox()
mailbox.uri = 'alpha://test.com'
expected_protocol = 'alpha'
actual_protocol = mailbox.... | Add tests to update Mailbox.last_polling | Add tests to update Mailbox.last_polling
| Python | mit | coddingtonbear/django-mailbox,ad-m/django-mailbox |
ccf9e48cf874e7970c5b2e587e797a0501483139 | spec/data/anagram_index_spec.py | spec/data/anagram_index_spec.py | from data import anagram_index, warehouse
from spec.mamba import *
with description('anagram_index'):
with before.all:
self.subject = anagram_index.AnagramIndex(warehouse.get('/words/unigram'))
with it('instantiates'):
expect(len(self.subject)).to(be_above(0))
with it('accepts pre-sort-jumbled anagrams... | import collections
from data import anagram_index
from spec.data.fixtures import tries
from spec.mamba import *
with description('anagram_index'):
with before.all:
words = collections.OrderedDict(tries.kitchen_sink_data())
self.subject = anagram_index.AnagramIndex(words)
with it('instantiates'):
expe... | Update anagram index spec data source. | Update anagram index spec data source.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
5a885124432ccb33d180a8e73c753ceab54ffdf5 | src/Itemizers.py | src/Itemizers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
def iconForName(klass, name):
"""Return the NSImage instance representing a `name` item."""
imgpath = NSBundle.bundleForClass_(klass).pathForResource_ofType_(name, 'png')
img = NSIma... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
haskellBundleIdentifier = 'org.purl.net.mkhl.haskell'
def iconForName(name):
"""Return the NSImage instance representing a `name` item."""
bundle = NSBundle.bundleWithIdentifier_(has... | Simplify the icon finder function. | Simplify the icon finder function.
We statically know our bundle identifier, so we don’t have too find the bundle by runtime class.
| Python | mit | mkhl/haskell.sugar |
92a3a4522968d170a8d19649bd6848187736f8f4 | src/DeltaDetector.py | src/DeltaDetector.py | import numpy as N
import gtk.gdk
class DeltaDetector(object):
def __init__(self, active=False, threshold=20.0):
self._previous_frame = None
self._frame = None
self.active = active
self.threshold = threshold
def send_frame(self, frame):
self._previous_frame = self._... | import numpy as N
import gobject
import gtk.gdk
class DeltaDetector(object):
def __init__(self, active=False, threshold=20.0):
self._previous_frame = None
self._frame = None
self.active = active
self.threshold = threshold
self._timed_out = False
def send_frame(self... | Add a timeout to the delta detector | Add a timeout to the delta detector
Make it so that the detector doesn't beep more than
once per second. It would be even better if the beeping
occurred in another thread...
| Python | mit | ptomato/Beams |
8eccb87791ca608be4508fee80f2de9454e4403c | pytask/urls.py | pytask/urls.py | from django.conf import settings
from django.conf.urls.defaults import *
from registration.views import register
from pytask.profile.forms import CustomRegistrationForm
from pytask.views import home_page
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', home_page),
(r... | from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from registration.views import register
from pytask.profile.forms import CustomRegistrationForm
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'pytask.views.home_page', name='home_page'),
(... | Modify the home page URL mapper to be consistent with other mappers. | Modify the home page URL mapper to be consistent with other mappers.
| Python | agpl-3.0 | madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask |
9b35326243c3e6d991bba8dfc948600262ebc557 | test/_helpers.py | test/_helpers.py | import datetime
import mock
from functools import wraps
from twisted.internet.defer import Deferred
class NewDate(datetime.date):
@classmethod
def today(cls):
return cls(2012, 12, 10)
class NewDateTime(datetime.datetime):
@classmethod
def now(cls):
return cls(2012, 12, 10, 00, 00, ... | import datetime
import mock
from functools import wraps
from twisted.internet.defer import Deferred
class NewDate(datetime.date):
@classmethod
def today(cls):
return cls(2012, 12, 10)
class NewDateTime(datetime.datetime):
@classmethod
def now(cls):
return cls(2012, 12, 10, 00, 00, ... | Make DeferredHelper even more like a Deferred by subclassing | Make DeferredHelper even more like a Deferred by subclassing
| Python | mit | mineo/lala,mineo/lala |
b15bf76c9a3d3a55423923038e374695a7b302a8 | microcosm_pubsub/chain/__init__.py | microcosm_pubsub/chain/__init__.py | from microcosm_pubsub.chain.chain import Chain # noqa: F401
from microcosm_pubsub.chain.decorators import binds, extracts # noqa: F401
from microcosm_pubsub.chain.statements import extract, when, switch, try_chain # noqa: F401
| from microcosm_pubsub.chain.chain import Chain # noqa: F401
from microcosm_pubsub.chain.decorators import binds, extracts # noqa: F401
from microcosm_pubsub.chain.statements import extract, when, switch, try_chain, for_each # noqa: F401
| Add for_each to chain exports | Add for_each to chain exports
| Python | apache-2.0 | globality-corp/microcosm-pubsub,globality-corp/microcosm-pubsub |
daafe2152e13d32e7e03533151feeeac9464dddf | mycli/packages/expanded.py | mycli/packages/expanded.py | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
total_len = header_len + data_len + 1
sep = u"-[ RECORD {0} ]".format(num)
if len(sep) < header_len:
sep = pad(sep, header_len - 1, u"-... | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
def expanded_table(rows, headers):
header_... | Fix formatting issue for \G. | Fix formatting issue for \G.
Closes #49
| Python | bsd-3-clause | ksmaheshkumar/mycli,douglasvegas/mycli,webwlsong/mycli,thanatoskira/mycli,tkuipers/mycli,qbdsoft/mycli,douglasvegas/mycli,chenpingzhao/mycli,D-e-e-m-o/mycli,oguzy/mycli,tkuipers/mycli,j-bennet/mycli,suzukaze/mycli,D-e-e-m-o/mycli,thanatoskira/mycli,suzukaze/mycli,mdsrosa/mycli,brewneaux/mycli,danieljwest/mycli,shaunsta... |
40ae95e87e439645d35376942f8c48ce9e62b2ad | test/test_pluginmount.py | test/test_pluginmount.py | from JsonStats.FetchStats.Plugins import *
from . import TestCase
import JsonStats.FetchStats.Plugins
from JsonStats.FetchStats import Fetcher
class TestPluginMount(TestCase):
def setUp(self):
# Do stuff that has to happen on every test in this instance
self.fetcher = Fetcher
def test_get_... | from . import TestCase
import JsonStats.FetchStats.Plugins
from JsonStats.FetchStats import Fetcher
class TestPluginMount(TestCase):
def setUp(self):
# Do stuff that has to happen on every test in this instance
self.fetcher = Fetcher
class _example_plugin(Fetcher):
def __ini... | Fix the plugin mount text. And make it way more intelligent. | Fix the plugin mount text. And make it way more intelligent.
| Python | mit | RHInception/jsonstats,pombredanne/jsonstats,pombredanne/jsonstats,RHInception/jsonstats |
0a0b87d584bd731c1db65e32a7e438b0f9aea1a9 | testing/test_direct_wrapper.py | testing/test_direct_wrapper.py | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
| import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
def test_open_file(tes... | Add test for open file | Add test for open file
| Python | mit | mindriot101/fitsio-cffi |
efa90202a0586f15575af11ef299b122de413b30 | duralex/AddGitHubIssueVisitor.py | duralex/AddGitHubIssueVisitor.py | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | Add the GitHub issue number as a new line in the commitMessage field. | Add the GitHub issue number as a new line in the commitMessage field.
| Python | mit | Legilibre/duralex |
0d1e5990d55bea9530beaa49aaf5091a6434a48e | newswall/providers/base.py | newswall/providers/base.py | from newswall.models import Story
class ProviderBase(object):
def __init__(self, source, config):
self.source = source
self.config = config
def update(self):
raise NotImplementedError
def create_story(self, object_url, **kwargs):
defaults = {'source': self.source}
... | from datetime import date, timedelta
from newswall.models import Story
class ProviderBase(object):
def __init__(self, source, config):
self.source = source
self.config = config
def update(self):
raise NotImplementedError
def create_story(self, object_url, **kwargs):
defa... | Set stories to inactive if a story with the same title has been published recently | Set stories to inactive if a story with the same title has been published recently
| Python | bsd-3-clause | HerraLampila/django-newswall,michaelkuty/django-newswall,matthiask/django-newswall,matthiask/django-newswall,HerraLampila/django-newswall,registerguard/django-newswall,registerguard/django-newswall,michaelkuty/django-newswall |
8840cedd74c6c1959358366a88a85e7567b84439 | tests/test_vector2_negation.py | tests/test_vector2_negation.py | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_scalar(vector: Vector2):
assert - vector == (-1) * vector
| from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_scalar(vector: Vector2):
assert - vector == (-1) * vector
@given(vector=vectors())
def test_negation_involutive(vector: Vector2):
assert vector == - (- vector)
| Test that negation is involutive | tests/negation: Test that negation is involutive
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
5f07fd7b5d916ca1442a5b599bcec49026295209 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
f3eb4ffe0017b850fcd9a66bcfa0bc00f724064e | gapipy/resources/booking/document.py | gapipy/resources/booking/document.py | from __future__ import unicode_literals
from ..base import Resource
class Document(Resource):
_resource_name = 'documents'
_is_listable = False
_as_is_fields = ['id', 'href', 'mime_type', 'content', 'type']
_date_time_fields_utc = ['date_created']
_resource_fields = [
('booking', 'Bookin... | from __future__ import unicode_literals
from ..base import Resource
class Document(Resource):
_resource_name = 'documents'
_is_listable = False
_as_is_fields = ['id', 'href', 'mime_type', 'content', 'type', 'audience']
_date_time_fields_utc = ['date_created']
_resource_fields = [
('booki... | Add audience field to Document resource | Add audience field to Document resource
- 'audience' field is displayed on list of invoices (bookings/<booking_id>/invoices) and now, also on list of documents (bookings/<booking_id>/documents) to match what is being returned in the API | Python | mit | gadventures/gapipy |
84e964eba11e344f6f0ec612b5743e693a8825bd | thoonk/config.py | thoonk/config.py | import json
import threading
import uuid
from thoonk.consts import *
class ConfigCache(object):
def __init__(self, pubsub):
self._feeds = {}
self.pubsub = pubsub
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
with self.lock:... | import json
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self... | Add docs to the ConfigCache. | Add docs to the ConfigCache.
| Python | mit | andyet/thoonk.py,fritzy/thoonk.py |
2e4b3f3dc8e0f949700c810912e32a2dffa2def3 | ttag/__init__.py | ttag/__init__.py | from ttag.args import Arg, BasicArg, BooleanArg, ConstantArg, DateArg, \
DateTimeArg, IntegerArg, IsInstanceArg, KeywordsArg, ModelInstanceArg, \
StringArg, TimeArg
from ttag.core import Tag
from ttag.exceptions import TagArgumentMissing, TagValidationError
VERSION = (1, 0, 'alpha')
def get_version(number_on... | try:
from ttag.args import Arg, BasicArg, BooleanArg, ConstantArg, DateArg, \
DateTimeArg, IntegerArg, IsInstanceArg, KeywordsArg, \
ModelInstanceArg, StringArg, TimeArg
from ttag.core import Tag
from ttag.exceptions import TagArgumentMissing, TagValidationError
except ImportError:
# Thi... | Work around an error if ttag is installed at the same time as Django | Work around an error if ttag is installed at the same time as Django
| Python | bsd-3-clause | caktus/django-ttag,caktus/django-ttag,matuu/django-ttag,matuu/django-ttag,lincolnloop/django-ttag,lincolnloop/django-ttag |
0ee942eaffc2a60b87c21eeec75f01eb1a50b8e0 | tests/demo_project/manage.py | tests/demo_project/manage.py | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
# We add ourselves into the python path, so we can find
# the package later.
demo_root =os.path.dirname(os.path.abspath(__file__))
crud_install = os.path.dirname(os.path.dirname(demo_root))
sys.path.inse... | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
# We add ourselves into the python path, so we can find
# the package later.
demo_root =os.path.dirname(os.path.abspath(__file__))
crud_install = os.path.dirname(os.path.dirname(demo_root))
sys.path.inse... | Make sure the demo project is in the pythonpath | Make sure the demo project is in the pythonpath
| Python | bsd-3-clause | oscarmlage/django-cruds-adminlte,oscarmlage/django-cruds-adminlte,oscarmlage/django-cruds-adminlte |
7d1dc8851f1571b2f39a886298bc7b8ff270a6b7 | tests/run/generators_py35.py | tests/run/generators_py35.py | # mode: run
# tag: generators, pure3.5
from __future__ import generator_stop
# "generator_stop" was only added in Py3.5.
def with_outer_raising(*args):
"""
>>> x = with_outer_raising(1, 2, 3)
>>> try:
... list(x())
... except RuntimeError:
... print("OK!")
... else:
... p... | # mode: run
# tag: generators, pure3.5
from __future__ import generator_stop
# "generator_stop" was only added in Py3.5.
def with_outer_raising(*args):
"""
>>> x = with_outer_raising(1, 2, 3)
>>> try:
... list(x())
... except RuntimeError:
... print("OK!")
... else:
... p... | Make annotation tests work with non-evaluated annotations (GH-4050) | Make annotation tests work with non-evaluated annotations (GH-4050)
Backported from 3dc2b9dfc23638fbef2558d619709b5235d5df08
Partial fix for https://github.com/cython/cython/issues/3919
| Python | apache-2.0 | scoder/cython,scoder/cython,cython/cython,da-woods/cython,scoder/cython,scoder/cython,cython/cython,da-woods/cython,da-woods/cython,da-woods/cython,cython/cython,cython/cython |
5a5e820fa50377904e6fdd592fed5e883698c3f0 | tests/testapp/models/city.py | tests/testapp/models/city.py | from django.db import models
from binder.models import BinderModel
class City(BinderModel):
country = models.ForeignKey('Country', null=False, blank=False, related_name='cities', on_delete=models.CASCADE)
name = models.TextField(unique=True, max_length=100)
class CityState(BinderModel):
"""
City st... | from django.db import models
from binder.models import BinderModel
class City(BinderModel):
country = models.ForeignKey('Country', null=False, blank=False, related_name='cities', on_delete=models.CASCADE)
name = models.CharField(unique=True, max_length=100)
class CityState(BinderModel):
"""
City st... | Change text field to charfields, since those are indexable in mysql | Change text field to charfields, since those are indexable in mysql
| Python | mit | CodeYellowBV/django-binder |
48132de52d573f7f650ab693c1ad0b6007ebfaef | cybox/test/common/vocab_test.py | cybox/test/common/vocab_test.py | import unittest
from cybox.common.vocabs import VocabString
import cybox.test
from cybox.utils import normalize_to_xml
class TestVocabString(unittest.TestCase):
def test_plain(self):
a = VocabString("test_value")
self.assertTrue(a.is_plain())
def test_round_trip(self):
attr_dict = {... | import unittest
from cybox.common.vocabs import VocabString
import cybox.test
from cybox.utils import normalize_to_xml
class TestVocabString(unittest.TestCase):
def test_plain(self):
a = VocabString("test_value")
self.assertTrue(a.is_plain())
def test_round_trip(self):
vocab_dict = ... | Clean up controlled vocab tests | Clean up controlled vocab tests
| Python | bsd-3-clause | CybOXProject/python-cybox |
05c057b44460eea6f6fe4a3dd891038d65e6d781 | naxos/naxos/settings/secretKeyGen.py | naxos/naxos/settings/secretKeyGen.py | """
Two things are wrong with Django's default `SECRET_KEY` system:
1. It is not random but pseudo-random
2. It saves and displays the SECRET_KEY in `settings.py`
This snippet
1. uses `SystemRandom()` instead to generate a random key
2. saves a local `secret.txt`
The result is a random and safely hidden `SECRET_KEY`... | """
Two things are wrong with Django's default `SECRET_KEY` system:
1. It is not random but pseudo-random
2. It saves and displays the SECRET_KEY in `settings.py`
This snippet
1. uses `SystemRandom()` instead to generate a random key
2. saves a local `secret.txt`
The result is a random and safely hidden `SECRET_KEY`... | Fix not closed file warning | fix: Fix not closed file warning
| Python | apache-2.0 | maur1th/naxos,maur1th/naxos,maur1th/naxos,maur1th/naxos |
09a18ba1b2ac5517b37b524fb2c7d7e2917ed251 | words.py | words.py | """
Pick a word from /usr/share/dict/words
"""
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
... | """
Pick a word from /usr/share/dict/words
"""
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
... | Add a main guard for testing | Add a main guard for testing
| Python | mit | tml/python-hangman-2017-summer |
0af3b589c6c271d07ad4e204fa41aa0fed167a94 | thinglang/parser/constructs/cast_operation.py | thinglang/parser/constructs/cast_operation.py | from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
class CastOperation(object):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@stat... | from thinglang.lexer.operators.casts import LexicalCast
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
from thin... | Add explicit parsing rule for cast operations | Add explicit parsing rule for cast operations
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
b17e6bd8d067951f28422c94aad628d031e334fd | fuzzers/011-ffconfig/generate.py | fuzzers/011-ffconfig/generate.py | #!/usr/bin/env python3
import sys, re
sys.path.append("../../../utils/")
from segmaker import segmaker
segmk = segmaker("design_%s.bits" % sys.argv[1])
print("Loading tags from design_%s.txt." % sys.argv[1])
with open("design_%s.txt" % sys.argv[1], "r") as f:
for line in f:
line = line.split()
s... | #!/usr/bin/env python3
import sys, re
sys.path.append("../../../utils/")
from segmaker import segmaker
segmk = segmaker("design_%s.bits" % sys.argv[1])
print("Loading tags from design_%s.txt." % sys.argv[1])
with open("design_%s.txt" % sys.argv[1], "r") as f:
for line in f:
line = line.split()
s... | Add more tags to ffconfig fuzzer (currently disabled) | Add more tags to ffconfig fuzzer (currently disabled)
Signed-off-by: Clifford Wolf <b28e7ff75903c06de987a1eb75ea100a79c89e3a@clifford.at>
Signed-off-by: Tim 'mithro' Ansell <57310ee00039176189a7bd7b876cda4d0d2a19aa@mithis.com>
| Python | isc | SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray |
01dd4901532df4f3da51501d4f223c873dd49dd8 | ideascube/tests/test_settings.py | ideascube/tests/test_settings.py | import glob
import os
import importlib
import pytest
@pytest.fixture(params=glob.glob('ideascube/conf/*.py'))
def setting_module(request):
basename = os.path.basename(request.param)
module, _ = os.path.splitext(basename)
return '.conf.%s' % module
def test_setting_file(setting_module):
from ideasc... | import glob
import os
import importlib
import pytest
@pytest.fixture(params=sorted([
f for f in glob.glob('ideascube/conf/*.py')
if not f.endswith('/__init__.py')
]))
def setting_module(request):
basename = os.path.basename(request.param)
module, _ = os.path.splitext(basename)
return '.conf.%s' ... | Improve the settings files testing fixture | tests: Improve the settings files testing fixture
Let's order these files, as it makes it nicer in the pytest output.
In addition, we can filter out the __init__.py file, since it is
completely empty.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
25b9818da4b1922d808812bb43a9c1b35c277b7e | integration-test/1687-fewer-places-at-low-zoom.py | integration-test/1687-fewer-places-at-low-zoom.py | # -*- encoding: utf-8 -*-
from . import FixtureTest
class LowZoomPlacesTest(FixtureTest):
def test_zoom_1(self):
import dsl
z, x, y = (3, 7, 3)
self.generate_fixtures(
dsl.way(607976629, dsl.tile_centre_shape(z, x, y), {
"min_zoom": 1,
"__ne_m... | # -*- encoding: utf-8 -*-
from . import FixtureTest
class LowZoomPlacesTest(FixtureTest):
def test_zoom_1(self):
import dsl
z, x, y = (3, 7, 3)
self.generate_fixtures(
dsl.way(607976629, dsl.tile_centre_shape(z, x, y), {
"min_zoom": 1,
"__ne_m... | Revert "update Guam to not show at zoom 2" | Revert "update Guam to not show at zoom 2"
This reverts commit b12f1560f6b6284c9d26dab96a6c09eac1942424.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
9209c56661c2b14a09db339cf1551e536965ad7f | {{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py | {{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py | from IPython.display import display, JSON
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': '... | from IPython.display import display, JSON
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': '... | Include display metadata in mime bundle | Include display metadata in mime bundle
| Python | cc0-1.0 | gnestor/mimerender-cookiecutter,gnestor/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter |
f43519e2fc6faf9956febcf61185c789454a4f0f | personal_website/models.py | personal_website/models.py | from sqlalchemy_wrapper import SQLAlchemy
db = SQLAlchemy(uri='sqlite:///intermediate_data.db')
class BlogPostModel(db.Model):
__tablename__ = 'blog_post'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
src_url = db.Column(db.String(128), unique=True)
dest_url = db.Column(db.String(1... | import os
from sqlalchemy_wrapper import SQLAlchemy
from constants import DATABASE_NAME
os.system('rm -f ' + DATABASE_NAME)
db = SQLAlchemy(uri='sqlite:///' + DATABASE_NAME)
class BlogPostModel(db.Model):
__tablename__ = 'blog_post'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
src_u... | Fix for tests failing because of persisted database file for the next build | Fix for tests failing because of persisted database file for the next build
| Python | mit | tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website |
e8db81b563688d977a3090f6f2d4fc7efaa42323 | tests/document_download/test_document_download.py | tests/document_download/test_document_download.py | import pytest
import requests
from retry.api import retry_call
from config import config
from tests.pages import DocumentDownloadLandingPage, DocumentDownloadPage
def upload_document(service_id, file_contents):
response = requests.post(
"{}/services/{}/documents".format(config['document_download']['api_h... | import base64
import pytest
import requests
from retry.api import retry_call
from config import config
from tests.pages import DocumentDownloadLandingPage, DocumentDownloadPage
def upload_document(service_id, file_contents):
response = requests.post(
f"{config['document_download']['api_host']}/services/... | Update how the document download test calls document-download-api | Update how the document download test calls document-download-api
document-download-api now accepts json content - it was still possible
to send files while we switched over, but we now want to only support
json. This is the only place where we weren't already sending json to
document-download-api.
| Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests |
edc8248e6122dcfc1c4e6972ae0a4866de5c0d42 | modules/urbandictionary.py | modules/urbandictionary.py | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... | Fix new lines in definition of UD module | Fix new lines in definition of UD module
| Python | mit | billyvg/piebot |
5d6049be925330803f8c782d884cd318ad23ba28 | repo-log.py | repo-log.py | #! /usr/bin/env python
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_... | #! /usr/bin/env python
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_... | Remove merges from the log. | Remove merges from the log.
| Python | mit | aplanas/hackweek11,aplanas/hackweek11 |
94be56593a43101abc21b30b187d340e7ef8c3f0 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=... | #!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLAS... | Fix tests for Django 1.7 by calling the new setup and explicitly including MIDDLEWARE_CLASSES. | Fix tests for Django 1.7 by calling the new setup and explicitly including MIDDLEWARE_CLASSES.
| Python | bsd-3-clause | vstoykov/django-sticky-uploads,caktus/django-sticky-uploads,caktus/django-sticky-uploads,vstoykov/django-sticky-uploads,caktus/django-sticky-uploads,vstoykov/django-sticky-uploads |
e005a5a1d10df7a5a2f6a599c3419c89bd61eeb2 | mrbelvedereci/cumulusci/admin.py | mrbelvedereci/cumulusci/admin.py | from django.contrib import admin
from mrbelvedereci.cumulusci.models import Org
from mrbelvedereci.cumulusci.models import Service
class OrgAdmin(admin.ModelAdmin):
list_display = ('name','repo','scratch')
list_filter = ('repo','scratch')
admin.site.register(Org, OrgAdmin)
class ServiceAdmin(admin.ModelAdmin)... | from django.contrib import admin
from mrbelvedereci.cumulusci.models import Org
from mrbelvedereci.cumulusci.models import Service
class OrgAdmin(admin.ModelAdmin):
list_display = ('name','repo','scratch')
list_filter = ('name', 'scratch', 'repo')
admin.site.register(Org, OrgAdmin)
class ServiceAdmin(admin.Mo... | Add filters to Org model | Add filters to Org model
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci |
d80b1465e6ea6019531a2bd1df4599e28afdebf4 | openstackclient/tests/functional/network/v2/test_network_service_provider.py | openstackclient/tests/functional/network/v2/test_network_service_provider.py | # Copyright (c) 2016, Intel Corporation.
# 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 r... | # Copyright (c) 2016, Intel Corporation.
# 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 r... | Fix network service provider functional test | Fix network service provider functional test
SDK refactor broken network service provider
functional test, tested this command works,
but there is a error in the funtional test,
so fix it.
Change-Id: I783c58cedd39a05b665e47709b2b5321871e558b
Closes-Bug: 1653138
| Python | apache-2.0 | dtroyer/python-openstackclient,openstack/python-openstackclient,dtroyer/python-openstackclient,openstack/python-openstackclient |
35c76035be66516de744cd4266cf705991023cf2 | logicaldelete/managers.py | logicaldelete/managers.py | from django.db import models
class LogicalDeletedManager(models.Manager):
"""
A manager that serves as the default manager for `logicaldelete.models.Model`
providing the filtering out of logically deleted objects. In addition, it
provides named querysets for getting the deleted objects.
"""
... | from django.db import models
from logicaldelete.query import LogicalDeleteQuerySet
class LogicalDeletedManager(models.Manager):
"""
A manager that serves as the default manager for `logicaldelete.models.Model`
providing the filtering out of logically deleted objects. In addition, it
provides named q... | Make sure QuerySet.delete() operation does not bypass protection | Make sure QuerySet.delete() operation does not bypass protection
This fixes #1
| Python | bsd-3-clause | angvp/django-logicaldelete,angvp/django-logical-delete,angvp/django-logicaldelete,Ubiwhere/pinax-models,angvp/django-logical-delete,naringas/pinax-models,pombredanne/django-logicaldelete,pinax/pinax-models |
be2e68d077e90f1915274ac9b0e110cc82a3b126 | zou/app/mixin.py | zou/app/mixin.py | from flask_restful import reqparse
from flask import request
class ArgsMixin(object):
"""
Helpers to retrieve parameters from GET or POST queries.
"""
def get_args(self, descriptors):
parser = reqparse.RequestParser()
for descriptor in descriptors:
action = None
... | from flask_restful import reqparse
from flask import request
class ArgsMixin(object):
"""
Helpers to retrieve parameters from GET or POST queries.
"""
def get_args(self, descriptors):
parser = reqparse.RequestParser()
for descriptor in descriptors:
action = None
... | Add a function to clean dict keys | [utils] Add a function to clean dict keys
Remove None values.
| Python | agpl-3.0 | cgwire/zou |
4193a49144227f8ff2694d602246d692ee9946bf | oauthenticator/__init__.py | oauthenticator/__init__.py | # include github, bitbucket, google here for backward-compatibility
# don't add new oauthenticators here.
from .oauth2 import *
from .github import *
from .bitbucket import *
from .generic import *
from .google import *
from .okpy import *
from ._version import __version__, version_info
| # include github, bitbucket, google here for backward-compatibility
# don't add new oauthenticators here.
from .oauth2 import *
from .github import *
from .bitbucket import *
from .google import *
from .okpy import *
from ._version import __version__, version_info
| Delete extra import. Prepare for PR. | Delete extra import. Prepare for PR.
| Python | bsd-3-clause | NickolausDS/oauthenticator,enolfc/oauthenticator,yuvipanda/mwoauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,minrk/oauthenticator,yuvipanda/mwoauthenticator,jupyterhub/oauthenticator,maltevogl/oauthenticator |
f875fb3973fe5f99f2bc343d2685774bc388deb3 | version.py | version.py | major = 0
minor=0
patch=0
branch="dev"
timestamp=1376506569.35 | major = 0
minor=0
patch=13
branch="master"
timestamp=1376507610.99 | Tag commit for v0.0.13-master generated by gitmake.py | Tag commit for v0.0.13-master generated by gitmake.py
| Python | mit | ryansturmer/gitmake |
0d1300165b2d33802124917d477047f7b414a69c | plugins/Tools/ScaleTool/ScaleToolHandle.py | plugins/Tools/ScaleTool/ScaleToolHandle.py | from UM.Scene.ToolHandle import ToolHandle
class ScaleToolHandle(ToolHandle):
def __init__(self, parent = None):
super().__init__(parent)
md = self.getMeshData()
md.addVertex(0, 0, 0)
md.addVertex(0, 20, 0)
md.addVertex(0, 0, 0)
md.addVertex(20, 0, 0)
md.ad... | from UM.Scene.ToolHandle import ToolHandle
from UM.Mesh.MeshData import MeshData
from UM.Mesh.MeshBuilder import MeshBuilder
from UM.Math.Vector import Vector
class ScaleToolHandle(ToolHandle):
def __init__(self, parent = None):
super().__init__(parent)
lines = MeshData()
lines.addVertex(0... | Implement proper scale tool handles | Implement proper scale tool handles
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
13e86e405a3b7e2933a5f7fca14d7903f30201ee | Largest_Palindrome_Product.py | Largest_Palindrome_Product.py | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
def largestPalindrome(n):
"... | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
def largestPalindrome(n):
"... | Solve Largest Palindrome Product for range of n is | Solve Largest Palindrome Product for range of n is [1,6]
| Python | mit | Kunal57/Python_Algorithms |
feb147bf3ed487a72128c3bbd3f5a0548c26933a | src/tests/program_page_test.py | src/tests/program_page_test.py | from lib.constants.test import create_new_program
from lib import base, page
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard = page.dashboard.DashboardPage(self.driver)
dashboard.navigate_to()
lhn_menu = dashboard.open_lhn_menu()
lhn_menu.select_a... | from lib.constants.test import create_new_program
from lib.page import dashboard
from lib import base
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard_page = dashboard.DashboardPage(self.driver)
dashboard_page.navigate_to()
lhn_menu = dashboard_page.open_l... | Fix import error for program page test | Fix import error for program page test
| Python | apache-2.0 | VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc... |
675178e41719da258941449f8457a6500c43ad9a | tool/zeroconf_ssh.py | tool/zeroconf_ssh.py | #!/usr/bin/python
import socket
import time
from zeroconf import *
def main():
print "Register SSH service ..."
service_type = "_ssh._tcp.local."
info = ServiceInfo(service_type,
"RPi3." + service_type,
socket.inet_aton("127.0.0.1"), 22,
0, 0, "", None)
zc = Zero... | #!/usr/bin/python
import socket
import time
from zeroconf import *
def main():
service_type = "_ssh._tcp.local."
service_port = 22
service_addr = socket.gethostbyname(socket.gethostname())
service_name = socket.gethostname().replace('.local', '.')
info = ServiceInfo(service_type,
serv... | Support use real ip and host name for service | Support use real ip and host name for service
| Python | apache-2.0 | TimonLio/rex-pi,TimonLio/rex-pi |
72ca8573f97c5950a7d6a885be295fddb34cb088 | recipyGui/views.py | recipyGui/views.py | from flask import Blueprint, request, redirect, render_template, url_for
from flask.views import MethodView
from recipyGui import recipyGui, mongo
from forms import SearchForm
runs = Blueprint('runs', __name__, template_folder='templates')
@recipyGui.route('/')
def index():
form = SearchForm()
query = reques... | from flask import Blueprint, request, redirect, render_template, url_for
from flask.views import MethodView
from recipyGui import recipyGui, mongo
from forms import SearchForm
runs = Blueprint('runs', __name__, template_folder='templates')
@recipyGui.route('/')
def index():
form = SearchForm()
query = reques... | Add search functionality for runs | Add search functionality for runs
Add search functionality for runs. Runs are searched using MongoDB's
full text search capabilities. Note that this requires a text index on
the collection (command used to create the text index:
db.recipies.createIndex({ "$**": "text" }, { name: "TextIndex" },
... | Python | apache-2.0 | musically-ut/recipy,github4ry/recipy,bsipocz/recipy,MichielCottaar/recipy,recipy/recipy-gui,MichielCottaar/recipy,bsipocz/recipy,MBARIMike/recipy,github4ry/recipy,musically-ut/recipy,MBARIMike/recipy,recipy/recipy,recipy/recipy,recipy/recipy-gui |
dfce3efecacfa53654e06ea9be94407155fe7e4c | airship/__init__.py | airship/__init__.py | import os
import json
from flask import Flask, render_template
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels()]
jsonbody = json.dumps(channels)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def make_airship(s... | import os
import json
from flask import Flask, render_template
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels()]
jsonbody = json.dumps(channels)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def make_airship(s... | Create a route for fetching grefs | Create a route for fetching grefs
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation |
c83c63a6b1ff1cc6d6d4f71f2da3affbb167738d | tabler/tabler.py | tabler/tabler.py | from parser import TableParser
class Tabler:
def __init__(self, html):
self._html = html
self.header = []
self.body = []
self.footer = []
self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row)
self.parser.feed(html)
def ro... | from parser import TableParser
class Tabler:
def __init__(self, html):
self._html = html
self.header = []
self.body = []
self.footer = []
self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row)
self.parser.feed(html)
def ro... | Use a class to store row data, and allow lookup via index or header cell value. | Use a class to store row data, and allow lookup via index or header cell value.
| Python | bsd-3-clause | bschmeck/tabler |
34f3d2d8c7828036deaeae7a78d33de2412759e3 | migrant.py | migrant.py | import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
content = file.... | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
... | Add shebang and make file executable | Add shebang and make file executable
| Python | mit | ranisalt/moita-migrant |
c44be6418bbf92121e56bf68d6c8e2ebef483e17 | script/generate_amalgamation.py | script/generate_amalgamation.py | #!/usr/bin/env python
import sys
import os.path
import re
INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
seen_files = set()
def add_file(filename):
basename = os.path.basename(filename)
# Only include each file at most once.
if basename in seen_files:
return
seen_files.add(basename)
path = o... | #!/usr/bin/env python
import sys
from os.path import basename, dirname, join
import re
INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
seen_files = set()
out = sys.stdout
def add_file(filename):
bname = basename(filename)
# Only include each file at most once.
if bname in seen_files:
return
see... | Add comments for file start/end | Add comments for file start/end
| Python | mit | Nave-Neel/wren,Nave-Neel/wren,minirop/wren,bigdimboom/wren,foresterre/wren,Nelarius/wren,minirop/wren,Nave-Neel/wren,foresterre/wren,Rohansi/wren,Rohansi/wren,minirop/wren,foresterre/wren,Nave-Neel/wren,minirop/wren,foresterre/wren,foresterre/wren,munificent/wren,bigdimboom/wren,Rohansi/wren,Nelarius/wren,Nelarius/wren... |
9fc53690c8b31fa62391aeec54b29f4ee216402a | test/test_label_install.py | test/test_label_install.py | import unittest
from neomodel import config, StructuredNode, StringProperty, install_all_labels
from neomodel.core import db
config.AUTO_INSTALL_LABELS = False
class NoConstraintsSetup(StructuredNode):
name = StringProperty(unique_index=True)
config.AUTO_INSTALL_LABELS = True
def test_labels_were_not_insta... | from neomodel import config, StructuredNode, StringProperty, install_all_labels
from neomodel.core import db
config.AUTO_INSTALL_LABELS = False
class NoConstraintsSetup(StructuredNode):
name = StringProperty(unique_index=True)
config.AUTO_INSTALL_LABELS = True
def test_labels_were_not_installed():
bob =... | Revert "Skip install labels test for now" | Revert "Skip install labels test for now"
This reverts commit 3016324f9eb84989bcdefa2d3dfe1f766f4ab7e6.
| Python | mit | robinedwards/neomodel,robinedwards/neomodel |
cc42cf63bc3bf887933635e824cc838204738e30 | tests/acceptance/shared.py | tests/acceptance/shared.py | """Shared acceptance test functions."""
from time import sleep
def wait(condition, step=0.1, max_steps=10):
"""Wait for a condition to become true."""
for i in range(max_steps - 1):
if condition():
return True
else:
sleep(step)
return condition()
def get_listing_c... | """Shared acceptance test functions."""
from time import sleep
def wait(condition, step=0.1, max_steps=10):
"""Wait for a condition to become true."""
for i in range(max_steps - 1):
if condition():
return True
else:
sleep(step)
return condition()
def get_listing_... | Fix acceptance tests: for for button to be visible | Fix acceptance tests: for for button to be visible
| Python | agpl-3.0 | xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/... |
739018911befdb6804f26bc1a99dba6faa1313b7 | mezzanine/core/auth_backends.py | mezzanine/core/auth_backends.py |
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.db.models import Q
from django.utils.http import base36_to_int
class MezzanineBackend(ModelBackend):
"""
Extends Django's ``ModelBackend... |
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.db.models import Q
from django.utils.http import base36_to_int
class MezzanineBackend(ModelBackend):
"""
Extends Django's ``ModelBackend... | Fix kwargs usage to work with other auth backends. | Fix kwargs usage to work with other auth backends.
| Python | bsd-2-clause | ryneeverett/mezzanine,nikolas/mezzanine,tuxinhang1989/mezzanine,dustinrb/mezzanine,sjuxax/mezzanine,emile2016/mezzanine,orlenko/sfpirg,Kniyl/mezzanine,webounty/mezzanine,molokov/mezzanine,spookylukey/mezzanine,Skytorn86/mezzanine,christianwgd/mezzanine,jjz/mezzanine,agepoly/mezzanine,jjz/mezzanine,tuxinhang1989/mezzani... |
54a345eb96bce8c3035b402ce009b1e3fda46a42 | quran_text/serializers.py | quran_text/serializers.py | from rest_framework import serializers
from .models import Sura, Ayah
class SuraSerializer(serializers.ModelSerializer):
class Meta:
model = Sura
fields = ['index', 'name']
class AyahSerializer(serializers.ModelSerializer):
class Meta:
model = Ayah
fields = ['sura', 'numbe... | from rest_framework import serializers
from .models import Sura, Ayah
class SuraSerializer(serializers.ModelSerializer):
class Meta:
model = Sura
fields = ['index', 'name']
class AyahSerializer(serializers.ModelSerializer):
sura_id = serializers.IntegerField(source='sura.pk')
sura_name... | Change label and add Sura name to Ayah Serlialzer | Change label and add Sura name to Ayah Serlialzer
| Python | mit | EmadMokhtar/tafseer_api |
bb7741ade270458564ea7546d372e39bbbe0f97d | rds/delete_db_instance.py | rds/delete_db_instance.py | #!/usr/bin/env python
# a script to delete an rds instance
# import the sys and boto3 libraries
import sys
import boto3
# create an rds client
rds = boto3.client('rds')
# use the first argument to the script as the name
# of the instance to be deleted
db = sys.argv[1]
try:
# delete the instance and catch the re... | #!/usr/bin/env python
# a script to delete an rds instance
# import the sys and boto3 libraries
import sys
import boto3
# use the first argument to the script as the name
# of the instance to be deleted
db = sys.argv[1]
# create an rds client
rds = boto3.client('rds')
try:
# delete the instance and catch the re... | Swap db and rds set up | Swap db and rds set up
| Python | mit | managedkaos/AWS-Python-Boto3 |
ce29f011a72bf695c9b0840ad4c121f85c9fcad1 | mica/stats/tests/test_guide_stats.py | mica/stats/tests/test_guide_stats.py | import tempfile
import os
from .. import guide_stats
def test_calc_stats():
guide_stats.calc_stats(17210)
def test_make_gui_stats():
"""
Save the guide stats for one obsid into a newly-created table
"""
# Get a temporary file, but then delete it, because _save_acq_stats will only
# make a n... | import tempfile
import os
from .. import guide_stats
def test_calc_stats():
guide_stats.calc_stats(17210)
def test_calc_stats_with_bright_trans():
s = guide_stats.calc_stats(17472)
# Assert that the std on the slot 7 residuals are reasonable
# even in this obsid that had a transition to BRIT
ass... | Add test to confirm more reasonable residual std on one obsid/slot | Add test to confirm more reasonable residual std on one obsid/slot
| Python | bsd-3-clause | sot/mica,sot/mica |
4d1ab55f2bbe8041421002a91dc4f58783913591 | services/search_indexes.py | services/search_indexes.py | from aldryn_search.utils import get_index_base
from .models import Service
class ServiceIndex(get_index_base()):
haystack_use_for_indexing = True
index_title = True
def get_title(self, obj):
# XXX what about language? concatenate all available languages?
return obj.name_en
def get_... | from aldryn_search.utils import get_index_base
from .models import Service
class ServiceIndex(get_index_base()):
haystack_use_for_indexing = True
index_title = True
def get_title(self, obj):
return obj.name
def get_index_queryset(self, language):
# For this language's index, don't i... | Implement language-specific aspects of indexing | Implement language-specific aspects of indexing
| Python | bsd-3-clause | theirc/ServiceInfo,theirc/ServiceInfo,theirc/ServiceInfo,theirc/ServiceInfo |
92f7ca684ed3e9113ccc709442a02b2c14fe662e | opengrid/tests/test_plotting.py | opengrid/tests/test_plotting.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 02:37:25 2013
@author: Jan
"""
import unittest
class PlotStyleTest(unittest.TestCase):
def test_default(self):
from opengrid.library.plotting import plot_style
plt = plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 02:37:25 2013
@author: Jan
"""
import matplotlib
import unittest
matplotlib.use('Agg')
class PlotStyleTest(unittest.TestCase):
def test_default(self):
from opengrid.library.plotting import plot_style
plt = plot_style()
class CarpetTest(unittes... | Resolve RuntimeError: Invalid DISPLAY variable | [TST] Resolve RuntimeError: Invalid DISPLAY variable
| Python | apache-2.0 | opengridcc/opengrid |
85999e2024027e45015fb2f2417867a6d9f324c7 | EditorConfig.py | EditorConfig.py | import sublime_plugin
from editorconfig import get_properties, EditorConfigError
LINE_ENDINGS = {
'lf': 'Unix',
'crlf': 'Windows',
'cr': 'CR'
}
class EditorConfig(sublime_plugin.EventListener):
def on_load(self, view):
try:
config = get_properties(view.file_name())
except EditorConfigError:
print 'Err... | import sublime_plugin
from editorconfig import get_properties, EditorConfigError
LINE_ENDINGS = {
'lf': 'Unix',
'crlf': 'Windows',
'cr': 'CR'
}
class EditorConfig(sublime_plugin.EventListener):
def on_load(self, view):
path = view.file_name()
if not path:
return
try:
config = get_properties(path)
... | Fix plugin not taking into account opening of unsaved buffers and some refactoring | Fix plugin not taking into account opening of unsaved buffers and some refactoring
| Python | mit | rivy/editorconfig-sublime,gatero/editorconfig-sublime,sindresorhus/editorconfig-sublime,SerkanSipahi/editorconfig-sublime |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.