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
5ffdb8b395576ffaff4dd948361b6baeffa1072c
pypeerassets/networks.py
pypeerassets/networks.py
from collections import namedtuple Network = namedtuple('Network', [ 'network_name', 'network_shortname', 'pubkeyhash', 'wif_prefix', 'scripthash', 'magicbytes' ]) networks = ( # Peercoin mainnet Network("Peercoin", "ppc", b'37', b'b7', b'75', b'e6e8e9e5'), # Peercoin testnet N...
from collections import namedtuple Network = namedtuple('Network', [ 'network_name', 'network_shortname', 'pubkeyhash', 'wif_prefix', 'scripthash', 'magicbytes' ]) networks = ( # Peercoin mainnet Network("Peercoin", "ppc", b'37', b'b7', b'75', b'e6e8e9e5'), # Peercoin testnet N...
Add specifications for Bitcoin mainnet and testnet
Add specifications for Bitcoin mainnet and testnet
Python
bsd-3-clause
PeerAssets/pypeerassets,backpacker69/pypeerassets
b1e2b05a3e77b869cf9d0de820134237ce5de5ba
sideloader/tasks.py
sideloader/tasks.py
from celery import task import os import sys import subprocess @task() def build(build, giturl, branch): # Use subprocess to execute a build, update the db with results local = os.path.dirname(sys.argv[0]) buildpack = os.path.join(local, 'bin/build_package') deployfile = build.project.deploy_file ...
from celery import task import os import sys import subprocess @task() def build(build, giturl, branch): # Use subprocess to execute a build, update the db with results local = os.path.dirname(sys.argv[0]) buildpack = os.path.join(local, 'bin/build_package') deployfile = build.project.deploy_file ...
Use communicate so process out does not deadlock
Use communicate so process out does not deadlock
Python
mit
praekelt/sideloader,praekelt/sideloader,praekelt/sideloader,praekelt/sideloader
297660a27dc5b23beb0f616965c60389bce3c2d8
h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py
h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 ...
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 ...
Add usage of nbins_cats to RF pyunit.
Add usage of nbins_cats to RF pyunit.
Python
apache-2.0
nilbody/h2o-3,YzPaul3/h2o-3,datachand/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,madmax983/h2o-3,weaver-viii/h2o-3,junwucs/h2o-3,michalkurka/h2o-3,tarasane/h2o-3,michalkurka/h2o-3,datachand/h2o-3,madmax983/h2o-3,spennihana/h2o-3,h2oai/h2o-3,junwucs/h2o-3,datachand/h2o-3,junwucs/h2o-3,YzPaul3/h2o-3,bospetersen/h2o-3,jango...
89e49a69e700f49fa70391b02c839e3a0a4a1c7f
server/accounts/views.py
server/accounts/views.py
from django.shortcuts import render # Create your views here.
from django.shortcuts import render from django.contrib.auth import login, logout from django.contrib.auth.models import User from rest_framework import viewsets from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView # Create your views her...
Update the models for Auth and User.
Update the models for Auth and User.
Python
agpl-3.0
TomDataworks/angular-inventory,TomDataworks/angular-inventory
0cb0fee339883adeb93f787b5cc19e5293463c06
skimage/_shared/utils.py
skimage/_shared/utils.py
import warnings import functools __all__ = ['deprecated'] class deprecated(object): '''Decorator to mark deprecated functions with warning. Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>. Parameters ---------- alt_func : str If given, tell user what function to use i...
import warnings import functools __all__ = ['deprecated'] class deprecated(object): '''Decorator to mark deprecated functions with warning. Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>. Parameters ---------- alt_func : str If given, tell user what function to use i...
Remove duplicate code for alternative function
Remove duplicate code for alternative function
Python
bsd-3-clause
michaelpacer/scikit-image,Midafi/scikit-image,jwiggins/scikit-image,Midafi/scikit-image,michaelaye/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,SamHames/scikit-image,GaZ3ll3/scikit-image,juliusbierk/scikit-image,WarrenWeckesser/scikits-image,ajaybhat/scikit-image,oew1v07/scikit-image,rjeli/scikit-image,Britef...
0b28fe44514969470db926c6f38615a8a5478bf6
smoke_signal/__init__.py
smoke_signal/__init__.py
from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("c...
from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_bluep...
Remove the no-JS version from the app
Remove the no-JS version from the app I haven't looked into it for a long while.
Python
mit
flacerdk/smoke-signal,flacerdk/smoke-signal,flacerdk/smoke-signal
2dbc4e2aec98aba8a0e307f951b412464db8b078
della/user_manager/urls.py
della/user_manager/urls.py
from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import (SignupView, UserProfileUpdateView, DrawNamesView, UserProfileDetailView, ActivateView) urlpatterns = [ url(r'^login/$', auth_views.login, name='login', kwargs={'template_name': 'use...
from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import (SignupView, UserProfileUpdateView, DrawNamesView, UserProfileDetailView, ActivateView) urlpatterns = [ url(r'^login/$', auth_views.login, name='login', kwargs={'template_name': 'use...
Add name for url config of `ActivateView`
Add name for url config of `ActivateView`
Python
mit
avinassh/della,avinassh/della,avinassh/della
9b8c1f35d057bbf6e336434bd028cb0b2673afb8
installer/installer_config/admin.py
installer/installer_config/admin.py
from django.contrib import admin from installer_config.models import Package, TerminalPrompt, EnvironmentProfile class PackageAdmin(admin.ModelAdmin): model = Package list_display = ('display_name', 'version', 'website') class TerminalPromptAdmin(admin.ModelAdmin): model = TerminalPrompt list_displa...
from django.contrib import admin from installer_config.models import Package, TerminalPrompt, EnvironmentProfile class PackageAdmin(admin.ModelAdmin): model = Package list_display = ('display_name', 'version', 'website') class TerminalPromptAdmin(admin.ModelAdmin): model = TerminalPrompt list_displa...
Add Environment Profile to Admin view
Add Environment Profile to Admin view
Python
mit
ezPy-co/ezpy,ezPy-co/ezpy,alibulota/Package_Installer,alibulota/Package_Installer
d379badd16528d2f7cd3826fcef5bd87be30cccf
nightreads/user_manager/user_service.py
nightreads/user_manager/user_service.py
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import (Subscription, SubscriptionActivation, UnsubscriptionActivation) def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) if tags_objs: user.subscription...
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import (Subscription, SubscriptionActivation, UnsubscriptionActivation) def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) if tags_objs: user.subscription...
Rename `get_user` to `get_or_create_user` and add a new `get_user`
Rename `get_user` to `get_or_create_user` and add a new `get_user`
Python
mit
avinassh/nightreads,avinassh/nightreads
8f0956313b140d7a0d51510cd9b4a5eec7d54570
plugins/holland.lib.lvm/tests/test_util.py
plugins/holland.lib.lvm/tests/test_util.py
import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def te...
import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def te...
Add test case to holland.lib.lvm for parsing snapshot-size without units
Add test case to holland.lib.lvm for parsing snapshot-size without units
Python
bsd-3-clause
m00dawg/holland,m00dawg/holland
fcfa0b96226ba8b8d2bbd62365c2cab3f6e42d99
salt/runners/state.py
salt/runners/state.py
''' Execute overstate functions ''' # Import Salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) over...
''' Execute overstate functions ''' # Import Salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) over...
Print and return the correct data
Print and return the correct data
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
f01e6fe6efb16a31a99b35cecaf000a0cb54bd4e
nodeconductor/core/authentication.py
nodeconductor/core/authentication.py
from __future__ import unicode_literals import nodeconductor.logging.middleware import rest_framework.authentication def user_capturing_auth(auth): class CapturingAuthentication(auth): def authenticate(self, request): result = super(CapturingAuthentication, self).authenticate(request) ...
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import rest_framework.authentication from rest_framework import exceptions import nodeconductor.logging.middleware TOKEN_KEY = 'x-auth-token' class TokenAuthentication(rest_framework.authentication.TokenAuthentication)...
Use get parameter in token auth (nc-544)
Use get parameter in token auth (nc-544)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
7bee444eeb17ec956478e999db47338fdf201411
querylist/tests/querylist_list_tests.py
querylist/tests/querylist_list_tests.py
import unittest2 from querylist import QueryList class QueryListActsAsList(unittest2.TestCase): """QueryList should behave as lists behave""" def setUp(self): self.src_list = [{'foo': 1}, {'foo': 2}, {'foo': 3}] self.query_list = QueryList(self.src_list) def test_QueryList_items_are_equal...
import unittest2 from querylist import QueryList class QueryListActsAsList(unittest2.TestCase): """QueryLists should act just like lists""" def setUp(self): self.src_list = [{'foo': 1}, {'foo': 2}, {'foo': 3}] self.query_list = QueryList(self.src_list) def test_QueryList_items_are_equal_t...
Add some more acts as list tests.
Add some more acts as list tests.
Python
mit
thomasw/querylist,zoidbergwill/querylist
8b519628839bc2360d2f0f48231e2cf7b9edc6b3
scripts/analytics/run_keen_summaries.py
scripts/analytics/run_keen_summaries.py
from framework.celery_tasks import app as celery_app from scripts.analytics.user_summary import UserSummary from scripts.analytics.node_summary import NodeSummary from scripts.analytics.base import DateAnalyticsHarness class SummaryHarness(DateAnalyticsHarness): @property def analytics_classes(self): ...
from framework.celery_tasks import app as celery_app from scripts.analytics.user_summary import UserSummary from scripts.analytics.node_summary import NodeSummary from scripts.analytics.institution_summary import InstitutionSummary from scripts.analytics.base import DateAnalyticsHarness class SummaryHarness(DateAnaly...
Add new InstitutionSummary to run_keen_summarries harness
Add new InstitutionSummary to run_keen_summarries harness
Python
apache-2.0
leb2dg/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,saradbowman/osf.io,chrisseto/osf.io,cwisecarver/osf.io,mluo613/osf.io,cwisecarver/osf.io,alexschiller/osf.io,acshi/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,sloria/osf.io,mluo613/osf.io,pattisdr/osf.io,...
51bae69bdbbc6cf19858ff8ed91efb09f4a0b845
spam_lists/exceptions.py
spam_lists/exceptions.py
# -*- coding: utf-8 -*- class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError, ValueError): '''The API k...
# -*- coding: utf-8 -*- class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError, ValueError): '''The API k...
Make InvalidHostnameError a subclass of InvalidHostError
Make InvalidHostnameError a subclass of InvalidHostError
Python
mit
piotr-rusin/spam-lists
94e7fb9821d904dba19fee1ca1d129259f33204e
skimage/draw/__init__.py
skimage/draw/__init__.py
from ._draw import line, polygon, ellipse, ellipse_perimeter, \ circle, circle_perimeter, set_color, bresenham
from ._draw import line, polygon, ellipse, ellipse_perimeter, \ circle, circle_perimeter, set_color, bresenham __all__ = ['line', 'polygon', 'ellipse', 'ellipse_perimeter', 'circle', 'circle_perimeter', 'set_color', 'bresen...
Add __all__ to draw package
Add __all__ to draw package
Python
bsd-3-clause
keflavich/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,robintw/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,chriscrosscutler/scikit-image,GaZ3ll3/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,ajaybhat/scikit-image,bennlich/scikit-image,vighneshbi...
6dde06470c9cd868319b1b4615d3065b61a6bc2c
sqlcop/cli.py
sqlcop/cli.py
import sys import sqlparse from .checks import has_cross_join def parse_file(filename): import json with open(filename, 'r') as fh: return json.load(fh) CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """ Run each of the defined checks on a query. "...
import sys import sqlparse from .checks import has_cross_join def parse_file(filename): return open(filename, 'r').readlines() CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """ Run each of the defined checks on a query. """ stmt = sqlparse.parse(el) f...
Work with plain SQL files
Work with plain SQL files
Python
bsd-3-clause
freshbooks/sqlcop
e8cee8b5a85762442e72079edd621363013455d9
src/config.py
src/config.py
sites_to_check = [ { "name": "Lissu Monitor", "url": "http://lissu.tampere.fi/monitor.php?stop=0014", "acceptable_statuses": [200], "mandatory_strings": [ "table2" ] }, { "name": "Siri API", "url": "https://siri.ij2010.tampere.fi/ws", ...
sites_to_check = [ { "name": "Lissu Monitor", "url": "http://lissu.tampere.fi/monitor.php?stop=0014", "acceptable_statuses": [200], "mandatory_strings": [ "table2" ] }, { "name": "Siri API", "url": "https://siri.ij2010.tampere.fi/ws", ...
Remove todo on lissu php ajax call. It returns and empty array in case of problems
Remove todo on lissu php ajax call. It returns and empty array in case of problems
Python
mit
Vilsepi/nysseituu,Vilsepi/nysseituu
752b4486c64fe0313f531b06bc0cb003804cc211
examples/rietveld/rietveld_helper/urls.py
examples/rietveld/rietveld_helper/urls.py
from django.conf.urls.defaults import * from django.contrib import admin from codereview.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/'}), (r'^accounts/login/$', 'django.contrib.auth...
from django.conf.urls.defaults import * from django.contrib import admin #from codereview.urls import urlpatterns admin.autodiscover() urlpatterns = patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/'}), (r'^accounts/login/$', 'django.contrib.auth...
Use include() instead of appending urlpatterns.
Use include() instead of appending urlpatterns.
Python
apache-2.0
andialbrecht/django-gae2django,bubenkoff/bubenkoff-gae2django,andialbrecht/django-gae2django,bubenkoff/bubenkoff-gae2django
9737eced8e2d667e3413a7d65946658d94f5868c
yg/emanate/__init__.py
yg/emanate/__init__.py
# -*- coding: utf-8 -*- from .events import Event __author__ = 'YouGov, plc' __email__ = 'dev@yougov.com' __version__ = '0.3.0' __all__ = ['Event']
# -*- coding: utf-8 -*- from .events import Event __author__ = 'YouGov, plc' __email__ = 'dev@yougov.com' __all__ = ['Event'] try: import pkg_resources dist = pkg_resources.get_distribution('yg.emanate') __version__ = dist.version except Exception: __version__ = 'unknown'
Load the version from the package metadata rather than trying to maintain it in a third place.
Load the version from the package metadata rather than trying to maintain it in a third place.
Python
mit
yougov/emanate
0d1b8597a75f7e24ce3e74f99aad359e27a32be5
fixcity/bmabr/tests/test_templatetags.py
fixcity/bmabr/tests/test_templatetags.py
import unittest class TestRecaptchaTags(unittest.TestCase): def test_recaptcha_html(self): from fixcity.bmabr.templatetags import recaptcha_tags from django.conf import settings html = recaptcha_tags.recaptcha_html() self.failUnless(settings.RECAPTCHA_PUBLIC_KEY in html) ...
import unittest import mock import django.conf class TestRecaptchaTags(unittest.TestCase): def test_recaptcha_html(self): from fixcity.bmabr.templatetags import recaptcha_tags from django.conf import settings html = recaptcha_tags.recaptcha_html() self.failUnless(settings.RECAP...
Fix tests to work when GOOGLE_ANALYTICS_KEY is not set.
Fix tests to work when GOOGLE_ANALYTICS_KEY is not set.
Python
agpl-3.0
openplans/fixcity,openplans/fixcity
c5938719a70debb521d7592bc0919dfc3f71bd22
gaphor/diagram/classes/generalization.py
gaphor/diagram/classes/generalization.py
""" Generalization -- """ from gi.repository import GObject from gaphor import UML from gaphor.diagram.diagramline import DiagramLine class GeneralizationItem(DiagramLine): __uml__ = UML.Generalization __relationship__ = "general", None, "specific", "generalization" def __init__(self, id=None, model=N...
""" Generalization -- """ from gi.repository import GObject from gaphor import UML from gaphor.UML.modelfactory import stereotypes_str from gaphor.diagram.presentation import LinePresentation from gaphor.diagram.shapes import Box, Text from gaphor.diagram.support import represents @represents(UML.Generalization) cl...
Use new line style for Generalization item
Use new line style for Generalization item
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
f9a349f902cb527314c22b384ddcf18de105cfc4
utilities.py
utilities.py
import re __author__ = 'tigge' from wand.image import Image def fix_image(filename, max_width): with Image(filename=filename) as img: img.auto_orient() if img.width > max_width: ratio = img.height / img.width img.resize(width=max_width, height=round(max_width * ratio)) ...
import re __author__ = 'tigge' from wand.image import Image def fix_image(filename, max_width): with Image(filename=filename) as img: img.auto_orient() if img.width > max_width: ratio = img.height / img.width img.resize(width=max_width, height=round(max_width * ratio)) ...
Support Google Apps drive urls
Support Google Apps drive urls
Python
mit
Tigge/trello-to-web,Tigge/trello-to-web
593020cf6305701e712d04b5bb3e68612dcf7bb4
fireplace/cards/wog/warrior.py
fireplace/cards/wog/warrior.py
from ..utils import * ## # Minions ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
from ..utils import * ## # Minions class OG_149: "Ravaging Ghoul" play = Hit(ALL_MINIONS - SELF, 1) class OG_218: "Bloodhoof Brave" enrage = Refresh(SELF, buff="OG_218e") OG_218e = buff(atk=3) class OG_312: "N'Zoth's First Mate" play = Summon(CONTROLLER, "OG_058") ## # Spells class OG_276: "Blood Warr...
Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate
Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate
Python
agpl-3.0
beheh/fireplace,NightKev/fireplace,jleclanche/fireplace
f64cb7c25d541421359dd8b5e1709444046d3fa0
gittools.py
gittools.py
import os import sha def gitsha(path): h = sha.sha() data = file(path).read() h.update("blob %d\0" % len(data)) h.update(data) return h.hexdigest() def git_info(): commithash = file('.git/HEAD').read().strip() if commithash.startswith("ref: "): commithash = file(commithash[5:]).rea...
import os import sha def gitsha(path): h = sha.sha() data = file(path).read() h.update("blob %d\0" % len(data)) h.update(data) return h.hexdigest() def git_info(): commithash = os.popen('git-rev-parse --verify HEAD').read().strip() if os.getuid() == os.stat(".git/index").st_uid: os...
Make resolving of git commit id use git-rev-parse.
OTHER: Make resolving of git commit id use git-rev-parse.
Python
lgpl-2.1
oneman/xmms2-oneman,theefer/xmms2,chrippa/xmms2,krad-radio/xmms2-krad,oneman/xmms2-oneman,six600110/xmms2,mantaraya36/xmms2-mantaraya36,oneman/xmms2-oneman,dreamerc/xmms2,oneman/xmms2-oneman-old,krad-radio/xmms2-krad,theefer/xmms2,oneman/xmms2-oneman,krad-radio/xmms2-krad,theefer/xmms2,six600110/xmms2,six600110/xmms2,x...
15cd72fd68bad8dbb2eab293c4abf8700a782219
test/trainer_test.py
test/trainer_test.py
import theanets import util class TestTrainer(util.MNIST): def setUp(self): super(TestTrainer, self).setUp() self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE)) def assert_progress(self, algo, **kwargs): trainer...
import theanets import util class TestTrainer(util.MNIST): def setUp(self): super(TestTrainer, self).setUp() self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE)) def assert_progress(self, algo, **kwargs): trainer...
Update test to work with new monitors.
Update test to work with new monitors.
Python
mit
devdoer/theanets,lmjohns3/theanets,chrinide/theanets
1d2eef3bf6a1a5c9b5a1f34c224d3a9651e77d73
gocd/response.py
gocd/response.py
import json class Response(object): def __init__(self, status_code, body, headers=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers @property def is_ok(s...
import json class Response(object): def __init__(self, status_code, body, headers=None, ok_status=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers self.o...
Add configurable ok status code for Response
Add configurable ok status code for Response When scheduling a pipeline the successful code is 202, so tihis needs to be configurable.
Python
mit
henriquegemignani/py-gocd,gaqzi/py-gocd
89fcfbd71a4fc9e8a5aaea65c106a092cbd27ac0
src/plone.example/plone/example/todo.py
src/plone.example/plone/example/todo.py
# -*- encoding: utf-8 -*- from aiohttp.web import Response from zope.interface import Attribute from zope.interface import Interface class ITodo(Interface): title = Attribute("""Title""") done = Attribute("""Done""") class View(object): def __init__(self, context, request): self.context = contex...
# -*- encoding: utf-8 -*- from aiohttp.web import Response from plone.supermodel import model from zope import schema class ITodo(model.Schema): title = schema.TextLine(title=u"Title", required=False) done = schema.Bool(title=u"Done", required=False) class ...
Use supermodel/zope.schema for Todo field definition
Use supermodel/zope.schema for Todo field definition
Python
bsd-2-clause
plone/plone.server,plone/plone.server
97bdc9679e9162a4ce101824dc37ac0f6e57e3d7
fanstatic/checksum.py
fanstatic/checksum.py
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: ...
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: ...
Fix given path order for Google App Engine
Fix given path order for Google App Engine
Python
bsd-3-clause
MiCHiLU/fanstatic-tools,MiCHiLU/fanstatic-gae,MiCHiLU/fanstatic-gae
d8557db156e277078e10584b2ee32320ac808772
sentry/client/handlers.py
sentry/client/handlers.py
import logging import sys class SentryHandler(logging.Handler): def emit(self, record): from sentry.client.models import get_client from sentry.client.middleware import SentryLogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(SentryLogMidd...
import logging import sys class SentryHandler(logging.Handler): def emit(self, record): from sentry.client.models import get_client from sentry.client.middleware import SentryLogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(SentryLogMidd...
Revert "fixed the issue of a client throwing exception - log to stderr and return gracefully"
Revert "fixed the issue of a client throwing exception - log to stderr and return gracefully" This reverts commit 4cecd6558ec9457d0c3e933023a8a1f77714eee5.
Python
bsd-3-clause
icereval/raven-python,patrys/opbeat_python,smarkets/raven-python,beeftornado/sentry,gg7/sentry,NickPresta/sentry,JamesMura/sentry,hzy/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,jokey2k/sentry,dirtycoder/opbeat_python,icereval/raven-python,jmagnusson/raven-python,johansteffner/raven-python,mvaled/sentry,J...
199aee78cb494169eb8b73fbb65de5ae40a5d436
other/wrapping-cpp/swig/c++/test_mylib.py
other/wrapping-cpp/swig/c++/test_mylib.py
import os import mylib os.system('make all') def test_squared(): assert 16. == mylib.squared(4) def test_myfunction(): assert 16. == mylib.myfunction(mylib.squared, 4) os.system('make clean')
import os import pytest @pytest.fixture def setup(request): def teardown(): print("Running make clean") os.system('make clean') print("Completed finaliser") request.addfinalizer(teardown) os.system('make clean') os.system('make all') def test_squared(setup): import mylib ...
Use pytest fixture to deal with compilation
Use pytest fixture to deal with compilation
Python
bsd-2-clause
fangohr/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python
08a09d1b258eb775f641c5edf3aba4ac1c522652
build/get_landmines.py
build/get_landmines.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This file emits the list of reasons why a particular build needs to be clobbered (or a list of 'landmines'). """ import sys de...
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This file emits the list of reasons why a particular build needs to be clobbered (or a list of 'landmines'). """ import sys de...
Add landmine after change to messages.h
Add landmine after change to messages.h BUG=N LOG=N TBR=machenbach@chromium.org Review URL: https://codereview.chromium.org/1174523004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#28875}
Python
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
b1906e66dc9f7ce7d164d0df2622e8c2213e1692
tests/query_test/test_chars.py
tests/query_test/test_chars.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestStringQueries(ImpalaTestSuite): @classmethod def get_workload(cls): return 'function...
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestStringQueries(ImpalaTestSuite): @classmethod def get_workload(cls): return 'function...
Fix char test to only run on test/none.
Fix char test to only run on test/none. Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326 Tested-by: jenkins Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
Python
apache-2.0
andybab/Impala,gistic/PublicSpatialImpala,ImpalaToGo/ImpalaToGo,andybab/Impala,andybab/Impala,andybab/Impala,gistic/PublicSpatialImpala,placrosse/ImpalaToGo,andybab/Impala,gistic/PublicSpatialImpala,AtScaleInc/Impala,placrosse/ImpalaToGo,andybab/Impala,AtScaleInc/Impala,placrosse/ImpalaToGo,ImpalaToGo/ImpalaToGo,Impala...
d2cbcad65914ccd26b57dcec12c048c3524ecdc4
src/cclib/__init__.py
src/cclib/__init__.py
# -*- coding: utf-8 -*- # # Copyright (c) 2016, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """A library for parsing and interpreting results from computational chemistry packages. The goals of cclib are centered ...
# -*- coding: utf-8 -*- # # Copyright (c) 2016, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """A library for parsing and interpreting results from computational chemistry packages. The goals of cclib are centered ...
Add alias cclib.ccopen for easy access
Add alias cclib.ccopen for easy access
Python
bsd-3-clause
langner/cclib,gaursagar/cclib,ATenderholt/cclib,cclib/cclib,berquist/cclib,berquist/cclib,langner/cclib,berquist/cclib,ATenderholt/cclib,gaursagar/cclib,langner/cclib,cclib/cclib,cclib/cclib
5fbf5bac84a7ededde99e109d206681af99c112c
sort/bubble_sort_optimized/python/bubble_sort_optimized.py
sort/bubble_sort_optimized/python/bubble_sort_optimized.py
class Solution: def bubbleSortOptimized(self, nums: List[int]) -> None: if len(nums) == 1: return nums else: swapped = False while not swapped: swapped = True for i in range(0, len(nums)-1): if nums[i] > nums[i+1...
class Solution: def bubbleSortOptimized(self, nums): if len(nums) == 1: return nums else: swapped = False while not swapped: swapped = True for i in range(0, len(nums)-1): if nums[i] > nums[i+1]: ...
Add dijkstras algorithm and depth first search in python
Add dijkstras algorithm and depth first search in python
Python
cc0-1.0
ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovs...
f0daa1674ef6fd59173fe7d1904f8598f7418f8b
tests/mock_vws/test_inactive_project.py
tests/mock_vws/test_inactive_project.py
""" Tests for inactive projects. """
""" Tests for inactive projects. """ import pytest from tests.utils import VuforiaServerCredentials @pytest.mark.usefixtures('verify_mock_vuforia') class TestInactiveProject: """ Tests for inactive projects. """ def test_inactive_project( self, verify_mock_vuforia_inactive: VuforiaS...
Add stub for inactive project test
Add stub for inactive project test
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
bcc962313107ec4714b2e53d793f172c4a77576f
src/shipit_code_coverage/shipit_code_coverage/coveralls.py
src/shipit_code_coverage/shipit_code_coverage/coveralls.py
import requests def upload(data): r = requests.post('https://coveralls.io/api/v1/jobs', files={ 'json_file': data }) try: print(r.json()) except ValueError: raise Exception('Failure to submit data. Response [%s]: %s' % (r.status_code, r.text)) # NOQA
import gzip import requests def upload(data): r = requests.post('https://coveralls.io/api/v1/jobs', files={ 'json_file': ('json_file', gzip.compress(data), 'gzip/json') }) try: print(r.json()) except ValueError: raise Exception('Failure to submit data. Response [%s]: %s' % (r....
Compress data sent to Coveralls using gzip
shipit_code_coverage: Compress data sent to Coveralls using gzip
Python
mpl-2.0
lundjordan/services,garbas/mozilla-releng-services,mozilla-releng/services,La0/mozilla-relengapi,La0/mozilla-relengapi,lundjordan/services,garbas/mozilla-releng-services,lundjordan/services,srfraser/services,mozilla-releng/services,srfraser/services,garbas/mozilla-releng-services,mozilla-releng/services,lundjordan/serv...
0e7be2adf1101ae842dddb3db3217957a8e5957f
iati/core/rulesets.py
iati/core/rulesets.py
"""A module containg a core representation of IATI Rulesets.""" class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually d...
"""A module containg a core representation of IATI Rulesets. Todo: Implement Rulesets (and Rules). Likely worth completing the Codelist implementation first since the two will be similar. """ class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(obje...
Add a ruleset module TODO
Add a ruleset module TODO
Python
mit
IATI/iati.core,IATI/iati.core
bf46ceea3c77f87768be7773fe2b26112a151606
src/waypoints_reader/scripts/yaml_reader.py
src/waypoints_reader/scripts/yaml_reader.py
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypo...
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypo...
Add errer handling for python code
Add errer handling for python code
Python
bsd-3-clause
CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg
76ca05a20fcdf36dc81d3ec98048f89f98325d68
imhotep_jsl/plugin.py
imhotep_jsl/plugin.py
from imhotep.tools import Tool from collections import defaultdict import re class JSL(Tool): regex = re.compile( r'^(?P<type>[WE]) ' r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$') def invoke(self, dirname, filenames=set()): retval = defaultdict(lambda: defaultdict(list...
from imhotep.tools import Tool from collections import defaultdict import re class JSL(Tool): regex = re.compile( r'^(?P<type>[WE]) ' r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$') def invoke(self, dirname, filenames=set()): retval = defaultdict(lambda: defaultdict(list...
Add support for imhotep to pass a list of filenames.
Add support for imhotep to pass a list of filenames.
Python
mit
hayes/imhotep_jsl
2c357a54e30eecb1d7b717be3ed774dcfecc2814
src/stratis_cli/_actions/_stratis.py
src/stratis_cli/_actions/_stratis.py
# Copyright 2016 Red Hat, 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 writing...
# Copyright 2016 Red Hat, 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 writing...
Use '_' prefix instead of disabling pylint unused-argument lint
Use '_' prefix instead of disabling pylint unused-argument lint It is more precise to mark the unused parameters this way. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
Python
apache-2.0
stratis-storage/stratis-cli,stratis-storage/stratis-cli
77ff64c858aa21c9651ccf58c95b739db45cd97b
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
# -*- coding: utf-8 -*- from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.fi...
# -*- coding: utf-8 -*- from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objec...
Update tags to use new template subdirectory.
kompomaatti: Update tags to use new template subdirectory.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
c2fd8515666476cc0b6760b72b6cd71ef030e6f4
thinc/neural/tests/unit/Affine/test_init.py
thinc/neural/tests/unit/Affine/test_init.py
# encoding: utf8 from __future__ import unicode_literals import pytest from flexmock import flexmock from hypothesis import given, strategies import abc from .... import vec2vec from ....ops import NumpyOps @pytest.fixture def model_with_no_args(): model = vec2vec.Affine(ops=NumpyOps()) return model def te...
# encoding: utf8 from __future__ import unicode_literals import pytest from mock import Mock, patch from hypothesis import given, strategies import abc from ...._classes.affine import Affine from ....ops import NumpyOps @pytest.fixture def model(): orig_desc = dict(Affine.descriptions) orig_on_init = list(Af...
Test Affine init calls hooks correctly, and sets descriptors
Test Affine init calls hooks correctly, and sets descriptors
Python
mit
explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
04eae79deb30e63f68534784f1eaf0412cfb1aa9
reporting_scripts/forum_data.py
reporting_scripts/forum_data.py
from collections import defaultdict import json import sys from base_edx import EdXConnection from generate_csv_report import CSV db_name = sys.argv[1] # Change name of collection as required connection = EdXConnection(db_name, 'forum' ) collection = connection.get_access_to_collection() forum_data = collection['...
from collections import defaultdict import json import sys from base_edx import EdXConnection from generate_csv_report import CSV db_name = sys.argv[1] # Change name of collection as required connection = EdXConnection(db_name, 'forum' ) collection = connection.get_access_to_collection() forum_data = collection['...
Update script with latest fields
Update script with latest fields
Python
mit
andyzsf/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
af45e43c46a22f3168ab946bf914a45eae9ade19
avatar/urls.py
avatar/urls.py
try: from django.conf.urls import patterns, url except ImportError: # Django < 1.4 from django.conf.urls.defaults import patterns, url from avatar import views urlpatterns = patterns('', url(r'^add/$', views.add, name='avatar_add'), url(r'^change/$', views.change, name='avatar_change'), url(r'...
try: from django.conf.urls import patterns, url except ImportError: # Django < 1.4 from django.conf.urls.defaults import url from avatar import views urlpatterns = [ url(r'^add/$', views.add, name='avatar_add'), url(r'^change/$', views.change, name='avatar_change'), url(r'^delete/$', views.del...
Remove replace urlpatterns with simple array, make compatible with Django 1.9
Remove replace urlpatterns with simple array, make compatible with Django 1.9
Python
bsd-3-clause
ad-m/django-avatar,ad-m/django-avatar,grantmcconnaughey/django-avatar,grantmcconnaughey/django-avatar,jezdez/django-avatar,jezdez/django-avatar,MachineandMagic/django-avatar,MachineandMagic/django-avatar
d0f18bed554c58873776eefba5b2be1d60926f95
elevator_cli/io.py
elevator_cli/io.py
# -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS def prompt(*args, **kwargs): current_db = kwargs.pop('current_db', 'default') ...
# -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. import shlex from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS def prompt(*args, **kwargs): current_db = kwargs.pop('current_db'...
Update : protect cli quoted arguments while parsing
Update : protect cli quoted arguments while parsing
Python
mit
oleiade/Elevator
22499afe4e434377e449226c5b073251165f4151
src/geoserver/style.py
src/geoserver/style.py
from geoserver.support import ResourceInfo, atom_link class Style(ResourceInfo): def __init__(self,catalog, node): self.catalog = catalog self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ResourceInfo.update(self) self.name = self.metadata.f...
from geoserver.support import ResourceInfo, atom_link class Style(ResourceInfo): def __init__(self,catalog, node): self.catalog = catalog self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ResourceInfo.update(self) self.name = self.metadata.f...
Add basic support for inspecting the body of SLDs
Add basic support for inspecting the body of SLDs
Python
mit
cristianzamar/gsconfig,Geode/gsconfig,scottp-dpaw/gsconfig,boundlessgeo/gsconfig,afabiani/gsconfig,garnertb/gsconfig.py
f48066555e6a4f778887b0600e13b304d36c9529
minutes/forms.py
minutes/forms.py
from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelFor...
from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects...
Allow admin preview in minutes as well
Allow admin preview in minutes as well
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
1b325d5d910039a3702db8a1b00127870625b209
test/conftest.py
test/conftest.py
from coverage import coverage cov = coverage(source=('doubles',)) cov.start() from doubles.pytest import pytest_runtest_call # noqa def pytest_sessionfinish(session, exitstatus): cov.stop() def pytest_terminal_summary(terminalreporter): print "\nCoverage report:\n" cov.report(show_missing=True, ignor...
from coverage import coverage cov = coverage(source=('doubles',)) cov.start() from doubles.pytest import pytest_runtest_call # noqa def pytest_sessionfinish(session, exitstatus): cov.stop() cov.save() def pytest_terminal_summary(terminalreporter): print "\nCoverage report:\n" cov.report(show_miss...
Save coverage data file to disk for Coveralls.
Save coverage data file to disk for Coveralls.
Python
mit
uber/doubles
99952c977eee74ecc95a6af4b2867738850bc435
topoflow_utils/hook.py
topoflow_utils/hook.py
def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameter...
"""Routines used by WMT hooks for TopoFlow components.""" choices_map = { 'Yes': 1, 'No': 0 } units_map = { 'meters': 'm^2', 'kilometers': 'km^2' } def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An ob...
Add choices_map and units_map global variables
Add choices_map and units_map global variables
Python
mit
csdms/topoflow-utils
95c2f9b9b0a64611a482d25993b0fa289f19ece8
test_settings.py
test_settings.py
DATABASES = {'default':{ 'NAME':':memory:', 'ENGINE':'django.db.backends.sqlite3' }} # install the bare minimum for # testing django-brake INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'brake', ) # This is where our ratelimiting information is stored. # Unfortunately, t...
DATABASES = {'default':{ 'NAME':':memory:', 'ENGINE':'django.db.backends.sqlite3' }} # install the bare minimum for # testing django-brake INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'brake', ) # This is where our ratelimiting information is stored. CACHES = { 'de...
Use LocMemCache instead of real memcache
Use LocMemCache instead of real memcache
Python
bsd-3-clause
SilentCircle/django-brake,skorokithakis/django-brake,skorokithakis/django-brake,SilentCircle/django-brake
3341ba14250f086ab11aa55d8d72de14fe95aceb
tests/test_db.py
tests/test_db.py
# -*- coding: utf-8 -*- import os import unittest from flask import Flask from coaster.utils import buid from coaster.sqlalchemy import BaseMixin from nodular.db import db class User(BaseMixin, db.Model): __tablename__ = 'user' userid = db.Column(db.Unicode(22), nullable=False, default=buid, unique=True) ...
# -*- coding: utf-8 -*- import os import unittest from flask import Flask from coaster.utils import buid from coaster.sqlalchemy import BaseMixin from nodular.db import db class User(BaseMixin, db.Model): __tablename__ = 'user' userid = db.Column(db.Unicode(22), nullable=False, default=buid, unique=True) ...
Disable warning for unused feature
Disable warning for unused feature
Python
bsd-2-clause
hasgeek/nodular,hasgeek/nodular
63f7ba49a3577a35de59490185ae9c06c20e1cc8
ticketing/app.py
ticketing/app.py
from django.conf.urls.defaults import patterns, url from oscar.core.application import Application from ticketing import views class TicketingApplication(Application): name = 'ticketing' ticket_list_view = views.TicketListView ticket_create_view = views.TicketCreateView ticket_update_view = views.T...
from django.conf.urls.defaults import patterns, url from django.contrib.auth.decorators import login_required from oscar.core.application import Application from ticketing import views class TicketingApplication(Application): name = 'ticketing' ticket_list_view = views.TicketListView ticket_create_view...
Fix login permissions for ticketing
Fix login permissions for ticketing
Python
bsd-3-clause
snowball-one/django-oscar-support,snowball-one/django-oscar-support,snowball-one/django-oscar-support
e6a1e9670e857119c7e6c9250849ee4edd026bad
tests/settings_base.py
tests/settings_base.py
import os ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tests.app', ] STATIC_URL = '/static/' SECRET_KEY = 'foobar' SITE_ID = 1234 # Needed for 1.3 compatibility # Used to construct unique...
import os ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tests.app', ] STATIC_URL = '/static/' SECRET_KEY = 'foobar' SITE_ID = 1234 # Needed for 1.3 compatibility # Used to construct unique...
Make sure AuthenticationMiddleware is defined in settings during tests.
Make sure AuthenticationMiddleware is defined in settings during tests.
Python
bsd-3-clause
ktosiek/pytest-django,RonnyPfannschmidt/pytest_django,pombredanne/pytest_django,hoh/pytest-django,davidszotten/pytest-django,ojake/pytest-django,bforchhammer/pytest-django,reincubate/pytest-django,pelme/pytest-django,thedrow/pytest-django,aptivate/pytest-django,tomviner/pytest-django,felixonmars/pytest-django
0f51a231b3b11e89a82a429be0adb6422fd01d8b
tests/test_Sanitize.py
tests/test_Sanitize.py
import unittest from s2f.Sanitize import ( sanitize_prefix, sanitize_for_latex ) class TestSanitize(unittest.TestCase): """ Test case for the Sanitize module """ def testSanitizePrefix(self): """ The function sanitize_prefix should only allow for lower case ASCII letters, digits and th...
#coding=utf-8 import unittest from s2f.Sanitize import ( sanitize_prefix, sanitize_for_latex ) class TestSanitize(unittest.TestCase): """ Test case for the Sanitize module """ def testSanitizePrefix(self): """ The function sanitize_prefix should only allow for lower case ASCII letters...
Add UTF8 compatibility switch for py2.
Add UTF8 compatibility switch for py2.
Python
mit
kdungs/lhcb-hltflow
64750014a91669b6067459a14743a6c5e6257856
umap/__init__.py
umap/__init__.py
from .umap_ import UMAP # Workaround: https://github.com/numba/numba/issues/3341 import numba import pkg_resources __version__ = pkg_resources.get_distribution("umap-learn").version
from .umap_ import UMAP # Workaround: https://github.com/numba/numba/issues/3341 import numba import pkg_resources try: __version__ = pkg_resources.get_distribution("umap-learn").version except pkg_resources.DistributionNotFound: __version__ = '0.4-dev'
Patch init import to allow for local dev of UMAP code
Patch init import to allow for local dev of UMAP code
Python
bsd-3-clause
lmcinnes/umap,lmcinnes/umap
c4c9115e7f67a6cc80b283cb0c2cc0e378e08ab8
tests/test_rainflow.py
tests/test_rainflow.py
import unittest, rainflow class TestRainflowCounting(unittest.TestCase): series = [0, -2, 1, -3, 5, -1, 3, -4, 4, -2, 0] cycles = [(3, 0.5), (4, 1.5), (6, 0.5), (8, 1.0), (9, 0.5)] def test_rainflow_counting(self): self.assertItemsEqual(rainflow.count_cycles(self.series), self.cycles) ...
import unittest, rainflow, random, itertools class TestRainflowCounting(unittest.TestCase): # Load series and corresponding cycle counts from ASTM E1049-85 series = [0, -2, 1, -3, 5, -1, 3, -4, 4, -2, 0] cycles = [(3, 0.5), (4, 1.5), (6, 0.5), (8, 1.0), (9, 0.5)] def test_rainflow_counting(...
Add additional tests for count_cycles
Add additional tests for count_cycles
Python
mit
iamlikeme/rainflow
4f3646e07d592d5da214977732298b680b8fdee7
zou/app/blueprints/crud/task_status.py
zou/app/blueprints/crud/task_status.py
from zou.app.models.task_status import TaskStatus from zou.app.services import tasks_service from .base import BaseModelResource, BaseModelsResource class TaskStatusesResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, TaskStatus) def check_read_permissions(self): ...
from zou.app.models.task_status import TaskStatus from zou.app.services import tasks_service from .base import BaseModelResource, BaseModelsResource class TaskStatusesResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, TaskStatus) def check_read_permissions(self): ...
Allow to modify the is_default flag
[tasks] Allow to modify the is_default flag
Python
agpl-3.0
cgwire/zou
01f2e41608e83fb4308c44c30ac9bb4fc6d49c86
server/kcaa/manipulators/automission.py
server/kcaa/manipulators/automission.py
#!/usr/bin/env python import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class ...
#!/usr/bin/env python import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class ...
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration.
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration.
Python
apache-2.0
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
a0114088c9b9ec1bf52ef2c9cfb46743754fe4e1
vagrant/roles/db/molecule/default/tests/test_default.py
vagrant/roles/db/molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB is listen concrete host and port def test_mongo_host_port(host): socket = host.socket("tcp://127.0.0.1:27017") assert ...
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB is listen concrete host and port def test_mongo_host_port(host): socket = host.socket("tcp://127.0.0.1:27017") assert ...
Edit test method 'test_config_file' to check configuration network interface
Edit test method 'test_config_file' to check configuration network interface
Python
mit
DmitriySh/infra,DmitriySh/infra,DmitriySh/infra
bc1e8baeb2698462dae5556e033c37a505cfcb2c
altair/examples/bar_chart_with_labels.py
altair/examples/bar_chart_with_labels.py
""" Simple Bar Chart with Labels ============================ This example shows a basic horizontal bar chart with labels created with Altair. """ # category: bar charts import altair as alt import pandas as pd source = pd.DataFrame({ 'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 'b': [28, 55, 43, 91, 81...
""" Bar Chart with Labels ===================== This example shows a basic horizontal bar chart with labels created with Altair. """ # category: bar charts import altair as alt from vega_datasets import data source = data.wheat.url bars = alt.Chart(source).mark_bar().encode( x='wheat:Q', y="year:O" ) text = ...
Standardize bar chat with labels example to use source consistent with other examples
DOC: Standardize bar chat with labels example to use source consistent with other examples
Python
bsd-3-clause
altair-viz/altair,jakevdp/altair
0fbd183a95c65eb80bb813368eeb045e9c43b630
ray/util.py
ray/util.py
import json import itertools as it all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0] all_types = ['Color', 'Texture', 'Edge', 'Orientation'] full_feature_set = list(it.product(all_types, all_sizes)) default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1])) def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfn, ...
import json import itertools as it all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0] all_types = ['Color', 'Texture', 'Edge', 'Orientation'] full_feature_set = list(it.product(all_types, all_sizes)) default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1])) def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfns,...
Allow multiple batch files for seg pipeline json
Allow multiple batch files for seg pipeline json
Python
bsd-3-clause
janelia-flyem/gala,jni/gala,jni/ray
7b9b144ce8e7fca38500f5f0c4e2f5ec3b5d9e0f
tests/px_rambar_test.py
tests/px_rambar_test.py
import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") ...
# coding=utf-8 import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal....
Verify rambar can do unicode
Verify rambar can do unicode
Python
mit
walles/px,walles/px
43edc7a519cb2e7c49a112f816c5192908ac7e6b
tests/test_validator.py
tests/test_validator.py
import pytest from web_test_base import * class TestIATIValidator(WebTestBase): requests_to_load = { 'IATI Validator': { 'url': 'http://validator.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the ...
import pytest from web_test_base import * class TestIATIValidator(WebTestBase): requests_to_load = { 'IATI Validator': { 'url': 'http://validator.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the ...
Check forms on validator page
Check forms on validator page Add a test to check that each of the three forms exist on the validator page. This test does not check whether the three forms work correctly.
Python
mit
IATI/IATI-Website-Tests
390f7ff95755feadc25236feb1eb92655e113b38
fancypages/__init__.py
fancypages/__init__.py
from __future__ import absolute_import import os __version__ = VERSION = "0.3.0" def get_fancypages_paths(path, use_with_oscar=False): """ Get absolute paths for *path* relative to the project root """ paths = [] if use_with_oscar: from fancypages.contrib import oscar_fancypages base_dir...
from __future__ import absolute_import import os __version__ = VERSION = "0.3.0" def get_fancypages_paths(path, use_with_oscar=False): """ Get absolute paths for *path* relative to the project root """ paths = [] if use_with_oscar: from fancypages.contrib import oscar_fancypages base_dir...
Remove south from app helper method for Django 1.7+
Remove south from app helper method for Django 1.7+
Python
bsd-3-clause
tangentlabs/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages
402f71cc65f714cf880c9c9569e83f5bcd47ec72
paintstore/widgets.py
paintstore/widgets.py
from django import forms from django.conf import settings from django.utils.safestring import mark_safe class ColorPickerWidget(forms.TextInput): class Media: css = { "all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),) } js = ( ("%s/%s" % (...
from django import forms from django.conf import settings from django.utils.safestring import mark_safe class ColorPickerWidget(forms.TextInput): class Media: css = { "all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),) } js = ( ("%s/%s" % (...
Change the background to reflect the color chosen
Change the background to reflect the color chosen
Python
mit
jamescw/django-paintstore,jamescw/django-paintstore
bad2fea8a3a8e7a7d1da9ee83ec48657824eaa07
tests/test_filesize.py
tests/test_filesize.py
from rich import filesize def test_traditional(): assert filesize.decimal(0) == "0 bytes" assert filesize.decimal(1) == "1 byte" assert filesize.decimal(2) == "2 bytes" assert filesize.decimal(1000) == "1.0 kB" assert filesize.decimal(1.5 * 1000 * 1000) == "1.5 MB" def test_pick_unit_and_suffix(...
from rich import filesize def test_traditional(): assert filesize.decimal(0) == "0 bytes" assert filesize.decimal(1) == "1 byte" assert filesize.decimal(2) == "2 bytes" assert filesize.decimal(1000) == "1.0 kB" assert filesize.decimal(1.5 * 1000 * 1000) == "1.5 MB" assert filesize.decimal(0, p...
Add some tests for new decimal() params
Add some tests for new decimal() params
Python
mit
willmcgugan/rich
c2789dd620a6f6d4c08e4608e94656a0d2b906c7
parsimonious/utils.py
parsimonious/utils.py
"""General tools which don't depend on other parts of Parsimonious""" import ast from sys import version_info from six import python_2_unicode_compatible class StrAndRepr(object): """Mix-in to add a ``__str__`` and ``__repr__`` which return the UTF-8-encoded value of ``__unicode__``""" if version_info ...
"""General tools which don't depend on other parts of Parsimonious""" import ast from six import python_2_unicode_compatible class StrAndRepr(object): """Mix-in to which gives the class the same __repr__ and __str__.""" def __repr__(self): return self.__str__() def evaluate_string(string): ""...
Fix a bug in unicode encoding of reprs.
Fix a bug in unicode encoding of reprs. The previous implementation could lead to double-decoding: >>> from parsimonious.utils import Token >>> repr(Token('asdf')) '<Token "asdf">' >>> repr(Token(u'💣')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "parsim...
Python
mit
lucaswiman/parsimonious,erikrose/parsimonious
79ff39c4d6a5ad91a32cfdc7b59a89fa5461d244
MongoHN/forms.py
MongoHN/forms.py
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired class LoginForm(Form): username = TextField('Username', validators = [ Requir...
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', vali...
Use ValidationError rather than ValueError
Use ValidationError rather than ValueError
Python
mit
bsandrow/MongoHN,bsandrow/MongoHN
543c7307f26553d78bf3f18b5f93a2bc23cfb875
reports/admin.py
reports/admin.py
# coding: utf-8 from django.contrib import admin from .models import Report class ReportAdmin(admin.ModelAdmin): list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at') list_filter = ['created_at'] search_fields = ['addressed_to', 'reported_from', 'content', '...
# coding: utf-8 from django.contrib import admin from .models import Report class ReportAdmin(admin.ModelAdmin): list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at') list_filter = ['created_at', 'content'] search_fields = ['addressed_to', 'reported_from__us...
Fix some issues, because of models change
Fix some issues, because of models change
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
c553db9e84344897ca995f56c710944da88c0a56
packages/syft/src/syft/core/node/domain/domain_interface.py
packages/syft/src/syft/core/node/domain/domain_interface.py
# third party from pydantic import BaseSettings # relative from ...adp.adversarial_accountant import AdversarialAccountant from ..abstract.node_service_interface import NodeServiceInterface from ..common.node_manager.association_request_manager import AssociationRequestManager from ..common.node_manager.dataset_manage...
# third party from pydantic import BaseSettings # relative from ...adp.adversarial_accountant import AdversarialAccountant from ..abstract.node_service_interface import NodeServiceInterface from ..common.node_manager.association_request_manager import AssociationRequestManager from ..common.node_manager.dataset_manage...
Remove groups attribute from DomainInterface
Remove groups attribute from DomainInterface
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
d7d1200846a3e19eb9399b3c47ec553e8c118046
smap-nepse/preprocessing/feat_select.py
smap-nepse/preprocessing/feat_select.py
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: de...
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: de...
Select features using classification model
Select features using classification model
Python
mit
samshara/Stock-Market-Analysis-and-Prediction
d50703ee3da5feb264c53d622c039a0bde67d233
airplay-sniff.py
airplay-sniff.py
#!/usr/bin/env python2 from scapy.all import * def airplay_callback(pkt): try: if pkt['Raw'].load[0:5] == 'SETUP': # Someone is starting to play! Add them to the list yo with open('/tmp/playing.txt', 'w') as f: f.write(pkt[IP].src) print "Updated playing.txt to " + pkt[IP].src elif pkt['Raw'].load[0:...
#!/usr/bin/env python2 from scapy.all import * cur_ip = False def airplay_callback(pkt): try: if pkt[IP].sprintf('%proto%') == 'tcp': # This could be anything! Parse further if pkt['Raw'].load[0:5] == 'TEARD': # Anyone can teardown, only remove the IP if it's the currently playing person global cur_i...
Change sniffing to be more robust
Change sniffing to be more robust Known bugs: Will update playing.txt when someone tries to use the speakers if already in use. Saving grace is it'll change to the right person a second later.
Python
bsd-2-clause
ss23/airplay-control-intercept,ss23/airplay-control-intercept,ss23/airplay-control-intercept
5d812fbacab2970a1a601f8d801b08305873490d
src/ekklesia_portal/concepts/argument/argument_contracts.py
src/ekklesia_portal/concepts/argument/argument_contracts.py
from colander import Length from deform import Form from deform.widget import TextAreaWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ class ArgumentSchema(Schema): title = string_property(title=_('title'), validator=Length(min=5, max=80))...
from colander import Length from deform import Form from deform.widget import TextAreaWidget, TextInputWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ TITLE_MAXLENGTH = 80 ABSTRACT_MAXLENGTH = 160 class ArgumentSchema(Schema): title = s...
Add maxlength to argument form title and abstract
Add maxlength to argument form title and abstract
Python
agpl-3.0
dpausp/arguments,dpausp/arguments,dpausp/arguments,dpausp/arguments
8ee00372c7ae005d6060ac2813a13b8db447b292
stock_request_direction/models/stock_request_order.py
stock_request_direction/models/stock_request_order.py
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ...
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ...
Add warehouse_id to existing onchange.
[IMP] Add warehouse_id to existing onchange.
Python
agpl-3.0
Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse
94a55dfc68fcd2352f867b01fc703a202c87f453
troposphere/events.py
troposphere/events.py
# Copyright (c) 2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Target(AWSProperty): props = { 'Arn': (basestring, True), 'Id': (basestring, True), 'Input': (basestring, False), 'InputPath': (...
# Copyright (c) 2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Target(AWSProperty): props = { 'Arn': (basestring, True), 'Id': (basestring, True), 'Input': (basestring, False), 'InputPath': (...
Remove RoleArn from Events::Rule and add to Target property
Remove RoleArn from Events::Rule and add to Target property
Python
bsd-2-clause
pas256/troposphere,pas256/troposphere,ikben/troposphere,7digital/troposphere,ikben/troposphere,cloudtools/troposphere,7digital/troposphere,johnctitus/troposphere,johnctitus/troposphere,cloudtools/troposphere
f6df4f359b3d949b3f87a22bda1a78237c396aef
tests/integrations/current/test_read.py
tests/integrations/current/test_read.py
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): dirs = set(os.listdir("%s/current" % self.mount_path)) assert dirs == set(['testing', 'me']) def test_read_from_a_file(self): with open("%s/current/testing" % self.mou...
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): dirs = set(os.listdir("%s/current" % self.mount_path)) assert dirs == set(['testing', 'me']) def test_read_from_a_file(self): with open("%s/current/testing" % self.mou...
Test time related stats from current view
Test time related stats from current view
Python
apache-2.0
bussiere/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs,PressLabs/gitfs
662791d49deb945e911be5e07af2bbb3499a45ca
tests/test_load_cfg.py
tests/test_load_cfg.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test load qc configurations (utils.load_cfg) """ import pkg_resources from cotede.utils import load_cfg CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg') if f[-5:] == '.json'] def test_inout(): """ load_cfg shouldn't overwrite ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test load qc configurations (utils.load_cfg) """ import os.path import pkg_resources from cotede.utils import load_cfg, cotede_dir CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg') if f[-5:] == '.json'] def test_no_local_duplicate_...
Test to check cfg duplicate in local cfg.
Test to check cfg duplicate in local cfg. If the factory config fail, the default is to fail safe searching to a local cfg file, what could hide problems with the builtin cfg file.
Python
bsd-3-clause
castelao/CoTeDe
c95d78378c7b3b234439e1d9a9bc41539b9080f5
preferences/models.py
preferences/models.py
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = mo...
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = mo...
Add rep and sen from address fields to Preferences model
Add rep and sen from address fields to Preferences model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
2bebbbfc12e1013e3c5c0a42329bac520c574b9b
tests/test_settings.py
tests/test_settings.py
import pytest import npc import os from tests.util import fixture_dir @pytest.fixture def settings(): return npc.settings.Settings() def test_creation(settings): assert settings is not None def test_override(settings): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = settings....
import pytest import npc import os from tests.util import fixture_dir def test_creation(prefs): assert prefs is not None def test_override(prefs): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = prefs.get('editor') prefs.load_more(override_path) assert prefs.get('editor') ...
Refactor settings tests to use global fixture
Refactor settings tests to use global fixture
Python
mit
aurule/npc,aurule/npc
7a8569fb28a1214b4898b113c384eb3967c656ef
tlsenum/parse_hello.py
tlsenum/parse_hello.py
import construct from tlsenum import hello_constructs class ClientHello(object): @property def protocol_version(self): return self._protocol_version @protocol_version.setter def protocol_version(self, protocol_version): assert protocol_version in ["3.0", "1.0", "1.1", "1.2"] ...
import time import os import construct from tlsenum import hello_constructs class ClientHello(object): @property def protocol_version(self): return self._protocol_version @protocol_version.setter def protocol_version(self, protocol_version): assert protocol_version in ["3.0", "1.0"...
Add random and session_id fields.
Add random and session_id fields.
Python
mit
Ayrx/tlsenum,Ayrx/tlsenum
1089413956f3eff9d233d276ebe728e89d814096
matchers/sifter.py
matchers/sifter.py
from base import BaseMatcher import os import requests import re import json NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ.get('SIFTER') def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url...
from base import BaseMatcher import os import requests import re import json NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)' API_KEY = os.environ.get('SIFTER') def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues...
Make the Sifter issue matching more specific.
Make the Sifter issue matching more specific. Now it matches: * 3-5 digit numbers * Preceded by a #, whitespace, or beginning-of-line. * Followed by a comma, period, question mark, exclamation point, whitespace, or end-of-line.
Python
bsd-2-clause
honza/nigel
061386e402fb3f1300c0c71be9b07ecc16590ecc
cronjobs/extract_kalliope_originators.py
cronjobs/extract_kalliope_originators.py
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for re...
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for re...
Make compatible with CentOS 8
Make compatible with CentOS 8
Python
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
d79fde9a1bceea2ea8bc9aa8d14e5ec66a44600d
mesoblog/models.py
mesoblog/models.py
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the...
from django.db import models import random import re import string # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" def...
Make sure slugs are unique and not integer only.
Make sure slugs are unique and not integer only. This fixes issues #1, #2 & #5
Python
mit
grundleborg/mesosphere
c91e42c32d8314d3d156c577f854fa311c5b1b67
model_presenter.py
model_presenter.py
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(timestamp, close, color='r', marker='....
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ...
Fix the error that X is required for plotting
Fix the error that X is required for plotting This enables money-monkey in server environment
Python
mit
cjluo/money-monkey
748e4d7e30e71f88095554db3d898c1702d17b50
wuvt/admin/__init__.py
wuvt/admin/__init__.py
from flask import Blueprint bp = Blueprint('admin', __name__) from wuvt.admin import views
from flask import Blueprint bp = Blueprint('admin', __name__) from wuvt.admin import views from wuvt import app from wuvt import format_datetime @app.context_processor def utility_processor(): def format_price(amount, currency='$'): return u'{1}{0:.2f}'.format(amount/100, currency) return dict(format...
Add format_price and format_datetime to jinja context.
Add format_price and format_datetime to jinja context.
Python
agpl-3.0
wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site
e08799591061e5b30723758a8c74e6118e9fe342
bgui/gl_utils.py
bgui/gl_utils.py
# This file handles differences between BGL and PyOpenGL, and provides various # utility functions for OpenGL try: from OpenGL.GL import * from OpenGL.GLU import * from bgl import Buffer USING_BGL = False except ImportError: from bgl import * USING_BGL = True if USING_BGL: _glGenTextures = glGenTextures def g...
# This file handles differences between BGL and PyOpenGL, and provides various # utility functions for OpenGL try: from bgl import * USING_BGL = True except ImportError: from OpenGL.GL import * from OpenGL.GLU import * from bgl import Buffer if USING_BGL: _glGenTextures = glGenTextures def glGenTextures(n, tex...
Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL.
Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL.
Python
mit
Moguri/bgui,Moguri/bgui,Remwrath/bgui,marcioreyes/bgui
0a97195dc8bb5f6caf68d84b96631c26e0c8c348
linguine/untokenize.py
linguine/untokenize.py
import string def untokenize(tokens): return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
import string def untokenize(tokens): #Joins all tokens in the list into a single string. #If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining. #Then strip the total string so that leading spaces and trailing spaces are removed. return "".join([" "+i i...
Add comment clarifying how it operates.
Add comment clarifying how it operates.
Python
mit
jmp3833/linguine-python,rigatoni/linguine-python,kmp3325/linguine-python,Pastafarians/linguine-python
3bfaff43564c0776912213afefe2e25664f0b1c0
server/server/urls.py
server/server/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventor...
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventor...
Add get and post functionality to the auth user stuff.
Add get and post functionality to the auth user stuff.
Python
agpl-3.0
TomDataworks/angular-inventory,TomDataworks/angular-inventory
5ddaf8f653df98752ca67b8bfec9b8adfcf168b1
pgcli/pgtoolbar.py
pgcli/pgtoolbar.py
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens...
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens...
Use the default buffer instead of current_buffer.
Use the default buffer instead of current_buffer.
Python
bsd-3-clause
nosun/pgcli,TamasNo1/pgcli,d33tah/pgcli,MattOates/pgcli,suzukaze/pgcli,zhiyuanshi/pgcli,dbcli/vcli,bitemyapp/pgcli,janusnic/pgcli,thedrow/pgcli,dbcli/pgcli,bitemyapp/pgcli,n-someya/pgcli,koljonen/pgcli,johshoff/pgcli,d33tah/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,darikg/pgcli,w4ngyi/pgcli,j-bennet/pgcli,MattOates/pgcli,dar...
2edd0ee699cfc0ef66d27ccb87ddefad26aa1a77
Challenges/chall_31.py
Challenges/chall_31.py
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pi...
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pi...
Add info for mandelbrot set
Add info for mandelbrot set
Python
mit
HKuz/PythonChallenge
9e1ea2d7ec5c8e7cfd0c1a15f552b1d5dcdd7546
helusers/providers/helsinki/provider.py
helusers/providers/helsinki/provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class HelsinkiAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('html_url') def...
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class HelsinkiAccount(ProviderAccount): def get_profile_url(...
Add account adapter for allauth
Add account adapter for allauth
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
df56478315c7b58526fbecf3fdfc4df5326d5ba0
custom_fixers/fix_alt_unicode.py
custom_fixers/fix_alt_unicode.py
# Taken from jinja2. Thanks, Armin Ronacher. # See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide from lib2to3 import fixer_base from lib2to3.fixer_util import Name, BlankLine class FixAltUnicode(fixer_base.BaseFix): PATTERN = """ func=funcdef< 'def' name='__unicode__' ...
# Taken from jinja2. Thanks, Armin Ronacher. # See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide from lib2to3 import fixer_base class FixAltUnicode(fixer_base.BaseFix): PATTERN = "'__unicode__'" def transform(self, node, results): new = node.clone() new.value = '__str__...
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
Python
mit
andreas-h/pybtex,andreas-h/pybtex,chbrown/pybtex,chbrown/pybtex
cb83a61df5ed82dd9af7ebd3c01d00a3d88e3491
infosystem/subsystem/domain/resource.py
infosystem/subsystem/domain/resource.py
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['active', 'name', 'parent_id'] attributes += entity.Entity.attributes active = db.Column(db.Boolean(), nullable=False) name = db.Column(db.String(60), nullable=False...
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['name', 'parent_id'] attributes += entity.Entity.attributes name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), ...
Remove attribute from domain and get from entity
Remove attribute from domain and get from entity
Python
apache-2.0
samueldmq/infosystem
7ac48c9a474f5a0edd10121f58442326d6e8d75c
backend/geonature/core/command/__init__.py
backend/geonature/core/command/__init__.py
import os import sys from geonature.core.command.main import main import geonature.core.command.create_gn_module # Load modules commands from geonature.utils.env import ROOT_DIR plugin_folder = os.path.join(str(ROOT_DIR), 'external_modules') sys.path.insert(0, os.path.join(plugin_folder)) for dirname in os.listdir(...
import os import sys from pathlib import Path from geonature.core.command.main import main import geonature.core.command.create_gn_module # Load modules commands from geonature.utils.env import ROOT_DIR def import_cmd(dirname): try: print("Import module {}".format(dirname)) module_cms = __impo...
TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module
TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module
Python
bsd-2-clause
PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature
e1819c59cc5debde7da26a76fb9d2589b2ad6879
Rynda/settings/test.py
Rynda/settings/test.py
# coding: utf-8 from .local import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_ROOT = os.path.join(S...
# coding: utf-8 from .local import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_ROOT = os.path.join(S...
Test database creator using syncdb instead of South
Test database creator using syncdb instead of South
Python
mit
sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda
5a8275a498a84d2110f58c1dbde4e67ddfa3748c
scripts/assemble_quests.py
scripts/assemble_quests.py
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ...
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ...
Fix build issue on OSX.
Fix build issue on OSX. Our script assumes the quest directory only has subdirectories of quests but OSX adds DS_STORE files to each directory and these were being picked up and causing the assemble quests script to fail.
Python
apache-2.0
lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-water...
f4b50b12ae8ad4da6e04ddc186c077c31af00611
SimpleHTTP404Server.py
SimpleHTTP404Server.py
import os import SimpleHTTPServer class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """ Overrides the default request handler to handle GitHub custom 404 pages. (Pretty much a 404.html page in your root.) See https://help.github.com/articles/custom-404-pages This currently only wor...
import os import SimpleHTTPServer class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """ Overrides the default request handler to handle GitHub custom 404 pages. (Pretty much a 404.html page in your root.) See https://help.github.com/articles/custom-404-pages This currently only wor...
Remove some print lines from the fake server.
Remove some print lines from the fake server.
Python
mit
clokep/SimpleHTTP404Server,clokep/SimpleHTTP404Server
6d924b21c40b5881d0b2c56b5550bf93f073e049
txircd/config.py
txircd/config.py
import yaml _defaults = { "bind_client": [ "tcp:6667:interface={::}", "ssl:6697:interface={::}" ], "bind_server": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not ...
import yaml _defaults = { "bind_client": [ "tcp:6667:interface={::}" ], "bind_server": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not in self._configData: ...
Remove the SSL default since it requires certs
Remove the SSL default since it requires certs
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
139eac65c71c729e7500dfe894dc9686bd384ab4
UConnRCMPy/constants.py
UConnRCMPy/constants.py
""" Constants used in UConnRCMPy. """ import cantera one_atm_in_torr = 760.0 """Conversion between atmosphere and Torr.""" one_atm_in_bar = 1.01325 """Conversion between atmosphere and bar.""" one_bar_in_pa = 1E5 """Conversion between bar and Pascal.""" cantera_version = None """Installed version of Cantera software."...
""" Constants used in UConnRCMPy. """ import cantera one_atm_in_torr = 760.0 """Conversion between atmosphere and Torr.""" one_atm_in_bar = 1.01325 """Conversion between atmosphere and bar.""" one_bar_in_pa = 1E5 """Conversion between bar and Pascal.""" cantera_version = None """Installed version of Cantera software."...
Fix map object not subscriptable in cantera_version
Fix map object not subscriptable in cantera_version
Python
bsd-3-clause
bryanwweber/UConnRCMPy