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 |
|---|---|---|---|---|---|---|---|---|---|
3b71f6600d437a4e5f167315683e7f0137cd3788 | tilenol/xcb/keysymparse.py | tilenol/xcb/keysymparse.py | import os
import re
keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)")
class Keysyms(object):
__slots__ = ('name_to_code', 'code_to_name', '__dict__')
def __init__(self):
self.name_to_code = {}
self.code_to_name = {}
def add_from_file(self, filename):
with open(filena... | import os
import re
import logging
log = logging.getLogger(__name__)
keysym_re = re.compile(
r"^#define\s+(XF86)?XK_(\w+)\s+"
r"(?:(0x[a-fA-F0-9]+)|_EVDEV\((0x[0-9a-fA-F]+)\))"
)
class Keysyms(object):
__slots__ = ('name_to_code', 'code_to_name', '__dict__')
def __init__(self):
self.name_to_... | Fix support of fresh keysym file | Fix support of fresh keysym file
| Python | mit | tailhook/tilenol,tailhook/tilenol |
0a718ccee8301f28e86791e06159e6ed8a2674b4 | twobuntu/articles/forms.py | twobuntu/articles/forms.py | from django import forms
from twobuntu.articles.models import Article, ScheduledArticle
class EditorForm(forms.ModelForm):
"""
Form for entering or editing articles.
"""
class Meta:
model = Article
fields = ('category', 'title', 'body')
class ScheduledArticleForm(forms.ModelForm):
... | from django import forms
from twobuntu.articles.models import Article, ScheduledArticle
class EditorForm(forms.ModelForm):
"""
Form for entering or editing articles.
"""
# The <textarea> needs this set so that the form can validate on the client
# side without any content (due to ACE editor)
... | Fix error submitting article caused by extra HTML attribute. | Fix error submitting article caused by extra HTML attribute.
| Python | apache-2.0 | 2buntu/2buntu-blog,2buntu/2buntu-blog,2buntu/2buntu-blog |
e12a4504da0b40ad66e116aa9a0373d1abc6d160 | mongo_test/handlers.py | mongo_test/handlers.py | import subprocess
import commands
import re
import signal
import os
import logging
_logger = logging.getLogger(__name__)
TARGET_DIR='test/target'
PORT='27018'
def startup():
_logger.info("about to start mongod")
p = subprocess.Popen([commands.getoutput('which mongod'),
'--port', PORT,
'--fork... | import subprocess
import commands
import signal
import os
import logging
_logger = logging.getLogger(__name__)
TARGET_DIR='test/target'
PORT='27018'
def startup(mongo_path):
_logger.info("about to start mongod")
path = mongo_path or commands.getoutput('which mongod')
p = subprocess.Popen([path,
'... | Allow the option of specifying a path in startup | Allow the option of specifying a path in startup
| Python | mit | idbentley/MongoTest |
cf8b49edfc38a98b4f6beba66bedcc13298eb114 | yunity/utils/tests/mock.py | yunity/utils/tests/mock.py | from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory
from yunity.models import Category
from yunity.utils.tests.fake import faker
class Mock(DjangoModelFactory):
class Meta:
strategy = CREATE_STRATEGY
model = None
abstract = True
class Mock... | from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory
from yunity.models import Category
from yunity.utils.tests.fake import faker
class Mock(DjangoModelFactory):
class Meta:
strategy = CREATE_STRATEGY
model = None
abstract = True
class Mock... | Rename some variables to try to explain magic | Rename some variables to try to explain magic
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core |
bc9f4d4e5022f4219727e9085164982f9efb005e | editor/views/generic.py | editor/views/generic.py | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
... | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
... | Set the git author name and e-mail | Set the git author name and e-mail
| Python | apache-2.0 | numbas/editor,numbas/editor,numbas/editor |
7b8ba30efc8853ab19dfd95a97f56c8329ddfb4b | newsParser/__init__.py | newsParser/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-11-01 21:02:00
# @Last Modified by: balicanta
# @Last Modified time: 2014-11-01 21:02:00
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-11-01 21:02:00
# @Last Modified by: balicanta
# @Last Modified time: 2014-11-05 22:19:01
from NewsParser import NewsParser
| Add initi for beautiful API | Add initi for beautiful API
| Python | mit | Lab-317/NewsParser |
e15484bc57b47513545b2be423f24d4dd0312590 | comics/management/commands/generatesecretkey.py | comics/management/commands/generatesecretkey.py | from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Genera... | from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Genera... | Fix some characters messing up the SECRET_KEY | Fix some characters messing up the SECRET_KEY
| Python | mit | Tenma-Server/Tenma,hmhrex/Tenma,Tenma-Server/Tenma,hmhrex/Tenma,Tenma-Server/Tenma,hmhrex/Tenma |
e3c7322b0efe10041ba9c38963b9e9f188d9a54a | pkit/slot/decorators.py | pkit/slot/decorators.py | import functools
from pkit.slot import get_slot_pool
def acquire(pool_name):
"""Actor's method decorator to auto-acquire a slot before execution"""
def decorator(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
slots_pool = get_slot_pool(pool_name)
... | import functools
from pkit.slot import get_slot_pool
def acquire(pool_name):
"""Actor's method decorator to auto-acquire a slot before execution"""
def decorator(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
slots_pool = get_slot_pool(pool_name)
... | Fix slot release on method exception | Fix slot release on method exception
| Python | mit | botify-labs/process-kit |
e567b70608d25a4f3e0e189ea51edb2c4f0aa2be | cronos/libraries/log.py | cronos/libraries/log.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.mail import send_mail
import logging
#import traceback
def cronos_debug(msg, logfile):
'''
To be deprecated, along with the import logging and settings
'''
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s: %(mess... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.mail import send_mail
def mail_cronos_admin(title, message):
'''
Wrapper function of send_mail
'''
try:
send_mail(title, message, 'notification@cronos.teilar.gr', [settings.ADMIN[0][1]])
except:
pass
class C... | Remove cronos_debug, un-hardcode the mail address in mail_cronos_admin | Remove cronos_debug, un-hardcode the mail address in mail_cronos_admin
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr |
06d0f52608f79f675847e903577e20be03189041 | django_any/forms.py | django_any/forms.py | # -*- coding: utf-8 -*-
"""
Django forms data generators
"""
from django import forms
from django_any import xunit
class FormFieldDataFactory(object):
def __init__(self):
self.registry = {}
def register(self, field_type, impl=None):
def _wrapper(func):
self.registry[field_type] = ... | # -*- coding: utf-8 -*-
"""
Django forms data generators
"""
from django import forms
from django_any import xunit
class FormFieldDataFactory(object):
"""
Registry storage for form field data functions
Works like one parameter multimethod
"""
def __init__(self):
self.registry = {}
de... | Fix some pylint found errors and warnings | Fix some pylint found errors and warnings
| Python | mit | kmmbvnr/django-any,abakar/django-whatever,abakar/django-whatever |
6dcbc85b59bd9cc7eed381c7ef0efeb2f78620cf | comics/comics/whomp.py | comics/comics/whomp.py | import re
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Whomp!"
language = "en"
url = "http://www.whompcomic.com/"
start_date = "2010-06-14"
rights = "Ronnie Filyaw"
class Crawler(CrawlerB... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Whomp!"
language = "en"
url = "http://www.whompcomic.com/"
start_date = "2010-06-14"
rights = "Ronnie Filyaw"
class Crawler(CrawlerBase):
h... | Rewrite crawler for "Whomp!" after feed change | Rewrite crawler for "Whomp!" after feed change
| Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics |
1224e7e2f12b455ffa1f8c102b30012d63716cae | flask_bracket/errors.py | flask_bracket/errors.py | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
... | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
... | Remove redundant status code from error response body. | Remove redundant status code from error response body.
| Python | bsd-3-clause | JsonChiu/flask-bracket |
4029da285fff38524cd30212475868ccda457df6 | pylibscrypt/__init__.py | pylibscrypt/__init__.py | 'Scrypt for Python'
__version__ = '1.1.0'
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, try the scrypt module
if not _done:
try:
from pyscrypt import *
except ImportError:
pass
els... | """Scrypt for Python"""
__version__ = '1.2.0-git'
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, try the scrypt module
if not _done:
try:
from pyscrypt import *
except ImportError:
pass... | Increment version number for git master | Increment version number for git master
| Python | isc | jvarho/pylibscrypt,jvarho/pylibscrypt |
efc9013bff8251fc910ecb70d546a8508ed0f7ec | tests/race_deleting_keys_test.py | tests/race_deleting_keys_test.py | import time as _time
import subprocess
import sys
import redisdl
import unittest
import json
import os.path
from . import util
from . import big_data
class RaceDeletingKeysTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
... | import nose.plugins.attrib
import time as _time
import subprocess
import sys
import redisdl
import unittest
import json
import os.path
from . import util
from . import big_data
@nose.plugins.attrib.attr('slow')
class RaceDeletingKeysTest(unittest.TestCase):
def setUp(self):
import redis
self.r = re... | Mark test slow via nose attrib plugin | Mark test slow via nose attrib plugin
| Python | bsd-2-clause | p/redis-dump-load,hyunchel/redis-dump-load,hyunchel/redis-dump-load,p/redis-dump-load |
ac7e966e22c9919ef3b3235ee2c69ee30d83c41f | test.py | test.py | import subprocess
import unittest
class CompareErrorMessages(unittest.TestCase):
def test_missing_file_return_code_the_same_as_ls(self):
args = ['./lss.sh', 'foo']
ret = subprocess.call(args)
args2 = ['ls', 'foo']
ret2 = subprocess.call(args2)
self.assertEqual(ret == 0, ret2... | import subprocess
import unittest
class CompareErrorMessages(unittest.TestCase):
def test_missing_file_return_code_the_same_as_ls(self):
args = ['./lss.sh', 'foo']
ret = subprocess.call(args)
args2 = ['ls', 'foo']
ret2 = subprocess.call(args2)
self.assertEqual(ret == 0, ret2... | Move retrieving output into method. | Move retrieving output into method.
| Python | bsd-3-clause | jwg4/les,jwg4/les |
d73492a62e5ddc1eb85f4b17a6a0e6ce88410070 | infosystem/scheduler.py | infosystem/scheduler.py | from apscheduler.schedulers.background import BackgroundScheduler
class Scheduler(BackgroundScheduler):
def __init__(self):
super().__init__()
self.start()
def schedule(self, callback, **kwargs):
self.add_job(callback, 'cron', **kwargs)
| from apscheduler.schedulers.background import BackgroundScheduler
class Scheduler(BackgroundScheduler):
def __init__(self):
super().__init__()
self.start()
def schedule(self, callback, **kwargs):
self.add_job(callback, 'cron', **kwargs)
def hourly(self, callback, minute=0):
... | Add hourly, daily, weelky and monthly sched helpers | Add hourly, daily, weelky and monthly sched helpers
| Python | apache-2.0 | samueldmq/infosystem |
86a357e9a954348aa59626a37d61fdb43c143142 | src/constants.py | src/constants.py | #!/usr/bin/env python
TRAJECTORY = 'squared'
CONTROLLER = 'pid'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075
MAX_... | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075
MAX_W... | Create constant to store path for results | Create constant to store path for results
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking |
6477768e3040ed43fb10072730b84c29bef1e949 | continuate/__init__.py | continuate/__init__.py | # -*- coding: utf-8 -*-
import importlib
__all__ = ["linalg", "single_parameter"]
for m in __all__:
importlib.import_module("continuate." + m)
| # -*- coding: utf-8 -*-
import importlib
import os.path as op
from glob import glob
__all__ = [op.basename(f)[:-3]
for f in glob(op.join(op.dirname(__file__), "*.py"))
if op.basename(f) != "__init__.py"]
for m in __all__:
importlib.import_module("continuate." + m)
| Change manual listing of submodules to automatic | Change manual listing of submodules to automatic
| Python | mit | termoshtt/continuate |
48a2eb277d234219dd116d9a0dec5a559b22aff8 | app/main/services/process_request_json.py | app/main/services/process_request_json.py | import types
from query_builder import FILTER_FIELDS, TEXT_FIELDS
from conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, types.ListType):
fixed = []
for i in values:
fixed.append(strip_and_lo... | from query_builder import FILTER_FIELDS, TEXT_FIELDS
from conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, list):
return [strip_and_lowercase(value) for value in values]
elif isinstance(values, basestring):... | Refactor argument processing to list comprehension | Refactor argument processing to list comprehension
| Python | mit | RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api |
33a4f91981373b284e005b245d19fae0000f9201 | pontoon/administration/management/commands/update_projects.py | pontoon/administration/management/commands/update_projects.py |
import datetime
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.utils.files import (
update_from_repository,
extract_to_database,
)
from pontoon.base.models import Project
class Command(BaseCommand):
help = 'Update all projects from their repositories and ... |
import datetime
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.utils.files import (
update_from_repository,
extract_to_database,
)
from pontoon.base.models import Project
class Command(BaseCommand):
args = '<project_id project_id ...>'
help = 'Update ... | Allow specifying which project to udpate with the management command | Allow specifying which project to udpate with the management command
| Python | bsd-3-clause | m8ttyB/pontoon,mozilla/pontoon,mastizada/pontoon,mastizada/pontoon,sudheesh001/pontoon,Jobava/mirror-pontoon,mozilla/pontoon,Osmose/pontoon,sudheesh001/pontoon,yfdyh000/pontoon,mozilla/pontoon,m8ttyB/pontoon,mathjazz/pontoon,participedia/pontoon,mastizada/pontoon,mathjazz/pontoon,sudheesh001/pontoon,Osmose/pontoon,mozi... |
052de49807dcb9895608e3882b799642b0b08d18 | exercises/circular-buffer/circular_buffer.py | exercises/circular-buffer/circular_buffer.py | class BufferFullException(Exception):
pass
class BufferEmptyException(Exception):
pass
class CircularBuffer(object):
def __init__(self):
pass
| class BufferFullException(Exception):
pass
class BufferEmptyException(Exception):
pass
class CircularBuffer(object):
def __init__(self, capacity):
pass
| Add parameter capacity to circular-buffer example | Add parameter capacity to circular-buffer example
Fixes #550 | Python | mit | jmluy/xpython,mweb/python,mweb/python,pheanex/xpython,exercism/xpython,jmluy/xpython,exercism/xpython,smalley/python,behrtam/xpython,behrtam/xpython,exercism/python,N-Parsons/exercism-python,exercism/python,N-Parsons/exercism-python,pheanex/xpython,smalley/python |
095f2a78416b12f23b4f59d6415103bd4873a86b | project/tenhou/main.py | project/tenhou/main.py | # -*- coding: utf-8 -*-
import logging
from tenhou.client import TenhouClient
from utils.settings_handler import settings
logger = logging.getLogger('tenhou')
def connect_and_play():
logger.info('Bot AI enabled: {}'.format(settings.ENABLE_AI))
client = TenhouClient()
client.connect()
try:
... | # -*- coding: utf-8 -*-
import logging
from tenhou.client import TenhouClient
from utils.settings_handler import settings
logger = logging.getLogger('tenhou')
def connect_and_play():
logger.info('Bot AI enabled: {}'.format(settings.ENABLE_AI))
client = TenhouClient()
client.connect()
try:
... | Handle unexpected errors and store stack trace to the log | Handle unexpected errors and store stack trace to the log
| Python | mit | MahjongRepository/tenhou-python-bot,huangenyan/Lattish,huangenyan/Lattish,MahjongRepository/tenhou-python-bot |
1f5ee2f729b947a31ab2b04a72ae8c40616db73a | tests/test_plugin_states.py | tests/test_plugin_states.py | from contextlib import contextmanager
from os import path
from unittest import TestCase
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd_packages import six
from canaryd.plugin import get_plugin_by_name
class TestPluginRealStates(TestCase):
def test_meta_plugin(self... | from contextlib import contextmanager
from os import path
from unittest import TestCase
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd_packages import six
from canaryd.plugin import get_plugin_by_name
from canaryd.settings import CanarydSettings
class TestPluginRealSt... | Fix tests by passing default settings object rather than empty dict. | Fix tests by passing default settings object rather than empty dict.
| Python | mit | Oxygem/canaryd,Oxygem/canaryd |
19a508aad7c42469923c6f62acef67113e280501 | memefarm/imagesearch.py | memefarm/imagesearch.py | import json
import os
import random
import requests
from PIL import Image
# GLOBALS
endpoint = "https://www.googleapis.com/customsearch/v1"
searchid = "013060195084513904668:z7-hxk7q35k"
# Retrieve my API key from a secret file
with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"), "r") as f:
API_KE... | import json
import os
import random
import requests
from io import BytesIO
from PIL import Image
# GLOBALS
endpoint = "https://www.googleapis.com/customsearch/v1"
searchid = "013060195084513904668:z7-hxk7q35k"
# Retrieve my API key from a secret file
with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"),... | Add method for getting PIL image | Add method for getting PIL image
Also change function names to be uniform throughout
| Python | mit | The-Penultimate-Defenestrator/memefarm |
f6a65fb602fb13c01ad2d9ee7cf50415df9ffa7e | sparkback/__init__.py | sparkback/__init__.py | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == ... | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == ... | Update command line interface to accept floating point input | Update command line interface to accept floating point input
| Python | mit | mmichie/sparkback |
f5c1255739fa50218af066f2bf690cc46424a38d | main.py | main.py | from crawlers.one337x import One337x
if __name__ == '__main__':
crawler = One337x()
torrents = list(crawler.fetch_torrents('arrow'))
| from crawlers.one337x import One337x
from flask import Flask, request, Response
from jsonpickle import encode
app = Flask(__name__)
app.secret_key = '\xb0\xf6\x86K\x0c d\x15\xfc\xdd\x96\xf5\t\xa5\xba\xfb6\x1am@\xb2r\x82\xc1'
@app.route('/')
def index():
data = {"message": 'Welcome to osprey'}
json_str = encod... | Add API layer using Flask :dancers: | Add API layer using Flask :dancers:
| Python | mit | fayimora/osprey,fayimora/osprey,fayimora/osprey |
062c46ca8b83dd7791cfed1305c2ba58872601af | go/api/views.py | go/api/views.py | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.api.go_api import client
import logging
logger = logging.getLogger(__name__)
@login_required
@csr... | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.api.go_api import client
import logging
logger = logging.getLogger(__name__)
@login_required
@csr... | Add explanatory docstring for the purpose of the go api proxy view | Add explanatory docstring for the purpose of the go api proxy view
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
fa2ac624bc33add0e88f158c525885eef8bf555b | user_management/models/tests/factories.py | user_management/models/tests/factories.py | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
| import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
@classmethod
def _prepare(cl... | Improve password handling in UserFactory. | Improve password handling in UserFactory.
| Python | bsd-2-clause | incuna/django-user-management,incuna/django-user-management |
4de18ece5ac2f563c6d8a6a247a77cdc8a45881e | hydromet/anomaly.py | hydromet/anomaly.py | def get_monthly_anomaly(ts, start, end):
"""
Get monthly anomaly.
Monthly anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to monthly.
:type ts: pandas.TimeSeries
:param start: Start da... | def get_monthly_anomaly(ts, start, end):
"""
Get monthly anomaly.
Monthly anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to monthly.
:type ts: pandas.TimeSeries
:param start: Start da... | Use start of month/year dates instead of end. | Use start of month/year dates instead of end.
| Python | bsd-3-clause | amacd31/hydromet-toolkit,amacd31/hydromet-toolkit |
86197635800e6b19a6b95e9be932999c79042720 | dipy/utils/arrfuncs.py | dipy/utils/arrfuncs.py | """ Utilities to manipulate numpy arrays """
import sys
import numpy as np
from nibabel.volumeutils import endian_codes, native_code, swapped_code
def as_native_array(arr):
""" Return `arr` as native byteordered array
If arr is already native byte ordered, return unchanged. If it is opposite
endian, ... | """ Utilities to manipulate numpy arrays """
import sys
import numpy as np
from nibabel.volumeutils import endian_codes, native_code, swapped_code
def as_native_array(arr):
""" Return `arr` as native byteordered array
If arr is already native byte ordered, return unchanged. If it is opposite
endian, ... | Add vectorized version of np.linalg.pinv | Add vectorized version of np.linalg.pinv
| Python | bsd-3-clause | matthieudumont/dipy,JohnGriffiths/dipy,FrancoisRheaultUS/dipy,matthieudumont/dipy,StongeEtienne/dipy,villalonreina/dipy,FrancoisRheaultUS/dipy,JohnGriffiths/dipy,nilgoyyou/dipy,villalonreina/dipy,nilgoyyou/dipy,StongeEtienne/dipy |
49a182c2b6b7c5e5a7be8452d1ccc262b0d45782 | delphi/urls.py | delphi/urls.py | """delphi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | """delphi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | Add url for static files | Add url for static files [development]
| Python | mit | VulcanoAhab/delphi,VulcanoAhab/delphi,VulcanoAhab/delphi |
612a411d0d4b2323bcbb3c3bdd41df945a075f53 | tree.py | tree.py | import verify
class Tree:
def __init__(self, elements):
self._elements = elements
def count(self):
return len(self._elements)
def elements(self):
result = []
for element in self._elements:
if element.__class__ == Tree:
result += [element.elements()]
else:
result += [... | import verify
import tokenizer
class Tree:
def __init__(self, elements):
self._elements = elements
def count(self):
return len(self._elements)
def elements(self):
result = []
for element in self._elements:
if element.__class__ == Tree:
result += [element.elements()]
else:
... | Switch from scanner to tokenizer. | Switch from scanner to tokenizer.
| Python | apache-2.0 | jkingdon/jh2gh |
1c60efdf0b0e2c1b49024ab14b8c012a1acaa71d | saw/filters/__init__.py | saw/filters/__init__.py | import os
import glob
import inspect
import saw.items
curr_path = os.path.dirname(__file__)
__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(curr_path + "/*.py")]
class Filter:
_filters = dict()
@classmethod
def _load_filters(self):
module_names = [ name.lower() for name in __all__ if name... | import os
import glob
import inspect
curr_path = os.path.dirname(__file__)
__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(curr_path + "/*.py")]
class Filter:
_filters = dict()
@classmethod
def _load_filters(self):
module_names = [ name.lower() for name in __all__ if name != '__init__' ]
... | Add support another classes for filters, not only Item and Items | Add support another classes for filters, not only Item and Items
| Python | mit | diNard/Saw |
2bde683bcfbdc7149a114abd609a3c91c19cac0f | tagcache/lock.py | tagcache/lock.py | # -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, write=False, block=False):
try:
lock_flags = fcntl.LOCK_EX if write else fcntl.LOCK_SH
... | # -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, ex=False, nb=True):
"""
Acquire a lock on the fd.
:param ex (optional): default False, acquire a... | Change parameter names in acquire. Add some doc. | Change parameter names in acquire.
Add some doc.
| Python | mit | huangjunwen/tagcache |
ca5877d66698179a3c26d12938dfac10cd19d932 | paci/commands/search.py | paci/commands/search.py | """The search command."""
from paci.helpers import display_helper, cache_helper
from .base import Base
class Search(Base):
"""Searches for a package!"""
def run(self):
pkg_name = self.options["<package>"]
result = cache_helper.find_pkg(pkg_name, self.settings["paci"]["registry"], self.repo_c... | """The search command."""
from paci.helpers import display_helper, cache_helper, std_helper
from termcolor import colored
from .base import Base
class Search(Base):
"""Searches for a package!"""
def run(self):
pkg_name = self.options["<package>"]
result = cache_helper.find_pkg(pkg_name, self... | Add a description of what the output represents | Add a description of what the output represents
| Python | mit | tradebyte/paci,tradebyte/paci |
78c100ac31c00f4b1c90eb897df2fd5062bf4b0f | tenant/models.py | tenant/models.py | from django.db import models
from django.conf import settings
from tenant.utils import parse_connection_string
from tenant.utils import connect_tenant_provider, disconnect_tenant_provider
from tenant import settings as tenant_settings
class Tenant(models.Model):
name = models.CharField(max_length=256, unique=Tru... | from django.db import models
from django.conf import settings
from tenant.utils import parse_connection_string
from tenant.utils import connect_tenant_provider, disconnect_tenant_provider
from tenant import settings as tenant_settings
class Tenant(models.Model):
created = models.DateTimeField(auto_now_add=True)
... | Add created and is_active field to match appschema model | Add created and is_active field to match appschema model
| Python | bsd-3-clause | allanlei/django-multitenant |
402e9c8f5d25ac4f9011176d3714193e6fe92c77 | linkcheck/management/commands/unignore_links.py | linkcheck/management/commands/unignore_links.py | from django.core.management.base import BaseCommand
from linkcheck.utils import unignore
class Command(BaseCommand):
help = "Goes through all models registered with Linkcheck and records any links found"
def execute(self, *args, **options):
print("Unignoring all links")
unignore()
| from django.core.management.base import BaseCommand
from linkcheck.utils import unignore
class Command(BaseCommand):
help = "Updates the `ignore` status of all links to `False`"
def execute(self, *args, **options):
print("Unignoring all links")
unignore()
| Fix help text of unignore command | Fix help text of unignore command
| Python | bsd-3-clause | DjangoAdminHackers/django-linkcheck,DjangoAdminHackers/django-linkcheck |
b618912444a1f30423432347c1ae970f28799bea | astroquery/dace/tests/test_dace_remote.py | astroquery/dace/tests/test_dace_remote.py | import unittest
from astropy.tests.helper import remote_data
from astroquery.dace import Dace
HARPS_PUBLICATION = '2009A&A...493..639M'
@remote_data
class TestDaceClass(unittest.TestCase):
def test_should_get_radial_velocities(self):
radial_velocities_table = Dace.query_radial_velocities('HD40307')
... | import unittest
from astropy.tests.helper import remote_data
from astroquery.dace import Dace
HARPS_PUBLICATION = '2009A&A...493..639M'
@remote_data
class TestDaceClass(unittest.TestCase):
def test_should_get_radial_velocities(self):
radial_velocities_table = Dace.query_radial_velocities('HD40307')
... | Add comment to explain the test with HARPS instrument | Add comment to explain the test with HARPS instrument
| Python | bsd-3-clause | imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery |
41eb6c371bb334acac25f5b89be1bb3312d77cc1 | examples/img_client.py | examples/img_client.py | #!/usr/bin/env python
"""
This example demonstrates a client fetching images from a server running img_server.py.
The first packet contains the number of chunks to expect, and then that number of chunks is read.
Lost packets are not handled in any way.
"""
from nuts import UDPAuthChannel
channel = UDPAu... | #!/usr/bin/env python
"""
This example demonstrates a client fetching images from a server running img_server.py.
The first packet contains the number of chunks to expect, and then that number of chunks is read.
Lost packets are not handled in any way.
"""
from nuts import UDPAuthChannel
channel = UDPAu... | Write .msg of chunk to file | Write .msg of chunk to file
| Python | mit | thusoy/nuts-auth,thusoy/nuts-auth |
3156cfcfb4bd642fe742bb36909e7b9b87e15963 | jesusmtnez/python/koans/koans/triangle.py | jesusmtnez/python/koans/koans/triangle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | Complete 'About Triangle Project 2' koans | [Python] Complete 'About Triangle Project 2' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
2261a15132a0b98821cb3e5614c044f1b41fbc73 | smsgateway/__init__.py | smsgateway/__init__.py | __version__ = '2.0.0'
def get_account(using=None):
from django.conf import settings
accounts = settings.SMSGATEWAY_ACCOUNTS
if using is not None:
return accounts[using]
else:
return accounts[accounts['__default__']]
def send(to, msg, signature, using=None, reliable=False):
"""
... | __version__ = '2.0.0'
def get_account(using=None):
from django.conf import settings
accounts = settings.SMSGATEWAY_ACCOUNTS
if using is not None:
return accounts[using]
else:
return accounts[accounts['__default__']]
def send(to, msg, signature, using=None, reliable=False):
"""
... | Add priority option to send_queued | Add priority option to send_queued
| Python | bsd-3-clause | peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway |
cf0033ee371925218237efdb613bcd312c0faefa | forms.py | forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, PasswordField, HiddenField
from wtforms.validators import DataRequired, Length, URL, Optional
class LoginForm(FlaskForm):
username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'})
password = Passwor... | from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, PasswordField, HiddenField
from wtforms.validators import DataRequired, Length, URL, Optional
class LoginForm(FlaskForm):
username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'})
password = Passwor... | Add 'newusername' id to username on signup page | Add 'newusername' id to username on signup page
Needed for js frontend.
| Python | mit | tortxof/flask-password,tortxof/flask-password,tortxof/flask-password |
0613c115f0ffccda8c6de9021c44d11085d84a1b | simplesqlite/_logger.py | simplesqlite/_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import logbook
logger = logbook.Logger("SimpleSQLie")
logger.disable()
def set_logger(is_enable):
if is_enable:
logger.enable()
else:
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
import logbook
import pytablereader
logger = logbook.Logger("SimpleSQLie")
logger.disable()
def set_logger(is_enable):
if is_ena... | Modify to avoid excessive logger initialization | Modify to avoid excessive logger initialization
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite |
7bc2d9f96a5e5bb677e8ea17bebe22516d78243c | index.py | index.py | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def load_data(dir_doc):
docs = {}
for dirpath, dirnames, filenames in os.walk(dir_doc):
for name in filenames:
file = os.path.join(dirpath, name)
with io.open(file, 'r+') as f:
docs[name] = f.read()
retu... | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def load_data(dir_doc):
docs = {}
for dirpath, dirnames, filenames in os.walk(dir_doc):
for name in filenames:
file = os.path.join(dirpath, name)
with io.open(file, 'r+') as f:
docs[name] = f.read()
retu... | Implement tokenization in preprocess function | Implement tokenization in preprocess function
| Python | mit | ikaruswill/vector-space-model,ikaruswill/boolean-retrieval |
6814bed9918640346e4a096c8f410a6fc2b5508e | corehq/tests/noseplugins/uniformresult.py | corehq/tests/noseplugins/uniformresult.py | """A plugin to format test names uniformly for easy comparison
Usage:
# collect django tests
COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt
# collect nose tests
./manage.py test -v2 --collect-only 2> tests-nose.txt
# clean up django test output: s/skipped\ \'.*\'$/ok... | """A plugin to format test names uniformly for easy comparison
Usage:
# collect django tests
COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt
# collect nose tests
./manage.py test -v2 --collect-only 2> tests-nose.txt
# clean up django test output: s/skipped\ \'.*\'$/ok... | Use a copypastable format for function tests | Use a copypastable format for function tests
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
b89a6a10e2a1beafe893faa6eec6e2562ded7492 | local-celery.py | local-celery.py | import sys
from deployer.celery import app
if __name__ == '__main__':
argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info']
app.worker_main(argv=argv)
| import sys
from deployer.celery import app
if __name__ == '__main__':
argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info']
app.conf.CELERYD_CONCURRENCY = 2
app.worker_main(argv=argv)
| Set concurrency to 2 for local | Set concurrency to 2 for local
| Python | mit | totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer |
6c02e42db82b0dfa808ac904c79ce00ed1a0f549 | load_discussions.py | load_discussions.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
from models import DiscussionMarker
import re
from datetime import datetime
from database import db_session
def main():
parser = argparse.ArgumentParser()
parser.add_argument('identifiers', type=str, nargs='+',
... | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
from models import DiscussionMarker
import re
from database import db_session
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('identifiers', type=str, nargs='*',
help='Disqus iden... | Allow loading discussions from file | Allow loading discussions from file
| Python | bsd-3-clause | omerxx/anyway,njenia/anyway,njenia/anyway,esegal/anyway,esegal/anyway,hasadna/anyway,HamutalCohen3/anyway,njenia/anyway,OmerSchechter/anyway,esegal/anyway,hasadna/anyway,OmerSchechter/anyway,omerxx/anyway,boazin/anyway,HamutalCohen3/anyway,idogi/anyway,yosinv/anyway,idogi/anyway,boazin/anyway,idogi/anyway,yosinv/anyway... |
a870433fab72fe184f12353397ad916aabe5cb61 | pegasus/gtfar/__init__.py | pegasus/gtfar/__init__.py | # Copyright 2007-2014 University Of Southern California
#
# 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... | # Copyright 2007-2014 University Of Southern California
#
# 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... | Add boilerplate code to configure the Flask app. | Add boilerplate code to configure the Flask app.
| Python | apache-2.0 | pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar |
9d02361c034591e44e1a6d745911ef72a3591950 | pingparsing/_interface.py | pingparsing/_interface.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from __future__ import division
import abc
class PingParserInterface(object):
@abc.abstractproperty
def packet_transmit(self): # pragma: no cover
pass
@abc.abstrac... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from __future__ import division
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class PingParserInterface(object):
@abc.abstractproperty
def packet_transmit(self): # pra... | Fix missing metaclass for an interface class | Fix missing metaclass for an interface class
| Python | mit | thombashi/pingparsing,thombashi/pingparsing |
1ce26a0b0cbddb49047da0f8bac8214fb298c646 | pymatgen/__init__.py | pymatgen/__init__.py | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jun 28, 2012"
__version__ = "2.0.0"
"""
Useful aliases for commonly used objects and modules.
"""
from pymatgen.core.periodic_table import Element, ... | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jun 28, 2012"
__version__ = "2.0.0"
"""
Useful aliases for commonly used objects and modules.
"""
from pymatgen.core.periodic_table import Element, ... | Add an alias to file_open_zip_aware as openz. | Add an alias to file_open_zip_aware as openz.
| Python | mit | Dioptas/pymatgen,yanikou19/pymatgen,yanikou19/pymatgen,Bismarrck/pymatgen,migueldiascosta/pymatgen,rousseab/pymatgen,sonium0/pymatgen,migueldiascosta/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,Dioptas/pymatgen,rousseab/pymatgen,ctoher/pymatgen,ctoher/pymatgen,sonium0/pymatgen,Bismarrck/pymatgen,yanikou19/pymatgen,Bi... |
b774bb5eb632743cc18961f31ea147799d8ba786 | lib/rapidsms/backends/backend.py | lib/rapidsms/backends/backend.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
class Backend(object):
def log(self, level, message):
self.router.log(level, message)
def start(self):
raise NotImplementedError
def stop(self):
raise NotImplementedError
def send(self):
raise NotImpleme... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
class Backend(object):
def __init__ (self, router):
self.router = router
def log(self, level, message):
self.router.log(level, message)
def start(self):
raise NotImplementedError
def stop(self):
raise NotImple... | Add a constructor method for Backend | Add a constructor method for Backend
| Python | bsd-3-clause | rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy |
8af8f3ab918a033fb250c06c4769ee3351ec9d5f | saau/utils/header.py | saau/utils/header.py | from operator import itemgetter
import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag f... | import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag for thing in xml_line.getiterator(... | Create and modify lines in same loop | Create and modify lines in same loop
| Python | mit | Mause/statistical_atlas_of_au |
e296cefacae7154fd4060ec76abb9ddefb6cd763 | src/akllt/news/views.py | src/akllt/news/views.py | from django.shortcuts import render
from akllt.models import NewsStory
def news_items(request):
return render(request, 'akllt/news/news_items.html', {
'news_items': NewsStory.objects.all()[:20]
})
| from django.shortcuts import render, get_object_or_404
from akllt.models import NewsStory
def news_items(request):
return render(request, 'akllt/news/news_items.html', {
'news_items': NewsStory.objects.all()[:20]
})
def news_details(request, news_item_id):
news_item = get_object_or_404(NewsStor... | Add view for news details | Add view for news details
| Python | agpl-3.0 | python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt |
35e1ba57785734789357f03a738e4d65152bb775 | salt/cli/__init__.py | salt/cli/__init__.py | '''
The management of salt command line utilities are stored in here
'''
# Import python libs
import optparse
import os
import sys
# Import salt components
import salt.client
class SaltCMD(object):
'''
The execution of a salt command happens here
'''
def __init__(self):
'''
Cretae a Sa... | '''
The management of salt command line utilities are stored in here
'''
# Import python libs
import optparse
import os
import sys
# Import salt components
import salt.client
class SaltCMD(object):
'''
The execution of a salt command happens here
'''
def __init__(self):
'''
Cretae a Sa... | Add regex support call to the command line | Add regex support call to the command line
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
f649913f8941837e5de5ca7b5134c04858f52e32 | utils/publish_message.py | utils/publish_message.py | import amqp
from contextlib import closing
def __get_channel(connection):
return connection.channel()
def __get_message(message_body):
return amqp.Message(message_body)
def __declare_exchange(channel, exchange, type):
channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False... | import amqp
from contextlib import closing
def publish_message(message_body, exchange, type, routing_key):
""" Publish a message to an exchange with exchange type and routing key specified.
A message is sent to a specified exchange with the provided routing_key.
:param message_body: The body of the mess... | Revert "Revert "EAFP and removing redundant functions"" | Revert "Revert "EAFP and removing redundant functions""
This reverts commit b03c0898897bbd89f8701e1c4d6d84d263bbd039.
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend |
9b54d728a245855cba724a91d372a15a4f4abb6d | shop/checkout/models.py | shop/checkout/models.py | # -*- coding: utf-8 -*-
"""Checkout Models"""
import functools
from flask import redirect, url_for
from fulfil_client.model import ModelType, StringType
from shop.fulfilio import Model
from shop.globals import current_cart, current_channel
def not_empty_cart(function):
@functools.wraps(function)
def wrapper(... | # -*- coding: utf-8 -*-
"""Checkout Models"""
import functools
from flask import redirect, url_for
from fulfil_client.model import ModelType, StringType
from shop.fulfilio import Model
from shop.globals import current_cart, current_channel
def not_empty_cart(function):
@functools.wraps(function)
def wrapper(... | Add expiry fields on card model | Add expiry fields on card model
| Python | bsd-3-clause | joeirimpan/shop,joeirimpan/shop,joeirimpan/shop |
f0bf059cfa7b6edc366a0b3246eac1f3ab68e865 | solutions/comparison.py | solutions/comparison.py | '''
comparison.py - Comparison of analytic and calculated solutions
Created on 12 Aug 2010
@author: Ian Huston
'''
from __future__ import division
import numpy as np
import analyticsolution
import calcedsolution
import fixtures
def compare_one_step(m, srcclass, nix):
"""
Compare the analytic and calculated ... | '''
comparison.py - Comparison of analytic and calculated solutions
Created on 12 Aug 2010
@author: Ian Huston
'''
from __future__ import division
import numpy as np
import analyticsolution
import calcedsolution
import fixtures
def compare_one_step(m, srcclass, nix):
"""
Compare the analytic and calculated ... | Return k with other results. | Return k with other results.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation |
b30d02bd077f1b7785c41e567aa4c4b44bba6a29 | backend/unimeet/mail/__init__.py | backend/unimeet/mail/__init__.py | __all__ = ['mail']
from .mail import send_mail, SUBJECTS
| __all__ = ['mail']
from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
| Add send_contact_{form,response} functions to mail init | Add send_contact_{form,response} functions to mail init
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet |
8a9e2666e173078ea98e52522442e6e943cc9e6e | banks.py | banks.py | """ Banks' header configurations.
Stored in a dictionary where the keys are bank names in lowercase and
only alpha-characters. A bank's header should include "date" and
"amount", otherwise it cannot be parsed since YNAB requires these two
fields.
"""
from collections import namedtuple
Bank = namedtuple('Bank', ['name'... | """ Banks' header configurations.
Stored in a dictionary where the keys are bank names in lowercase and
only alpha-characters. A bank's header should include "date" and
"amount", otherwise it cannot be parsed since YNAB requires these two
fields.
"""
from collections import namedtuple
Bank = namedtuple('Bank', ['name'... | Prepare for new Nordea header | Prepare for new Nordea header
In June, Nordea will switch to a new web-interface.
This new interface also has a new csv-export format.
This commit adapts Nordea to the new format, while the previous
header is called "Nordea (gamal)".
I might remove the previous header come late June, after Nordea has
made the switch... | Python | mit | adnilsson/Bank2YNAB |
b1aac6a0b29a6ed46b77aab37ff52c765a280ec6 | ikalog/utils/matcher.py | ikalog/utils/matcher.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA, Junki MIZUSHIMA
#
# 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:/... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA, Junki MIZUSHIMA
#
# 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:/... | Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance | utils: Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance
Signed-off-by: Takeshi HASEGAWA <80595b5c49522665976d35e515d02ac963124d00@gmail.com>
| Python | apache-2.0 | deathmetalland/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog,hasegaw/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog |
a5fd2ece2f318030d7790014add66d1e5019ef0d | dodge.py | dodge.py | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_is_macintosh()
def select... | import platform
class OSXDodger(object):
allowed_version = "10.6.1"
allowed_system = "darwin"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_i... | Add allowed_system as a class variable | Add allowed_system as a class variable
| Python | mit | yoda-yoda/osx-dock-dodger,denisKaranja/osx-dock-dodger |
6ebf55543e74771a80f4e871af5b3cfc8f845101 | indico/MaKaC/plugins/Collaboration/RecordingManager/__init__.py | indico/MaKaC/plugins/Collaboration/RecordingManager/__init__.py | # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
##... | # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
##... | Make RecordingManager work with new plugin system | [FIX] Make RecordingManager work with new plugin system
| Python | mit | OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,mic4ael/indico,mic4ael/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,pferreir/indico,OmeGak/indico,pferreir/indico,mic4ael/indico,indico/indico,mvidalgarcia/indico,ThiefMaster/indico,DirkHoffmann/indico,i... |
78747b26f642af4d1404df5a3a6d08160f07d2f0 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='hawkular-client',
version='0.4.0',
description='Python client to communicate with Hawkular over HTTP(S)',
author='Michael Burman',
author_email='miburman@redhat.com',
url='http://github.com/hawkular/hawkular-client-python... | #!/usr/bin/env python
from distutils.core import setup
from os import path
from setuptools.command.install import install
import pypandoc
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
long_description = f.read()
# Create rst here from Markdown
z = pypandoc.convert('RE... | Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt | Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt
| Python | apache-2.0 | hawkular/hawkular-client-python,burmanm/hawkular-client-python,burmanm/hawkular-client-python,hawkular/hawkular-client-python |
72b41b512f4413c456cd0bfde7da349b5094aadd | setup.py | setup.py | """
PyLatex
-------
PyLatex is a Python library for creating LaTeX files. The point of this library
is being an easy, but extensible interface between Python and Latex.
"""
from distutils.core import setup
setup(name='PyLatex',
version='0.2.0',
author='Jelte Fennema',
author_email='pylatex@jeltef.n... | """
PyLatex
-------
PyLatex is a Python library for creating LaTeX files. The point of this library
is being an easy, but extensible interface between Python and Latex.
Features
~~~~~~~~
The library contains some basic features I have had the need for so far.
Currently those are:
- Document generation and compilat... | Update long description for PyPi | Update long description for PyPi
| Python | mit | sebastianhaas/PyLaTeX,JelteF/PyLaTeX,ovaskevich/PyLaTeX,ovaskevich/PyLaTeX,sebastianhaas/PyLaTeX,JelteF/PyLaTeX,bjodah/PyLaTeX,votti/PyLaTeX,jendas1/PyLaTeX,votti/PyLaTeX,bjodah/PyLaTeX,jendas1/PyLaTeX |
de613623c638b923a6bbfb6c33c373794d654000 | setup.py | setup.py | from distutils.core import setup
setup(
name='django_dust',
description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers',
packages=[
'django_dust',
'django_dust.management',
'django_dust.management.commands',
'... | from distutils.core import setup
import os.path
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2]
setup(
name='django_dust',
version='0.1',
description='Distributed Upload STorage for Django, a file backend '
... | Add version, long description and classifiers. | Add version, long description and classifiers.
| Python | bsd-3-clause | aaugustin/django-resto |
0b6db0b19e9389b1c5e62ddab5cdab4886364252 | setup.py | setup.py |
from distutils.core import setup
setup(name='slowboy',
version='0.0.1',
packages=['slowboy'],
url='https://github.com/zmarvel/slowboy/',
author='Zack Marvel',
author_email='zpmarvel at gmail dot com',
install_requires=[
"Pillow==4.1.1",
"PySDL2==0.9.5",
]... |
from distutils.core import setup
setup(name='slowboy',
version='0.0.1',
packages=['slowboy'],
url='https://github.com/zmarvel/slowboy/',
author='Zack Marvel',
author_email='zpmarvel at gmail dot com',
install_requires=[
"PySDL2",
],
extras_require={
... | Move Pillow to development deps; add pytest to development deps | Move Pillow to development deps; add pytest to development deps
| Python | mit | zmarvel/slowboy |
7df69e47b88988e9797d42e7329c8bfc61e2dbcc | reporter/test/logged_unittest.py | reporter/test/logged_unittest.py | # -*- coding: utf-8 -*-
"""
Provides a custom unit test base class which will log to sentry.
:copyright: (c) 2010 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import unittest
import logging
from reporter import setup_logger
setup_logger()
LOGGER = logging.getLogger('osm-reporter')
cl... | # -*- coding: utf-8 -*-
"""
Provides a custom unit test base class which will log to sentry.
:copyright: (c) 2010 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import unittest
import logging
from reporter import setup_logger
setup_logger()
LOGGER = logging.getLogger('osm-reporter')
cl... | Fix for calling super during exception logging | Fix for calling super during exception logging
| Python | bsd-3-clause | meomancer/field-campaigner,meomancer/field-campaigner,meomancer/field-campaigner |
8e980445723f3f185eb88022adbd75f1a01aaef4 | fabfile/ubuntu.py | fabfile/ubuntu.py | from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('apt-get -y upgrade') | from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.operations import reboot
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('DEBIAN_FRONTEND=nonint... | Add apt-get upgrade without grub-install | Add apt-get upgrade without grub-install
| Python | mit | maruina/kanedias,maruina/kanedias,maruina/kanedias,maruina/kanedias |
fd98983e0880b6d2cf81a72da7d65082487359c1 | lib/rapidsms/contrib/messagelog/app.py | lib/rapidsms/contrib/messagelog/app.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import datetime
from rapidsms.apps.base import AppBase
from .models import Message
class App(AppBase):
def _who(self, msg):
to_return = {}
if msg.contact: to_return["contact"] = msg.contact
if msg.connection: to_return["connection... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import datetime
from rapidsms.apps.base import AppBase
from .models import Message
try:
from django.utils.timezone import now as datetime_now
except ImportError:
datetime_now = datetime.datetime.now
class App(AppBase):
def _who(self, msg):
to_... | Use new timezone-aware datetime.now with Django versions that support it | Use new timezone-aware datetime.now with Django versions that support it
| Python | bsd-3-clause | lsgunth/rapidsms,peterayeni/rapidsms,caktus/rapidsms,caktus/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,catalpainternational/rapidsms,ehealthafrica-ci/rapidsms,caktus/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,eHealthAfrica/rapidsms,ehealthafrica-ci/rapidsms,ehealthafrica-ci... |
04c82d00517428bc60e7c4204f01e55452c2c8f2 | oscar_mws/receivers.py | oscar_mws/receivers.py | import logging
from django.utils.translation import ugettext_lazy as _
from oscar_mws.fulfillment import gateway
logger = logging.getLogger('oscar_mws')
def submit_order_to_mws(order, user, **kwargs):
if kwargs.get('raw', False):
return
from oscar_mws.fulfillment.creator import FulfillmentOrderCre... | import logging
from django.utils.translation import ugettext_lazy as _
logger = logging.getLogger('oscar_mws')
def submit_order_to_mws(order, user, **kwargs):
if kwargs.get('raw', False):
return
# these modules have to be imported here because they rely on loading
# models from oscar_mws using ... | Fix issue with importing models in fulfillment gateway | Fix issue with importing models in fulfillment gateway
| Python | bsd-3-clause | django-oscar/django-oscar-mws,django-oscar/django-oscar-mws |
f8277d426aa88e45bf492d3d4f6dfd2703702dff | numba/exttypes/utils.py | numba/exttypes/utils.py | "Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba exte... | "Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba exte... | Add utility to retrieve all extension type bases | Add utility to retrieve all extension type bases
| Python | bsd-2-clause | gdementen/numba,stuartarchibald/numba,stonebig/numba,stefanseefeld/numba,GaZ3ll3/numba,ssarangi/numba,stuartarchibald/numba,sklam/numba,cpcloud/numba,ssarangi/numba,sklam/numba,ssarangi/numba,gmarkall/numba,sklam/numba,stefanseefeld/numba,pitrou/numba,stonebig/numba,gdementen/numba,pitrou/numba,cpcloud/numba,pombredann... |
74983cc059bc3480331b0815240c579b0b4517fc | bluebottle/assignments/filters.py | bluebottle/assignments/filters.py | from django.db.models import Q
from rest_framework_json_api.django_filters import DjangoFilterBackend
from bluebottle.assignments.transitions import ApplicantTransitions
class ApplicantListFilter(DjangoFilterBackend):
"""
Filter that shows all applicant if user is owner,
otherwise only show accepted appl... | from django.db.models import Q
from rest_framework_json_api.django_filters import DjangoFilterBackend
from bluebottle.assignments.transitions import ApplicantTransitions
class ApplicantListFilter(DjangoFilterBackend):
"""
Filter that shows all applicant if user is owner,
otherwise only show accepted appl... | Tweak filtering of applicants on assignment | Tweak filtering of applicants on assignment
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
e18f4bd7db18743bb290fed276ff21a9e63e6922 | petulant/meme/tests.py | petulant/meme/tests.py | from django.test import TestCase
# Create your tests here.
| import json
from django.test import TestCase, Client
class MemeTests(TestCase):
def test_can_post_to_db(self):
response = json.loads(self.client.post('/', {'url':'https://foo.bar/baz.gif', 'keywords':'omg, this, is, great'}).content)
self.assertTrue(response['success'])
| Add test for posting content to the server | Add test for posting content to the server
| Python | apache-2.0 | AutomatedTester/petulant-meme,AutomatedTester/petulant-meme,AutomatedTester/petulant-meme |
9b3443186c103c5f08465773f2e34591aa724179 | paypal/gateway.py | paypal/gateway.py | import requests
import time
import urlparse
from paypal import exceptions
def post(url, params):
"""
Make a POST request to the URL using the key-value pairs. Return
a set of key-value pairs.
:url: URL to post to
:params: Dict of parameters to include in post payload
"""
for k in params... | import requests
import time
import urlparse
import urllib
from paypal import exceptions
def post(url, params):
"""
Make a POST request to the URL using the key-value pairs. Return
a set of key-value pairs.
:url: URL to post to
:params: Dict of parameters to include in post payload
"""
... | Revert back to using urllib to encode params | Revert back to using urllib to encode params
But take a snippet from #69 which decodes the response back to unicode.
Fixes #67
| Python | bsd-3-clause | bharling/django-oscar-worldpay,bharling/django-oscar-worldpay,FedeDR/django-oscar-paypal,st8st8/django-oscar-paypal,vintasoftware/django-oscar-paypal,nfletton/django-oscar-paypal,ZachGoldberg/django-oscar-paypal,lpakula/django-oscar-paypal,st8st8/django-oscar-paypal,embedded1/django-oscar-paypal,lpakula/django-oscar-pa... |
bf36831f062c8262e9d7f8a5f63b5b4a0f413c5f | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mongodb-org')
assert package.is_ins... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB package is installed
def test_mongodb_is_installed(host):
package = host.package('mongodb-org')
assert package.is_ins... | Add test of mongodb package version | Add test of mongodb package version
| Python | bsd-2-clause | jugatsu-infra/ansible-role-mongodb |
5504dde1cc940fc8f55ff1bcba7ae225ad9759c1 | account_invoice_subcontractor/models/hr.py | account_invoice_subcontractor/models/hr.py | # © 2015 Akretion
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
... | # © 2015 Akretion
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
... | FIX set default subcontractor type on employee | FIX set default subcontractor type on employee
| Python | agpl-3.0 | akretion/subcontractor |
6cc48b08fd0b3a0dda2a8dfdc55b8d8d3b9022b1 | pyramda/math/mean_test.py | pyramda/math/mean_test.py | from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
| from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
assert_equal(mean([5, 7, 3]), 5)
| Add test establishing no change in behavior for unsorted input arrays | Add test establishing no change in behavior for unsorted input arrays
| Python | mit | jackfirth/pyramda |
0e7d1df97590152781e364b3acea34e0bb42bc2a | tests/constants_test.py | tests/constants_test.py | import unittest
from mtglib.constants import base_url, card_flags
class DescribeConstants(unittest.TestCase):
def should_have_base_url(self):
url = ('http://gatherer.wizards.com/Pages/Search/Default.aspx'
'?output=standard&')
assert base_url == url
def should_have_card_flags(s... | import unittest
from mtglib.constants import base_url, card_flags
class DescribeConstants(unittest.TestCase):
def should_have_base_url(self):
url = ('http://gatherer.wizards.com/Pages/Search/Default.aspx'
'?output=standard&action=advanced&')
assert base_url == url
def should_h... | Update base url in tests. | Update base url in tests.
| Python | mit | chigby/mtg,chigby/mtg |
d6643fa72f6783fc0f92cb9d8f44daf52fc1bf5f | registry/admin.py | registry/admin.py | from models import Resource, ResourceCollection, Contact
from django.contrib import admin
class ResourceAdmin(admin.ModelAdmin):
list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
filter_horizontal = ['editors', 'collections']
list_filter = ('published', 'collections')
search_f... | from models import Resource, ResourceCollection, Contact
from django.contrib import admin
def make_published(modeladmin, request, queryset):
queryset.update(published=True)
make_published.short_description = "Mark selected resources as published"
class ResourceAdmin(admin.ModelAdmin):
list_display = ('title',... | Add bulk updating of a model's published status | Add bulk updating of a model's published status
| Python | bsd-3-clause | usgin/metadata-repository,usgin/metadata-repository,usgin/nrrc-repository,usgin/nrrc-repository |
9f323dae623e38261a1a63016b8447c96fe021b4 | python-pscheduler/pscheduler/pscheduler/api.py | python-pscheduler/pscheduler/pscheduler/api.py | """
Functions related to the pScheduler REST API
"""
def api_root():
return '/pscheduler'
def api_url(host = None, # Don't default this. It breaks 'None' behavior.
path = None,
port = None,
protocol = 'http'
):
if path is not None and path.startswith('/'):
... | """
Functions related to the pScheduler REST API
"""
import socket
def api_root():
"Return the standard root location of the pScheduler hierarchy"
return '/pscheduler'
def api_url(host = None,
path = None,
port = None,
protocol = 'http'
):
"""Format a URL ... | Return fully-qualified URLS. Doc changes. | Return fully-qualified URLS. Doc changes.
| Python | apache-2.0 | perfsonar/pscheduler,perfsonar/pscheduler,perfsonar/pscheduler,perfsonar/pscheduler,mfeit-internet2/pscheduler-dev,mfeit-internet2/pscheduler-dev |
0463adb64976c05bf22edc4d819a4ddeabc013f6 | src/txkube/testing/strategies.py | src/txkube/testing/strategies.py | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedOb... | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedOb... | Apply a couple refinements to object name strategy. | Apply a couple refinements to object name strategy.
Zero length names are invalid.
So are names beginning or ending with -.
| Python | mit | LeastAuthority/txkube |
d843b9c51888fb0391fb303f1aa3d74e00fcd0c1 | codepot/views/prices/__init__.py | codepot/views/prices/__init__.py | import time
from django.utils import timezone
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from codepot.models import Product
@api_view(['GET', ])
def get_prices(request, **kwargs):
products = Product.objects.all()
... | import time
from django.utils import timezone
from rest_framework.decorators import (
api_view,
permission_classes,
)
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from codepot.models import Product
@api_view(['GET',... | Allow to access prices without auth. | Allow to access prices without auth.
| Python | mit | codepotpl/codepot-backend,codepotpl/codepot-backend,codepotpl/codepot-backend |
e28541c00be7f02b3ca6de25e4f95ce4dd099524 | nodeconductor/iaas/perms.py | nodeconductor/iaas/perms.py | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
c... | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
c... | Allow InstanceSlaHistory to be managed by staff | Allow InstanceSlaHistory to be managed by staff
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
a6061ef140e371101c3d04c5b85562586293eee8 | scrappyr/scraps/tests/test_models.py | scrappyr/scraps/tests/test_models.py | from test_plus.test import TestCase
from ..models import Scrap
class TestScrap(TestCase):
def test__str__(self):
scrap = Scrap(raw_title='hello')
assert str(scrap) == 'hello'
def test_html_title(self):
scrap = Scrap(raw_title='hello')
assert scrap.html_title == 'hello'
... | from test_plus.test import TestCase
from ..models import Scrap
class TestScrap(TestCase):
def test__str__(self):
scrap = Scrap(raw_title='hello')
assert str(scrap) == 'hello'
def test_html_title(self):
scrap = Scrap(raw_title='hello')
assert scrap.html_title == 'hello'
... | Add test of block-elements in scrap title | Add test of block-elements in scrap title
| Python | mit | tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app |
0a2fd079c828a8d2f48f8e2c33574aec2d416f06 | mbuild/lib/atoms/c3.py | mbuild/lib/atoms/c3.py | from __future__ import division
import numpy as np
import mbuild as mb
class C3(mb.Compound):
"""A tri-valent, planar carbon."""
def __init__(self):
super(C3, self).__init__()
self.add(mb.Particle(name='C'))
self.add(mb.Port(anchor=self[0]), 'up')
self['up'].translate(self['... | from __future__ import division
import numpy as np
import mbuild as mb
class C3(mb.Compound):
"""A tri-valent, planar carbon."""
def __init__(self):
super(C3, self).__init__()
self.add(mb.Particle(name='C'))
self.add(mb.Port(anchor=self[0]), 'up')
self['up'].translate(np.arr... | Fix bug in translate call | Fix bug in translate call
| Python | mit | iModels/mbuild,ctk3b/mbuild,tcmoore3/mbuild,summeraz/mbuild,summeraz/mbuild,ctk3b/mbuild,iModels/mbuild,tcmoore3/mbuild |
1d8185ed29d448ae181779913b8a0c4f513a799c | opsimulate/constants.py | opsimulate/constants.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 James Wen
KEYS_DIR_NAME = './keys'
PRIVATE_KEY_FILE = '{}/opsimulate'.format(KEYS_DIR_NAME)
PUBLIC_KEY_FILE = '{}/opsimulate.pub'.format(KEYS_DIR_NAME)
SERVICE_ACCOUNT_FILE = 'service-account.json'
ZONE = 'us-east4-a'
MACHINE_TYPE = 'n1-standard-1'
... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 James Wen
import os
HOME = os.path.expanduser("~")
OPSIMULATE_HOME = os.path.join(HOME, '.opsimulate')
KEYS_DIR_NAME = os.path.join(OPSIMULATE_HOME, 'keys')
PRIVATE_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate')
PUBLIC_KEY_FILE = os.path.join(... | Install keys and service-account.json in ~/.opsimulate directory | Install keys and service-account.json in ~/.opsimulate directory
- This ensures that opsimulate can be ran as a regular pip installed
CLI tool and not just via pip -e or direct script invocation
| Python | mit | RochesterinNYC/opsimulate,RochesterinNYC/opsimulate |
a424fa213c14a64f0f2aa54a7adba0e9710032c6 | osbrain/tests/common.py | osbrain/tests/common.py | import random
import pytest
from Pyro4.errors import NamingError
from osbrain.nameserver import NameServer
from osbrain.address import SocketAddress
@pytest.fixture(scope='function')
def nsaddr(request):
while True:
try:
# Bind to random port
host = '127.0.0.1'
port = r... | import random
import pytest
from Pyro4.errors import NamingError
from osbrain.nameserver import NameServer
from osbrain.address import SocketAddress
@pytest.yield_fixture(scope='function')
def nsaddr(request):
while True:
try:
# Bind to random port
host = '127.0.0.1'
po... | Use `yield_fixture` instead of classic `fixture` with pytest | Use `yield_fixture` instead of classic `fixture` with pytest
| Python | apache-2.0 | opensistemas-hub/osbrain |
80b882b3a790241d3d67ae190b0e32d7e9d7b8ed | mesonwrap/inventory.py | mesonwrap/inventory.py | _ORGANIZATION = 'mesonbuild'
_RESTRICTED_PROJECTS = [
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
_RESTRICTED_ORG_PROJECTS = [
_ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS
]
def is_wrap_project_name(project: str) -> bo... | _ORGANIZATION = 'mesonbuild'
_RESTRICTED_PROJECTS = [
'dubtestproject',
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
_RESTRICTED_ORG_PROJECTS = [
_ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS
]
def is_wrap_project_na... | Add dubtestproject to the list of restricted projects | Add dubtestproject to the list of restricted projects
| Python | apache-2.0 | mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb |
752f0f019163e4932b113d7aa72c4a935e6ae516 | planetstack/model_policies/__init__.py | planetstack/model_policies/__init__.py | from .model_policy_Slice import *
from .model_policy_User import *
from .model_policy_Network import *
from .model_policy_Site import *
from .model_policy_SitePrivilege import *
from .model_policy_SlicePrivilege import *
from .model_policy_ControllerSlice import *
from .model_policy_Controller import *
from .model_poli... | from .model_policy_Slice import *
from .model_policy_User import *
from .model_policy_Network import *
from .model_policy_Site import *
from .model_policy_SitePrivilege import *
from .model_policy_SlicePrivilege import *
from .model_policy_ControllerSlice import *
from .model_policy_ControllerSite import *
from .model_... | Enable user and site model policies | Enable user and site model policies
| Python | apache-2.0 | open-cloud/xos,zdw/xos,opencord/xos,cboling/xos,cboling/xos,zdw/xos,open-cloud/xos,opencord/xos,zdw/xos,cboling/xos,zdw/xos,cboling/xos,open-cloud/xos,opencord/xos,cboling/xos |
2392ae642e9f9dd8ede478b63f4c838cfe1dee69 | pysyte/text_streams.py | pysyte/text_streams.py | """Module to handle streams of text"""
import os
import sys
import contextlib
from itertools import chain
from six import StringIO
from pysyte import iteration
from pysyte.platforms import get_clipboard_data
def clipboard_stream(name=None):
stream = StringIO(get_clipboard_data())
stream.name = name or '<cl... | """Module to handle streams of text"""
import os
import sys
import contextlib
from itertools import chain
from six import StringIO
from pysyte import iteration
from pysyte.platforms import get_clipboard_data
def clipboard_stream(name=None):
stream = StringIO(get_clipboard_data())
stream.name = name or '<cl... | Use sys.stdin if not other streams found for all() | Use sys.stdin if not other streams found for all()
| Python | mit | jalanb/dotsite |
d686524149a11be5e849b449a49429416ef7005d | camelot/roundtable/models.py | camelot/roundtable/models.py | # -*- coding: utf-8
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Knight(models.Model):
name = models.CharField(max_length=63)
traitor = models.BooleanField()
def __str__(self):
... | # -*- coding: utf-8
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Knight(models.Model):
name = models.CharField(max_length=63)
traitor = models.BooleanField(default=False)
def __str__(s... | Add False default to traitor BooleanField. | Add False default to traitor BooleanField.
| Python | bsd-2-clause | jambonrose/djangocon2014-updj17 |
e70537eb2c1a8a68a6a66550e6714816e048bb5e | tests/integration/modules/git.py | tests/integration/modules/git.py | # -*- coding: utf-8 -*-
import shutil
import subprocess
import tempfile
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class GitModuleTest(integration.ModuleCase):
@classmethod
def setUpClass(cls):
from ... | # -*- coding: utf-8 -*-
# Import Python Libs
import shutil
import subprocess
import tempfile
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class GitModuleTest(integration.ModuleCase):
'''
Integration tests for ... | Fix missing cls variable and add some docstring info | Fix missing cls variable and add some docstring info
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
8a3b4dd4821f22fcb54e9da6386d5e7b90cc99cc | tests/search_backend_postgres.py | tests/search_backend_postgres.py | from wolis.test_case import WolisTestCase
class SearchBackendPostgresTest(WolisTestCase):
def test_set_search_backend(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
self.change_acp_knob(
link_text='Search settings',
check_pa... | from wolis.test_case import WolisTestCase
class SearchBackendPostgresTest(WolisTestCase):
def test_set_search_backend(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
self.change_acp_knob(
link_text='Search settings',
check_pa... | Make postgres search backend test actually change search backend | Make postgres search backend test actually change search backend
| Python | bsd-2-clause | p/wolis-phpbb,p/wolis-phpbb |
20a2a530f797d0eb2e59b283c9c0bdff9d3bb616 | conda_env/installers/base.py | conda_env/installers/base.py | ENTRY_POINT = 'conda_env.installers'
class InvalidInstaller(Exception):
def __init__(self, name):
msg = 'Unable to load installer for {}'.format(name)
super(InvalidInstaller, self).__init__(msg)
def get_installer(name):
try:
return __import__(ENTRY_POINT + '.' + name)
except Impo... | import importlib
ENTRY_POINT = 'conda_env.installers'
class InvalidInstaller(Exception):
def __init__(self, name):
msg = 'Unable to load installer for {}'.format(name)
super(InvalidInstaller, self).__init__(msg)
def get_installer(name):
try:
return importlib.import_module(ENTRY_POINT... | Switch to using importlib to work | Switch to using importlib to work
| Python | bsd-3-clause | ESSS/conda-env,dan-blanchard/conda-env,mikecroucher/conda-env,ESSS/conda-env,isaac-kit/conda-env,mikecroucher/conda-env,isaac-kit/conda-env,nicoddemus/conda-env,nicoddemus/conda-env,phobson/conda-env,conda/conda-env,asmeurer/conda-env,asmeurer/conda-env,conda/conda-env,phobson/conda-env,dan-blanchard/conda-env |
08c1b6d8523936319dee2525dc795db844432a5d | fjord/heartbeat/tests/__init__.py | fjord/heartbeat/tests/__init__.py | import time
import factory
from fjord.heartbeat.models import Answer, Survey
class SurveyFactory(factory.DjangoModelFactory):
class Meta:
model = Survey
name = 'survey123'
enabled = True
class AnswerFactory(factory.DjangoModelFactory):
class Meta:
model = Answer
experiment_ve... | import time
import factory
from factory import fuzzy
from fjord.heartbeat.models import Answer, Survey
class SurveyFactory(factory.DjangoModelFactory):
class Meta:
model = Survey
name = fuzzy.FuzzyText(length=100)
enabled = True
class AnswerFactory(factory.DjangoModelFactory):
class Meta:... | Change some fields to use fuzzy values | Change some fields to use fuzzy values
This makes it easier to have tests generate multiple surveys and
answers without hitting integrity issues.
| Python | bsd-3-clause | hoosteeno/fjord,hoosteeno/fjord,mozilla/fjord,mozilla/fjord,mozilla/fjord,hoosteeno/fjord,mozilla/fjord,hoosteeno/fjord |
6a53185da27ca3c1257d503389fe66936a4d8014 | testing/test_rm_dirs.py | testing/test_rm_dirs.py | from __future__ import absolute_import, print_function
import os
import sys
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def create_update_dir(request):
os.mkdir('downloads')
files=['tesfeo','fjfesf','fihghg']
filedir=[os.path.join('downloads',fi) for fi in ... | from __future__ import absolute_import, print_function
import os
import sys
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def create_update_dir(request):
os.mkdir('downloads')
files=['tesfeo','fjfesf','fihghg']
filedir=[os.path.join('downloads',fi) for fi in ... | Fix test to add assertion | Fix test to add assertion
rmdir test now expected to fail
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
6c16fb42efd148a6e99788e55e20fa7d55b15cab | tests/docs/test_docs.py | tests/docs/test_docs.py | import subprocess
import unittest
import os
class Doc_Test(unittest.TestCase):
@property
def path_to_docs(self):
dirname, file_name = os.path.split(os.path.abspath(__file__))
return dirname.split(os.path.sep)[:-2] + ["docs"]
def test_html(self):
wd = os.getcwd()
os.chdir(o... | import subprocess
import unittest
import os
class Doc_Test(unittest.TestCase):
@property
def path_to_docs(self):
dirname, file_name = os.path.split(os.path.abspath(__file__))
return dirname.split(os.path.sep)[:-2] + ["docs"]
def test_html(self):
wd = os.getcwd()
os.chdir(o... | Update link check to look at platform | Update link check to look at platform
| Python | mit | simpeg/discretize,simpeg/discretize,simpeg/discretize |
4b84cedd15a2774391544a6edee3532e5e267608 | tests/docs/test_docs.py | tests/docs/test_docs.py | import subprocess
import unittest
import os
import subprocess
import unittest
import os
class Doc_Test(unittest.TestCase):
@property
def path_to_docs(self):
dirname, filename = os.path.split(os.path.abspath(__file__))
return dirname.split(os.path.sep)[:-2] + ['docs']
def test_html(self)... | import subprocess
import unittest
import os
import subprocess
import unittest
import os
class Doc_Test(unittest.TestCase):
@property
def path_to_docs(self):
dirname, filename = os.path.split(os.path.abspath(__file__))
return dirname.split(os.path.sep)[:-2] + ['docs']
def test_html(self)... | Edit docs test for local test on windows machine | Edit docs test for local test on windows machine
| Python | mit | simpeg/simpeg |
17390cc09c7ffd8583fd170acb2a4b1e8d4efabd | tests/formats/visual.py | tests/formats/visual.py | from __future__ import unicode_literals
import unittest
from pyaavso.formats.visual import VisualFormatWriter
class VisualFormatWriterTestCase(unittest.TestCase):
def test_writer_init(self):
writer = VisualFormatWriter()
| from __future__ import unicode_literals
import unittest
from StringIO import StringIO
from pyaavso.formats.visual import VisualFormatWriter
class VisualFormatWriterTestCase(unittest.TestCase):
"""
Tests for VisualFormatWriter class.
"""
def test_write_header_obscode(self):
"""
Check ... | Test for obscode in file. | Test for obscode in file.
| Python | mit | zsiciarz/pyaavso |
3a2fc6b73aec538802adff2bd95261ffc56ca475 | rover.py | rover.py | class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
@property
def compass_index(self):
return next... | class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
@property
def compass_index(self):
return next... | Add default arguments to set_position, add self argument to move function | Add default arguments to set_position, add self argument to move function
| Python | mit | authentik8/rover |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.