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 |
|---|---|---|---|---|---|---|---|---|---|
d7a3bcf72df3cededc4220f46f976a0daef539a6 | marvin/tests/__init__.py | marvin/tests/__init__.py | from marvin import create_app
import unittest
class AppCreationTest(unittest.TestCase):
def test_create_app(self):
app = create_app(MY_CONFIG_VALUE='foo')
self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo')
| from marvin import create_app
import os
import tempfile
import unittest
class AppCreationTest(unittest.TestCase):
def setUp(self):
self.config_file = tempfile.NamedTemporaryFile(delete=False)
self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8'))
self.config_file.close()
def... | Add test for app creation with config file. | Add test for app creation with config file.
Also be explicit about encoding when writing to file.
| Python | mit | streamr/marvin,streamr/marvin,streamr/marvin |
ec52babd52abce01873b8452f00b01c651c2deef | zappa/__init__.py | zappa/__init__.py | import sys
SUPPORTED_VERSIONS = [(2, 7), (3, 6), (3, 7)]
python_major_version = sys.version_info[0]
python_minor_version = sys.version_info[1]
if (python_major_version, python_minor_version) not in SUPPORTED_VERSIONS:
formatted_supported_versions = ['{}.{}'.format(mav, miv) for mav, miv in SUPPORTED_VERSIONS]
... | import sys
SUPPORTED_VERSIONS = [(2, 7), (3, 6), (3, 7)]
if sys.version_info[:2] not in SUPPORTED_VERSIONS:
formatted_supported_versions = ['{}.{}'.format(*version) for version in SUPPORTED_VERSIONS]
err_msg = ('This version of Python ({}.{}) is not supported!\n'.format(*sys.version_info) +
'Za... | Simplify Python version detection and remove the backslash | Simplify Python version detection and remove the backslash | Python | mit | Miserlou/Zappa,Miserlou/Zappa |
23419cf96eb2f9d45b60cfbc085d9a77190c40b5 | django_lightweight_queue/job.py | django_lightweight_queue/job.py | import sys
import time
from django.utils import simplejson
from .utils import get_path, get_middleware
class Job(object):
def __init__(self, path, args, kwargs):
self.path = path
self.args = args
self.kwargs = kwargs
def run(self):
start = time.time()
middleware = ge... | import sys
import time
from django.utils import simplejson
from .utils import get_path, get_middleware
class Job(object):
def __init__(self, path, args, kwargs):
self.path = path
self.args = args
self.kwargs = kwargs
@classmethod
def from_json(cls, json):
return cls(**sim... | Add ability to generate a Job easily. | Add ability to generate a Job easily.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | prophile/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue |
81c567e4be0d3c2f91d3cfa3d04b0b738859da6a | yargy/utils.py | yargy/utils.py | from itertools import count, takewhile
def frange(start, stop, step):
return takewhile(lambda x: x <= stop, (start + i * step for i in count()))
def get_original_text(text, tokens):
'''
Returns original text captured by parser grammars
'''
if not tokens:
return None
head, tail = token... | from itertools import count, takewhile
def frange(start, stop, step):
return takewhile(lambda x: x <= stop, (start + i * step for i in count()))
def get_tokens_position(tokens):
if not tokens:
return None
head, tail = tokens[0], tokens[-1]
return head.position[0], tail.position[1]
def get_or... | Add get_tokens_position and decode_roman_number functions | Add get_tokens_position and decode_roman_number functions
| Python | mit | bureaucratic-labs/yargy |
d3f09baf1e1de0272e1a579a207f685feb6c673f | common/mixins.py | common/mixins.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_a... | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model... | Return user-friendly error message for SlugifyMixin class | Return user-friendly error message for SlugifyMixin class
| Python | mit | teamtaverna/core |
a816d0655504051ea12718a0e34bc9645fc92730 | personal-site/projects/views.py | personal-site/projects/views.py | from django.shortcuts import render
from django.views.generic.detail import DetailView
from projects.models import Project
from misc.code_blocks_preprocessor import CodeBlockExtension
import markdown
class ProjectDetailView(DetailView):
model = Project
context_object_name='project'
template_name = 'proje... | from django.shortcuts import render
from django.views.generic.detail import DetailView
from projects.models import Project
from misc.code_blocks_preprocessor import CodeBlockExtension
import markdown
class ProjectDetailView(DetailView):
model = Project
context_object_name='project'
template_name = 'proje... | Remove unnecessary projects added to context | Remove unnecessary projects added to context
| Python | bsd-3-clause | brandonw/personal-site,brandonw/personal-site,brandonw/personal-site |
2d9c4128898c8504813e6ea42eb2d634cf7e56a1 | kepakkoconverter.py | kepakkoconverter.py | #!/usr/bin/env python3
import PIL
from PIL import Image
LED_COUNT = 60
def resize_image(path):
img = Image.open(path)
old_width = img.size[0]
old_height = img.size[1]
ratio = 60.0/old_height
return img.resize((int(old_width*ratio), int(old_height*ratio)),
PIL.Image.ANTIALIAS... | #!/usr/bin/env python3
import PIL
import sys
from PIL import Image
LED_COUNT = 60
def resize_image(path):
img = Image.open(path)
old_width = img.size[0]
old_height = img.size[1]
ratio = 60.0/old_height
return img.resize((int(old_width*ratio), int(old_height*ratio)),
PIL.Imag... | Switch to using palette in the converter | Switch to using palette in the converter
| Python | mit | myrjola/Valokepakko,myrjola/Valokepakko,myrjola/Valokepakko |
4c080197dce0d452047203dbf06dd160086fcbdf | website/snat/forms.py | website/snat/forms.py | # -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import Required, IPAddress
class SnatForm(Form):
sou... | # -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField, ValidationError
from wtforms.validators import Required, IPAddress
def IPorNet(... | Add snat ip or net validator. | Add snat ip or net validator.
| Python | bsd-3-clause | sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW,sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW |
6e05ed3d47ab2e98b68ee284ab68cf1b0fc4e2af | www/tests/test_aio.py | www/tests/test_aio.py | from browser import console
import asyncio
from async_manager import AsyncTestManager
aio = AsyncTestManager()
async def wait_secs(s, result):
await asyncio.sleep(s)
console.log("Returning result", result)
return result
@aio.async_test(0.5)
def test_simple_coroutine():
console.log("coro_wait_secs")... | from browser import console, aio
async def wait_secs(s, result):
await aio.sleep(s)
console.log("Returning result", result)
return result
async def test_simple_coroutine():
console.log("coro_wait_secs")
coro_wait_secs = wait_secs(0.1, 10)
console.log("ensuring future")
fut = await coro_wai... | Replace asyncio tests by browser.aio tests | Replace asyncio tests by browser.aio tests
| Python | bsd-3-clause | brython-dev/brython,kikocorreoso/brython,kikocorreoso/brython,brython-dev/brython,kikocorreoso/brython,brython-dev/brython |
6808758a22e6bb0235038c01366fcbc250e60f84 | nlppln/commands/freqs.py | nlppln/commands/freqs.py | #!/usr/bin/env python
import os
import click
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pandas as pd
from nlppln.utils import create_dirs, get_files
from nlppln.liwc_tokenized import split
@click.command()
@click.argument('in_dir', type=click.Path(exists=True))
@click.optio... | #!/usr/bin/env python
import os
import click
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pandas as pd
from nlppln.utils import create_dirs, get_files, split
@click.command()
@click.argument('in_dir', type=click.Path(exists=True))
@click.option('--out_dir', '-o', default=os.g... | Use utility function split for splitting text | Use utility function split for splitting text
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln |
3651d4076899f86f3b6627b0fd7e8af197c5149c | bin/pympit_fork.py | bin/pympit_fork.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals, with_statement
from mpi4py import MPI
import sys
import os
import numpy as np
import scipy as sc
from astropy.io import fits
import argparse
import subprocess as sp
import pympit as pt
parser = argparse.A... | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals, with_statement
from mpi4py import MPI
import sys
import os
import numpy as np
import scipy as sc
from astropy.io import fits
import argparse
import subprocess as sp
import pympit as pt
parser = argparse.A... | Add communicator split to forking test. | Add communicator split to forking test.
| Python | bsd-2-clause | tskisner/pympit,tskisner/pympit |
6f60d2c76ece73e8f37f2ae1014cc26b485495d0 | numpy/distutils/setup.py | numpy/distutils/setup.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_d... | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_d... | Make the gfortran/vs2003 hack source file known to distutils. | Make the gfortran/vs2003 hack source file known to distutils.
| Python | bsd-3-clause | simongibbons/numpy,ContinuumIO/numpy,BabeNovelty/numpy,rherault-insa/numpy,cjermain/numpy,madphysicist/numpy,ahaldane/numpy,BabeNovelty/numpy,abalkin/numpy,naritta/numpy,dimasad/numpy,dch312/numpy,GrimDerp/numpy,MichaelAquilina/numpy,has2k1/numpy,jankoslavic/numpy,sonnyhu/numpy,madphysicist/numpy,ogrisel/numpy,gmcastil... |
e601172065ca3959c1399608c294243fa2b83cef | tests/test_SwitchController.py | tests/test_SwitchController.py | import unittest
from mpf.system.machine import MachineController
from tests.MpfTestCase import MpfTestCase
from mock import MagicMock
import time
class TestSwitchController(MpfTestCase):
def getConfigFile(self):
return 'config.yaml'
def getMachinePath(self):
return '../tests/machine_files/sw... | from tests.MpfTestCase import MpfTestCase
class TestSwitchController(MpfTestCase):
def getConfigFile(self):
return 'config.yaml'
def getMachinePath(self):
return '../tests/machine_files/switch_controller/'
def _callback(self):
self.isActive = self.machine.switch_controller.is_a... | Add test for initial switch states | Add test for initial switch states
| Python | mit | missionpinball/mpf,missionpinball/mpf |
29419cf81068183029b1dc63e718937de155a754 | test/weakref_test.py | test/weakref_test.py | import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assert_(ref() is self.core)
def test_weakref_node(self):
video =... | import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assertTrue(ref() is self.core)
def test_weakref_node(self):
vide... | Fix one more deprecation warning | Fix one more deprecation warning
| Python | lgpl-2.1 | vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth |
1964407097b15c92e9b3aa77dc3d6d94bb656757 | turbustat/tests/test_dendro.py | turbustat/tests/test_dendro.py | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
import numpy as np
import numpy.testing as npt
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
min_deltas = np.logspace... | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
import numpy as np
import numpy.testing as npt
import os
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
min_deltas = n... | Add testing of loading and saving for Dendrogram_Stats | Add testing of loading and saving for Dendrogram_Stats
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat |
8b09bc6854075f43bf408169a743d023f60fbe0b | telemetry/telemetry/page/actions/navigate.py | telemetry/telemetry/page/actions/navigate.py | # Copyright 2013 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.
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction... | # Copyright 2013 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.
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction... | Add a timeout attr to NavigateAction. | Add a timeout attr to NavigateAction.
BUG=320748
Review URL: https://codereview.chromium.org/202483006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@257922 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catap... |
12d525b79e78d8e183d75a2b81221f7d18519897 | tests/kernel_test.py | tests/kernel_test.py | from kernel.kernel import Kernel
from modules import AbstractModule
from kernel.module_chain import ModuleChain
import glob
import os
import json
def test_get_module():
mod = Kernel.get_module('modules', 'file.Extension')
assert isinstance(mod, AbstractModule)
try:
mod = Kernel.get_module('module... | from kernel.kernel import Kernel
from modules import AbstractModule
from kernel.config import Config
from kernel.result import Result
from kernel.module_chain import ModuleChain
import glob
import os
import json
def test_get_module():
mod = Kernel.get_module('modules', 'file.Extension')
assert isinstance(mod,... | Fix tests related to result collection | Fix tests related to result collection
| Python | mit | vdjagilev/desefu |
98de0f94332cd2a0faedd1c72d2ee4092552fdb0 | tests/unit/helper.py | tests/unit/helper.py | import mock
import github3
import unittest
MockedSession = mock.create_autospec(github3.session.GitHubSession)
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **... | import mock
import github3
import unittest
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **kwargs)
class UnitHelper(unittest.TestCase):
# Sub-classes must... | Fix the issue where the mock is persisting calls | Fix the issue where the mock is persisting calls
| Python | bsd-3-clause | jim-minter/github3.py,wbrefvem/github3.py,agamdua/github3.py,h4ck3rm1k3/github3.py,krxsky/github3.py,balloob/github3.py,ueg1990/github3.py,sigmavirus24/github3.py,icio/github3.py,christophelec/github3.py,itsmemattchung/github3.py,degustaf/github3.py |
64c04167b800c6e90c8473c2d89896fb2bfa3bc7 | nashvegas/models.py | nashvegas/models.py | from datetime import datetime
from django.db import models
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=datetime.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)... | from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=Tr... | Fix timezone support for migrations | Fix timezone support for migrations | Python | mit | paltman-archive/nashvegas,paltman/nashvegas,dcramer/nashvegas,jonathanchu/nashvegas,iivvoo/nashvegas |
8b73f0e4e70fa1ac6705a4c44878f4910beb8cfb | tests/scratchtest2.py | tests/scratchtest2.py | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... | Revert r67, which was not the changeset intended for commit. | Revert r67, which was not the changeset intended for commit.
| Python | bsd-3-clause | sussman/zvm,sussman/zvm |
c2a5a62e14780a90e7b0dab5a570d1e02d6e9030 | api/ud_helper.py | api/ud_helper.py | from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find model for lan... | import re
from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find mod... | Improve parsing of short strings by adding period. | Improve parsing of short strings by adding period.
Former-commit-id: 812679f50e3dc89a10b1bc7c70061d2e6087c041 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger |
78977a0f976615e76db477b0ab7b35193b34d189 | api/__init__.py | api/__init__.py | from flask import Flask
app = Flask(__name__)
app.secret_key = ''
import api.userview
| from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''
KVSessionExtension(store, app)
import api.userview
| Change so that kvsession (server side sessions) is used instead of flask default | Change so that kvsession (server side sessions) is used instead of flask default
| Python | isc | tobbez/lys-reader |
2056fff6f93d07c3c257748ff82a93a4383da9f5 | src/ansible/tests/test_views.py | src/ansible/tests/test_views.py | from django.test import TestCase
from ansible.models import Playbook
from django.core.urlresolvers import reverse
class PlaybookListViewTest(TestCase):
@classmethod
def setUpTestData(cls):
Playbook.query_set.create(username='lozadaomr',repository='ansi-dst',
inventory='hosts',user='ubu... | from django.test import TestCase
from ansible.models import Playbook
from django.core.urlresolvers import reverse
class PlaybookListViewTest(TestCase):
@classmethod
def setUpTestData(cls):
Playbook.query_set.create(username='lozadaomr',repository='ansi-dst',
inventory='hosts',user='ubu... | Add test for detailed view | Add test for detailed view
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
e5776e8bd4e7ee73fea10788fd60d236abfbbfc3 | docrepr/__init__.py | docrepr/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Tim Dumol
# Copyright (c) 2012- Spyder Development team
#
# Licensed under the terms of the MIT or BSD Licenses
# (See every file for its license)
"""
Docrepr library
Library to generate rich and plain representations of docstrings,
including several metadat... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Tim Dumol
# Copyright (c) 2013- The Spyder Development team
#
# Licensed under the terms of the Modified BSD License
"""
Docrepr library
Library to generate rich and plain representations of docstrings,
including several metadata of the object to which the doc... | Fix license in init file | Fix license in init file
| Python | bsd-3-clause | techtonik/docrepr,spyder-ide/docrepr,techtonik/docrepr,spyder-ide/docrepr,spyder-ide/docrepr,techtonik/docrepr |
b99a8e2fe4a4d26b8b9dfbc4b3a9effad9c89f90 | calexicon/dates/tests/test_bce.py | calexicon/dates/tests/test_bce.py | import unittest
from calexicon.dates import BCEDate
class TestBCEDate(unittest.TestCase):
def test_make_bce_date(self):
bd = BCEDate(-4713, 1, 1)
self.assertEqual(bd.julian_representation(), (-4713, 1, 1))
def test_equality(self):
self.assertEqual(BCEDate(-44, 3, 15), BCEDate(-44, 3... | import unittest
from datetime import timedelta
from calexicon.dates import BCEDate
class TestBCEDate(unittest.TestCase):
def test_make_bce_date(self):
bd = BCEDate(-4713, 1, 1)
self.assertEqual(bd.julian_representation(), (-4713, 1, 1))
def test_equality(self):
self.assertEqual(BCE... | Add tests for the subtraction operator for BCEDate. | Add tests for the subtraction operator for BCEDate.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual |
bacab2b55907c6c263862c2e8d9e0a58f4fbfb29 | mediacenter/tests/test_utils.py | mediacenter/tests/test_utils.py | import pytest
from ..utils import guess_kind
@pytest.mark.parametrize('input,expected', [
['pouet.jpg', 'image'],
['pouet.jpeg', 'image'],
['pouet.png', 'image'],
['pouet.mp4', 'video'],
['pouet.avi', 'video'],
['pouet.mp3', 'audio'],
['pouet.ogg', 'audio'],
['pouet.pdf', 'pdf'],
... | import pytest
from ..utils import guess_kind
@pytest.mark.parametrize('input,expected', [
['pouet.jpg', 'image'],
['pouet.jpeg', 'image'],
['pouet.png', 'image'],
['pouet.mp4', 'video'],
['pouet.avi', 'video'],
['pouet.mp3', 'audio'],
['pouet.ogg', 'audio'],
['pouet.pdf', 'pdf'],
... | Add case of unknown extension when testing guess_kind | Add case of unknown extension when testing guess_kind
| Python | agpl-3.0 | Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan |
106868c0c4b3bb947d251a8416bbd3698af5948b | backend/session/permissions.py | backend/session/permissions.py |
from rest_framework import permissions
class IsStaffOrTargetUser(permissions.BasePermission):
def has_permission(self, request, view):
return view.action == 'retrieve' or request.user.is_staff
def has_object_permission(self, request, view, obj):
return request.user.is_staff or obj == reques... | from rest_framework import permissions
class IsStaffOrTargetUser(permissions.BasePermission):
def has_permission(self, request, view):
if view.action == 'retrieve':
return True
else:
return hasattr(request, 'user') and request.user.is_staff
def has_object_permission(se... | Fix IsStaffOrTargetUser permission when no user in request. | Fix IsStaffOrTargetUser permission when no user in request.
| Python | mit | ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists |
e8175497157ed34f91b9ba96118c4e76cd3ed0e4 | bmsmodules/Events.py | bmsmodules/Events.py | from operator import isCallable
class Events(object):
def __init__(self):
self._events_ = {}
def addEvent(self, eventname, func):
if not isCallable(func):
raise RuntimeError("func argument must be a function!")
elif not isinstance(eventname, basestring):
r... | from operator import isCallable
class Events(object):
def __init__(self):
self._events_ = {}
def addEvent(self, eventname, func):
if not isCallable(func):
raise RuntimeError("func argument must be a function!")
elif not isinstance(eventname, (basestring, int)):
... | Add event execution, allow integers as event name | Add event execution, allow integers as event name
| Python | bsd-3-clause | RenolY2/py-playBMS |
6782e88a48a40dffead893f9fdb2ac0eb6dae7f4 | datashape/error.py | datashape/error.py | """Error handling"""
syntax_error = """
File {filename}, line {lineno}
{line}
{pointer}
{error}: {msg}
"""
class DataShapeSyntaxError(SyntaxError):
"""
Makes datashape parse errors look like Python SyntaxError.
"""
def __init__(self, lexpos, filename, text, msg=None):
self.lexpos =... | """Error handling"""
syntax_error = """
File {filename}, line {lineno}
{line}
{pointer}
{error}: {msg}
"""
class DataShapeSyntaxError(SyntaxError):
"""
Makes datashape parse errors look like Python SyntaxError.
"""
def __init__(self, lexpos, filename, text, msg=None):
self.lexpos =... | Remove the print from datashape | Remove the print from datashape
| Python | bsd-2-clause | cowlicks/datashape,cpcloud/datashape,quantopian/datashape,ContinuumIO/datashape,llllllllll/datashape,quantopian/datashape,cpcloud/datashape,cowlicks/datashape,ContinuumIO/datashape,blaze/datashape,llllllllll/datashape,blaze/datashape |
0916ed4903914ee46dbe4e451d367dff719c9a15 | tests/example_project/urls.py | tests/example_project/urls.py | from os.path import dirname, join, normpath
import django
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib.admin import autodiscover
import ella
from ella import newman
from ella.utils import installedapps
newman.autodiscover()
installedapps.init_logger()
ADMIN_ROOTS = ... | from os.path import dirname, join, normpath
import django
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
import ella
from ella import newman
from ella.utils import installedapps
newman.autodiscover()
admin.autodiscover()
installedapps.init_logger()
ADMIN_... | Test running both newman/ and admin/ - some templates still mixed. | Test running both newman/ and admin/ - some templates still mixed.
| Python | bsd-3-clause | petrlosa/ella,ella/ella,whalerock/ella,WhiskeyMedia/ella,WhiskeyMedia/ella,petrlosa/ella,MichalMaM/ella,whalerock/ella,MichalMaM/ella,whalerock/ella |
98b66fd28d0651022a55fb3d32c69a533e395760 | tests/test_get_user_config.py | tests/test_get_user_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and restore it after the tes... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import os
import shutil
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and ... | Remove self references from setup/teardown | Remove self references from setup/teardown
| Python | bsd-3-clause | Vauxoo/cookiecutter,willingc/cookiecutter,Springerle/cookiecutter,lucius-feng/cookiecutter,agconti/cookiecutter,lucius-feng/cookiecutter,dajose/cookiecutter,atlassian/cookiecutter,dajose/cookiecutter,vintasoftware/cookiecutter,cguardia/cookiecutter,michaeljoseph/cookiecutter,tylerdave/cookiecutter,audreyr/cookiecutter,... |
2a322d26d4ed299d21a1b931e03311ff02a23e0f | app/status/views/healthcheck.py | app/status/views/healthcheck.py | from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client, version
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
... | from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
retu... | Remove git commit/version from status endpoint | Remove git commit/version from status endpoint
This is temporary for the purpose of getting running in
Docker with minimal build steps.
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
7898e0aea72313b769e0c42eea961319539f543b | apps/contribution/serializers.py | apps/contribution/serializers.py | from rest_framework import serializers
from apps.contribution.models import Repository
class RepositorySerializer(serializers.ModelSerializer):
class Meta:
model = Repository
fields = ('id', 'name', 'description', 'url', 'updated_at')
| from rest_framework import serializers
from apps.contribution.models import Repository, RepositoryLanguage
class RepositoryLanguagesSerializer(serializers.ModelSerializer):
class Meta(object):
model = RepositoryLanguage
fields = ('type', 'size')
class RepositorySerializer(serializers.ModelSeria... | Add languages to api endpoint | Add languages to api endpoint
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
fb59c2c7c01da9f4040c6b9c818d1fe2fc7993bb | get_weather_data.py | get_weather_data.py | # get_weather_data.py
import pandas as pd
import constants as const
import utils
def main():
engine = utils.get_db_engine()
today = utils.get_current_time()
resp = utils.get_uri_content(uri=const.DARK_SKY_URI,
content_type='json')
for key in resp.keys():
if ... | # get_weather_data.py
import pandas as pd
import constants as const
import utils
def main():
engine = utils.get_db_engine()
today = utils.get_current_time()
resp = utils.get_uri_content(uri=const.DARK_SKY_URI,
content_type='json')
for key in resp.keys():
if ... | Fix bug with data frames | Fix bug with data frames
| Python | mit | tmthyjames/Achoo,tmthyjames/Achoo,tmthyjames/Achoo,tmthyjames/Achoo,tmthyjames/Achoo |
fddd30a01f3d7b3a6e4e125919e3fc607980fded | btcx/__init__.py | btcx/__init__.py | __version__ = "0.0.1"
VERSION = (0, 0, 1, "handle-with-care")
|
import btce
import mtgox
import cfgmanager
__version__ = "0.0.1"
VERSION = (0, 0, 1, "handle-with-care")
| Support for `import btcx; btcx.btce; ...` | Support for `import btcx; btcx.btce; ...`
| Python | mit | knowitnothing/btcx,knowitnothing/btcx |
3a8c738d8696f31f7024691d56b5edc411289b1b | registries/views.py | registries/views.py | from django.http import HttpResponse
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from registries.models import Organization
from registries.serializers import DrillerListSerializer, DrillerSerializer
class APIDrillerListCreateView(Lis... | from django.http import HttpResponse
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from registries.models import Organization
from registries.serializers import DrillerListSerializer, DrillerSerializer
class APIDrillerListCreateView(Lis... | Add docstrings to view classes | Add docstrings to view classes
| Python | apache-2.0 | bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,rstens/gwells |
1af9ad69ff57d43fa009967a2afd31aa4a610b00 | helpers/__init__.py | helpers/__init__.py | import os
import sys
import platform
# Various helpers for the build scripts
def get_lib_dir():
if sys.platform.startswith("win"):
if platform.architecture()[0] == '32bit':
# 32 bit
return ['prebuilt-x86/lib']
else:
# 64 bit
return ['prebuilt-x64/lib... | import os
import sys
import platform
# Various helpers for the build scripts
def get_lib_dir():
"""Return the library path for SDL and other libraries.
Assumes we're using the pygame prebuilt zipfile on windows"""
if sys.platform.startswith("win"):
if platform.architecture()[0] == '32bit':
... | Fix spacing. Add docstrings to helpers | Fix spacing. Add docstrings to helpers
| Python | lgpl-2.1 | CTPUG/pygame_cffi,CTPUG/pygame_cffi,CTPUG/pygame_cffi |
e03cf2206733dc9f005375abef78238cf4011b50 | dashi/config.py | dashi/config.py | import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
def _load_config():
for path in ['dashi.conf', os.path.j... | import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
@property
def first_name(self):
return self.... | Add the ability to get users and represent them | Add the ability to get users and represent them
Also added a handy first name property for easy table display
| Python | mit | EliRibble/dashi,EliRibble/dashi |
8b538c452242050e468b71ca937e3d4feb57887b | mopidy/backends/stream/__init__.py | mopidy/backends/stream/__init__.py | from __future__ import unicode_literals
import mopidy
from mopidy import ext
__doc__ = """A backend for playing music for streaming music.
This backend will handle streaming of URIs in
:attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are
installed.
**Issues:**
https://github.com/mopidy/mopidy/i... | from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.stream]
# If the stream extension should be enabled or not
enabled = true
# Whitelist of URI schemas to support streaming from
protocols =
http
https
mms
... | Add default config and config schema | stream: Add default config and config schema
| Python | apache-2.0 | tkem/mopidy,jcass77/mopidy,jmarsik/mopidy,ZenithDK/mopidy,swak/mopidy,vrs01/mopidy,diandiankan/mopidy,quartz55/mopidy,adamcik/mopidy,abarisain/mopidy,liamw9534/mopidy,vrs01/mopidy,tkem/mopidy,dbrgn/mopidy,liamw9534/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,abarisain/mopidy,glogiotatidis/mopidy,hkariti/mopidy,mopidy/... |
ad35ec7d4adb91e79bd3382f0846e9fff2a417c7 | osf/management/commands/update_preprint_share_dates.py | osf/management/commands/update_preprint_share_dates.py | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated
logger = logging.getLogger(__name__)
def update_share_preprint_modified_... | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from django.db.models import F
from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated
logger = logging.getLogger(__name__)
def ... | Fix SHARE capitalization, use self-referential query | Fix SHARE capitalization, use self-referential query
| Python | apache-2.0 | sloria/osf.io,chrisseto/osf.io,mattclark/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,caseyrollins/osf.io,erinspace/osf.io,aaxelb/osf.io,sloria/osf.io,aaxelb/osf.io,binoculars/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,leb2dg/osf.io,adlius/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,chennan4... |
46cfd25a4acf075650a5471c388457cb04cd9a15 | invenio_mail/api.py | invenio_mail/api.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Template based messages."""
from __future__ import absolute_import, print_functio... | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Template based messages."""
from __future__ import absolute_import, print_functio... | Use sentinel value for ctx | Use sentinel value for ctx
| Python | mit | inveniosoftware/invenio-mail,inveniosoftware/invenio-mail,inveniosoftware/invenio-mail |
b11ac934c95e4bbaee46ae2b73c3e7129acc06f3 | salt/modules/key.py | salt/modules/key.py | # -*- coding: utf-8 -*-
'''
Functions to view the minion's public key information
'''
from __future__ import absolute_import
# Import python libs
import os
# Import Salt libs
import salt.utils
def finger():
'''
Return the minion's public key fingerprint
CLI Example:
.. code-block:: bash
s... | # -*- coding: utf-8 -*-
'''
Functions to view the minion's public key information
'''
from __future__ import absolute_import
# Import python libs
import os
# Import Salt libs
import salt.utils
def finger():
'''
Return the minion's public key fingerprint
CLI Example:
.. code-block:: bash
s... | Use hash_type param for pem_finger | Use hash_type param for pem_finger
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
590494bf9d840cb6353260392b94700656db5d47 | fabfile/__init__.py | fabfile/__init__.py | """
Fabric's own fabfile.
"""
from __future__ import with_statement
import nose
from fabric.api import abort, local, task
import tag
from utils import msg
@task(default=True)
def test(args=None):
"""
Run all unit tests and doctests.
Specify string argument ``args`` for additional args to ``nosetests`... | """
Fabric's own fabfile.
"""
from __future__ import with_statement
import nose
from fabric.api import abort, local, task
import tag
from utils import msg
@task(default=True)
def test(args=None):
"""
Run all unit tests and doctests.
Specify string argument ``args`` for additional args to ``nosetests`... | Fix super dumb mistake causing all test runs to hit tests folder. | Fix super dumb mistake causing all test runs to hit tests folder.
This causes integration level tests to run both test suites.
Oops!
| Python | bsd-2-clause | cgvarela/fabric,raimon49/fabric,elijah513/fabric,StackStorm/fabric,amaniak/fabric,kmonsoor/fabric,mathiasertl/fabric,opavader/fabric,bspink/fabric,fernandezcuesta/fabric,pgroudas/fabric,likesxuqiang/fabric,xLegoz/fabric,tekapo/fabric,jaraco/fabric,bitmonk/fabric,sdelements/fabric,kxxoling/fabric,itoed/fabric,SamuelMark... |
efbcd8104470234e50ad2e40719b0edf1fbc45c4 | zou/app/utils/date_helpers.py | zou/app/utils/date_helpers.py | from datetime import date, timedelta
def get_date_from_now(nb_days):
return date.today() - timedelta(days=nb_days)
def get_date_diff(date_a, date_b):
return abs((date_b - date_a).total_seconds())
| from babel.dates import format_datetime
from datetime import date, datetime, timedelta
def get_date_from_now(nb_days):
return date.today() - timedelta(days=nb_days)
def get_date_diff(date_a, date_b):
return abs((date_b - date_a).total_seconds())
def get_date_string_with_timezone(date_string, timezone):
... | Add helper to handle timezone in date strings | [utils] Add helper to handle timezone in date strings
| Python | agpl-3.0 | cgwire/zou |
2f8206d5d2ef699b368d4e2b0c87f1f9d5b0dd64 | setup_extensions.py | setup_extensions.py | #!python3
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup (
name = 'PyDoom rendering module',
ext_modules = cythonize (
[
Extension (
"pydoom.extensions.video",
["pydoom/extensions/video.pyx... | #!python3
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup (
name = 'PyDoom rendering module',
ext_modules = cythonize (
[
Extension (
"pydoom.extensions.video",
["pydoom/extensions/video.pyx... | Use the generic names for these as well. | Use the generic names for these as well.
| Python | bsd-3-clause | Pink-Silver/PyDoom,Pink-Silver/PyDoom |
336cdd2619df5fe60a3b0a8a8a91b34b7c1b2ee4 | grokapi/queries.py | grokapi/queries.py | # -*- coding: utf-8 -*-
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se service."""
base_url = "http://s... | # -*- coding: utf-8 -*-
BASE_URL = "http://stats.grok.se/json/"
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se... | Make base_url a global variable | Make base_url a global variable
| Python | mit | Commonists/Grokapi |
538f4b2d0e030a9256ecd68eaf0a1a2e5d649f49 | haas/tests/mocks.py | haas/tests/mocks.py | import itertools
import traceback
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter(itertools.repeat(ret))
def utcnow(self):
return next(self.ret)
| class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter((ret,))
def utcnow(self):
try:
return next(self.ret)
except StopIteration:
raise ValueError('No more mock values!')
| Raise error in mock if there are not enough mock datetime values | Raise error in mock if there are not enough mock datetime values
| Python | bsd-3-clause | sjagoe/haas,itziakos/haas,itziakos/haas,scalative/haas,sjagoe/haas,scalative/haas |
2141e4fd2b09d3a8a95e032fb02eafb9e6f818c9 | i3pystatus/shell.py | i3pystatus/shell.py | from i3pystatus import IntervalModule
from subprocess import check_output, CalledProcessError
class Shell(IntervalModule):
"""
Shows output of shell command
"""
color = "#FFFFFF"
error_color = "#FF0000"
settings = (
("command", "command to be executed"),
("color", "standard co... | from i3pystatus import IntervalModule
from subprocess import check_output, CalledProcessError
class Shell(IntervalModule):
"""
Shows output of shell command
"""
color = "#FFFFFF"
error_color = "#FF0000"
settings = (
("command", "command to be executed"),
("color", "standard co... | Add exception handling for output | Add exception handling for output
| Python | mit | opatut/i3pystatus,teto/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,juliushaertl/i3pystatus,m45t3r/i3pystatus,richese/i3pystatus,claria/i3pystatus,ncoop/i3pystatus,paulollivier/i3pystatus,paulollivier/i3pystatus,ismaelpuerto/i3pystatus,asmikhailov/i3pystatus,eBrnd/i3pystatus,fmarchenko/i3pystatus,plumps/i3pystatus,o... |
2477822fa7589e4968465b56e77885378d30bbc5 | first/polls/admin.py | first/polls/admin.py | from django.contrib import admin
from .models import Choice, Question
# Register your models here.
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
admin.site.register(Question, QuestionA... | from django.contrib import admin
from .models import Choice, Question
# Register your models here.
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information... | Make Choice object editable on Question Admin page | Make Choice object editable on Question Admin page
| Python | mit | ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects |
b32b047656abd28dd794ee16dfab682337a753b1 | accounts/tests.py | accounts/tests.py | from django.test import TestCase
# Create your tests here.
| """accounts app unittests
"""
from django.test import TestCase
class WelcomePageTest(TestCase):
def test_uses_welcome_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'accounts/welcome.html')
| Add first unit test for welcome page | Add first unit test for welcome page
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
bd4643e35a9c75d15bb6a4bfef63774fdd8bee5b | test/regress/cbrt.cpp.py | test/regress/cbrt.cpp.py | #!/usr/bin/python
import shtest, sys, math
def cbrt(l, types=[]):
return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types)
def insert_into(test):
test.add_test(cbrt((0.0, 1.0, 2.0, 3.0)))
test.add_test(cbrt((1.0,)))
test.add_make_test((3,), [(27,)], ['i', 'i'])
# Test the cube root in st... | #!/usr/bin/python
import shtest, sys, math
def cbrt(l, types=[]):
return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types)
def insert_into(test):
test.add_test(cbrt((0.0, 1.0, 2.0, 3.0)))
test.add_test(cbrt((1.0,)))
test.add_test(cbrt((4000.2, 27)))
#test.add_make_test((3,), [(27,)], ... | Add a typical 2-component case. Comment out a case that fail until integer support is fixed. | Add a typical 2-component case.
Comment out a case that fail until integer support is fixed.
git-svn-id: f6f47f0a6375c1440c859a5b92b3b3fbb75bb58e@2508 afdca40c-03d6-0310-8ede-e9f093b21075
| Python | lgpl-2.1 | libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh |
dc622e41059c75da619f90423e35c35d8a3730d4 | tests/test_qccfg.py | tests/test_qccfg.py | import numpy as np
from seabird import cnv
import cotede.qc
from cotede.utils.supportdata import download_testdata
def test_multiple_cfg():
""" I should think about a way to test if the output make sense.
"""
datafile = download_testdata("dPIRX010.cnv")
data = cnv.fCNV(datafile)
pqc = cotede.qc.... |
import pkg_resources
import json
import numpy as np
from seabird import cnv
import cotede.qc
from cotede.utils.supportdata import download_testdata
def test_cfg_json():
""" All config files should comply with json format
In the future, when move load cfg outside, refactor here.
"""
cfgfiles = ... | Test if all QC cfg are proper json files. | Test if all QC cfg are proper json files.
| Python | bsd-3-clause | castelao/CoTeDe |
8eb66d72452d69d683a576c75cdf2be72b2370fa | tests/test_utils.py | tests/test_utils.py | import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img... | import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img_... | Add test for inc page num, good format | Add test for inc page num, good format
| Python | mit | ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork |
2ab601492a76be5d32a2e1d5009c150269e5fb03 | src/interviews/managers.py | src/interviews/managers.py | import logging
from datetime import timedelta
from django.db import models
from django.utils import timezone
from .google_analytics import get_most_read_pages
logger = logging.getLogger(__name__)
class InterviewManager(models.Manager):
def active(self, *args, **kwargs):
return super(InterviewManager, s... | import logging
from datetime import timedelta
from django.db import models
from django.utils import timezone
from .google_analytics import get_most_read_pages
logger = logging.getLogger(__name__)
class InterviewManager(models.Manager):
def active(self, *args, **kwargs):
return super(InterviewManager, s... | Order `most_read` queryset by slug. | Order `most_read` queryset by slug.
| Python | mit | vermpy/thespotlight,vermpy/thespotlight,vermpy/thespotlight |
e42d20547add5b92df8c8ce56bb2340b7b63ced9 | timpani/settings.py | timpani/settings.py | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | Add validation display_name and theme | Add validation display_name and theme
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani |
69f1013a11e540a93b1afff9da819d5f8028078a | utils/lit/tests/xunit-output.py | utils/lit/tests/xunit-output.py | # Check xunit output
# RUN: rm -rf %t.xunit.xml
# RUN: not %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/xunit-output
# If xmllint is installed verify that the generated xml is well-formed
# RUN: sh -c 'if command -v xmllint 2>/dev/null; then xmllint --noout %t.xunit.xml; fi'
# RUN: FileCheck < %t.xunit.xml %s
# CH... | # REQUIRES: shell
# Check xunit output
# RUN: rm -rf %t.xunit.xml
# RUN: not %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/xunit-output
# If xmllint is installed verify that the generated xml is well-formed
# RUN: sh -c 'if command -v xmllint 2>/dev/null; then xmllint --noout %t.xunit.xml; fi'
# RUN: FileCheck < %t... | Mark test with "REQUIRES: shell" since it directly invokes "sh" and was failing on Windows. | Mark test with "REQUIRES: shell" since it directly invokes "sh" and was failing on Windows.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@332563 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llv... |
92b13c26c216a6ced37017041242ad410890c406 | stats-to-datadog.py | stats-to-datadog.py | import urllib2
import json
import sys
from statsd import statsd
statsd.connect('localhost', 8125)
topology = sys.argv[1]
toporoot = sys.argv[2]
topic = sys.argv[3]
state = urllib2.urlopen(
"http://localhost:9000/api/status?toporoot={}&topic={}".format(
toporoot, topic
)
).read()
data = json.loads(st... | import urllib2
import json
import sys
from statsd import statsd
statsd.connect('localhost', 8125)
topology = sys.argv[1]
toporoot = sys.argv[2]
topic = sys.argv[3]
state = urllib2.urlopen(
"http://localhost:9000/api/status?toporoot={}&topic={}".format(
toporoot, topic
)
).read()
data = json.loads(st... | Print something from stats script so you can see it works! | Print something from stats script so you can see it works!
| Python | mit | evertrue/capillary,evertrue/capillary,keenlabs/capillary,evertrue/capillary,evertrue/capillary,keenlabs/capillary,keenlabs/capillary |
5dd758cd0b9b917968b16948db0f635db8571d92 | jsonfield/utils.py | jsonfield/utils.py | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.... | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder,... | Revert changes: freezegun has been updated. | Revert changes: freezegun has been updated.
| Python | bsd-3-clause | chrismeyersfsu/django-jsonfield |
b6fc94d9c6b5015ad2dc882d454127d4b0a6ecee | django_foodbot/api/models.py | django_foodbot/api/models.py | from django.db import models
class Menu(models.Model):
day = models.CharField(max_length=10, blank=False, null=False)
food = models.CharField(max_length=60, blank=False, null=False)
meal = models.CharField(max_length=10, blank=False, null=False)
option = models.IntegerField(null=False)
week = mod... | from django.db import models
class Menu(models.Model):
day = models.CharField(max_length=10, blank=False, null=False)
food = models.CharField(max_length=120, blank=False, null=False)
meal = models.CharField(max_length=10, blank=False, null=False)
option = models.IntegerField(null=False)
week = mo... | Increase character length for food | Increase character length for food
| Python | mit | andela-kanyanwu/food-bot-review |
b7e1b52e3482de19430d4b04faa90967bd623199 | Generator.py | Generator.py | import random
def generateWord(meaning, form, categories, settings, formrules=None):
'''Takes an English string, desired form, generation
categories, settings, and optional form-specific rules.
Returns a generated word.
'''
word = ""
print(categories)
minS = settings["minS"]
maxS = se... | import random
def generateWord(meaning, form, categories, settings, formrules=None):
'''Takes an English string, desired form, generation
categories, settings, and optional form-specific rules.
Returns a generated word.
'''
word = ""
print(categories)
minS = settings["minS"]
maxS = se... | Fix crash if form-specific rules were not specified | Fix crash if form-specific rules were not specified
| Python | mit | kdelwat/Lexeme |
96962b19518186b55c41a19d1cfdaae23eb899e3 | eduid_signup_amp/__init__.py | eduid_signup_amp/__init__.py | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist(user_id)
else:
# white list of valid attributes for security reasons
for attr in ('emai... | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reas... | Change to sync with latest changes in eduid_am related to Exceptions | Change to sync with latest changes in eduid_am related to Exceptions
| Python | bsd-3-clause | SUNET/eduid-signup-amp |
ea2247fe90836e92067ce27e5b22cf8e7dc7bc1b | saleor/app/tasks.py | saleor/app/tasks.py | import logging
from django.core.exceptions import ValidationError
from requests import HTTPError, RequestException
from .. import celeryconf
from ..core import JobStatus
from .installation_utils import install_app
from .models import AppInstallation
logger = logging.getLogger(__name__)
@celeryconf.app.task
def ins... | import logging
from django.core.exceptions import ValidationError
from requests import HTTPError, RequestException
from .. import celeryconf
from ..core import JobStatus
from .installation_utils import install_app
from .models import AppInstallation
logger = logging.getLogger(__name__)
@celeryconf.app.task
def ins... | Add more context to install app msg | Add more context to install app msg
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor |
b47bdb4eca8c357a8c33c5b95ab80748f1358e00 | lintreview/utils.py | lintreview/utils.py | import os
import subprocess
def in_path(name):
"""
Check whether or not a command line tool
exists in the system path.
@return boolean
"""
for dirname in os.environ['PATH'].split(os.pathsep):
if os.path.exists(os.path.join(dirname, name)):
return True
return False
de... | import os
import subprocess
def in_path(name):
"""
Check whether or not a command line tool
exists in the system path.
@return boolean
"""
for dirname in os.environ['PATH'].split(os.pathsep):
if os.path.exists(os.path.join(dirname, name)):
return True
return False
de... | Handle case where bundler exists, but there is no Gemfile | Handle case where bundler exists, but there is no Gemfile
```
adrian@kamek:~$ bundle list
Could not locate Gemfile
adrian@kamek:~$ echo $?
10
```
| Python | mit | zoidbergwill/lint-review,markstory/lint-review,markstory/lint-review,adrianmoisey/lint-review,markstory/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review |
f7f20c50b82e3b8f8f2be4687e661348979fe6a6 | script_helpers.py | script_helpers.py | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | Allow for directories argument to be optional | Allow for directories argument to be optional
| Python | bsd-3-clause | mwcraig/msumastro |
31f81fd98a678949b1bb7d14863d497ab40d5afc | locksmith/common.py | locksmith/common.py | import hashlib
import hmac
import urllib, urllib2
API_OPERATING_STATUSES = (
(1, 'Normal'),
(2, 'Degraded Service'),
(3, 'Service Disruption'),
(4, 'Undergoing Maintenance')
)
API_STATUSES = (
(1, 'Active'),
(2, 'Deprecated'),
(3, 'Disabled')
)
KEY_STATUSES = (
('U', 'Unactivated'),
... | import hashlib
import hmac
import urllib, urllib2
API_OPERATING_STATUSES = (
(1, 'Normal'),
(2, 'Degraded Service'),
(3, 'Service Disruption'),
(4, 'Undergoing Maintenance')
)
API_STATUSES = (
(1, 'Active'),
(2, 'Deprecated'),
(3, 'Disabled')
)
KEY_STATUSES = (
('U', 'Unactivated'),
... | Convert url param values to unicode before encoding. | Convert url param values to unicode before encoding.
| Python | bsd-3-clause | sunlightlabs/django-locksmith,sunlightlabs/django-locksmith,sunlightlabs/django-locksmith |
e5a634100feb5ee486c1de0cdb21325de6477538 | services/vimeo.py | services/vimeo.py | import foauth.providers
class Vimeo(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://vimeo.com/'
docs_url = 'http://developer.vimeo.com/apis/advanced'
category = 'Videos'
# URLs to interact with the API
request_token_url = 'https://vimeo.com/oauth/request_tok... | import foauth.providers
class Vimeo(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://vimeo.com/'
docs_url = 'http://developer.vimeo.com/apis/advanced'
category = 'Videos'
# URLs to interact with the API
request_token_url = 'https://vimeo.com/oauth/request_tok... | Rewrite Vimeo to use the new scope selection system | Rewrite Vimeo to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
973ff308f16fe033b5da60a28cb0d6448062a8f9 | examples/basic_datalogger.py | examples/basic_datalogger.py | from pymoku import Moku
from pymoku.instruments import *
import time, logging
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscil... | from pymoku import Moku
from pymoku.instruments import *
import time, logging
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku('192.168.69.122')#.get_by_name('e... | Make sure the schema gets pulled in as a module | HG-1494: Make sure the schema gets pulled in as a module
| Python | mit | liquidinstruments/pymoku |
ca3978b6068add93418b4c5db8346143533beb7e | examples/forwarder_device.py | examples/forwarder_device.py | import os
import zmq
import yaml
name = 'zmq_document_forwarder'
filenames = [
os.path.join('/etc', name + '.yml'),
os.path.join(os.path.expanduser('~'), '.config', name, 'connection.yml'),
]
config = {}
for filename in filenames:
if os.path.isfile(filename):
print('found config file at', fil... | import os
import zmq
import yaml
name = 'zmq_document_forwarder'
filenames = [
os.path.join('/etc', name + '.yml'),
os.path.join(os.path.expanduser('~'), '.config', name, 'connection.yml'),
]
config = {}
for filename in filenames:
if os.path.isfile(filename):
print('found config file at', fil... | Print ports when forwarder device starts. | MNT: Print ports when forwarder device starts.
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky |
2c1ffd6abed12de8878ec60021ae16dc9c011975 | auth0/v2/authentication/link.py | auth0/v2/authentication/link.py | from .base import AuthenticationBase
class Link(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,... | from .base import AuthenticationBase
class Link(AuthenticationBase):
"""Link accounts endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
"""Unlink an ac... | Add docstrings in Link class | Add docstrings in Link class
| Python | mit | auth0/auth0-python,auth0/auth0-python |
7bc63a405e278cf5d1b7d7dac0df938dfd7b7583 | lelei/parser.py | lelei/parser.py | import xml.etree.ElementTree as ET
import re
from sizes import SIZE_CHECKERS
def _getroot(str_):
return ET.fromstring(str_)
def bitsForStructure(struct_type, read_bits):
try:
return SIZE_CHECKERS[struct_type](read_bits)
except KeyError:
raise ValueError("the given structure typ... | import xml.etree.ElementTree as ET
import re
from .sizes import SIZE_CHECKERS
def _getroot(str_):
return ET.fromstring(str_)
def bitsForStructure(struct_type, read_bits):
try:
return SIZE_CHECKERS[struct_type](read_bits)
except KeyError:
raise ValueError("the given structure ty... | Improve field parsing: fixed-size fields may not have `bits` attribute | Improve field parsing: fixed-size fields may not have `bits` attribute
Some fields whose type imposes a fixed size may not find
useful a `bits` attribute.
For the sake of explaining, you cannot define a "bitfield float":
not only it makes no sense, but it's not possible to define it in
a C struct or in WSGD format.
| Python | bsd-2-clause | alfateam123/lelei |
68b01ea3b6d70a991d3ca0f3e6bff08290caa292 | packr/home/views.py | packr/home/views.py | from flask import Blueprint, render_template
home = Blueprint('home', __name__)
@home.route('/', defaults={'path': ''})
@home.route('/<path:path>')
def index(path):
print('angularhit')
return render_template('index.html')
| from flask import Blueprint, render_template
home = Blueprint('home', __name__)
@home.route('/', defaults={'path': ''})
@home.route('/<path:path>')
def index(path):
return render_template('index.html')
| Remove uneccessary 'angularhit' debug printout. | Remove uneccessary 'angularhit' debug printout.
| Python | mit | KnightHawk3/packr,KnightHawk3/packr,KnightHawk3/packr,KnightHawk3/packr,KnightHawk3/packr,KnightHawk3/packr |
356257d3a0db07548c2efe0694c2fb210900b38a | keystoneclient/exceptions.py | keystoneclient/exceptions.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.a... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.a... | Migrate the keystone.common.cms to keystoneclient | Migrate the keystone.common.cms to keystoneclient
- Add checking the openssl return code 2, related to following review
https://review.openstack.org/#/c/22716/
- Add support set subprocess to the cms, when we already know which
subprocess to use.
Closes-Bug: #1142574
Change-Id: I3f86e6ca8bb7738f57051ce7f0f5662b... | Python | apache-2.0 | citrix-openstack-build/keystoneauth,jamielennox/keystoneauth,sileht/keystoneauth |
a9755fc4b30629ea2c9db51aa6d4218f99fcabc3 | frigg/deployments/migrations/0004_auto_20150725_1456.py | frigg/deployments/migrations/0004_auto_20150725_1456.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment'... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
... | Set FRIGG_PREVIEW_IMAGE in db migrations | Set FRIGG_PREVIEW_IMAGE in db migrations
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq |
5547f8a11192e9182b6d9aceef99249fc7b9d2cb | froide/publicbody/migrations/0007_auto_20171224_0744.py | froide/publicbody/migrations/0007_auto_20171224_0744.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-24 06:44
from __future__ import unicode_literals
from django.db import migrations
def create_classifications(apps, schema_editor):
from ..models import Classification # Use treebeard API
# Classification = apps.get_model('publicbody', 'Classifi... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-24 06:44
from __future__ import unicode_literals
from django.db import migrations
def create_classifications(apps, schema_editor):
from ..models import Classification as RealClassification # Use treebeard API
Classification = apps.get_model('p... | Fix pb migration, by faking treebeard | Fix pb migration, by faking treebeard | Python | mit | fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide |
262a8fe3651a4ad368fd6594cba0669267c2d225 | run_deploy_job_wr.py | run_deploy_job_wr.py | #!/usr/bin/env python
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/ver... | #!/usr/bin/env python
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/ver... | Add *.json to the list of artifacts backed up by Workspace Runner. | Add *.json to the list of artifacts backed up by Workspace Runner. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju |
b26a92d1e1480a73de4ce5ebe6ea4630fb3bfbc8 | main.py | main.py | """`main` is the top level module for your Flask application."""
# Import the Flask Framework
from flask import Flask
app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
@app.route('/')
def hello():
"""Return a friendly HTTP... | """`main` is the top level module for your Flask application."""
# Import the Flask Framework
from flask import Flask
app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
@app.route('/')
def hello():
"""Return a friendly HTTP... | Add custom 500 error handler so app handler errors aren't supressed | Add custom 500 error handler so app handler errors aren't supressed
| Python | apache-2.0 | psykidellic/appengine-flask-skeleton,STEMgirlsChina/flask-tools,susnata1981/lendingclub,wink-app/wink,googlearchive/appengine-flask-skeleton,igorg1312/googlepythonsskeleton,lchans/ArcAudit,bruxr/Sirius2,waprin/appengine-flask-skeleton,jonparrott/flask-ferris-example,waprin/appengine-flask-skeleton,jsatch/twitclass,susn... |
2775c7f39c0e26b728fe6fb31168328ba4caeab2 | opps/api/models.py | opps/api/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Mod... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Mod... | Fix signal create api key on post save User | Fix signal create api key on post save User
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps |
9e77d9a40ae13cff09051c9975361dca9259b426 | gala/__init__.py | gala/__init__.py | """
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan N... | """
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan N... | Update email in module init | Update email in module init
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala |
b4d43bfbcc03b93826c194fb98a52b411dc6304b | turbustat/tests/test_wrapper.py | turbustat/tests/test_wrapper.py | # Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
| # Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Trav... | Split wrapper tests into smaller chunks | Split wrapper tests into smaller chunks
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat |
f798066d20116d2cfd35cae0bf0771799677f6c2 | py509/bin/verify.py | py509/bin/verify.py | #!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()... | #!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description... | Allow --ca parameter to specify trust store | Allow --ca parameter to specify trust store
| Python | apache-2.0 | sholsapp/py509 |
3131f282d6ad1a703939c91c0d7dc0b3e4e54046 | iati/versions.py | iati/versions.py | """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if... | """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args... | Document the current state of the Version class. | Document the current state of the Version class.
| Python | mit | IATI/iati.core,IATI/iati.core |
ff336e34ab2996c0e01378945b10e4f3bc870a2e | simplekv/_compat.py | simplekv/_compat.py | # -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urll... | # -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
... | Use PY2 check instead of PY3 check. | Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.
| Python | mit | fmarczin/simplekv,fmarczin/simplekv,karteek/simplekv,mbr/simplekv,karteek/simplekv,mbr/simplekv |
eeb284b86e4f6bf535afe0bb7bb009344ff7ec0f | simplekv/_compat.py | simplekv/_compat.py | """Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unq... | """Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unq... | Use basestring to check for key validity in Python 2 | Use basestring to check for key validity in Python 2
| Python | mit | karteek/simplekv,karteek/simplekv |
6654c3741f314e6617d53de6468f739b4304c5eb | tequila/deploy.py | tequila/deploy.py | import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected... | import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected... | Add support for encrypted secrets | Add support for encrypted secrets
| Python | bsd-3-clause | caktus/tequila-django |
ea90ef7193aa779bf6286ef59dc42229ed23c953 | csat/collectors/pygit/__init__.py | csat/collectors/pygit/__init__.py | from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_a... | try:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__ve... | Disable collector and only produce a warning if the git module is not installed | Disable collector and only produce a warning if the git module is not installed
| Python | mit | GaretJax/csat,GaretJax/csat,GaretJax/csat,GaretJax/csat |
4a2b7b775d65aa95f160e1b1f16b7101fbd1e949 | jellyblog/models.py | jellyblog/models.py | from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.For... | import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class... | Document 모델의 category 칼럼명 수정 | Document 모델의 category 칼럼명 수정
| Python | apache-2.0 | kyunooh/JellyBlog,kyunooh/JellyBlog,kyunooh/JellyBlog |
98dce0d4c7eb62edb599aafeb97e2291c01e4dc8 | tests/serial_0.py | tests/serial_0.py | #!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
... | Complete the data print interface. | Complete the data print interface.
| Python | mit | EchoFUN/raspi |
b344d63ad3ff7abff0772a744e951d5d5c8438f3 | carepoint/models/address_mixin.py | carepoint/models/address_mixin.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bin... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This i... | Add ForeignKey on addr_id in carepoint cph address model | Add ForeignKey on addr_id in carepoint cph address model
| Python | mit | laslabs/Python-Carepoint |
4a07f271db4d1aa0b375914093479b3157c4496b | scheduler/listen.py | scheduler/listen.py | import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
... | import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
... | Make is so we run performance against merged patches | Make is so we run performance against merged patches
| Python | apache-2.0 | lbragstad/keystone-performance,lbragstad/keystone-performance,lbragstad/keystone-performance |
6959458a8de9d0536ae859fca2a7fa62bb4bf169 | greatbigcrane/project/forms.py | greatbigcrane/project/forms.py | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 agre... | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 agre... | Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space. | Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.
| Python | apache-2.0 | pnomolos/greatbigcrane,pnomolos/greatbigcrane |
42320a1baa7b4e69170b881090e17a25080bf45c | lib/assemblers/none.py | lib/assemblers/none.py | """Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_c... | """Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_c... | Change file name for output for no assembler given | Change file name for output for no assembler given
| Python | bsd-3-clause | juliema/aTRAM |
daceec30fc422ea035163e80c826423a806d0b85 | django/wwwhisper_auth/backend.py | django/wwwhisper_auth/backend.py | """Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
clas... | """Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
clas... | Correct check if assertion verification failed. | Correct check if assertion verification failed.
| Python | mit | wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper |
aee0c96593343b3b1064d38579bec666bd51c9fa | python/atemctrl.py | python/atemctrl.py | # Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
... | # Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
... | Fix script ending. Set value to show program in aux output. | Fix script ending. Set value to show program in aux output.
| Python | mit | qrila/khvidcontrol,qrila/khvidcontrol |
3c0d52aa0a936b3ae138ddfba66e7ba9dcc5f934 | sympy/plotting/proxy_pyglet.py | sympy/plotting/proxy_pyglet.py | from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versi... | from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future ver... | Change the import location of DeprecationWarning used by plotting module | Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.
| Python | bsd-3-clause | pbrady/sympy,grevutiu-gabriel/sympy,rahuldan/sympy,atsao72/sympy,kmacinnis/sympy,yashsharan/sympy,drufat/sympy,iamutkarshtiwari/sympy,shikil/sympy,atsao72/sympy,jaimahajan1997/sympy,meghana1995/sympy,jerli/sympy,oliverlee/sympy,ahhda/sympy,garvitr/sympy,sahmed95/sympy,abloomston/sympy,kaushik94/sympy,jbbskinny/sympy,cs... |
e507abe78dee3ae4a4261d8bde645f3df7d8b842 | tests/atest/run_tests.py | tests/atest/run_tests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
| Fix test runner for acceptance tests | Fix test runner for acceptance tests
| Python | mit | Eficode/robotframework-imagehorizonlibrary |
b8421633753fae1c0ad849dcc496e1861833243f | memegen/routes/root.py | memegen/routes/root.py | from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route(... | from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route(... | Move version to the bottom of the list | Move version to the bottom of the list
| Python | mit | DanLindeman/memegen,joshfriend/memegen,joshfriend/memegen,DanLindeman/memegen,joshfriend/memegen,DanLindeman/memegen,joshfriend/memegen,DanLindeman/memegen |
b9d8ac45f9cfec1fd1c3a3b0831815026e448a24 | members/views.py | members/views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
memb... | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_vi... | Add view function for councili arhive | Add view function for councili arhive
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
ae4af32bf5ca21b2c7d80e2034560ed23f6a2ea7 | src/main-rpython.py | src/main-rpython.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library... | Add error to make sure we have RPython when using the RPython main | Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
| Python | mit | SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,SOM-st/PySOM,SOM-st/RPySOM,SOM-st/PySOM |
86d6b1cb8655d1734bcd5e5987e9e3df7e69c534 | mkt/operators/views.py | mkt/operators/views.py | from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt... | from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuth... | Allow shared secret auth on OperatorPermissionViewSet. | Allow shared secret auth on OperatorPermissionViewSet.
| Python | bsd-3-clause | clouserw/zamboni,mozilla/zamboni,mudithkr/zamboni,mstriemer/zamboni,mozilla/zamboni,washort/zamboni,ayushagrawal288/zamboni,Jobava/zamboni,Jobava/zamboni,ayushagrawal288/zamboni,elysium001/zamboni,ingenioustechie/zamboni,eviljeff/zamboni,washort/zamboni,ddurst/zamboni,elysium001/zamboni,eviljeff/zamboni,tsl143/zamboni,... |
e56fe4e39db2a6043493542664d320c6127d4741 | ecmd-core/pyapi/init/__init__.py | ecmd-core/pyapi/init/__init__.py | # import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from ... | # import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join... | Rework of path insert since del line was causing issues | Rework of path insert since del line was causing issues
| Python | apache-2.0 | open-power/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.