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 |
|---|---|---|---|---|---|---|---|---|---|
d1a893514092a2495fcd2b14365b9b014fd39f59 | calaccess_processed/models/__init__.py | calaccess_processed/models/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Import all of the models from submodules and thread them together.
"""
from calaccess_processed.models.campaign.entities import (
Candidate,
CandidateCommittee,
)
from calaccess_processed.models.campaign.filings import (
Form460,
Form460Version,
Sche... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Import all of the models from submodules and thread them together.
"""
from calaccess_processed.models.campaign.entities import (
Candidate,
CandidateCommittee,
)
from calaccess_processed.models.campaign.filings import (
Form460,
Form460Version,
Sche... | Add missing models to __all__ list | Add missing models to __all__ list
| Python | mit | california-civic-data-coalition/django-calaccess-processed-data,california-civic-data-coalition/django-calaccess-processed-data |
64dd3ecb1cf5adbf68d59d231b67e7d30ace715f | scripts/create-hosted-graphite-dashboards.py | scripts/create-hosted-graphite-dashboards.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description:
To add
Usage:
scripts/create-hosted-graphite-dashboards.py <hosted_graphite_api_key>
Example:
scripts/create-hosted-graphite-dashboards.py apikey
"""
import os
import sys
import requests
from docopt import docopt
sys.path.insert(0, '.') # ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description:
This pushes dashboards defined in /grafana directory up to our hosted graphite.
You can get the <hosted_graphite_api_key> from the "Account Home" page of hosted graphite.
To change a dashboard a process you should follow is:
1. Set "editabl... | Update docstring for creating hosted graphite dashboards | Update docstring for creating hosted graphite dashboards
| Python | mit | alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws |
1bba76808aa5c598f1558cd127d8ed4a006692e1 | tests/conftest.py | tests/conftest.py | import os
def pytest_configure(config):
if 'USE_QT_API' in os.environ:
os.environ['QT_API'] = os.environ['USE_QT_API'].lower()
def pytest_report_header(config):
versions = os.linesep
versions += 'PyQt4: '
try:
from PyQt4 import Qt
versions += "PyQt: {0} - Qt: {1}".format(Qt... | import os
def pytest_configure(config):
if 'USE_QT_API' in os.environ:
os.environ['QT_API'] = os.environ['USE_QT_API'].lower()
# We need to import qtpy here to make sure that the API versions get set
# straight away.
import qtpy
def pytest_report_header(config):
versions = os.linesep
... | Make sure we import qtpy before importing any Qt wrappers directly | Make sure we import qtpy before importing any Qt wrappers directly | Python | mit | spyder-ide/qtpy,goanpeca/qtpy,davvid/qtpy,davvid/qtpy,goanpeca/qtpy |
8359d60480371a8f63bdd4ea1b7cf03f231c1350 | djangopress/settings_tinymce.py | djangopress/settings_tinymce.py | # if you want support for tinymce in the admin pages
# add tinymce to the installed apps (after installing if needed)
# and then import these settings, or copy and adjust as needed
TINYMCE_DEFAULT_CONFIG = {
'relative_urls': False,
'plugins': "table code image link colorpicker textcolor wordcount",
'tools'... | # if you want support for tinymce in the admin pages
# add tinymce to the installed apps (after installing if needed)
# and then import these settings, or copy and adjust as needed
TINYMCE_DEFAULT_CONFIG = {
'relative_urls': False,
'plugins': "table code image link colorpicker textcolor wordcount",
'tools'... | Update settings for tinymce to allow show_blog_latest tag | Update settings for tinymce to allow show_blog_latest tag
| Python | mit | codefisher/djangopress,codefisher/djangopress,codefisher/djangopress,codefisher/djangopress |
3ca7c667cbf37499dc959b336b9ff0e88f5d4275 | dbarray/tests/run.py | dbarray/tests/run.py | """From http://stackoverflow.com/a/12260597/400691"""
import sys
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbarray',
'HOST': 'localhost'
}
},
INSTALLED_APPS... | """From http://stackoverflow.com/a/12260597/400691"""
import sys
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbarray',
'HOST': 'localhost'
}
},
INSTALLED_APPS... | Remove commented code . | Remove commented code [ci skip].
| Python | bsd-3-clause | ecometrica/django-dbarray |
a1bf03f69b9cadddcc7e0015788f23f9bad0f862 | apps/splash/views.py | apps/splash/views.py | import datetime
from django.shortcuts import render
from apps.splash.models import SplashEvent, SplashYear
def index(request):
# I'm really sorry ...
splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180)))
return render(request, 'splash/base.html', {'splas... | import datetime
from django.shortcuts import render
from apps.splash.models import SplashEvent, SplashYear
def index(request):
# I'm really sorry ...
splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180)))
splash_year.events = _merge_events(splash_year.sp... | Append event merging on splash_events | Append event merging on splash_events
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
3fad3c64a317956265c14c82c182b66979ba8554 | greatbigcrane/preferences/forms.py | greatbigcrane/preferences/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... | Append a trailing newline to the project directory | Append a trailing newline to the project directory
| Python | apache-2.0 | pnomolos/greatbigcrane,pnomolos/greatbigcrane |
62454216b7d0426c23d75ba4aafd761093447e63 | compiler.py | compiler.py | #!/usr/local/bin/python3
import http.client, urllib.parse, sys, argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--js", default='/dev/stdin', help="Input file")
parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
parser.add_argument("--compila... | #!/usr/local/bin/python3
import http.client, urllib.parse, sys, argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--js", default='/dev/stdin', help="Input file")
parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
parser.add_argument("--compila... | Add js_externs parameter for API | Add js_externs parameter for API
| Python | mit | femtopixel/docker-google-closure-compiler-api,femtopixel/docker-google-closure-compiler-api |
d8344f9bea9cfbc8ab22b952f223d2365de907b4 | cli_helpers/tabular_output/terminaltables_adapter.py | cli_helpers/tabular_output/terminaltables_adapter.py | # -*- coding: utf-8 -*-
"""Format adapter for the terminaltables module."""
import terminaltables
from cli_helpers.utils import filter_dict_by_key
from .preprocessors import (bytes_to_string, align_decimals,
override_missing_value)
supported_formats = ('ascii', 'double', 'github')
preproc... | # -*- coding: utf-8 -*-
"""Format adapter for the terminaltables module."""
import terminaltables
from cli_helpers.utils import filter_dict_by_key
from .preprocessors import (bytes_to_string, align_decimals,
override_missing_value)
supported_formats = ('ascii', 'double', 'github')
preproc... | Remove try/except that should never be hit. | Remove try/except that should never be hit.
Increases code coverage.
| Python | bsd-3-clause | dbcli/cli_helpers,dbcli/cli_helpers |
9a58d241e61301b9390b17e391e4b65a3ea85071 | squadron/libraries/apt/__init__.py | squadron/libraries/apt/__init__.py | import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'stri... | import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'stri... | Remove extra print in apt | Remove extra print in apt
| Python | mit | gosquadron/squadron,gosquadron/squadron |
aae84224b5a2d1689b1739da319d140474702c96 | zuice/bindings.py | zuice/bindings.py | class Bindings(object):
def __init__(self):
self._bindings = {}
def bind(self, key):
if key in self:
raise AlreadyBoundException("Cannot rebind key: %s" % key)
return Binder(key, self._bindings)
def copy(self):
copy = Bindings()
copy._bindings = ... | class Bindings(object):
def __init__(self):
self._bindings = {}
def bind(self, key, provider=None):
if key in self:
raise AlreadyBoundException("Cannot rebind key: %s" % key)
if provider is None:
return Binder(key, self)
else:
... | Simplify detection of keys already bound | Simplify detection of keys already bound
| Python | bsd-2-clause | mwilliamson/zuice |
66212e51341562f156353a0ae195d15b0d22b21b | scripts/import.py | scripts/import.py | #!/usr/bin/env python
import sys
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir in subdirs:... | #!/usr/bin/env python
import sys
import json
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir... | PUT services rather than POSTing them | PUT services rather than POSTing them
| Python | mit | RichardKnop/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,mtekel/digitalmarketplace-api,mtekel/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,alphagov/digitalmarketplace-api,mtekel/digitalmarketplace-api,alphagov/digitalmarketplace-api,mtekel/digitalmarketplace-... |
95b08a7cb2d473c25c1d326b0394336955b47af4 | appy/models.py | appy/models.py | from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
class... | from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
def __unicode__(self):
return self.description
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = model... | Add unicode representations for tags/positions | Add unicode representations for tags/positions
| Python | mit | merdey/ApPy,merdey/ApPy |
2b43ab4eb41e305c5bdadf5c338e134e5569249d | tests/conftest.py | tests/conftest.py | # pylint: disable=C0111
import pytest
import os
import tarfile
BASEDIR = os.path.dirname(__file__)
@pytest.fixture(autouse=False)
def set_up(tmpdir):
# print BASEDIR
tmpdir.chdir()
tar = tarfile.open(os.path.join(BASEDIR, "MockRepos.tar.gz"))
tar.extractall()
tar.close()
os.chdir('MockRepos')
print('In directo... | # pylint: disable=C0111
import pytest
import os
import tarfile
BASEDIR = os.path.dirname(__file__)
@pytest.fixture(autouse=False)
def set_up(tmpdir):
# print BASEDIR
tmpdir.chdir()
tar = tarfile.open(os.path.join(BASEDIR, "MockRepos.tar.gz"))
tar.extractall()
tar.close()
os.chdir('MockRepos')
print('In directo... | Add session setup and teardown fixtures. | Add session setup and teardown fixtures. | Python | mit | bilderbuchi/ofStateManager |
98bded02b1b5116db640f5e58f73920108af0b0c | tests/test_set.py | tests/test_set.py | import matplotlib
import fishbowl
original = []
updated = [r'\usepackage{mathspec}',
r'\setallmainfonts(Digits,Latin,Greek){Arbitrary}']
def test_context_set():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
assert matplotlib.rcParams['pgf... | import matplotlib
import fishbowl
original = True
updated = False
def test_context_set():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
assert matplotlib.rcParams['axes.spines.left'] == updated
def test_context_reset():
fishbowl.reset_style()
... | Update tests to remove pgf.preamble | Update tests to remove pgf.preamble
| Python | mit | baxen/fishbowl |
e6d965cc36d92ee8f138d487614244c6e3deda69 | run_tests.py | run_tests.py | from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
test_list = []
dist_dir = libtbx.env.dist_path(module)
class TestDiscoveryPlugin:
def pytest_... | from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
def pytest_warning():
print "=" * 60
print "WARNING: Skipping some tests\n"
print "To run all available tests you need to install pytest"
print "... | Add warning for skipped tests if pytest not available | Add warning for skipped tests if pytest not available
| Python | bsd-3-clause | xia2/i19 |
baedff75f2b86f09368e3bd72b72e27bf887cc88 | rotational-cipher/rotational_cipher.py | rotational-cipher/rotational_cipher.py | import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
return "".join(rot_gen(s,n))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
def rot_gen(s, n):
rules = shift_rules(n)
f... | import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(map(lambda k: rules.get(k, k), s))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
| Use lambda function with method | Use lambda function with method
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
939ebf2eb4536fd5a6318d6cc4b55a9dc4c8def2 | documentation/compile_documentation.py | documentation/compile_documentation.py | import sys
import os
def find_code(text):
START_TAG = '```lpg'
END_TAG = '```'
first_index = text.find(START_TAG)
if first_index == -1:
return None, None
last_index = text.find(END_TAG, first_index + 1)
return first_index + len(START_TAG), last_index
def process_file(path):
conte... | import sys
import os
def find_code(text):
START_TAG = '```lpg'
END_TAG = '```'
first_index = text.find(START_TAG)
if first_index == -1:
return None, None
last_index = text.find(END_TAG, first_index + 1)
return first_index + len(START_TAG), last_index
def process_file(path):
conte... | Split the documentation compilation into different files | Split the documentation compilation into different files
| Python | mit | TyRoXx/Lpg,TyRoXx/Lpg,TyRoXx/Lpg,mamazu/Lpg,mamazu/Lpg,mamazu/Lpg,TyRoXx/Lpg,mamazu/Lpg,TyRoXx/Lpg |
c7fd327623dfa84a91931771265932d4da95d766 | 001-xoxoxo-obj/harness.py | 001-xoxoxo-obj/harness.py | from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._outpu... | from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._outpu... | Fix nierozpoznawania bledu gracza w pierwszym ruchu | Fix nierozpoznawania bledu gracza w pierwszym ruchu
| Python | mit | gynvael/stream,gynvael/stream,gynvael/stream,gynvael/stream,gynvael/stream,gynvael/stream |
9a34e663f9ef65cdac91c42dcf198ae28d4385be | txircd/modbase.py | txircd/modbase.py | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
class Module(object):
def hook(self, base):
self.... | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
class Module(object):
def hook(self, base):
self.... | Add a function for commands to process parameters | Add a function for commands to process parameters
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd,DesertBus/txircd |
a1cc1c08e9ff36ff0293f0224ca0acb41f065073 | alg_selection_sort.py | alg_selection_sort.py | def selection_sort(a_list):
"""Selection Sort algortihm.
Concept: Find out the maximun item's original slot first,
then switch it to the max slot. Iterate the procedure.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
... | def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the maximun item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in ra... | Revise doc string for selection sort’s concept | Revise doc string for selection sort’s concept
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
a30e51ccb74bc55924be6f7f79dc4b6038c9b457 | altair/examples/bar_chart_with_highlighted_segment.py | altair/examples/bar_chart_with_highlighted_segment.py | """
Bar Chart with Highlighted Segment
----------------------------------
This example shows a bar chart that highlights values beyond a threshold.
"""
import altair as alt
import pandas as pd
from vega_datasets import data
source = data.wheat()
threshold = pd.DataFrame([{"threshold": 90}])
bars = alt.Chart(source).m... | """
Bar Chart with Highlighted Segment
----------------------------------
This example shows a bar chart that highlights values beyond a threshold.
"""
# category: bar charts
import altair as alt
import pandas as pd
from vega_datasets import data
source = data.wheat()
threshold = pd.DataFrame([{"threshold": 90}])
bar... | Move bar chart with highlighted segment chart into the bar charts section | Move bar chart with highlighted segment chart into the bar charts section | Python | bsd-3-clause | altair-viz/altair |
09340916e7db6ba8ccb5697b9444fbccc0512103 | example/example/views.py | example/example/views.py | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = fo... | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = fo... | Add `can_delete=True` to the example formset | Add `can_delete=True` to the example formset
| Python | bsd-2-clause | pretix/django-formset-js,pretix/django-formset-js,pretix/django-formset-js |
de11b473a6134ed1403e91d55d30c23e6683a926 | test/runner/versions.py | test/runner/versions.py | #!/usr/bin/env python
"""Show python and pip versions."""
import os
import sys
try:
import pip
except ImportError:
pip = None
print('.'.join(u'%s' % i for i in sys.version_info))
if pip:
print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
| #!/usr/bin/env python
"""Show python and pip versions."""
import os
import sys
try:
import pip
except ImportError:
pip = None
print(sys.version)
if pip:
print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
| Revert "Relax ansible-test python version checking." | Revert "Relax ansible-test python version checking."
This reverts commit d6cc3c41874b64e346639549fd18d8c41be0db8b.
| Python | mit | thaim/ansible,thaim/ansible |
c3ead540e7008ba1a3d01df695620bc952564805 | sphinx/fabfile.py | sphinx/fabfile.py | from fabric.api import run, env, roles
from fabric.contrib.project import rsync_project
import sys
sys.path.append("source")
import conf
env.roledefs = {
'web': ['bokeh.pydata.org']
}
env.user = "bokeh"
@roles('web')
def deploy(v=None):
if v is None:
v = conf.version
# make a backup of the old ... | from fabric.api import run, env, roles
from fabric.contrib.files import exists
from fabric.contrib.project import rsync_project
import sys
sys.path.append("source")
import conf
env.roledefs = {
'web': ['bokeh.pydata.org']
}
env.user = "bokeh"
@roles('web')
def deploy(v=None):
if v is None:
v = conf.... | Add error if latest is passed to deploy. Also check if the path exist before meaking the symlink. | Add error if latest is passed to deploy. Also check if the path exist before meaking the symlink.
| Python | bsd-3-clause | Karel-van-de-Plassche/bokeh,aavanian/bokeh,clairetang6/bokeh,matbra/bokeh,quasiben/bokeh,justacec/bokeh,schoolie/bokeh,rothnic/bokeh,evidation-health/bokeh,ptitjano/bokeh,muku42/bokeh,percyfal/bokeh,daodaoliang/bokeh,KasperPRasmussen/bokeh,aiguofer/bokeh,CrazyGuo/bokeh,draperjames/bokeh,mindriot101/bokeh,percyfal/bokeh... |
cb28bba6ee642828df473383ea469a6aa46ca59c | skimage/util/unique.py | skimage/util/unique.py | import numpy as np
def unique_rows(ar):
"""Remove repeated rows from a 2D array.
Parameters
----------
ar : 2D np.ndarray
The input array.
Returns
-------
ar_out : 2D np.ndarray
A copy of the input array with repeated rows removed.
Raises
------
ValueError : ... | import numpy as np
def unique_rows(ar):
"""Remove repeated rows from a 2D array.
Parameters
----------
ar : 2D np.ndarray
The input array.
Returns
-------
ar_out : 2D np.ndarray
A copy of the input array with repeated rows removed.
Raises
------
ValueError : ... | Add note describing array copy if discontiguous | Add note describing array copy if discontiguous
| Python | bsd-3-clause | paalge/scikit-image,Midafi/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,warmspringwinds/scikit-image,Britefury/scikit-image,rjeli/scikit-image,ofgulban/scikit-image,emon10005/scikit-image... |
88ec3066a191f22b1faa3429ae89cbd76d45ac9b | aore/config/dev.py | aore/config/dev.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .common import *
sphinx_conf.listen = "127.0.0.1:9312"
sphinx_conf.var_dir = "C:\\Sphinx"
db_conf.database = "postgres"
db_conf.host = "localhost"
db_conf.port = 5432
db_conf.user = "postgres"
db_conf.password = "intercon"
unrar_config.path = "C:\... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .common import *
sphinx_conf.listen = "192.168.0.37:9312"
sphinx_conf.var_dir = "C:\\Sphinx"
db_conf.database = "postgres"
db_conf.host = "192.168.0.37"
db_conf.port = 5432
db_conf.user = "postgres"
db_conf.password = "intercon"
unrar_config.path ... | Test global ip with Sphinx | Test global ip with Sphinx
| Python | bsd-3-clause | jar3b/py-phias,jar3b/py-phias,jar3b/py-phias,jar3b/py-phias |
f60b940205a5e1011ce1c9c5672cb262c4649c0b | app/mod_auth/forms.py | app/mod_auth/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField, PasswordField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('username', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
remember_me... | from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField, PasswordField
from wtforms.validators import DataRequired, ValidationError, EqualTo
from .models import User
class LoginForm(FlaskForm):
username = StringField('username', validators=[DataRequired()])
password = PasswordField('pass... | Validate username and password on signup | Validate username and password on signup
| Python | mit | ziel980/website,ziel980/website |
3d38af257f55a0252cb41408a404faa66b30d512 | pyconde/speakers/models.py | pyconde/speakers/models.py | from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Speaker(models.Model):
"""
The speaker model acts as user-abstraction for various session and proposal
related objects.
"""
user = models.OneToOneField(User, related_name='sp... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
class Speaker(models.Model):
"""
... | Create a speaker profile for each user that is registered. | Create a speaker profile for each user that is registered.
| Python | bsd-3-clause | pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep |
579286426cf20c5cd5d4c94d97fd0a55eb571f8f | talks_keeper/templatetags/tk_filters.py | talks_keeper/templatetags/tk_filters.py | from django import template
from django.forms import CheckboxInput
register = template.Library()
@register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
@register.filter(name='is_checkbox')
def is_checkbox(field):
return field.field.widget.__class__.__name_... | from django import template
from django.forms import CheckboxInput
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
@register.filter(name='is_checkbox')
def is_checkbox(field):
... | Add templatetag to check if user included in group | Add templatetag to check if user included in group
| Python | mit | samitnuk/talks_keeper,samitnuk/talks_keeper,samitnuk/talks_keeper |
d52c9731b0c6494e9f4181fc33f00cdf39adb3ca | tests/unit/test_util.py | tests/unit/test_util.py | import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
| import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
@pytest.has_internet
def test_emergency_compliment():
assert util.load_emergency_compliments()
| Add test for emergency compliments | Add test for emergency compliments
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot |
5b8bcdd802858baae3854fbfb8758dc65bdd8d34 | hardware/unicorn_hat_hd/demo_lights.py | hardware/unicorn_hat_hd/demo_lights.py | #!/usr/bin/env python
import unicornhathd
import os
try:
unicornhathd.set_pixel(0, 0, 255, 255, 255)
unicornhathd.set_pixel(15, 0, 255, 255, 255)
unicornhathd.set_pixel(0, 15, 255, 255, 255)
unicornhathd.set_pixel(15, 15, 255, 255, 255)
unicornhathd.show()
raw_input("Press the <ENTER> key or <C... | #!/usr/bin/env python
import unicornhathd
import os
from time import sleep
class Point:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def turn_on(self):
unicornhathd.set_pixel(self.x, self.y, 255, 255, 255)
def turn_off(self):
... | Make the 4 lights bounce backwards and forwards along each edge. | Make the 4 lights bounce backwards and forwards along each edge.
| Python | mit | claremacrae/raspi_code,claremacrae/raspi_code,claremacrae/raspi_code |
59c4dd56e427e29eb26e81512c3066fe3f8b13b8 | tools/gdb/gdb_chrome.py | tools/gdb/gdb_chrome.py | #!/usr/bin/python
# Copyright (c) 2011 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.
"""GDB support for Chrome types.
Add this to your gdb by amending your ~/.gdbinit as follows:
python
import sys
sys.path.insert(... | #!/usr/bin/python
# Copyright (c) 2011 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.
"""GDB support for Chrome types.
Add this to your gdb by amending your ~/.gdbinit as follows:
python
import sys
sys.path.insert(... | Add FilePath to the gdb pretty printers. | Add FilePath to the gdb pretty printers.
Review URL: http://codereview.chromium.org/6621017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,nacl-webk... |
ad5cb91fa011e067a96835e59e05581af3ea3a53 | acctwatch/configcheck.py | acctwatch/configcheck.py | import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
geoipdb = None
def main():
config = Co... | import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
print ("GeoIP is missing, please install de... | Clean up configuration check utility | Clean up configuration check utility
| Python | isc | GuardedRisk/Google-Apps-Auditing |
fae3f6aaba91167c5da2f3d5d9b6b1a66068f9f7 | setup.py | setup.py | from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',... | import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',... | Test edit - to check svn email hook | Test edit - to check svn email hook | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD |
2a7877c1ed3e1dc9a5bcc27220847a5a75cf65ab | spiff/membership/management/commands/bill_members.py | spiff/membership/management/commands/bill_members.py | from django.core.management import BaseCommand
from spiff.membership.utils import monthRange
from spiff.membership.models import Member, RankLineItem
from spiff.payment.models import Invoice
class Command(BaseCommand):
help = 'Bills active members for the month'
def handle(self, *args, **options):
for member ... | from django.core.management import BaseCommand
from spiff.membership.utils import monthRange
from spiff.membership.models import Member, RankLineItem
from spiff.payment.models import Invoice
class Command(BaseCommand):
help = 'Bills active members for the month'
def handle(self, *args, **options):
for member ... | Fix swapped dates on invoices | Fix swapped dates on invoices
| Python | agpl-3.0 | SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff |
e3409c94b64deac85deada28f57a30ae08d0083d | api/caching/listeners.py | api/caching/listeners.py | from functools import partial
from api.caching.tasks import ban_url
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from modularodm import signals
@signals.save.connect
def ban_object_from_cache(sender, instance, fields_changed, cached_data):
abs_url = None
if hasattr(instance, 'absol... | from functools import partial
from api.caching.tasks import ban_url
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from modularodm import signals
@signals.save.connect
def ban_object_from_cache(sender, instance, fields_changed, cached_data):
abs_url = None
if hasattr(instance, 'absolu... | Fix passing arguments to ban_url | Fix passing arguments to ban_url
h/t @cwisecarver
| Python | apache-2.0 | chrisseto/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,SSJohns/osf.io,alexschiller/osf.io,mluke93/osf.io,rdhyee/osf.io,zachjanicki/osf.io,wearpants/osf.io,leb2dg/osf.io,caneruguz/osf.io,zamattiac/osf.io,TomHeatwole/osf.io,mattclark/osf.io,aaxelb/osf.io,felliott/osf.io,caseyrollins/osf.io,mluke93/osf.io,erinspace/osf.io,R... |
d3e2a11f72f6de811f39ac10aa0abde74b99d269 | hcibench/pipeline/__init__.py | hcibench/pipeline/__init__.py | """
The :mod:`hcibench.pipeline` module provides a flexible infrastructure for
data processing and implements some common types of processing blocks.
"""
from .base import PipelineBlock, Pipeline, PassthroughPipeline
from .common import Windower, Filter, FeatureExtractor
__all__ = ['PipelineBlock',
'Pipeli... | """
The :mod:`hcibench.pipeline` module provides a flexible infrastructure for
data processing and implements some common types of processing blocks.
"""
from .base import PipelineBlock, Pipeline, PassthroughPipeline
from .common import Windower, Filter, FeatureExtractor, Estimator
__all__ = ['PipelineBlock',
... | Make Estimator importable from pipeline. | Make Estimator importable from pipeline.
| Python | mit | ucdrascal/axopy,ucdrascal/hcibench |
fdb7c400adb777cdc60cf034569d81e95797cc10 | infupy/backends/common.py | infupy/backends/common.py | import sys
from abc import ABCMeta, abstractmethod
def printerr(msg, e=''):
msg = "Backend: " + str(msg)
print(msg.format(e), file=sys.stderr)
class CommandError(Exception):
def __str__(self):
return "Command error: {}".format(self.args)
class Syringe(metaclass=ABCMeta):
_events = set()
... | import sys
from abc import ABCMeta, abstractmethod
def printerr(msg, e=''):
msg = "Backend: " + str(msg)
print(msg.format(e), file=sys.stderr)
class CommandError(Exception):
def __str__(self):
return "Command error: {}".format(self.args)
class Syringe(metaclass=ABCMeta):
_events = set()
... | Make abstract methods raise not implemented | Make abstract methods raise not implemented
| Python | isc | jaj42/infupy |
ff921ad5b1d85dc9554dfcd9d94d96f9f80b0d2b | setup.py | setup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017 qsuscs, TobiX
import os
import sys
from glob import glob
os.chdir(os.path.dirname(__file__))
exit = 0
for f in glob('dot.*'):
dst = os.path.expanduser('~/' + f[3:].replace(u'\u2571', '/'))
src = os.path.join(os.getcwd(), f)
src_rel = os.path.relpath... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017 qsuscs, TobiX
from __future__ import print_function, unicode_literals
import os
import sys
from glob import glob
os.chdir(os.path.dirname(os.path.abspath(__file__)))
exit = 0
for f in glob('dot.*'):
dst = os.path.expanduser('~/' + f[3:].replace(u'\u2571', ... | Fix compatibility with Python 2 ;) | Fix compatibility with Python 2 ;)
| Python | isc | TobiX/dotfiles,TobiX/dotfiles |
c638dbf619030c8d207e3bfd2e711da7c6c5cdf4 | passman.py | passman.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from splash import showSplash
from functions import quit, getServiceFromUser, getPasswordFromUser, writeToFile
def main():
while True:
service = getServiceFromUser()
pw = getPasswordFromUser()
writeToFile(service, pw)
# run the program
showSp... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import hashlib
from splash import showSplash
from functions import quit, getServiceFromUser, getPasswordFromUser, \
getUserInput, handleLogin, welcomeMessage, showMenu
from database import addUser, getAllServices, checkIfServiceExists, \
addService, removeService,... | Clean up main a bit | Clean up main a bit
| Python | mit | regexpressyourself/passman |
1dbc30202bddfd4f03bdc9a8005de3c363d2ac1d | blazar/plugins/dummy_vm_plugin.py | blazar/plugins/dummy_vm_plugin.py | # Copyright (c) 2013 Mirantis 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | # Copyright (c) 2013 Mirantis 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Add update_reservation to dummy plugin | Add update_reservation to dummy plugin
update_reservation is now an abstract method. It needs to be added to
all plugins.
Change-Id: I921878bd5233613b804b17813af1aac5bdfed9e7
| Python | apache-2.0 | ChameleonCloud/blazar,ChameleonCloud/blazar,openstack/blazar,stackforge/blazar,stackforge/blazar,openstack/blazar |
7fa490cb598aca2848ce886dfc45bb8606f07e58 | backend/geonature/core/gn_profiles/models.py | backend/geonature/core/gn_profiles/models.py | from geonature.utils.env import DB
from utils_flask_sqla.serializers import serializable
@serializable
class VmCorTaxonPhenology(DB.Model):
__tablename__ = "vm_cor_taxon_phenology"
__table_args__ = {"schema": "gn_profiles"}
cd_ref = DB.Column(DB.Integer)
period = DB.Column(DB.Integer)
id_nomenclatu... | from flask import current_app
from geoalchemy2 import Geometry
from utils_flask_sqla.serializers import serializable
from utils_flask_sqla_geo.serializers import geoserializable
from geonature.utils.env import DB
@serializable
class VmCorTaxonPhenology(DB.Model):
__tablename__ = "vm_cor_taxon_phenology"
__ta... | Add VM valid profile model | Add VM valid profile model
| Python | bsd-2-clause | PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature |
c5b73be1bf0f0edd05c4743c2449bee568d01c76 | setup.py | setup.py | from distutils.core import setup
from turbasen import VERSION
name = 'turbasen'
setup(
name=name,
packages=[name],
version=VERSION,
description='Client for Nasjonal Turbase REST API',
author='Ali Kaafarani',
author_email='ali.kaafarani@turistforeningen.no',
url='https://github.com/Turbase... | from distutils.core import setup
from os import path
from turbasen import VERSION
name = 'turbasen'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name=name,
packages=[name],
version=VERSION,
descript... | Add long description from README | Add long description from README
| Python | mit | Turbasen/turbasen.py |
69281da6f69bbdc5cfb832efa0b0c1b7810eb262 | setup.py | setup.py | # -*- coding: utf-8 -*-
from distutils.core import setup
readme_file = open('README.rst')
setup(
name='django-db-file-storage',
version='0.3.1',
author='Victor Oliveira da Silva',
author_email='victor_o_silva@hotmail.com',
packages=['db_file_storage'],
url='https://github.com/victor-o-silva/d... | # -*- coding: utf-8 -*-
from distutils.core import setup
readme_file = open('README.rst')
setup(
name='django-db-file-storage',
version='0.3.1',
author='Victor Oliveira da Silva',
author_email='victor_o_silva@hotmail.com',
packages=['db_file_storage'],
url='https://github.com/victor-o-silva/d... | Mark as compatible for python 2.7, 3.3 and 3.4 | Mark as compatible for python 2.7, 3.3 and 3.4
Add `classifiers` parameter to `setup` function call in `setup.py` file. | Python | mit | victor-o-silva/db_file_storage,victor-o-silva/db_file_storage |
ae966a3cb7f99e5604c8302680f125e12087003a | blackhole/state.py | blackhole/state.py |
class MailState():
_reading_data = False
def set_reading(self, val):
self._reading_data = val
def get_reading(self):
return self._reading_data
| class MailState():
_reading_data = False
def set_reading(self, val):
self._reading_data = val
@property
def reading(self):
return self._reading_data
| Change getter in to property | Change getter in to property | Python | mit | kura/blackhole,kura/blackhole |
e50fc12459e6ff77864fe499b512a57e89f7ead2 | pi_control_service/gpio_service.py | pi_control_service/gpio_service.py | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_ur... | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_ur... | Send exception message in response | Send exception message in response
| Python | mit | projectweekend/Pi-Control-Service,HydAu/ProjectWeekds_Pi-Control-Service |
fe4fec66cbf4100752c4b7414090019ab8ddb8ce | ideascube/conf/idb_bdi.py | ideascube/conf/idb_bdi.py | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... | Add cards for Ideasbox in Burundi | Add cards for Ideasbox in Burundi
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
d75a79d10658ad32a9b1d71e472372d8335c7bb6 | ml/test_amaranth_lib.py | ml/test_amaranth_lib.py | # Lint as: python3
"""These tests ensure correctness for the helper functions in amaranth_lib."""
import unittest
class TestAmaranthHelpers(unittest.TestCase):
def test_load_calorie_data(self):
raise NotImplementedError
def test_clean_data(self):
raise NotImplementedError
def test_add_calorie_labels... | # Lint as: python3
"""These tests ensure correctness for the helper functions in amaranth_lib."""
import unittest
class TestAmaranthHelpers(unittest.TestCase):
def test_combine_dataframes(self):
raise NotImplementedError
def test_get_calorie_data(self):
raise NotImplementedError
def test_clean_data(... | Update testing stubs with helper lib changes | Update testing stubs with helper lib changes
| Python | apache-2.0 | googleinterns/amaranth,googleinterns/amaranth |
3bc52b94479e3b0e147ff6ef4bcc8379a5b57249 | trunk/mobile_portal/mobile_portal/core/middleware.py | trunk/mobile_portal/mobile_portal/core/middleware.py | from django.conf import settings
import geolocation
from mobile_portal.wurfl.wurfl_data import devices
from mobile_portal.wurfl import device_parents
from pywurfl.algorithms import DeviceNotFound
from mobile_portal.wurfl.vsm import VectorSpaceAlgorithm
class LocationMiddleware(object):
vsa = VectorSpaceAlgorithm(... | from django.conf import settings
import geolocation
from mobile_portal.wurfl.wurfl_data import devices
from mobile_portal.wurfl import device_parents
from pywurfl.algorithms import DeviceNotFound
from mobile_portal.wurfl.vsm import VectorSpaceAlgorithm
class LocationMiddleware(object):
vsa = VectorSpaceAlgorithm(... | Fix bug when Opera Mini (and possibly others) present no X-OperaMini-Phone header. | Fix bug when Opera Mini (and possibly others) present no X-OperaMini-Phone header.
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
ef81886e4ecf08c12783e0cc2b934ed812accb97 | Zika_vdb_upload.py | Zika_vdb_upload.py | import os, re, time, datetime, csv, sys
import rethinkdb as r
from Bio import SeqIO
from vdb_upload import vdb_upload
from vdb_upload import parser
class Zika_vdb_upload(vdb_upload):
def __init__(self, fasta_fields, fasta_fname, database, virus, source, locus=None, vsubtype=None, authors=None, path=None, auth_ke... | import os, re, time, datetime, csv, sys
import rethinkdb as r
from Bio import SeqIO
from vdb_upload import vdb_upload
from vdb_upload import parser
class Zika_vdb_upload(vdb_upload):
def __init__(self, fasta_fields, fasta_fname, database, virus, source, locus=None, vsubtype=None, authors=None, path=None, auth_ke... | Modify Zika fasta fields to match default VIPRBRC ordering. | Modify Zika fasta fields to match default VIPRBRC ordering.
| Python | agpl-3.0 | blab/nextstrain-db,nextstrain/fauna,blab/nextstrain-db,nextstrain/fauna |
0319ff5049da2c53d8b6507d7fc625ce00a421af | compare.py | compare.py | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a pytho... | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr clas... | Implement @matcher decorator to register matchers. | Implement @matcher decorator to register matchers.
| Python | bsd-3-clause | rudylattae/compare,rudylattae/compare |
52c8ee184cc0071187c1915c4f3e6f287f3faa81 | config/__init__.py | config/__init__.py | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Re... | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Re... | Make sure use_testing() is not detected as a unit test by nose | config: Make sure use_testing() is not detected as a unit test by nose
| Python | agpl-3.0 | shadowoneau/skylines,kerel-fs/skylines,Turbo87/skylines,kerel-fs/skylines,snip/skylines,Harry-R/skylines,snip/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,skylines-project/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines,skylines-project/... |
7db4a5a365c0d96d65b38b3fd33872080179cf93 | benchexec/tools/kissat.py | benchexec/tools/kissat.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | Modify the tool-info module according to Philipp's reviews | Modify the tool-info module according to Philipp's reviews
| Python | apache-2.0 | ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec |
c6dcb3cb3dd0a7ab4101275a1e96c629e5d7ba28 | tools/misc/python/test-data-in-out3.py | tools/misc/python/test-data-in-out3.py | # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
| # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
| Move python3 custom runtime to sadl | Move python3 custom runtime to sadl | Python | mit | chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools |
ab4983e577b9831b91290976be00917edb9fad6f | mlox/modules/resources.py | mlox/modules/resources.py | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b... | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b... | Switch back to using the old SVN update location. | Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update.
| Python | mit | EmperorArthur/mlox,EmperorArthur/mlox,EmperorArthur/mlox |
2b2696dde438a46a7b831867111cc767a88bf77e | lib/DjangoLibrary.py | lib/DjangoLibrary.py | from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST S... | # -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance... | Add version, utf-8 and some comments. | Add version, utf-8 and some comments.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary |
ac7902ad4d4c4df94fa6b13ae9ef18623d63b900 | tests/_utils.py | tests/_utils.py | import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
| import os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
| Tweak support load path jazz | Tweak support load path jazz
| Python | bsd-2-clause | mkusz/invoke,sophacles/invoke,singingwolfboy/invoke,pfmoore/invoke,kejbaly2/invoke,alex/invoke,pfmoore/invoke,pyinvoke/invoke,kejbaly2/invoke,frol/invoke,mkusz/invoke,mattrobenolt/invoke,mattrobenolt/invoke,frol/invoke,pyinvoke/invoke,tyewang/invoke |
9660fb734ecf2ad2c181eba790cdd2ddc9ed423e | cyder/core/system/forms.py | cyder/core/system/forms.py | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
... | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
... | Fix system form interface_type choices | Fix system form interface_type choices
| Python | bsd-3-clause | murrown/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,OSU-Net/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder |
8f6ee9e2f39803ba2d47a96f795d36655d18edfb | contentpages/tests.py | contentpages/tests.py | from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route =... | from django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template... | Remove unused import from contentpages test | Remove unused import from contentpages test
| Python | mit | bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject |
0b0d26373f8f2f0cf869bce430eaaf6a84407f2c | src/nodeconductor_assembly_waldur/invoices/filters.py | src/nodeconductor_assembly_waldur/invoices/filters.py | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):... | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.Multipl... | Make filtering invoices and payment details by customer consistent with serializer (WAL-231) | Make filtering invoices and payment details by customer consistent with serializer (WAL-231)
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind |
3cb07a7f547b4187c918e7340d15c172cb9a7231 | fabfile.py | fabfile.py | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True... | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True... | Exit if tuple of remote hosts is empty. | Exit if tuple of remote hosts is empty.
| Python | apache-2.0 | gasull/src-git-pull |
a75dc02612fd2159731d8fdc04e85a2fbc0138d0 | bvspca/core/templatetags/utility_tags.py | bvspca/core/templatetags/utility_tags.py | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
... | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
re... | Switch from deprecated assignment tags to simple tags | Switch from deprecated assignment tags to simple tags
| Python | mit | nfletton/bvspca,nfletton/bvspca,nfletton/bvspca,nfletton/bvspca |
1caccbc11a17c1f01d802ec0dc3d52d5de9d5049 | coda/coda_replication/tests/test_urls.py | coda/coda_replication/tests/test_urls.py | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
... | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
... | Add a test for queue_search_JSON. | Add a test for queue_search_JSON.
| Python | bsd-3-clause | unt-libraries/coda,unt-libraries/coda,unt-libraries/coda,unt-libraries/coda |
5d2649fc005e514452c8d83f103b4fd2c5b03519 | tailor/output/printer.py | tailor/output/printer.py | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Locat... | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Locat... | Increment column to be printed by 1 | Increment column to be printed by 1
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
617df13670573b858b6c23249f4287786807d8b6 | website/notifications/listeners.py | website/notifications/listeners.py | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
l... | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
l... | Remove incorrect check for institution_id | Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/
| Python | apache-2.0 | brianjgeiger/osf.io,adlius/osf.io,erinspace/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,cslzchen/osf.io,Nesiehr/osf.io,chennan47/osf.io,caneruguz/osf.io,acshi/osf.io,leb2dg/osf.io,chrisseto/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,acshi/osf.io,pattisdr/osf.io,aaxelb/osf.io,aaxelb/osf.io,acsh... |
95fe3ba491c539780f8876faf3504a366ec2ca56 | yowsup/layers/protocol_iq/layer.py | yowsup/layers/protocol_iq/layer.py | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
... | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
... | Use _sendIq for handling pongs | Use _sendIq for handling pongs
| Python | mit | biji/yowsup,ongair/yowsup |
9e148028300a46f9074b9f188dc04d87884c8905 | rsr/headerbar.py | rsr/headerbar.py | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query t... | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query t... | Hide preferences button for now. | Hide preferences button for now.
| Python | mit | andialbrecht/runsqlrun |
c1d22d24e6c1d7aa1a70e07e39ee0196da86b26f | scripts/stock_price/white_noise.py | scripts/stock_price/white_noise.py | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y i... | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # s... | Fix distributions of the white noise sampler | Fix distributions of the white noise sampler
| Python | mit | zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend |
1b47c9eb39a2c5bbdf05397c949619d5a044f2ae | fabfile.py | fabfile.py | from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service(... | import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.use... | Set password in env var | Set password in env var
| Python | mit | exitcodezero/picloud,exitcodezero/pi-cloud-sockets |
43662a6417a9d589bac2ab49e5b9b5441adf1115 | atomic/__init__.py | atomic/__init__.py | from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
el... | Set path to find _xxdata.so files | Set path to find _xxdata.so files
| Python | mit | cfe316/atomic |
ad8600f94268adaa00b71a92adc601a87d2cef14 | test_echo.py | test_echo.py | from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
| from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my... | Add long and empty strings for testing | Add long and empty strings for testing
| Python | mit | jwarren116/network-tools,jwarren116/network-tools |
eba712b9efced9cb8d2d6cd0683fb550e5f5b1ca | mininews/sitemaps.py | mininews/sitemaps.py | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.ob... | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| Remove defaults from the sitemap.py that should not be set in Mininews. | Remove defaults from the sitemap.py that should not be set in Mininews.
| Python | mit | richardbarran/django-minipub,richardbarran/django-minipub,richardbarran/django-mininews,richardbarran/django-mininews,richardbarran/django-mininews |
4ae0f5ea2c48aaa141f25edc0d35e07da0d5e5f4 | project/api/managers.py | project/api/managers.py | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=... | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs... | Update `create_user` method manager to require person | Update `create_user` method manager to require person
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api |
1cda977eff5a2edaa0de82882ef2e7d1611329b7 | tests/test_protocol.py | tests/test_protocol.py | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connectio... | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the co... | Add tests for invalid and no provided sub-protocols | Add tests for invalid and no provided sub-protocols
| Python | mit | saltyrtc/saltyrtc-server-python,saltyrtc/saltyrtc-server-python |
a86ecdb187c06da216be0dd5020748bf84f8638b | tests/test_settings.py | tests/test_settings.py | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
... | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
... | Add test settings for HipChatChannel | Add test settings for HipChatChannel
| Python | mit | ymyzk/django-channels,ymyzk/kawasemi |
0b797d14a609172d4965320aa30eae9e9c1f892e | tests/test_strutils.py | tests/test_strutils.py | # -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(... | # -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert str... | Add is_uuid unit-tests, including garbage types. | Add is_uuid unit-tests, including garbage types.
| Python | bsd-3-clause | zeroSteiner/boltons,doublereedkurt/boltons,markrwilliams/boltons |
1ce23f576888d9e5acf506443374ce0844e70e21 | south/signals.py | south/signals.py | """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
... | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... | Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models. | Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.
| Python | apache-2.0 | nimnull/django-south,RaD/django-south,RaD/django-south,philipn/django-south,nimnull/django-south,RaD/django-south,philipn/django-south |
83d767f75534da4c225eca407ec5eff6ed5774a2 | crmapp/contacts/views.py | crmapp/contacts/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'... | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contac... | Create the Contacts App - Part II > New Contact - Create View | Create the Contacts App - Part II > New Contact - Create View
| Python | mit | deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp |
0a2fa84285a586282d79146f85d9efba12a528dd | Parallel/Testing/Cxx/TestSockets.py | Parallel/Testing/Cxx/TestSockets.py | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... | Return code from script must reflect that of the test. | BUG: Return code from script must reflect that of the test.
| Python | bsd-3-clause | mspark93/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,keithroe/vtkoptix,daviddoria/PointGraphsPhase1,SimVascular/VTK,collects/VTK,SimVascular/VTK,sumedhasingla/VTK,mspark93/VTK,biddisco/VTK,sgh/vtk,jmerkow/VTK,aashish24/VTK-old,demarle/VTK,demarle/VTK,aashish24/VTK-old,johnkit/v... |
52803c6cea6a1e1b06486f137f62e6e827cdcb1d | tests/conftest.py | tests/conftest.py | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
... | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
... | Add token type to test id | Add token type to test id
| Python | apache-2.0 | devicehive/devicehive-python |
701402c4a51474b244ff28dd2d5c9a0731440308 | mozcal/events/api.py | mozcal/events/api.py | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
| from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | Allow filtering of event by title | Allow filtering of event by title
| Python | bsd-3-clause | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents |
f5af9624359523ddf67b63327d8fe85382497c47 | pycroft/helpers/user.py | pycroft/helpers/user.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.... | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context... | Set deprecated password hashing schemes | Set deprecated password hashing schemes
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft |
a5409ca51e95b4d6ca99a63e0422ca1fe8d344f8 | tags/templatetags/tags_tags.py | tags/templatetags/tags_tags.py | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Retu... | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Li... | Fix server error in tag search for non-existing tag. | Fix server error in tag search for non-existing tag.
| Python | bsd-3-clause | ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio |
33f1c68dbb0228cf995fb120f659fbad20968bf6 | mopidy_dleyna/__init__.py | mopidy_dleyna/__init__.py | import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def ge... | import pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_co... | Use pathlib to read ext.conf | Use pathlib to read ext.conf
| Python | apache-2.0 | tkem/mopidy-dleyna |
0f48c588e8f7f3a2a678b981d58df0e792bfdf1d | mopidy_pandora/pydora.py | mopidy_pandora/pydora.py | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
... | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
... | Remove superfluous override of 'get_playlist'. | Remove superfluous override of 'get_playlist'.
| Python | apache-2.0 | rectalogic/mopidy-pandora,jcass77/mopidy-pandora |
5c435749b043f0605e9d1b5279a5a8fd4a5a1c25 | pyfolio/tests/test_nbs.py | pyfolio/tests/test_nbs.py | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current impor... | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current impor... | Make nb_tests for bayesian optional because PyMC3 is not a hard dependency | TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency
| Python | apache-2.0 | ChinaQuants/pyfolio,chayapan/pyfolio,ChinaQuants/pyfolio,quantopian/pyfolio,YihaoLu/pyfolio,quantopian/pyfolio,femtotrader/pyfolio,femtotrader/pyfolio,YihaoLu/pyfolio |
572feef82f113e25b480ea8428f36ca0f7510fc3 | getwords.py | getwords.py | from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
... | from subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
... | Use a separate lock path | Use a separate lock path
| Python | mit | DeltaHeavy/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework |
b776a05c8bb57d63259263c985883422f56298c7 | pyvac/helpers/calendar.py | pyvac/helpers/calendar.py | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:... | import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:V... | Fix bug with ics url format with latest vobject version | Fix bug with ics url format with latest vobject version
| Python | bsd-3-clause | sayoun/pyvac,sayoun/pyvac,sayoun/pyvac |
a5cd7e2bea66003c1223891853077e47df24b7cf | vx_intro.py | vx_intro.py | import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tic... | import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tic... | Add ~/.python to PYTHONPATH and import rc | Add ~/.python to PYTHONPATH and import rc
| Python | mit | philipdexter/vx,philipdexter/vx |
b9d5c21a1c18fafd205e6fdc931b82cad6875bc8 | unit_tests/test_ccs.py | unit_tests/test_ccs.py | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input... | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input... | Add tests for parsing percentages | Add tests for parsing percentages
| Python | mit | ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData |
43a54b9d8e753f721619aa5fcecec39eb4ca6eff | django_amber/utils.py | django_amber/utils.py | from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=defa... | from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_... | Add logging and increase timeout | Add logging and increase timeout | Python | mit | PyconUK/2017.pyconuk.org,PyconUK/2017.pyconuk.org,PyconUK/2017.pyconuk.org |
5254e31d2309aa21b347d854293084eefddaa465 | virtool/error_pages.py | virtool/error_pages.py | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)... | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
... | Make HTTPExceptions return errors for /api calls | Make HTTPExceptions return errors for /api calls
| Python | mit | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool |
90a265c9c673856a6f119ab04bbd5d57ab375dc6 | django_fsm_log/models.py | django_fsm_log/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
cla... | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from ... | Switch from auto_now_add=True to default=now | Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures. | Python | mit | ticosax/django-fsm-log,blueyed/django-fsm-log,Andrey86/django-fsm-log,gizmag/django-fsm-log,fjcapdevila/django-fsm-log,mord4z/django-fsm-log,pombredanne/django-fsm-log |
2359b65a59b5326a07768578469177d65bbddf6e | celery/__init__.py | celery/__init__.py | """Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
| """Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
| Use from .. import (...) parens | Use from .. import (...) parens
| Python | bsd-3-clause | frac/celery,cbrepo/celery,frac/celery,WoLpH/celery,WoLpH/celery,ask/celery,mitsuhiko/celery,cbrepo/celery,ask/celery,mitsuhiko/celery |
610c979d00b3b89f3f2b16d58e4b2a797b380d41 | tests/fixtures/postgres.py | tests/fixtures/postgres.py | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("... | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("... | Add connection string for connecting to virtool database in order to create a test database | Add connection string for connecting to virtool database in order to create a test database
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool |
253ec40f59d2d28a848e17a7c62f85c3bd97dce9 | pages/views.py | pages/views.py | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
temp... | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
temp... | Add documentation to the default view | Add documentation to the default view | Python | bsd-3-clause | PiRSquared17/django-page-cms,google-code-export/django-page-cms,PiRSquared17/django-page-cms,PiRSquared17/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,Alwnikrotikz/django-page-cms,pombreda/django-page-cms,odyaka341/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms,pom... |
ae01c2c1e5ca693193aed12b66fb78e9d613faa7 | tests/unit/test_context.py | tests/unit/test_context.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | Use testtools as test base class. | Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtoo... | Python | apache-2.0 | dims/oslo.context,citrix-openstack-build/oslo.context,yanheven/oslo.middleware,JioCloud/oslo.context,varunarya10/oslo.context,openstack/oslo.context |
c10afc4ebd4d7ec8571c0685c0d87f76b25b3af9 | scipy/special/_precompute/utils.py | scipy/special/_precompute/utils.py | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g... | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g... | Use list comprehension instead of lambda function | Use list comprehension instead of lambda function
| Python | bsd-3-clause | grlee77/scipy,WarrenWeckesser/scipy,vigna/scipy,endolith/scipy,andyfaff/scipy,rgommers/scipy,scipy/scipy,grlee77/scipy,mdhaber/scipy,Stefan-Endres/scipy,zerothi/scipy,rgommers/scipy,andyfaff/scipy,scipy/scipy,zerothi/scipy,tylerjereddy/scipy,endolith/scipy,mdhaber/scipy,endolith/scipy,rgommers/scipy,mdhaber/scipy,endol... |
105864b44af3f1210e194e2deabfc760cac25055 | talempd/zest/skype/FirstRound/MiddleRandom.py | talempd/zest/skype/FirstRound/MiddleRandom.py | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(wor... | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(wor... | Fix Two Bugs for MidRand | Fix Two Bugs for MidRand
| Python | mit | cc13ny/Allin,Chasego/codi,cc13ny/algo,cc13ny/Allin,cc13ny/algo,cc13ny/Allin,cc13ny/algo,Chasego/codirit,Chasego/codi,Chasego/codirit,Chasego/codirit,Chasego/codi,Chasego/cod,Chasego/cod,Chasego/cod,Chasego/codi,cc13ny/algo,Chasego/codi,Chasego/cod,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/cod,cc13ny/Allin,cc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.