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 |
|---|---|---|---|---|---|---|---|---|---|
3744a620bddde501c0b2634b7cd54a755433c17a | djangopeoplenet/manage.py | djangopeoplenet/manage.py | #!/usr/bin/env python
import sys
paths = (
'/home/simon/sites/djangopeople.net',
'/home/simon/sites/djangopeople.net/djangopeoplenet',
'/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib',
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.m... | #!/usr/bin/env python
import sys, os
root = os.path.dirname(__file__)
paths = (
os.path.join(root),
os.path.join(root, "djangopeople", "lib"),
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.management import execute_manager
try:
import settings # Assume... | Make the lib imports work on other computers than Simon's | Make the lib imports work on other computers than Simon's | Python | mit | brutasse/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,django/djangopeople |
5ead9e24ec73ee66886858bf70f357ae170bdf3b | spillway/mixins.py | spillway/mixins.py | class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class DefaultSerializer(self.model_serializer_class):
cl... | from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class Defaul... | Throw ValidationError for invalid form, drop get_query_form() | Throw ValidationError for invalid form, drop get_query_form()
| Python | bsd-3-clause | kuzmich/django-spillway,barseghyanartur/django-spillway,bkg/django-spillway |
6676a47806c3c35d800450ff9480cabdc52928e8 | tedx/views.py | tedx/views.py | from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_registration(request):
if request.method == 'POST':
form = RegistrationForm(request.POST... | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import render
from clubs.models import Team
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_regis... | Add permission check for TEDx | Add permission check for TEDx
| Python | agpl-3.0 | osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz |
3ad466fc9b1971f3c10123db7b962bc93f79eb78 | sahara_dashboard/enabled/_1810_data_processing_panel_group.py | sahara_dashboard/enabled/_1810_data_processing_panel_group.py | from django.utils.translation import ugettext_lazy as _
# The slug of the panel group to be added to HORIZON_CONFIG. Required.
PANEL_GROUP = 'data_processing'
# The display name of the PANEL_GROUP. Required.
PANEL_GROUP_NAME = _('Data Processing')
# The slug of the dashboard the PANEL_GROUP associated with. Required.
... | # 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, software
# distributed u... | Add Apache 2.0 license to source file | Add Apache 2.0 license to source file
As per OpenStack licensing guide lines [1]:
[H102 H103] Newly contributed Source Code should be licensed under
the Apache 2.0 license.
[H104] Files with no code shouldnt contain any license header nor
comments, and must be left completely empty.
[1] http://docs.openstack.org/dev... | Python | apache-2.0 | openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard |
3fc9588a0f689a01ac8da0f43551418d3b3649b5 | extractor_train/assets.py | extractor_train/assets.py | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
"libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/boo... | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
# "libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/bo... | Remove inlcudes for no longer needed libraries. | Remove inlcudes for no longer needed libraries.
| Python | bsd-3-clause | dlarochelle/extractor_train,dlarochelle/extractor_train,dlarochelle/extractor_train |
dde9b3808b3e85f5513cc3604fd219a90774c047 | bot.py | bot.py |
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_messa... |
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_messa... | Update 0.4.2 - Added hashtags | Update 0.4.2
- Added hashtags
| Python | mit | FXelix/space_facts_bot |
734903c777fb237509c21a988f79318ec14e997d | st2api/st2api/controllers/sensors.py | st2api/st2api/controllers/sensors.py | import six
from pecan import abort
from pecan.rest import RestController
from mongoengine import ValidationError
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.base import jsexpose
from st2common.models.api.reactor import SensorTypeAPI
http_client = six... | import six
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.api.reactor import SensorTypeAPI
from st2api.controllers.resource import ResourceController
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(Reso... | Use ResourceController instead of duplicating logic. | Use ResourceController instead of duplicating logic.
| Python | apache-2.0 | pinterb/st2,armab/st2,peak6/st2,pixelrebel/st2,Plexxi/st2,armab/st2,Plexxi/st2,punalpatel/st2,grengojbo/st2,jtopjian/st2,jtopjian/st2,StackStorm/st2,alfasin/st2,dennybaa/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,pinterb/st2,grengojbo/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,pixelrebel/st2,alfasin/st2,emedvedev/st2,... |
d0b40c90bd5af1ba9ef0d617c10700566d4e3775 | tests/unit/directory/test_directory.py | tests/unit/directory/test_directory.py | """Contains the unit tests for the inner directory package"""
import unittest
class TestDirectory(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main() | """Contains the unit tests for the inner directory package"""
import unittest
class TestDirectory(unittest.TestCase):
def setUp(self):
self.fake_path = os.path.abspath("hello-world-dir")
return
if __name__ == "__main__":
unittest.main() | Add TestDirectory.setUp() to the directory package's test file | Add TestDirectory.setUp() to the directory package's test file
| Python | mit | SizzlingVortex/classyfd |
24c6b759c1e8898946cdae591bce236e3ddbc2d8 | topStocks.py | topStocks.py | """Find top stocks and post them to Twitter."""
import sys
import tweetPoster
import stockPrices
from stockList import getStockList
import time
def main():
# Get the list of stock symobls
currentStockList = getStockList()
# Get the stock prices
oldStockPrices = stockPrices.getStockPrices(currentStockL... | """Find top stocks and post them to Twitter."""
import sys
import tweetPoster
import stockPrices
from stockList import getStockList
import time
def main():
# Get the list of stock symobls
currentStockList = getStockList()
# Get the stock prices
oldStockPrices = stockPrices.getStockPrices(currentStockL... | Make sure "percentage" is a string before concatenating it. | Make sure "percentage" is a string before concatenating it.
| Python | mit | trswany/topStocks |
23c699e1be6c7d779491b62811913a0c73b45a39 | utilities/test_parse_vcf.py | utilities/test_parse_vcf.py | import pytest
import parse_vcf as pv
def test_openfile():
assert pv.openfile('test_parse_vcf.py')[0] == True
| import pytest
import parse_vcf as pv
def test_openfile():
# The real input file is called: 001.vcfmod
assert pv.openfile('001.vcfmod')[0] == True
| Use one of the real data files in test | Use one of the real data files in test
| Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various |
2e5c0b1507dcfac46c380102ff338a4be9f25d97 | tests/sentry/auth/providers/test_oauth2.py | tests/sentry/auth/providers/test_oauth2.py | from __future__ import absolute_import, print_function
import pytest
from sentry.auth.exceptions import IdentityNotValid
from sentry.auth.providers.oauth2 import OAuth2Provider
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import TestCase
class OAuth2ProviderTest(TestCase):
def setU... | from __future__ import absolute_import, print_function
import pytest
from sentry.auth.exceptions import IdentityNotValid
from sentry.auth.providers.oauth2 import OAuth2Provider
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import TestCase
class OAuth2ProviderTest(TestCase):
def setU... | Correct identity data in test | Correct identity data in test
| Python | bsd-3-clause | daevaorn/sentry,ewdurbin/sentry,mvaled/sentry,daevaorn/sentry,imankulov/sentry,llonchj/sentry,looker/sentry,BayanGroup/sentry,felixbuenemann/sentry,jean/sentry,vperron/sentry,BuildingLink/sentry,argonemyth/sentry,mvaled/sentry,boneyao/sentry,nicholasserra/sentry,gencer/sentry,JTCunning/sentry,imankulov/sentry,JamesMura... |
115c9343e4aa6bf39dd2038a53a32fb5695fce2b | tools/pygments_k3/pygments_k3/lexer.py | tools/pygments_k3/pygments_k3/lexer.py | from pygments.token import Keyword, Text, Token
from pygments.lexer import RegexLexer
class K3Lexer(RegexLexer):
name = 'K3'
aliases = ['k3']
filenames = ['*.k3']
keywords = {
'preprocessor': "include",
"declaration": [
"annotation", "declare", "feed", "provides", "require... | from pygments.token import Comment, Keyword, Literal, Operator, Text
from pygments.lexer import RegexLexer
class K3Lexer(RegexLexer):
name = 'K3'
aliases = ['k3']
filenames = ['*.k3']
keywords = {
'preprocessor': "include",
"declaration": [
"annotation", "declare", "feed",... | Add more syntactic construct lexing. | Add more syntactic construct lexing.
| Python | apache-2.0 | DaMSL/K3,DaMSL/K3,yliu120/K3 |
b20cfef1e54d9f22769f6d0ec6ae06031bf86ec3 | tests/CrawlerProcess/asyncio_deferred_signal.py | tests/CrawlerProcess/asyncio_deferred_signal.py | import asyncio
import sys
from scrapy import Spider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.defer import deferred_from_coro
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
a... | import asyncio
import sys
from scrapy import Spider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.defer import deferred_from_coro
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
a... | Remove unnecessary line from test | Remove unnecessary line from test
| Python | bsd-3-clause | dangra/scrapy,pablohoffman/scrapy,scrapy/scrapy,pablohoffman/scrapy,elacuesta/scrapy,pawelmhm/scrapy,dangra/scrapy,pawelmhm/scrapy,elacuesta/scrapy,elacuesta/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,scrapy/scrapy,scrapy/scrapy |
819e34fb8cd60a25b7796508f72a1e9ba00b5faf | incuna_test_utils/factories/user.py | incuna_test_utils/factories/user.py | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
| import factory
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError: # Django 1.4
from django.contrib.auth.models import User
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = User
email = factory.Sequence(lambda i: 'email{}@example.com'.forma... | Fix UserFactory for django 1.4 | Fix UserFactory for django 1.4
| Python | bsd-2-clause | incuna/incuna-test-utils,incuna/incuna-test-utils |
d953055801c8d618c70cea81e3e35684122c66a7 | setuptools/config/__init__.py | setuptools/config/__init__.py | """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", boun... | """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", boun... | Add stacklevel=2 to make calling code clear | Add stacklevel=2 to make calling code clear | Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
1fb77715c4766e3e437970a048154a5a9fe1b2c8 | tools/httpdtest.py | tools/httpdtest.py | #! /bin/env python3
#
# Simple HTTP server for testing purposes.
import http.server
import sys
from argparse import ArgumentParser
class RequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.requestline)
for (key, header) in self.headers.items():
print("{}... | #! /bin/env python3
#
# Simple HTTP server for testing purposes.
import http.server
import json
import sys
from argparse import ArgumentParser
class RequestHandler(http.server.BaseHTTPRequestHandler):
# Handle GET requests
def do_GET(self):
response = {}
# Capture the URL request
r... | Send back GET request in response | Send back GET request in response
The response to a GET request now returns the request string
and all header fields as a JSON encoded response.
| Python | bsd-3-clause | rolfmichelsen/Just4Fun |
44650a0b3d395b4201a039bd2f3eb916987dce8d | _grains/osqueryinfo.py | _grains/osqueryinfo.py | # -*- coding: utf-8 -*-
import salt.utils
import salt.modules.cmdmod
__salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet}
def osquerygrain():
'''
Return osquery version in grain
'''
# Provides:
# osqueryversion
# osquerybinpath
grains = {}
option = '--version'
# Prefer our... | # -*- coding: utf-8 -*-
import salt.utils
import salt.modules.cmdmod
__salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet}
def osquerygrain():
'''
Return osquery version in grain
'''
# Provides:
# osqueryversion
# osquerybinpath
grains = {}
option = '--version'
# Prefer our... | Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0 | DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
| Python | apache-2.0 | hubblestack/hubble-salt |
eed33b6ba9a3d5cf5d841d451ad03fd2f57c43bf | openfisca_senegal/senegal_taxbenefitsystem.py | openfisca_senegal/senegal_taxbenefitsystem.py | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities, scenarios
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
class SenegalTaxBenefitSystem(TaxBenefitSystem):
"""Senegalese tax and benefit system"""
CURRENCY = u"FCFA"
def _... | # -*- coding: utf-8 -*-
import os
import xml.etree.ElementTree
from openfisca_core import conv, legislationsxml
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities, scenarios
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
class SenegalTaxBenefitSystem(TaxBenefitSystem):... | Implement adding legislation XML from string | Implement adding legislation XML from string
| Python | agpl-3.0 | openfisca/senegal |
448d4697803ad6993d81ca556a63977f1c039a7f | requestsexceptions/__init__.py | requestsexceptions/__init__.py | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Add SubjectAltNameWarning and a helper function | Add SubjectAltNameWarning and a helper function
shade hits the SubjectAltName problem when talking to Rackspace. Also,
one of the things you want to do is turn off the warnings - so add a
function for that.
Change-Id: I3a55c66e5a4033a47a9d8704dd30709a5c53edc9
| Python | apache-2.0 | openstack-infra/requestsexceptions |
54db30c6db4df1f8a0e9030258cfcab4937d0c13 | python/castle-on-the-grid.py | python/castle-on-the-grid.py | #!/bin/python3
import math
import os
import random
import re
import sys
class CastleOnGrid:
def __init__(self, grid, start, goal):
self.grid = grid
self.start = start
self.goal = goal
def min_moves(self):
pass
if __name__ == '__main__':
grid_size = int(input())
grid ... | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
class CastleOnGrid:
def __init__(self, grid, grid_size, start, goal):
self.grid = grid
self.grid_size = grid_size
self.start = start
self.goal = goal
def min_moves(self):
... | Solve castle on grid (timeout test case 11) | Solve castle on grid (timeout test case 11)
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
aacfe5de01dd11486f7f39bb414c87853c8c8857 | likert_field/templatetags/likert_star_tools.py | likert_field/templatetags/likert_star_tools.py | #-*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import string_types
def render_stars(num, max_stars, star_set):
"""
Star renderer returns a HTML string of stars
If num is None or a blank string, it returns the unanswered tag
Otherwise, the returned string will contain num so... | #-*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.six import string_types
def render_stars(num, max_stars, star_set):
"""
Star renderer returns a HTML string of stars
If num is None or a blank string, it returns the unanswered tag
Otherwise, the returned string will c... | Use Dj provided compat tools | Use Dj provided compat tools
| Python | bsd-3-clause | kelvinwong-ca/django-likert-field,kelvinwong-ca/django-likert-field |
5bbdfb6d38878e2e1688fe37415662ec0dc176ee | sphinxcontrib/openstreetmap.py | sphinxcontrib/openstreetmap.py | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | Check whether required id parameter is specified | Check whether required id parameter is specified
| Python | bsd-2-clause | kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap |
ac04cd5301d6aa4788fbd2d6bdaeb207f77a489e | alfred_listener/views.py | alfred_listener/views.py | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | Change the way to instaniate models | Change the way to instaniate models
| Python | isc | alfredhq/alfred-listener |
bc4d11a6b5584975c3e9f16c2a4e25b26ff3da11 | mooc_aggregator_restful_api/mooc_aggregator.py | mooc_aggregator_restful_api/mooc_aggregator.py | '''
This module aggregates all the course information from different MOOC platforms
and stores them in the database (MongoDB)
'''
from mongoengine import connect
from flask.ext.mongoengine import MongoEngine
from udacity import UdacityAPI
from coursera import CourseraAPI
class MOOCAggregator(object):
'''
Thi... | '''
This module aggregates all the course information from different MOOC platforms
and stores them in the database (MongoDB)
'''
from mongoengine import connect
from flask.ext.mongoengine import MongoEngine
from udacity import UdacityAPI
from coursera import CourseraAPI
from models import Mooc
class MOOCAggregator(... | Add functionality to store courses in database | Add functionality to store courses in database
| Python | mit | ueg1990/mooc_aggregator_restful_api |
0ca4e0898fc6ee84109b458dfd505cdf42a5bae3 | tests/shared/core/test_constants.py | tests/shared/core/test_constants.py | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... | Fix some code quality issues. | Fix some code quality issues.
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu |
0f2950fcb44efc9b629242743574af503e8230d4 | tip/algorithms/sorting/mergesort.py | tip/algorithms/sorting/mergesort.py | def merge(a, b):
if len(a) * len(b) == 0:
return a + b
v = (a[0] < b[0] and a or b).pop(0)
return [v] + merge(a, b)
def mergesort(list):
if len(list) < 2:
return list
m = len(list) / 2
return merge(mergesort(list[:m]), mergesort(list[m:]))
| def merge(a, b):
if len(a) * len(b) == 0:
return a + b
v = (a[0] < b[0] and a or b).pop(0)
return [v] + merge(a, b)
def mergesort(list):
if len(list) < 2:
return list
m = len(list) / 2
return merge(mergesort(list[:int(m)]), mergesort(list[int(m):]))
| Fix slices for Python 3 | Fix slices for Python 3
| Python | unlicense | davidgasquez/tip |
58ce7f451263616c19599171305965b03807a853 | thinglang/foundation/definitions.py | thinglang/foundation/definitions.py | from thinglang.lexer.values.identifier import Identifier
"""
The internal ordering of core types used by the compiler and runtime
"""
INTERNAL_TYPE_ORDERING = {
Identifier("text"): 1,
Identifier("number"): 2,
Identifier("bool"): 3,
Identifier("list"): 4,
Identifier("Console"): 5,
Identifier("F... | from thinglang.lexer.values.identifier import Identifier
"""
The internal ordering of core types used by the compiler and runtime
"""
INTERNAL_TYPE_ORDERING = {
Identifier("text"): 1,
Identifier("number"): 2,
Identifier("bool"): 3,
Identifier("list"): 4,
Identifier("Console"): 5,
Identifier("F... | Add new types to INTERNAL_TYPE_ORDERING | Add new types to INTERNAL_TYPE_ORDERING
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
aca7c4ef6998786abfd2119fee26e1d94d501c16 | _build/drake-build.py | _build/drake-build.py | #!/usr/bin/python
import sys
sys.path.append('../src')
import drake
drake.run('..')
| #!/usr/bin/python
import os
import sys
sys.path.append('../src')
if 'PYTHONPATH' in os.environ:
os.environ['PYTHONPATH'] = '../src:%s' % os.environ['PYTHONPATH']
else:
os.environ['PYTHONPATH'] = '../src'
import drake
drake.run('..')
| Add drake in the PYTHONPATH for the tests. | Add drake in the PYTHONPATH for the tests.
| Python | agpl-3.0 | mefyl/drake,mefyl/drake,mefyl/drake,infinit/drake,infinit/drake,infinit/drake |
a4e9c3c47ff3999b56d769208106d3a605e1b50e | tests/test_client.py | tests/test_client.py | from __future__ import unicode_literals
import balanced
from . import utils
class TestClient(utils.TestCase):
def setUp(self):
super(TestClient, self).setUp()
def test_configure(self):
balanced.configure('XXX')
expected_headers = {
'content-type': 'application/vnd.api+j... | from __future__ import unicode_literals
import balanced
from . import utils
class TestClient(utils.TestCase):
def setUp(self):
super(TestClient, self).setUp()
def test_configure(self):
expected_headers = {
'content-type': 'application/vnd.api+json;revision=1.1',
'ac... | Fix 401 in test suite | Fix 401 in test suite | Python | mit | balanced/balanced-python,trenton42/txbalanced |
0c405fd30d059164509308dee604f50d9857202d | scripts/slave/recipe_modules/webrtc/resources/cleanup_files.py | scripts/slave/recipe_modules/webrtc/resources/cleanup_files.py | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args o... | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args o... | Make clean script return successful if clean dir is missing. | WebRTC: Make clean script return successful if clean dir is missing.
I thought it would be good to have the script fail for an
incorrectly specified directory, but the out/ dir is missing
on fresh installed slave machines, so better just skip cleaning
with a line printed to stdout instead when the dir is missing.
TES... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
a0bc95155bc3aed691793afb8fec639661cb9d5b | polyaxon/polyaxon/config_settings/events_handlers/__init__.py | polyaxon/polyaxon/config_settings/events_handlers/__init__.py | from polyaxon.config_settings.volume_claims import *
from .apps import *
| from polyaxon.config_settings.volume_claims import *
from polyaxon.config_settings.spawner import *
from .apps import *
| Add spawner to event handlers | Add spawner to event handlers
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
00bfddc9317660f6e7464288fc070d40a1ebad6b | server/constants.py | server/constants.py | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, LAB_ASSISTANT_ROLE, GRADER_ROLE, STAFF_ROLE,
INSTRUCTOR_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]... | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, LAB_ASSISTANT_ROLE, GRADER_ROLE, STAFF_ROLE,
INSTRUCTOR_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]... | Add /rq to banned course names | Add /rq to banned course names
| Python | apache-2.0 | Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok |
c5103eea181455afded264528bb97ac8a9982db0 | enable/__init__.py | enable/__init__.py | # Copyright (c) 2007-2014 by Enthought, Inc.
# All rights reserved.
""" A multi-platform object drawing library.
Part of the Enable project of the Enthought Tool Suite.
"""
from __future__ import absolute_import
from ._version import full_version as __version__
__requires__ = [
'traitsui',
'PIL',
'... | # Copyright (c) 2007-2014 by Enthought, Inc.
# All rights reserved.
""" A multi-platform object drawing library.
Part of the Enable project of the Enthought Tool Suite.
"""
from enable._version import full_version as __version__
__requires__ = [
'traitsui',
'PIL',
'kiwisolver',
]
| Use an absolute import to avoid breaking the docs build. | Use an absolute import to avoid breaking the docs build.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable |
926c4662c7b3059503bd0a22ee9624bb39ab40fd | sharepa/__init__.py | sharepa/__init__.py | from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
from sharepa.helpers import source_agg, source_counts
| from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
| Remove helper functions from sharepa init | Remove helper functions from sharepa init
| Python | mit | samanehsan/sharepa,erinspace/sharepa,CenterForOpenScience/sharepa,fabianvf/sharepa |
2d534b7be13bda60646815e16a91e778da71c3f8 | auditlog/__manifest__.py | auditlog/__manifest__.py | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | Remove pre_init_hook reference from openerp, no pre_init hook exists any more | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
| Python | agpl-3.0 | Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools |
b02c36bc23af41ee82414f36eb6cf20ffa5a4a46 | edx_data_research/reporting/basic/user_info.py | edx_data_research/reporting/basic/user_info.py | '''
This module will retrieve info about students registered in the course
'''
def user_info(edx_obj):
edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment']
cursor = edx_obj.collections['auth_userprofile'].find()
result = []
for item ... | '''
This module will retrieve info about students registered in the course
'''
def user_info(edx_obj):
edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment']
cursor = edx_obj.collections['auth_userprofile'].find()
result = []
for item ... | Add hash_id column to user-info output | Add hash_id column to user-info output
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research |
8af2699f6d0f190081254243e2c90369b4541e34 | happening/db.py | happening/db.py | """ Custom happening database manipulation. """
from django.contrib.sites.managers import CurrentSiteManager as Manager
from django.db import models
from django.contrib.sites.models import Site
from multihost import sites
import os
class Model(models.Model):
""" Custom model for use in happening.
Ensures t... | """ Custom happening database manipulation. """
from django.contrib.sites.managers import CurrentSiteManager as Manager
from django.db import models
from django.contrib.sites.models import Site
from multihost import sites
import os
class Model(models.Model):
""" Custom model for use in happening.
Ensures t... | Make travis tests work with sites | Make travis tests work with sites
| Python | mit | happeninghq/happening,happeninghq/happening,jscott1989/happening,happeninghq/happening,jscott1989/happening,jscott1989/happening,jscott1989/happening,happeninghq/happening |
db6222adea234921f82a843846778f5327566aaf | homebrew/logger.py | homebrew/logger.py | import logging
import sys
logger = logging.getLogger()
logFormatter = logging.Formatter("%(message)s")
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logge... | import logging
import sys
logger = logging.getLogger()
formatter = logging.Formatter("%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logger.info(logline)
logger.... | Rename variables used for setting up logging | Rename variables used for setting up logging
| Python | isc | igroen/homebrew |
7558f0ed7c14cd4a1cfb87fdefc631adf8d1aff0 | server/dummy/dummy_server.py | server/dummy/dummy_server.py | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def do_POST(self):
print '---> dummy server: got post!'
print 'command... | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def do_POST(self):
print '\n---> dummy server: got post!'
print 'comma... | Clean up post formatting and response code | Clean up post formatting and response code
| Python | mit | jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle |
49015e6d1a4c8670172ea00776e168f6cec0092b | openedx/core/djangoapps/user_api/accounts/forms.py | openedx/core/djangoapps/user_api/accounts/forms.py | """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
cancel_retirement = forms.BooleanField(required=True)
def save(self, retir... | """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
from openedx.core.djangoapps.user_api.accounts.utils import generate_password
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
c... | Reset learners password when user is unGDPRed/unretired via django admin. | Reset learners password when user is unGDPRed/unretired via django admin.
| Python | agpl-3.0 | cpennington/edx-platform,a-parhom/edx-platform,philanthropy-u/edx-platform,arbrandes/edx-platform,msegado/edx-platform,eduNEXT/edunext-platform,ESOedX/edx-platform,philanthropy-u/edx-platform,jolyonb/edx-platform,jolyonb/edx-platform,edx/edx-platform,stvstnfrd/edx-platform,EDUlib/edx-platform,edx/edx-platform,angelappe... |
d66a412efad62d47e7df8d2ff4922be4c268a93e | hunittest/utils.py | hunittest/utils.py | # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"))
def mod_spli... | # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
import unittest
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"... | Add helper to load a single test case. | Add helper to load a single test case.
| Python | bsd-2-clause | nicolasdespres/hunittest |
4de3b357101b3c304a6d89fd02175156ffecc656 | src/mailme/constants.py | src/mailme/constants.py |
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154
INBOX = 'inbox'
DRAFTS = 'drafts'
SPAM = 'spam'
ARCHIVE = 'archive'
SENT = 'sent'
TRASH = 'trash'
ALL = 'all'
IMPORTANT = 'important'
# Default mapping to unify various provider behaviors
DEFAULT_FOLDER_MAPPING = {
'inbox': INBOX,
'drafts': D... |
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154
INBOX = 'inbox'
DRAFTS = 'drafts'
SPAM = 'spam'
ARCHIVE = 'archive'
SENT = 'sent'
TRASH = 'trash'
ALL = 'all'
IMPORTANT = 'important'
# Default mapping to unify various provider behaviors
DEFAULT_FOLDER_MAPPING = {
'inbox': INBOX,
'drafts': D... | Add 'sent items' to default folder mapping | Add 'sent items' to default folder mapping
| Python | bsd-3-clause | mailme/mailme,mailme/mailme |
75632e699b6b83eba3d87506b2fed2de45f695bc | ai/STA/Strategy/stay_away.py | ai/STA/Strategy/stay_away.py | # Under MIT license, see LICENSE.txt
from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall
from ai.STA.Strategy.Strategy import Strategy
from ai.Util.role import Role
class StayAway(Strategy):
def __init__(self, p_game_state):
super().__init__(p_game_state)
roles_to_consider = [Role.FIRS... | # Under MIT license, see LICENSE.txt
from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall
from ai.STA.Strategy.Strategy import Strategy
from ai.Util.role import Role
class StayAway(Strategy):
def __init__(self, p_game_state):
super().__init__(p_game_state)
for r in Role:
p =... | Fix StayAway strat for pull request | Fix StayAway strat for pull request
| Python | mit | RoboCupULaval/StrategyIA,RoboCupULaval/StrategyIA |
af56c549a8eae5ebb0d124e2bb397241f11e47af | indico/__init__.py | indico/__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Fix pip install failing due to wtforms monkeypatch | Fix pip install failing due to wtforms monkeypatch
| Python | mit | OmeGak/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,pferreir/indico,pferreir/indico,OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,mic4ael/indico,mic4ael/indico,mvidalgarci... |
275301d7a2c2e8c44ff1cfb3d49d9388f9531b56 | invalidate_data.py | invalidate_data.py | #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
... | #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
... | Update invalidate to remove failed trials. | Update invalidate to remove failed trials.
| Python | bsd-2-clause | jskinn/robot-vision-experiment-framework,jskinn/robot-vision-experiment-framework |
4946adddd889db89d65764f3a680ccc6853ea949 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Hidden/Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass '... | Update category and website on module description | Update category and website on module description
| Python | agpl-3.0 | xcgd/document_attachment |
9ee00a148763c7caac1ae0d7dcb3efa496121ee7 | lamana/__init__.py | lamana/__init__.py | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.11-dev'
__author__ = 'P. Robinson II'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015, P. Robinson II'
import lamana.input_
import lamana.distributions
import lamana.constructs
import lamana.the... | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.11.dev0' # PEP 440 style
##__version__ = '0.4.11-dev'
__author__ = 'P. Robinson II'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015, P. Robinson II'
import lamana.... | Modify dev versioning; see PEP 440 | Modify dev versioning; see PEP 440
| Python | bsd-3-clause | par2/lamana |
e6e40df6e23f6623c4672b9ec3aab982f5588c8c | downstream-farmer/client.py | downstream-farmer/client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import random
import hashlib
import requests
from heartbeat import Challenge, Heartbeat
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import random
import hashlib
import requests
from heartbeat import Challenge, Heartbeat
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.... | Set heartbeat attrib in init | Set heartbeat attrib in init
| Python | mit | Storj/downstream-farmer |
fa9577f875c999ea876c99e30614051f7ceba129 | authentication_app/models.py | authentication_app/models.py | from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class ... | from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : AccountManager
@desc : AccountManager model. The AccountManager is responsible to manage
the creation of users and superusers.
'''
class AccountManager(BaseUserManager):
def create_user(sel... | Add the account manager that support the creation of accounts. | Add the account manager that support the creation of accounts.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app |
332ea322d55b2d0410db172616fe51ccd0de050d | create_coverage_database.py | create_coverage_database.py | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | Move setting of row factory to after session object is created | Move setting of row factory to after session object is created
| Python | mit | GastonLab/ddb-datastore,dgaston/ddb-variantstore,dgaston/ddb-datastore,dgaston/ddbio-variantstore |
1fe4a129ba96f14dc91832754de00271a29f48ca | tests/tools/test_foodcritic.py | tests/tools/test_foodcritic.py | from lintreview.review import Comment
from lintreview.review import Problems
from lintreview.tools.foodcritic import Foodcritic
from unittest import TestCase
from nose.tools import eq_
class TestFoodcritic(TestCase):
fixtures = [
'tests/fixtures/foodcritic/noerrors',
'tests/fixtures/foodcritic/er... | from lintreview.review import Comment
from lintreview.review import Problems
from lintreview.tools.foodcritic import Foodcritic
from lintreview.utils import in_path
from unittest import TestCase, skipIf
from nose.tools import eq_
critic_missing = not(in_path('foodcritic'))
class TestFoodcritic(TestCase):
needs_... | Fix tests failing when foodcritic is not installed. | Fix tests failing when foodcritic is not installed.
Tool tests should skip, not fail.
| Python | mit | markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,markstory/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,markstory/lint-review |
7f2df3979458df73e4e3f0a9fdcb16905960de81 | _config.py | _config.py | # Amazon S3 Settings
AWS_KEY = 'REQUIRED'
AWS_SECRET_KEY = 'REQUIRED'
AWS_BUCKET = 'REQUIRED'
AWS_DIRECTORY = '' # Leave blank *not false* unless project not at base URL
# i.e. example.com/apps/ instead of example.com/
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRE... | # Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = ''
AWS_DIRECTORY = '' # Use if S3 bucket is not root
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Setti... | Update settings for new configuration | Update settings for new configuration
| Python | apache-2.0 | vprnet/EOTS-iframe-widget,vprnet/app-template,vprnet/live-from-the-fort,vprnet/timeline-dcf-systemic-failure,vprnet/app-template,vprnet/old-app-template,vprnet/app-template,vprnet/interactive-transcript-gov-peter-shumlins-third-inaugural-address,vprnet/soundcloud-podcast,vprnet/interactive-transcript-gov-peter-shumlins... |
6c1a285d58825942e51689e7370316151345ab1f | examples/tornado/auth_demo.py | examples/tornado/auth_demo.py | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | Add the settings to the authdemo. | Add the settings to the authdemo. | Python | bsd-3-clause | ged/mongrel2,ged/mongrel2,ged/mongrel2,ged/mongrel2 |
0e8d4e6649b6a48ac7bd87746574119a5ce5fd1a | qiime_studio/api/v1.py | qiime_studio/api/v1.py | from flask import Blueprint, jsonify
from .security import validate_request_authentication
from qiime.sdk import PluginManager
v1 = Blueprint('v1', __name__)
v1.before_request(validate_request_authentication)
@v1.route('/', methods=['GET', 'POST'])
def root():
return jsonify(content="!")
@v1.route('/plugins', ... | from flask import Blueprint, jsonify
from .security import validate_request_authentication
from qiime.sdk import PluginManager
PLUGIN_MANAGER = PluginManager()
v1 = Blueprint('v1', __name__)
v1.before_request(validate_request_authentication)
@v1.route('/', methods=['GET', 'POST'])
def root():
return jsonify(con... | Add plugin workflow fetching to API | Add plugin workflow fetching to API
| Python | bsd-3-clause | jakereps/qiime-studio,qiime2/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio,jakereps/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio-frontend,qiime2/qiime-studio,jakereps/qiime-studio-frontend,qiime2/qiime-studio |
ccdb064c0523e9293dca13adefa13d155d372505 | spotifyconnect/sink.py | spotifyconnect/sink.py | from __future__ import unicode_literals
import spotifyconnect
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want to
turn the sink... | from __future__ import unicode_literals
import spotifyconnect
__all__ = [
'Sink'
]
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want... | Add Sink class to initial spotify-connect import | Add Sink class to initial spotify-connect import
| Python | apache-2.0 | chukysoria/pyspotify-connect,chukysoria/pyspotify-connect |
0a1d7a76407f834a40d8cb96312cf6a5d322c65c | datastage/web/user/models.py | datastage/web/user/models.py | import pam
from django.contrib.auth import models as auth_models
class User(auth_models.User):
class Meta:
proxy = True
def check_password(self, raw_password):
return pam.authenticate(self.username, raw_password)
# Monkey-patch User model
auth_models.User = User | import dpam.pam
from django.contrib.auth import models as auth_models
class User(auth_models.User):
class Meta:
proxy = True
def check_password(self, raw_password):
return dpam.pam.authenticate(self.username, raw_password)
# Monkey-patch User model
auth_models.User = User
| Use django_pams pam.authenticate, instead of some other pam module. | Use django_pams pam.authenticate, instead of some other pam module.
| Python | mit | dataflow/DataStage,dataflow/DataStage,dataflow/DataStage |
9888a03368ad7b440cc43384024c71147aa647a3 | fireplace/cards/tgt/shaman.py | fireplace/cards/tgt/shaman.py | from ..utils import *
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
| from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class... | Implement Shaman cards for The Grand Tournament | Implement Shaman cards for The Grand Tournament
| Python | agpl-3.0 | oftc-ftw/fireplace,smallnamespace/fireplace,amw2104/fireplace,jleclanche/fireplace,Ragowit/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,liujimj/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,amw2104/fireplace,Meerkov/fireplace |
7db366558418f9fb997f8688f4816a500348e5c6 | tools/pdb-files.py | tools/pdb-files.py | import os
import os.path
import sys
import zipfile
'''
Seeks for *.pdb files from current directory and all child directories.
All found pdb files are copied to 'pdb-files.zip' file with their relative file paths.
'''
fileList = []
rootdir = os.curdir
zip_file_name = "pdb-files.zip"
if os.path.isfile(zip_file_name):... | import os
import os.path
import sys
import zipfile
'''
Seeks for *.pdb files from current directory and all child directories.
All found pdb files are copied to 'pdb-files.zip' file with their relative file paths.
'''
fileList = []
rootdir = os.getcwd()[0:-6] # strip the /tools from the end
zip_file_name = "Tundra-pd... | Fix py script to package all .pdb files now that its moved to tools. | Fix py script to package all .pdb files now that its moved to tools.
| Python | apache-2.0 | pharos3d/tundra,BogusCurry/tundra,realXtend/tundra,realXtend/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,realXtend/tundra,jesterKing/naali,BogusCurry/tundra,realXtend/tundra,jesterKing/naali,realXtend/tundra,BogusCurry/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,jesterKing/naali,jesterKing/naali,Alpha... |
42be4a39b9241ff3138efa52b316070713fc552a | people/serializers.py | people/serializers.py | from rest_framework import serializers
from people.models import Customer
from people.models import InternalUser
class CustomerSerializer(serializers.ModelSerializer):
phone_number = serializers.IntegerField(validators=[lambda x: len(str(x)) == 10])
class Meta:
model = Customer
fields = '__al... | from django.contrib.gis import serializers
from rest_framework import serializers
from people.models import Customer
from people.models import InternalUser
class CustomerSerializer(serializers.ModelSerializer):
phone_number = serializers.IntegerField()
def validate_phone_number(self, val):
if len(str... | Put validators in phone numbers | Put validators in phone numbers
| Python | apache-2.0 | rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory |
326cf5d548e9dcb231cac8d10410c0f589c545a2 | cabot/celeryconfig.py | cabot/celeryconfig.py | import os
from datetime import timedelta
BROKER_URL = os.environ['CELERY_BROKER_URL']
# Set environment variable if you want to run tests without a redis instance
CELERY_ALWAYS_EAGER = os.environ.get('CELERY_ALWAYS_EAGER', False)
CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', None)
CELERY_IMPORTS = ('... | import os
from datetime import timedelta
from cabot.settings_utils import environ_get_list
BROKER_URL = environ_get_list(['CELERY_BROKER_URL', 'CACHE_URL'])
# Set environment variable if you want to run tests without a redis instance
CELERY_ALWAYS_EAGER = os.environ.get('CELERY_ALWAYS_EAGER', False)
CELERY_RESULT_BACK... | Support CACHE_URL for the Celery broker as well. | Support CACHE_URL for the Celery broker as well.
| Python | mit | maks-us/cabot,arachnys/cabot,arachnys/cabot,maks-us/cabot,arachnys/cabot,maks-us/cabot,maks-us/cabot,arachnys/cabot |
ac3819cc978c83db10d4bdd151cc2db4d3c28eaf | wagtail_embed_videos/migrations/0002_collections.py | wagtail_embed_videos/migrations/0002_collections.py | # Generated by Django 2.0.1 on 2018-01-28 01:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0040_page_draft_title'),
('wagtail_embed_... | # Generated by Django 2.0.1 on 2018-01-28 01:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from wagtail.wagtailcore.models import Collection
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0040_page_draft_title'),
... | Change importing in order to make Wagtail<2.0 comp | Change importing in order to make Wagtail<2.0 comp | Python | bsd-3-clause | SalahAdDin/wagtail-embedvideos,SalahAdDin/wagtail-embedvideos,SalahAdDin/wagtail-embedvideos |
99aabf10b091df07a023dbf638cf605c01db1d74 | src/pcapi/utils/admin.py | src/pcapi/utils/admin.py | import argparse
import os
import shutil
from pcapi import get_resource
def create_skeleton(path):
if os.path.exists(path):
print 'Directory already exist'
return False
config_file = get_resource('pcapi.ini.example')
# create the folder structure
os.makedirs(os.path.join(path, 'data'... | import argparse
import os
import shutil
from pkg_resources import resource_filename
def create_skeleton(path):
if os.path.exists(path):
print 'Directory already exist'
return False
config_file = resource_filename('pcapi', 'data/pcapi.ini.example')
# create the folder structure
os.ma... | Use the pkg api for reading the resources in the package | Use the pkg api for reading the resources in the package
Issue cobweb-eu/pcapi#18
| Python | bsd-3-clause | cobweb-eu/pcapi,xmichael/pcapi,edina/pcapi,xmichael/pcapi,cobweb-eu/pcapi,edina/pcapi |
b5f980b700707ecc611746f93b1f62650c76c451 | pgcrypto_fields/aggregates.py | pgcrypto_fields/aggregates.py | from django.db import models
class Decrypt(models.Aggregate):
"""`Decrypt` creates an alias for `DecryptFunctionSQL`.
`alias` is `{self.lookup}__decrypt` where 'decrypt' is `self.name.lower()`.
`self.lookup` is defined in `models.Aggregate.__init__`.
"""
def add_to_query(self, query, alias, col... | from django.db import models
from pgcrypto_fields.sql import aggregates
class Decrypt(models.Aggregate):
"""`Decrypt` creates an alias for `DecryptFunctionSQL`.
`alias` is `{self.lookup}__decrypt` where 'decrypt' is `self.name.lower()`.
`self.lookup` is defined in `models.Aggregate.__init__`.
"""
... | Move import to top of the file | Move import to top of the file
| Python | bsd-2-clause | incuna/django-pgcrypto-fields,atdsaa/django-pgcrypto-fields |
f4807197cb48da72a88a0b12c950902614f4b9f6 | celery_bungiesearch/tasks/bulkdelete.py | celery_bungiesearch/tasks/bulkdelete.py | from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE... | from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
from elasticsearch import TransportError
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
... | Add error handling code to bulk delete | Add error handling code to bulk delete
| Python | mit | afrancis13/celery-bungiesearch |
02bb859424301bf7697a444a50a23c8c834466ab | loldb/__main__.py | loldb/__main__.py | """
Usage:
loldb --path=<path> [options]
loldb -h | --help
loldb --version
Options:
-p, --path=<path> Location of LoL installation.
--lang=<language> Language to output [default: en_US].
-h, --help Display this message.
--version Display version number.
"""
import os
import docopt
... | """
Usage:
loldb --path=<path> [options]
loldb -h | --help
loldb --version
Options:
-p, --path=<path> Location of LoL installation.
-o, --out=<path> File path to save json representation.
--lang=<language> Language to output [default: en_US].
-h, --help Display this message.
--version ... | Save data to file from CLI. | Save data to file from CLI.
| Python | mit | Met48/League-of-Legends-DB |
78bbb6cbf145ee7d78c41f39b4f078d986265232 | comics/comics/pennyarcade.py | comics/comics/pennyarcade.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Penny Arcade"
language = "en"
url = "http://penny-arcade.com/"
start_date = "1998-11-18"
rights = "Mike Krahulik & Jerry Holkins"
class Crawler... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Penny Arcade"
language = "en"
url = "http://penny-arcade.com/"
start_date = "1998-11-18"
rights = "Mike Krahulik & Jerry Holkins"
class Crawler... | Check "Penny Arcade" for 404 page without 404 header | Check "Penny Arcade" for 404 page without 404 header
| Python | agpl-3.0 | jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics |
39ebab1a41975bd37549129e2b915c99d153ee0a | src/bindings/pygaia/scripts/classification/balanced_sampling.py | src/bindings/pygaia/scripts/classification/balanced_sampling.py | # This script creates a balanced ground truth given an unbalanced on by applying
# random sampling. The size of the resulting classes equals to the minimum size
# among original classes.
import sys
import yaml
from random import shuffle
try:
input_gt = sys.argv[1]
balanced_gt = sys.argv[2]
except:
print... | # This script creates a balanced ground truth given an unbalanced on by applying
# random sampling. The size of the resulting classes equals to the minimum size
# among original classes.
import sys
import yaml
from random import shuffle
try:
input_gt = sys.argv[1]
balanced_gt = sys.argv[2]
except:
print... | Fix previous commit (balancing scripts) | Fix previous commit (balancing scripts)
| Python | agpl-3.0 | kartikgupta0909/gaia,ChristianFrisson/gaia,MTG/gaia,kartikgupta0909/gaia,kartikgupta0909/gaia,ChristianFrisson/gaia,ChristianFrisson/gaia,MTG/gaia,MTG/gaia,ChristianFrisson/gaia,kartikgupta0909/gaia,MTG/gaia |
5458a44ed193a7c4a37a3414e860a23dc5564c39 | github3/repos/deployment.py | github3/repos/deployment.py | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.users import User
class Deployment(GitHubCore):
CUSTOM_HEADERS = {
'Accept': 'application/vnd.github.cannonball-preview+json'
}
def __init__(self, deployment, session=None):
super(Deployment, self).__init__(dep... | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.users import User
class Deployment(GitHubCore):
CUSTOM_HEADERS = {
'Accept': 'application/vnd.github.cannonball-preview+json'
}
def __init__(self, deployment, session=None):
super(Deployment, self).__init__(dep... | Add repr to Deployment class | Add repr to Deployment class
| Python | bsd-3-clause | wbrefvem/github3.py,icio/github3.py,jim-minter/github3.py,itsmemattchung/github3.py,sigmavirus24/github3.py,ueg1990/github3.py,agamdua/github3.py,balloob/github3.py,krxsky/github3.py,degustaf/github3.py,christophelec/github3.py,h4ck3rm1k3/github3.py |
8ee8c42cd4d4be09d47cb7ebf5941583183bb3f3 | logger/utilities.py | logger/utilities.py | #!/usr/bin/env python3
"""Small utility functions for use in various places."""
__all__ = ["pick", "is_dunder", "convert_to_od"]
import collections
def pick(arg, default):
"""Handler for default versus given argument."""
return default if arg is None else arg
def is_dunder(name):
"""Return True if a __... | #!/usr/bin/env python3
"""Small utility functions for use in various places."""
__all__ = ["pick", "is_dunder", "convert_to_od"]
import collections
import itertools
def pick(arg, default):
"""Handler for default versus given argument."""
return default if arg is None else arg
def is_dunder(name):
"""Re... | Add a 'counter_to_iterable' utility function | Add a 'counter_to_iterable' utility function
| Python | bsd-2-clause | Vgr255/logging |
4f48fa8636000a1b780c962288bb588b2760465f | pyheufybot/utils/fileutils.py | pyheufybot/utils/fileutils.py | import codecs, os
def readFile(filePath):
try:
with open(filePath, "r") as f:
return f.read()
except Exception as e:
print "*** ERROR: An exception occurred while reading file \"{}\" ({})".format(filePath, e)
return None
def writeFile(filePath, line, append=False):
try:... | import codecs, os, time
def readFile(filePath):
try:
with open(filePath, "r") as f:
return f.read()
except Exception as e:
today = time.strftime("[%H:%M:%S]")
print "{} *** ERROR: An exception occurred while reading file \"{}\" ({})".format(today, filePath, e)
return... | Improve error logging in file IO | Improve error logging in file IO
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
c2128be32df870a601224be9f7e746dbd9cb72ee | makerscience_profile/api.py | makerscience_profile/api.py | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileRe... | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileRe... | Add teams field in MakerScienceProfileResource | Add teams field in MakerScienceProfileResource
| Python | agpl-3.0 | atiberghien/makerscience-server,atiberghien/makerscience-server |
0321591b9a9596c876e615ac9bacfe63e2c44b2c | midterm/problem8.py | midterm/problem8.py | # Problem 8
# 20.0 points possible (graded)
# Implement a function that meets the specifications below.
# For example, the following functions, f, g, and test code:
# def f(i):
# return i + 2
# def g(i):
# return i > 5
# L = [0, -10, 5, 6, -4]
# print(applyF_filterG(L, f, g))
# print(L)
# Should print:
# 6
... | # Problem 8
# 20.0 points possible (graded)
# Implement a function that meets the specifications below.
# For example, the following functions, f, g, and test code:
# def f(i):
# return i + 2
# def g(i):
# return i > 5
# L = [0, -10, 5, 6, -4]
# print(applyF_filterG(L, f, g))
# print(L)
# Should print:
# 6
... | Fix applyF_filterG function to pass test case | Fix applyF_filterG function to pass test case
| Python | mit | Kunal57/MIT_6.00.1x |
bb26d56cbce6d7f5d12bd9a2e5c428df6bf4b1d7 | fabfile.py | fabfile.py | import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be i... | import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be i... | Allow empty so we can force new build | Allow empty so we can force new build
| Python | bsd-3-clause | datamicroscopes/release,jzf2101/release,datamicroscopes/release,jzf2101/release |
5be4dec175c9e672ec5e7e011be604ad39459565 | apps/polls/admin.py | apps/polls/admin.py | from django.contrib import admin
from apps.polls.models import Poll, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['colla... | from django.contrib import admin
from apps.polls.models import Poll, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['colla... | Add date_hierarchy = 'pub_date' to PollAdmin | Add date_hierarchy = 'pub_date' to PollAdmin
| Python | bsd-3-clause | teracyhq/django-tutorial,datphan/teracy-tutorial |
143c0188566ac07ac3fdb9e6dfca8863cc169bbb | ts3observer/observer.py | ts3observer/observer.py | '''
Created on Nov 9, 2014
@author: fechnert
'''
import yaml
import logging
import features
class Configuration(dict):
''' Read and provide the yaml config '''
def __init__(self, path):
''' Initialize the file '''
with open(path, 'r') as f:
self.update(yaml.load(f))
class Supe... | '''
Created on Nov 9, 2014
@author: fechnert
'''
import yaml
import logging
import features
class Configuration(dict):
''' Read and provide the yaml config '''
def __init__(self, path):
''' Initialize the file '''
with open(path, 'r') as f:
self.update(yaml.load(f))
class Supe... | Add client and channel models | Add client and channel models
| Python | mit | HWDexperte/ts3observer |
1cab84d3f3726df2a7cfe4e5ad8efee81051c73e | tests/test_patched_stream.py | tests/test_patched_stream.py | import nose
import StringIO
import cle
def test_patched_stream():
stream = StringIO.StringIO('0123456789abcdef')
stream1 = cle.PatchedStream(stream, [(2, 'AA')])
stream1.seek(0)
nose.tools.assert_equal(stream1.read(), '01AA456789abcdef')
stream2 = cle.PatchedStream(stream, [(2, 'AA')])
strea... | import nose
import StringIO
import os
import cle
tests_path = os.path.join(os.path.dirname(__file__), '..', '..', 'binaries', 'tests')
def test_patched_stream():
stream = StringIO.StringIO('0123456789abcdef')
stream1 = cle.PatchedStream(stream, [(2, 'AA')])
stream1.seek(0)
nose.tools.assert_equal(st... | Add tests for loading binaries with malformed sections | Add tests for loading binaries with malformed sections
| Python | bsd-2-clause | angr/cle |
de2a2e296ba1cb60a333fc52fef39d260e5ad4e5 | tests/basics/unary_op.py | tests/basics/unary_op.py | x = 1
print(+x)
print(-x)
print(~x)
print(not None)
print(not False)
print(not True)
print(not 0)
print(not 1)
print(not -1)
print(not ())
print(not (1,))
print(not [])
print(not [1,])
print(not {})
print(not {1:1})
| x = 1
print(+x)
print(-x)
print(~x)
print(not None)
print(not False)
print(not True)
print(not 0)
print(not 1)
print(not -1)
print(not ())
print(not (1,))
print(not [])
print(not [1,])
print(not {})
print(not {1:1})
# check user instance
class A: pass
print(not A())
# check user instances derived from builtins
class... | Add test for "not" of a user defined class. | tests: Add test for "not" of a user defined class.
| Python | mit | lowRISC/micropython,Timmenem/micropython,lowRISC/micropython,drrk/micropython,PappaPeppar/micropython,ernesto-g/micropython,deshipu/micropython,pozetroninc/micropython,AriZuu/micropython,Peetz0r/micropython-esp32,AriZuu/micropython,jmarcelino/pycom-micropython,redbear/micropython,micropython/micropython-esp32,turbinenr... |
3bbfc62cb194c1c68ce24ffe9fa0732a0f00fd9c | test/664-raceway.py | test/664-raceway.py | # https://www.openstreetmap.org/way/28825404
assert_has_feature(
16, 10476, 25242, 'roads',
{ 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' })
# https://www.openstreetmap.org/way/59440900
# Thunderoad Speedway Go-carts
assert_has_feature(
16, 10516, 25247, 'roads',
{ 'id': 59440900, 'kind'... | # https://www.openstreetmap.org/way/28825404
assert_has_feature(
16, 10476, 25242, 'roads',
{ 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway', 'sort_key': 375 })
# https://www.openstreetmap.org/way/59440900
# Thunderoad Speedway Go-carts
assert_has_feature(
16, 10516, 25247, 'roads',
{ 'id':... | Add sort_key assertion to raceway tests | Add sort_key assertion to raceway tests
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
1e6a424e2669441e6910d3a2803bc139df16dd51 | new_validity.py | new_validity.py | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
def main(lta_name):
os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
di... | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
def main():
lta_file = str(argv[1])
calibrator_list = ['3C48', '3C147', '... | Add scratch file for testing new validity | Add scratch file for testing new validity
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu |
3ceb8bbcc6b5b43deae31a1c64331e86555eb601 | python/ql/test/library-tests/frameworks/cryptography/test_ec.py | python/ql/test/library-tests/frameworks/cryptography/test_ec.py | # see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa.html
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
private_key = ec.generate_private_key(curve=ec.SECP384R1()) # $ PublicKeyGenera... | # see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa.html
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
private_key = ec.generate_private_key(curve=ec.SECP384R1()) # $ PublicKeyGenera... | Add cryptography test for EC | Python: Add cryptography test for EC
Apparently, passing in the class (without instantiating it) is allowed
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql |
8bccbe0fdb3d6770ecbbe28528628f10988145bd | kitchen/dashboard/graphs.py | kitchen/dashboard/graphs.py | import os
import pydot
from kitchen.settings import STATIC_ROOT
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
for node in nodes:
label = node['name'] + "\n" + "\n".join(
[role for role in node['role'] if n... | import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
for node in nodes:
label = node['name'] + "\n" + "\n".join(
[role for role in node['role'... | Use the env prefix setting | Use the env prefix setting
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen |
9401ce692e8b0362e387cb5fb042f530edd2c0b3 | toolkit/models/models.py | toolkit/models/models.py | import arrow
from django.conf import settings
from django.db import models
from .mixins import ModelPermissionsMixin
class CCEModel(ModelPermissionsMixin, models.Model):
"""
Abstract base model with permissions mixin.
"""
class Meta:
abstract = True
class CCEAuditModel(CCEModel):
"""
... | from django.db import models
from django.utils.timezone import localtime
from .mixins import ModelPermissionsMixin
class CCEModel(ModelPermissionsMixin, models.Model):
"""
Abstract base model with permissions mixin.
"""
class Meta:
abstract = True
class CCEAuditModel(CCEModel):
"""
... | Update Timezone aware values for CCEAuditModel | Update Timezone aware values for CCEAuditModel
| Python | bsd-3-clause | cceit/cce-toolkit,cceit/cce-toolkit,cceit/cce-toolkit |
0958ec9188bc2017be576de62911e76247cbe45f | scikits/gpu/tests/test_fbo.py | scikits/gpu/tests/test_fbo.py | from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo =... | from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo =... | Test that framebuffer can't be bound after deletion. | Test that framebuffer can't be bound after deletion.
| Python | mit | certik/scikits.gpu,stefanv/scikits.gpu |
4eada6970d72b3863104790229286edf8d17720c | accelerator/tests/contexts/user_role_context.py | accelerator/tests/contexts/user_role_context.py | from builtins import object
from accelerator.tests.factories import (
ExpertFactory,
ProgramFactory,
ProgramRoleFactory,
ProgramRoleGrantFactory,
UserRoleFactory,
)
class UserRoleContext(object):
def __init__(self, user_role_name, program=None, user=None):
if user and not program:
... | from builtins import object
from accelerator.tests.factories import (
ExpertFactory,
ProgramFactory,
ProgramRoleFactory,
ProgramRoleGrantFactory,
UserRoleFactory,
)
from accelerator.models import UserRole
class UserRoleContext(object):
def __init__(self, user_role_name, program=None, user=No... | Make UserRoleContext safe to use | [AC-7397] Make UserRoleContext safe to use
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
85245f55fe430bfcf4946d2501394dad813a6591 | core/modules/html_has_same_domain.py | core/modules/html_has_same_domain.py | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
... | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
... | Add logic to check for cross-site anchor tags to naver | Add logic to check for cross-site anchor tags to naver
| Python | bsd-2-clause | mjkim610/phishing-detection,jaeyung1001/phishing_site_detection |
c0455de3061ba049ad9d501b85118f8ef4cd673c | peakachulib/tmm.py | peakachulib/tmm.py | import numpy as np
import pandas as pd
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
class TMM(object):
def __init__(self, count_df):
r("suppressMessages(library(edgeR))")
self.count_df = count_df
def calc_size_factors(self, method="TMM"):
# Convert pandas dataf... | import numpy as np
import pandas as pd
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
class TMM(object):
def __init__(self, count_df):
r("suppressMessages(library(edgeR))")
self.count_df = count_df
def calc_size_factors(self):
# Convert pandas dataframe to R dataframe
... | Fix TMM as normalization method from edgeR package | Fix TMM as normalization method from edgeR package
| Python | isc | tbischler/PEAKachu |
23f709e483bc7b0dfa15da8207ddc509715ebaa0 | petlib/__init__.py | petlib/__init__.py | # The petlib version
VERSION = '0.0.25' | # The petlib version
VERSION = '0.0.26'
def run_tests():
# These are only needed in case we test
import pytest
import os.path
import glob
# List all petlib files in the directory
petlib_dir = dir = os.path.dirname(os.path.realpath(__file__))
pyfiles = glob.glob(os.path.join(petlib_dir, '*.... | Make a petlib.run_tests() function that tests an install | Make a petlib.run_tests() function that tests an install
| Python | bsd-2-clause | gdanezis/petlib |
4ca953b2210c469e5d09bb03c66cbe0839959e49 | libvirt/libvirt_list_vms.py | libvirt/libvirt_list_vms.py | #!/usr/bin/python
import libvirt
import sys
conn=libvirt.open("qemu:///system")
if conn == None:
print('Failed to open connection to qemu:///system', sys.stderr)
exit(1)
#vms = conn.listDefinedDomains()
#print '\n'.join(vms)
vms = conn.listAllDomains(0)
if len(vms) != 0:
for vm in vms:
print(vm.n... | #!/usr/bin/python
import libvirt
import sys
def getConnection():
try:
conn=libvirt.open("qemu:///system")
return conn
except libvirt.libvirtError, e:
print e.get_error_message()
sys.exit(1)
def delConnection(conn):
try:
conn.close()
except:
print get_error_message()
sys.exit(1)
d... | Update script list domain libvirt | Update script list domain libvirt
| Python | apache-2.0 | skylost/heap,skylost/heap,skylost/heap |
e7a771011e93660c811effb8357df035bae8f9a6 | pentai/gui/settings_screen.py | pentai/gui/settings_screen.py | from kivy.uix.screenmanager import Screen
#from kivy.properties import *
from kivy.uix.settings import SettingSpacer
from my_setting import *
import audio as a_m
class SettingsScreen(Screen):
def __init__(self, *args, **kwargs):
super(SettingsScreen, self).__init__(*args, **kwargs)
def adjust_volumes... | from kivy.uix.screenmanager import Screen
#from kivy.properties import *
from kivy.uix.settings import SettingSpacer
from my_setting import *
import audio as a_m
from kivy.uix.widget import Widget
class HSpacer(Widget):
pass
class VSpacer(Widget):
pass
class SettingsScreen(Screen):
def __init__(self, *... | Use our own spacer widgets | Use our own spacer widgets
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai |
e42d38f9ad3f8b5229c9618e4dd9d6b371de89c5 | test/test_am_bmi.py | test/test_am_bmi.py | import unittest
import utils
import os
import sys
import shutil
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(TOPDIR, 'lib'))
sys.path.append(TOPDIR)
import cryptosite.am_bmi
class Tests(unittest.TestCase):
def test_get_sas(self):
"""Test get_sas() fu... | import unittest
import utils
import os
import sys
import shutil
import subprocess
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import cryptosite.am_bmi
class Tests(unittest.TestCase):
def test_get_sas(self):
"""Test get_sas() function"""
wi... | Test simple complete run of am_bmi. | Test simple complete run of am_bmi.
| Python | lgpl-2.1 | salilab/cryptosite,salilab/cryptosite,salilab/cryptosite |
291ae1ae359b7985f25c4d32ee31ff6ccbc6eb7d | curious/commands/__init__.py | curious/commands/__init__.py | # This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious is distributed in the ho... | # This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious is distributed in the ho... | Add ratelimit and help to autosummary. | Add ratelimit and help to autosummary.
Signed-off-by: Laura F. D <07c342be6e560e7f43842e2e21b774e61d85f047@veriny.tf>
| Python | mit | SunDwarf/curious |
f8640410f4271b22a2836d9fe4f5d09b28c7b19c | angr/storage/memory_mixins/regioned_memory/abstract_merger_mixin.py | angr/storage/memory_mixins/regioned_memory/abstract_merger_mixin.py | import logging
from typing import Iterable, Tuple, Any
from .. import MemoryMixin
l = logging.getLogger(name=__name__)
class AbstractMergerMixin(MemoryMixin):
def _merge_values(self, values: Iterable[Tuple[Any,Any]], merged_size: int):
if self.category == 'reg' and self.state.arch.register_endness == ... | import logging
from typing import Iterable, Tuple, Any
from .. import MemoryMixin
l = logging.getLogger(name=__name__)
class AbstractMergerMixin(MemoryMixin):
def _merge_values(self, values: Iterable[Tuple[Any,Any]], merged_size: int):
# if self.category == 'reg' and self.state.arch.register_endness =... | Remove reversing heuristics from merge_values for abstract memory. | Remove reversing heuristics from merge_values for abstract memory.
This is because SimMemoryObject handles endness now.
Also re-introduce the logic for dealing with uninit memory values.
| Python | bsd-2-clause | angr/angr,angr/angr,angr/angr |
c1e9d369680e779d481aa7db17be9348d56ec29d | test_linked_list.py | test_linked_list.py | from __future__ import unicode_literals
import linked_list
# def func(x):
# return x + 1
# def tdest_answer():
# assert func(3) == 5
# init
a = linked_list.LinkedList()
def test_size():
assert a.size is 0
def test_head():
assert a.head is None
def test_init():
assert type(a) is linked_lis... | """Pytest file for linked_list.py
Run this with the command 'py.test test_linked_list.py'
"""
from __future__ import unicode_literals
import linked_list
import copy
# init method
a = linked_list.LinkedList()
def test_init_size():
assert a.sizeOfList is 0
assert type(a.sizeOfList) is int
def test_init_... | Add comments to test file | Add comments to test file
Add comments after all tests passed
| Python | mit | jesseklein406/data-structures |
7c68a78a81721ecbbda0f999576b91b803a34a3e | .circleci/get-commit-range.py | .circleci/get-commit-range.py | #!/usr/bin/env python3
import os
import argparse
from github import Github
def from_pr(project, repo, pr_number):
gh = Github()
pr = gh.get_repo(f'{project}/{repo}').get_pull(pr_number)
base = pr.base.ref
head = pr.head.ref
return f'origin/{base}...{head}'
def main():
argparser = argparse.Ar... | #!/usr/bin/env python3
import os
import argparse
from github import Github
def from_pr(project, repo, pr_number):
gh = Github()
pr = gh.get_repo(f'{project}/{repo}').get_pull(pr_number)
base = pr.base.sha
head = pr.base.sha
return f'{base}...{head}'
def main():
argparser = argparse.ArgumentP... | Use SHAs for commit_range rather than refs | Use SHAs for commit_range rather than refs
Refs are local and might not always be present in the checkout.
| Python | bsd-3-clause | ryanlovett/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub,ryanlovett/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub |
93d9ae1275aa6f40f3ad4a63b6919eb3eaaf6cf8 | nimble/sources/elementary.py | nimble/sources/elementary.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..composition import SeekableSource
import numpy as np
class IntegerIdentitySource(SeekableSource):
"""Return the integer used as position argument."""
def __init__(self, size=np.iinfo(np.uint32).max, **kwargs):
self.parallel_possi... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..composition import SeekableSource
import numpy as np
class IntegerIdentitySource(SeekableSource):
"""Return the integer used as position argument."""
def __init__(self, size=np.iinfo(np.uint32).max, **kwargs):
self.parallel_possi... | Set identity integer source data type | Set identity integer source data type
| Python | mit | risteon/nimble |
6d507595b0e51ed4a366c3288eec808ac91e30bc | pyinfra/modules/virtualenv.py | pyinfra/modules/virtualenv.py | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python='python3', site_packages=False, alw... | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python='python3', site_packages=False, alw... | Fix no yield from in middle ages | Fix no yield from in middle ages
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
6d567ad3eb7749692b05a7685ffbd99f74d965cd | manage.py | manage.py | import os
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask.ext.migrate import MigrateCommand
from flask_security.utils import encrypt_password
from service.models import *
from service import app
from service import db
from service import user_datastore
app.config.from_object(os... | import os
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask.ext.migrate import MigrateCommand
from flask_security.utils import encrypt_password
from service.models import *
from service import app
from service import db
from service import user_datastore
app.config.from_object(os... | Fix create user command to work locally and on heroku | Fix create user command to work locally and on heroku
| Python | mit | LandRegistry/service-frontend-alpha,LandRegistry/service-frontend-alpha,LandRegistry/service-frontend-alpha,LandRegistry/service-frontend-alpha,LandRegistry/service-frontend-alpha |
d1e0949533ad30e2cd3e5afccbf59d835c1b0fe3 | doc/examples/plot_entropy.py | doc/examples/plot_entropy.py | """
=======
Entropy
=======
Image entropy is a quantity which is used to describe the amount of information
coded in an image.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
from skimage.util import img_as_ub... | """
=======
Entropy
=======
Image entropy is a quantity which is used to describe the amount of information
coded in an image.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
from skimage.util import img_as_ub... | Update entropy example with improved matplotlib usage | Update entropy example with improved matplotlib usage
| Python | bsd-3-clause | dpshelio/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,oew1v07/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,bsipocz/scikit-image,jwiggins/scikit-image,michaelpacer/scikit-image,almarklein/scikit-image,... |
411b594c7d363f68555a97fccff92a43392d0d04 | webshop/core/util.py | webshop/core/util.py | # Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop 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 Free Software Foundation; either version 2, or (at... | # Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop 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 Free Software Foundation; either version 2, or (at... | Make sure we have actually looked up a model in get_model_from_string. | Make sure we have actually looked up a model
in get_model_from_string.
| Python | agpl-3.0 | dokterbob/django-shopkit,dokterbob/django-shopkit |
aa94c28835a67ca000226eb30bdbb0ef852383c5 | jshbot/configurations.py | jshbot/configurations.py | import json
from jshbot.exceptions import ConfiguredBotException, ErrorTypes
CBException = ConfiguredBotException('Configurations')
def get(bot, plugin_name, key=None, extra=None, extension='json'):
"""Gets the configuration file for the given plugin.
Keyword arguments:
key -- Gets the specified key fr... | import json
import yaml
from jshbot.exceptions import ConfiguredBotException, ErrorTypes
CBException = ConfiguredBotException('Configurations')
def get(bot, plugin_name, key=None, extra=None, extension='yaml'):
"""Gets the configuration file for the given plugin.
Keyword arguments:
key -- Gets the spec... | Change default extension to yaml | Change default extension to yaml
| Python | mit | jkchen2/JshBot,jkchen2/JshBot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.