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 |
|---|---|---|---|---|---|---|---|---|---|
0fa817e3efee4e9a539432d6e308534f82448c60 | ReligiousPhraseMC/holy_twitter.py | ReligiousPhraseMC/holy_twitter.py | """Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
| """Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
... | Add the twitter streaming solution as module | Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them
| Python | mit | salvor7/MarkovChainBibleBot |
1b187ed85aede9ffe39ce52303694f852a8d02a2 | vantage/shell.py | vantage/shell.py | import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
i... | import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
... | Fix missing cmd name in error message | Fix missing cmd name in error message
| Python | mit | vantage-org/vantage,vantage-org/vantage |
c4109fadf0a66db5af0e579600a70e4b7e28493d | csdms/dakota/experiment.py | csdms/dakota/experiment.py | """A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
... | """A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
... | Refactor init method with _blocks attribute | Refactor init method with _blocks attribute
| Python | mit | csdms/dakota,csdms/dakota |
71bba7197f1e9faaa99cb54dfde452a7c8b1ff0f | nupic/research/frameworks/sigopt/common_experiments.py | nupic/research/frameworks/sigopt/common_experiments.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers. | Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers. | Python | agpl-3.0 | numenta/nupic.research,mrcslws/nupic.research,subutai/nupic.research,numenta/nupic.research,subutai/nupic.research,mrcslws/nupic.research |
c9ffe560879d6264eb4aed5b3dc96553f4ab2666 | xudd/tools.py | xudd/tools.py | import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(a... | import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(a... | Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local. | Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.
| Python | apache-2.0 | xudd/xudd |
8a4295876a4e1059f46f8fadaa1562062bfe877e | tests/test_edge_cases.py | tests/test_edge_cases.py | from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG")... | from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG")... | Fix test to support NoFeatureFlagFound. | Fix test to support NoFeatureFlagFound.
| Python | apache-2.0 | iromli/Flask-FeatureFlags,trustrachel/Flask-FeatureFlags,jskulski/Flask-FeatureFlags |
640d5de356d58b80f4d6ebb1c503ce88e144ea90 | core/models.py | core/models.py | from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
| from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
| Add property for converting price float to integer | Add property for converting price float to integer
| Python | unlicense | kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no |
d720d58ef9e140460cad0dc90f7d43f384d031e1 | djangosaml2/urls.py | djangosaml2/urls.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | Fix imports for Django 1.6 and above | Fix imports for Django 1.6 and above
| Python | apache-2.0 | kradalby/djangosaml2,kradalby/djangosaml2 |
63bb771df22c73d2e45e6577a01bf4e4a7c60dc6 | bumblebee/modules/arch-update.py | bumblebee/modules/arch-update.py | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... | Fix for previous versions of python | Fix for previous versions of python
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status |
5598a6ae434f85b3657120aae8944b5814e5ec37 | samples/barebone/views.py | samples/barebone/views.py | import settings
__author__ = 'Maruf Maniruzzaman'
import tornado
from tornado import gen
from cosmos.service.requesthandler import RequestHandler
class IndexHandler(RequestHandler):
@gen.coroutine
def get(self):
try:
with open(settings.INDEX_HTML_PATH) as f:
self.write(f... | import settings
__author__ = 'Maruf Maniruzzaman'
import tornado
from tornado import gen
from cosmos.service.requesthandler import RequestHandler
class IndexHandler(RequestHandler):
@gen.coroutine
def get(self):
try:
with open(settings.INDEX_HTML_PATH) as f:
self.write(f... | Put detailed error message for development environment in index view. | Put detailed error message for development environment in index view.
| Python | mit | kuasha/cosmos |
2073942c49cb85664c068412951f2c1f7351679f | add_random_answers.py | add_random_answers.py | import pandas as pd
import time
from datetime import datetime, date
start_date = date(2014, 1, 1)
end_date = datetime.now()
date_range = pd.date_range(start_date, end_date)
for date in date_range:
print(date)
| import pandas as pd
import time
from datetime import datetime, date
from random import randint
start_date = date(2014, 1, 1)
end_date = datetime.now()
date_range = pd.date_range(start_date, end_date)
for date in date_range:
random_hour = randint(10, 17)
random_minute = randint(0, 59)
random_second = randi... | Print random time based on date range | Print random time based on date range
| Python | mit | andrewlrogers/srvy |
22c6976985f565260b71439a0519e2d3b38ddf01 | moa/tools.py | moa/tools.py |
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
... |
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False' or val == '0':
return False
return ... | Fix to_bool to accept 0. | Fix to_bool to accept 0.
| Python | mit | matham/moa |
8c528fb604c67a06ec8babb0ad595a9693993451 | api/projects/tasks.py | api/projects/tasks.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... | Fix issue with celery rescheduling task | Fix issue with celery rescheduling task
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
04cbfb1a0d7506e37dbb48569e6815b0d06c5238 | orders/views.py | orders/views.py | from django.http import HttpResponse
from django.template import RequestContext, loader
from orders.models import Item
def index(request):
item_list = Item.objects.all()
template = loader.get_template('orders/index.html')
context = RequestContext(request, {
'item_list': item_list,
})
retur... | from django.shortcuts import render
from orders.models import Item
def index(request):
item_list = Item.objects.all()
context = {'item_list': item_list}
return render(request, 'orders/index.html', context)
| Use render in the index view | Use render in the index view
| Python | cc0-1.0 | joostrijneveld/eetFestijn,WKuipers/eetFestijn,joostrijneveld/eetFestijn,joostrijneveld/eetFestijn,WKuipers/eetFestijn,WKuipers/eetFestijn |
f0f3c50a65aae1393928579ca0e48891d1ac8f18 | app/access_control.py | app/access_control.py | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "... | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "... | Create a decorator `for_guest` for access control on pages for guests. | Create a decorator `for_guest` for access control on pages for guests.
| Python | mit | alchermd/flask-todo-app,alchermd/flask-todo-app |
3c0e434385558871e75ffb0d1810382ad9893143 | functional_tests.py | functional_tests.py | from selenium import webdriver
import pytest
@pytest.fixture(scope='function')
def browser(request):
browser_ = webdriver.Firefox()
def fin():
browser_.quit()
request.addfinalizer(fin)
return browser_
def test_can_show_a_relevant_code_snippet(browser):
browser.get('http://localhost:800... | from selenium import webdriver
import pytest
@pytest.fixture(scope='function')
def browser(request):
browser_ = webdriver.Firefox()
def fin():
browser_.quit()
request.addfinalizer(fin)
return browser_
def test_can_show_a_relevant_code_snippet(browser):
# Jan visits the site
browser... | Change FT to expect site name in title | Change FT to expect site name in title
| Python | mit | jvanbrug/scout,jvanbrug/scout |
081e2a4e2e98e385cae1671c69638db825e10e8a | wtfhack/settings/__init__.py | wtfhack/settings/__init__.py | """ Settings for wtfhack """
from .base import *
try:
from .local import *
except ImportError, exc:
#exc.args = tuple(
# ['%s (did you rename settings/local-dist.py?)' % exc.args[0]])
#raise exc
| """ Settings for wtfhack """
from .base import *
try:
from .local import *
except ImportError, exc:
print '%s (did you rename settings/local-dist.py?)' % exc.args[0] | Add code that actually works | Add code that actually works
| Python | bsd-3-clause | sloria/wtfhack,sloria/wtfhack,sloria/wtfhack,sloria/wtfhack,sloria/wtfhack |
925bf95f364676b26254afe5da90720e08dc3846 | app/initial_tables.py | app/initial_tables.py | from tables import engine
def create_tables():
"""
Create tables the lazy way... with raw SQL.
"""
conn = engine.raw_connection()
cur = conn.cursor()
cur.execute(
"""
CREATE TABLE file_upload_meta(
document_name TEXT NOT NULL
, document_slug TEXT NOT NULL
, time_uploaded TEXT NOT NU... | from tables import engine
def create_tables():
"""
Create tables the lazy way... with raw SQL.
"""
conn = engine.raw_connection()
cur = conn.cursor()
cur.execute(
"""
DROP TABLE IF EXISTS file_upload_meta;
"""
)
conn.commit()
cur.execute(
"""
CREATE TABLE file_upload_meta(
docum... | Drop table if exists in initial tables before creating | Drop table if exists in initial tables before creating
| Python | mit | sprin/heroku-tut |
ba34ea366d8ee9ac47f1bb3044ad04dcd482c6eb | cybox/test/objects/win_mailslot_test.py | cybox/test/objects/win_mailslot_test.py | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from cybox.objects.win_mailslot_object import WinMailslot
from cybox.test.objects import ObjectTestCase
class TestWinMailslot(ObjectTestCase, unittest.TestCase):
object_type = "WindowsMailslot... | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from cybox.objects.win_mailslot_object import WinMailslot
from cybox.test.objects import ObjectTestCase
class TestWinMailslot(ObjectTestCase, unittest.TestCase):
object_type = "WindowsMailslot... | Fix WinMailslot object to only use a single handle rather than a list | Fix WinMailslot object to only use a single handle rather than a list
| Python | bsd-3-clause | CybOXProject/python-cybox |
53f98ee4f0f5922bc154e109aac0e4447f4ed062 | setup.py | setup.py | # -*- coding: utf-8 -*-
from distutils.core import setup
with open('requirements.txt') as reqs:
requirements = reqs.read().split()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
description='Brazilian daylight saving time',
author='João ... | # -*- coding: utf-8 -*-
from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
description='Brazilian daylight saving time',
long_description=long_descript... | Remove parâmetros inutilizados e adiciona a descrição longa | Remove parâmetros inutilizados e adiciona a descrição longa
| Python | mit | joaocarlosmendes/pybrdst |
83617b63544ccb0336a8afc2726fd2e8dfacb69f | avalon/nuke/workio.py | avalon/nuke/workio.py | """Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["p... | """Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["p... | Fix undefined work_dir and scene_dir variables | Fix undefined work_dir and scene_dir variables
| Python | mit | mindbender-studio/core,mindbender-studio/core,getavalon/core,getavalon/core |
d54cb3d29f78ce1e06e549de783326c052054777 | mezzanine_api/settings.py | mezzanine_api/settings.py |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.Django... |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.Django... | Add LOGIN_URL setting for Oauth2 | Add LOGIN_URL setting for Oauth2
| Python | mit | gcushen/mezzanine-api,gcushen/mezzanine-api |
5d67010a0ea8e8f23495c8c7aa2d972f1e0cd547 | bake/test/test_mix.py | bake/test/test_mix.py | #!/usr/bin/env python
import unittest
import load
import os
import mix
class parseBPlinesTestCase(unittest.TestCase):
def test_overwrite(self):
# Test that a later line overwrites a previous line
grid = mix.parseBPlines(['@foo@;bar;baz', '@foo@;rag'])
self.assertEqual(grid.tokens[0], '@foo@')
self.assertEqual... | #!/usr/bin/env python
import unittest
import load
import os
import mix
class parseBPlinesTestCase(unittest.TestCase):
def test_overwrite(self):
# Test that a later line overwrites a previous line
grid = mix.parseBPlines(['@foo@;bar;baz', '@foo@;rag'])
self.assertEqual(grid.tokens[0], '@fo... | Make pep8 happy, remove mixed tabs and spaces | Make pep8 happy, remove mixed tabs and spaces
| Python | mit | AlexSzatmary/bake |
8f2650961ec2c080037f6a8d7a768563bbde8132 | webapp/tests/__init__.py | webapp/tests/__init__.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('t... | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('t... | Drop database before every test run, too, to remove data from failed tests. | Drop database before every test run, too, to remove data from failed tests.
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps |
22909289586427b4c6ef80e794c02b08d505b416 | api/crossref/permissions.py | api/crossref/permissions.py | # -*- coding: utf-8 -*-
import hmac
import hashlib
from rest_framework import permissions
from rest_framework import exceptions
from framework import sentry
from website import settings
class RequestComesFromMailgun(permissions.BasePermission):
"""Verify that request comes from Mailgun.
Adapted here from co... | # -*- coding: utf-8 -*-
import hmac
import hashlib
from rest_framework import permissions
from rest_framework import exceptions
from framework import sentry
from website import settings
class RequestComesFromMailgun(permissions.BasePermission):
"""Verify that request comes from Mailgun.
Adapted here from co... | Return False early if mailgun API key isn't set locally | Return False early if mailgun API key isn't set locally
| Python | apache-2.0 | cslzchen/osf.io,sloria/osf.io,erinspace/osf.io,mattclark/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,mattclark/osf.io,felliott/osf.io,mfraezz/osf.io,adlius/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,sloria/osf.io,adlius/osf.io,H... |
a59d756072a72e3110875058729e15f17a4b7f8a | bibliopixel/util/log_errors.py | bibliopixel/util/log_errors.py | from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
... | from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
... | Fix log_error so it now catches exceptions | Fix log_error so it now catches exceptions
* This got accidentally disabled
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel |
563316ca4df666ada6e2b0c6a224a159b06884d0 | tests.py | tests.py | #!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal
from pandas_finance import get_stock, get_required_tickers
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stock_called_correctly(s... | #!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal
from pandas_finance import get_stock, get_required_tickers
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stock_called_correctly(s... | Remove unnecessary call to mock_datareader(). | Remove unnecessary call to mock_datareader().
| Python | agpl-3.0 | scraperwiki/stock-tool,scraperwiki/stock-tool |
f550b3a321b240a5df921905fd47e4026ddc2bbd | gaphor/RAAML/modelinglanguage.py | gaphor/RAAML/modelinglanguage.py | """The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems
from gaphor.RAAML impo... | """The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems, raaml
from gaphor.RAA... | Fix STPA modeling elements can't be loaded from saved model | Fix STPA modeling elements can't be loaded from saved model
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
074f76547fbc01137e135f5de57b28fee82b810c | pylibui/core.py | pylibui/core.py | """
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def start(self):
"""
Starts the application main loop.
:return: N... | """
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def __enter__(self):
self.start()
def start(self):
"""
Star... | Make App a context manager | Make App a context manager
This means it can be used either as it is now unchanged or like this:
with libui.App():
... # code
Note that (1) the build instructions for libui appear to be wrong "make" vs "cmake ."; and (2) I can't build libui because of a bug in it or Ubuntu 14.04's cmake I don't know which. ... | Python | mit | joaoventura/pylibui,superzazu/pylibui,superzazu/pylibui,joaoventura/pylibui |
6fa13c56c38b14226d1902f8d686241ed88b875a | satnogsclient/scheduler/tasks.py | satnogsclient/scheduler/tasks.py | # -*- coding: utf-8 -*-
from urlparse import urljoin
import requests
from dateutil import parser
from satnogsclient import settings
from satnogsclient.scheduler import scheduler
def spawn_observation(*args, **kwargs):
raise NotImplementedError
def get_jobs():
"""Query SatNOGS Network API to GET jobs."""
... | # -*- coding: utf-8 -*-
from urlparse import urljoin
import requests
from dateutil import parser
from satnogsclient import settings
from satnogsclient.observer import Observer
from satnogsclient.scheduler import scheduler
def spawn_observation(*args, **kwargs):
obj = kwargs.pop('obj')
observer = Observer()... | Initialize and call observer on new observation task. | Initialize and call observer on new observation task.
| Python | agpl-3.0 | adamkalis/satnogs-client,cshields/satnogs-client,cshields/satnogs-client,adamkalis/satnogs-client |
1803cfffb53581b8325ad076d8eb62c5897f911d | other/iterate_deadlock.py | other/iterate_deadlock.py |
"""
Demonstrates deadlock related to attribute iteration.
"""
from threading import Thread
import h5py
FNAME = "deadlock.hdf5"
def make_file():
with h5py.File(FNAME,'w') as f:
for idx in xrange(1000):
f.attrs['%d'%idx] = 1
def list_attributes():
with h5py.File(FNAME, 'r') as f:
... |
"""
Demonstrates deadlock related to attribute iteration.
"""
from threading import Thread
import sys
import h5py
FNAME = "deadlock.hdf5"
def make_file():
with h5py.File(FNAME,'w') as f:
for idx in range(1000):
f.attrs['%d'%idx] = 1
def list_attributes():
with h5py.File(FNAME, 'r')... | Make deadlock script work on Python 3 | Make deadlock script work on Python 3
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py |
11fdccbc4144c2b1e27d2b124596ce9122c365a2 | froide/problem/apps.py | froide/problem/apps.py | import json
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from . import signals # noqa
re... | import json
from django.apps import AppConfig
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from froid... | Add user merging to problem, menu for moderation | Add user merging to problem, menu for moderation | Python | mit | fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide |
bd5ac74d2aaed956a1db4db2482076470d8c150f | google-oauth-userid/app.py | google-oauth-userid/app.py | from gevent.wsgi import WSGIServer
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from werkzeug.contrib.fixers import ProxyFix
import os
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.secret_key = os.urandom(64)
blueprint = make_google_... | from gevent.wsgi import WSGIServer
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from werkzeug.contrib.fixers import ProxyFix
import os
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.secret_key = os.urandom(64)
blueprint = make_google_... | Update scope to use changed profile | Update scope to use changed profile
| Python | mit | openshift-cs/OpenShift-Troubleshooting-Templates,openshift-cs/OpenShift-Troubleshooting-Templates |
03b19d542a50f9f897aa759c5921933cba8bf501 | sim_services_local/dispatcher.py | sim_services_local/dispatcher.py | # Copyright (C) 2015, University of Notre Dame
# All rights reserved
from django.utils import timezone
import subprocess
import sys
import os
from data_services import models as data_models
def submit(simulation_group):
"""
Run a simulation group on a local machine in background.
Raises RuntimeError if th... | # Copyright (C) 2015, University of Notre Dame
# All rights reserved
from django.utils import timezone
from django.conf import settings
import subprocess
import sys
import os
from data_services import models as data_models
def submit(simulation_group):
"""
Run a simulation group on a local machine in backgrou... | Fix for broken job submission in apache | Fix for broken job submission in apache
| Python | mpl-2.0 | vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om |
a42f3c3899a20505f9aebe100aed6db4c91f4002 | coop_cms/apps/email_auth/urls.py | coop_cms/apps/email_auth/urls.py | # -*- coding: utf-8 -*-
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import login, password_change, password_reset, password_reset_confirm
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm... | # -*- coding: utf-8 -*-
"""urls"""
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordResetView, PasswordResetConfirmView
from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, E... | Fix auth views : use class-based views | Fix auth views : use class-based views
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms |
b190afa49a6b0939d692adcaee2396c619e632ff | setup.py | setup.py | from distutils.core import setup
import os
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path, 'rb').read().decode('utf-8')
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, o... | from distutils.core import setup
import os
import io
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = io.open(readme_path, encoding='utf-8').read()
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular... | Use io module for simplicity and closer alignment to recommended usage. | Use io module for simplicity and closer alignment to recommended usage.
| Python | mit | hugovk/inflect.py,pwdyson/inflect.py,jazzband/inflect |
491161d5ecdf6ef3c914b3e28175e8f3da9725f7 | i2cADC_read.py | i2cADC_read.py | from ABE_ADCPi import ADCPi
from ABE_helpers import ABEHelpers
import datetime, time
import os, sys
"""
================================================
ABElectronics ADC Pi 8-Channel ADC data-logger demo
Version 1.0 Created 11/05/2014
Version 1.1 16/11/2014 updated code and functions to PEP8 format
Requires python s... | from libs.ABE_ADCPi import ADCPi
from libs.ABE_helpers import ABEHelpers
import datetime, time
import os, sys
"""
================================================
ABElectronics ADC Pi 8-Channel ADC data-logger demo
Version 1.0 Created 11/05/2014
Version 1.1 16/11/2014 updated code and functions to PEP8 format
Require... | Set to work with libs package | Set to work with libs package
| Python | apache-2.0 | OkTekk/a.gus |
df3583ba3a7a1bade8b411d885a0df1609dd8465 | setup.py | setup.py | import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1dev',
author="Osvaldo Santana Neto",
author_email="forecast@osantana.me",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'f... | import os
from distutils.core import setup
path = os.path.dirname(__file__)
setup(
name='forecast',
version='0.1',
author="Osvaldo Santana Neto",
author_email="forecast@osantana.me",
packages=[
'forecast',
'forecast.applications',
'forecast.applications.core',
'fore... | Remove 'dev' from version name and add data files to install process | Remove 'dev' from version name and add data files to install process
| Python | mit | osantana/forecast |
b280771f37b5535cee61ab636f2f3256d6c18cee | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple(... | #!/usr/bin/env python
from distutils.core import setup
from platform import python_version_tuple
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
LONG_DESCRIPTION = open("README.rst").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple(... | Add Python 3.4 to classifiers | Add Python 3.4 to classifiers
All tests passed on Python 3.4.
| Python | mit | astanin/python-tabulate,kyokley/tabulate |
7c9fd4911aa9289310f3aa925e9cb4e6fe23b75b | piptools/sync.py | piptools/sync.py | import pip
exceptions = ['pip', 'setuptools', 'wheel']
def diff(requirements, installed):
"""
Calculate which modules should be installed or uninstalled,
given a set of requirements and a list of installed modules.
"""
requirements = { r.req.key: r for r in requirements }
to_be_installed = s... | import pip
EXCEPTIONS = [
'pip',
'pip-tools',
'setuptools',
'wheel',
]
def diff(requirements, installed):
"""
Calculate which modules should be installed or uninstalled,
given a set of requirements and a list of installed modules.
"""
requirements = {r.req.key: r for r in require... | Add pip-tools itself to the list of exceptions | Add pip-tools itself to the list of exceptions
| Python | bsd-2-clause | suutari/prequ,suutari/prequ,suutari-ai/prequ |
3ff6b8a2e8eecf48bfe74d5a0b0972e29ace15fd | imagetagger/imagetagger/annotations/admin.py | imagetagger/imagetagger/annotations/admin.py | from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
admin.site.register(Annotation)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(Verification)
admin.site.register(ExportFormat)
| from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
@admin.register(Annotation)
class AnnotationAdmin(admin.ModelAdmin):
raw_id_fields = (
'image',
)
@admin.register(Verification)
class VerificationAdmin(admin.ModelAdmin):
raw_id_fi... | Use raw id fields for annotation and verification foreign keys | Use raw id fields for annotation and verification foreign keys
| Python | mit | bit-bots/imagetagger,bit-bots/imagetagger,bit-bots/imagetagger,bit-bots/imagetagger |
14c9da0610f947c0b4f7f0d19f88e7c592e5e110 | numpy/linalg/setup.py | numpy/linalg/setup.py |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack... | Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack. | Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@5002 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | illume/numpy3k,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,illume/numpy3k,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,teoliphant/numpy-r... |
b2d813956f09e49b72a78b51fa398d17473cd0c7 | oauthenticator/tests/test_awscognito.py | oauthenticator/tests/test_awscognito.py | import os
from unittest.mock import patch
from pytest import fixture
with patch.dict(os.environ, AWSCOGNITO_DOMAIN='jupyterhub-test.auth.us-west-1.amazoncognito.com'):
from ..awscognito import AWSCognitoAuthenticator, AWSCOGNITO_DOMAIN
from .mocks import setup_oauth_mock
def user_model(username):
"""Return... | import os
from unittest.mock import patch
from pytest import fixture
with patch.dict(os.environ, AWSCOGNITO_DOMAIN='jupyterhub-test.auth.us-west-1.amazoncognito.com'):
from ..awscognito import AWSCognitoAuthenticator, AWSCOGNITO_DOMAIN
from .mocks import setup_oauth_mock
def user_model(username):
"""Return... | Fix mock results are not in json format | Fix mock results are not in json format
| Python | bsd-3-clause | minrk/oauthenticator,NickolausDS/oauthenticator,jupyterhub/oauthenticator |
e87e136dd590134b7be6f5d04aebeed719880c9e | paasta_tools/paasta_native_serviceinit.py | paasta_tools/paasta_native_serviceinit.py | from __future__ import absolute_import
from __future__ import unicode_literals
from paasta_tools import native_mesos_scheduler
from paasta_tools.mesos_tools import status_mesos_tasks_verbose
from paasta_tools.utils import calculate_tail_lines
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import... | from __future__ import absolute_import
from __future__ import unicode_literals
from paasta_tools.frameworks.native_scheduler import MESOS_TASK_SPACER
from paasta_tools.mesos_tools import status_mesos_tasks_verbose
from paasta_tools.utils import calculate_tail_lines
from paasta_tools.utils import compose_job_id
from pa... | Fix broken import in native scheduler | Fix broken import in native scheduler
| Python | apache-2.0 | Yelp/paasta,somic/paasta,Yelp/paasta,somic/paasta |
eb365afe5b6045260a336ed37aa56cb256ccc3e4 | tests/test_kqml_reader.py | tests/test_kqml_reader.py | import sys
from io import BytesIO
from kqml import KQMLObject
from kqml.kqml_reader import KQMLReader
from kqml.kqml_list import KQMLList
def test_read_list():
s = b'(FAILURE :reason INVALID_DESCRIPTION)'
sreader = BytesIO(s)
kr = KQMLReader(sreader)
lst = kr.read_list()
for obj in lst:
ass... | import sys
from io import BytesIO
from kqml import KQMLObject
from kqml.kqml_reader import KQMLReader
from kqml.kqml_list import KQMLList
def test_read_list():
s = b'(FAILURE :reason INVALID_DESCRIPTION)'
sreader = BytesIO(s)
kr = KQMLReader(sreader)
lst = kr.read_list()
for obj in lst:
ass... | Add unicode test for reading performatives | Add unicode test for reading performatives
| Python | bsd-2-clause | bgyori/pykqml |
40fe604adc38095a65b2fd9168badb50daa65b14 | thefuck/rules/git_pull.py | thefuck/rules/git_pull.py | def match(command, settings):
return ('git' in command.script
and 'pull' in command.script
and 'set-upstream' in command.stderr)
def get_new_command(command, settings):
line = command.stderr.split('\n')[-3].strip()
branch = line.split(' ')[-1]
set_upstream = line.replace('<remo... | from thefuck import shells
def match(command, settings):
return ('git' in command.script
and 'pull' in command.script
and 'set-upstream' in command.stderr)
def get_new_command(command, settings):
line = command.stderr.split('\n')[-3].strip()
branch = line.split(' ')[-1]
set_u... | Replace use of '&&' by shells.and_ | Replace use of '&&' by shells.and_
| Python | mit | scorphus/thefuck,subajat1/thefuck,bigplus/thefuck,beni55/thefuck,barneyElDinosaurio/thefuck,roth1002/thefuck,bigplus/thefuck,nvbn/thefuck,mcarton/thefuck,sekaiamber/thefuck,mlk/thefuck,gogobebe2/thefuck,petr-tichy/thefuck,SimenB/thefuck,hxddh/thefuck,PLNech/thefuck,LawrenceHan/thefuck,gaurav9991/thefuck,redreamality/th... |
a02ed17f79bba6e948c3b38d70ed6c2adbf1d0eb | py/tables.py | py/tables.py | import sqlalchemy
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = "posts"
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True)
title = sqlalchemy.Column(sqlalchemy.String)
body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text... | import sqlalchemy
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = "posts"
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True)
title = sqlalchemy.Column(sqlalchemy.String)
body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text... | Change type of time_posted to DATETIME and add author column | Change type of time_posted to DATETIME and add author column
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani |
18813ca36853296e09a7a4c38cd931f5bb2f8810 | pymt/__init__.py | pymt/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
| from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
try:
np.set_printoptions(legacy='1.13')
except Ty... | Use a try block for numpy<1.14 | Use a try block for numpy<1.14
| Python | mit | csdms/coupling,csdms/pymt,csdms/coupling |
dc9f61996a19c2181ec9e70e595480366fdfe9d8 | 2020-03-26-Python-Object-Model/examples/construction-and-finalization.py | 2020-03-26-Python-Object-Model/examples/construction-and-finalization.py | # Construction and finalization.
class A:
# __new__() is a special-cased static method so you do not have to declare
# it as such.
def __new__(cls, a):
print('A.__new__()')
return super().__new__(cls)
def __init__(self, a):
print('A.__init__()')
self.a = a
def __de... | # Construction and finalization.
class A:
# __new__() is a special-cased static method so you do not have to declare
# it as such.
def __new__(cls, a):
print('A.__new__()')
return super().__new__(cls)
def __init__(self, a):
print('A.__init__()')
self.a = a
def __de... | Add a note concerning __del__() in one of the examples. | 2020-03-26: Add a note concerning __del__() in one of the examples.
| Python | bsd-3-clause | s3rvac/talks,s3rvac/talks,s3rvac/talks,s3rvac/talks |
296c17310ab89aa19843ec8b5d313e9b622f9f86 | 14/src.py | 14/src.py | import sys
import itertools
import re
from md5 import md5
puzzle_input = 'yjdafjpo'
def key(n):
return md5(puzzle_input + str(n)).hexdigest()
def otp_keys(horizon):
lookahead = {k: -1 for k in '0123456789abcdef'}
def update_lookahead(n):
for quint in re.finditer(r'(.)\1{4}', key(n)):
lookahead[quint.... | import sys
import itertools
import re
from md5 import md5
puzzle_input = 'yjdafjpo'
def basic_hash(n):
return md5(puzzle_input + str(n)).hexdigest()
def otp_keys(horizon, hash_func):
lookahead = {k: -1 for k in '0123456789abcdef'}
def update_lookahead(n):
for quint in re.finditer(r'(.)\1{4}', hash_func(n))... | Make the hash function a parameter | Make the hash function a parameter
| Python | mit | amalloy/advent-of-code-2016 |
cefa3ffbcd1efb5cf030ec9d895b630c9fd650ad | newsletter/utils.py | newsletter/utils.py | """ Generic helper functions """
import logging
import random
from datetime import datetime
from hashlib import sha1
from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes
logger = logging.getLogger(__name__)
# Possible actions that user can perform
ACTIONS = ('subscribe', 'u... | """ Generic helper functions """
import logging
from django.contrib.sites.models import Site
from django.utils.crypto import get_random_string
logger = logging.getLogger(__name__)
# Possible actions that user can perform
ACTIONS = ('subscribe', 'unsubscribe', 'update')
def make_activation_code():
""" Genera... | Use Django’s crypto code to generate random code. | Use Django’s crypto code to generate random code.
Many thanks to Cédric Picard for his extensive
security report. | Python | agpl-3.0 | dsanders11/django-newsletter,dsanders11/django-newsletter,dsanders11/django-newsletter |
53d5f47c828bec78e7241cb9e3d4f614dd18e6f9 | responder.py | responder.py | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)... | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)... | Fix bug with text/plain response | Fix bug with text/plain response
| Python | mit | aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools |
1ba617690bbf50648a096875f419774064d284a6 | rstfinder/__init__.py | rstfinder/__init__.py | # Ensure there won't be logging complaints about no handlers being set
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler()) | # Ensure there won't be logging complaints about no handlers being set
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
try:
import zpar
except ImportError:
raise ImportError("The 'python-zpar' package is missing. Run 'pip install python-zpar' to install it.") from None
| Add check for python zpar when importing rstfinder. | Add check for python zpar when importing rstfinder.
| Python | mit | EducationalTestingService/discourse-parsing,EducationalTestingService/discourse-parsing |
b0f4158beebdb1edac9305e63a9fb77946d3a59f | run_tests.py | run_tests.py | import os
import sys
import contextlib
import subprocess
@contextlib.contextmanager
def binding(binding):
"""Prepare an environment for a specific binding"""
sys.stderr.write("""\
#
# Running tests with %s..
#
""" % binding)
os.environ["QT_PREFERRED_BINDING"] = binding
try:
yield
except... | import os
import sys
import contextlib
import subprocess
@contextlib.contextmanager
def binding(binding):
"""Prepare an environment for a specific binding"""
sys.stderr.write("""\
#
# Running tests with %s..
#
""" % binding)
os.environ["QT_PREFERRED_BINDING"] = binding
try:
yield
except... | Throw exception when primary tests fail | Throw exception when primary tests fail
| Python | mit | mottosso/Qt.py,fredrikaverpil/Qt.py,mottosso/Qt.py,fredrikaverpil/Qt.py |
0a2f63367cdb8bffdf762da78fb4888bef9c7d22 | run_tests.py | run_tests.py | #!/usr/bin/env python
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):... | #!/usr/bin/env python
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):... | Support running test just by test name | Support running test just by test name
| Python | apache-2.0 | illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit |
4136358896654b24df42c6dc963c0d071c31eec3 | snakewatch/config.py | snakewatch/config.py | import json
import importlib
class Config(object):
available_actions = {}
def __init__(self, cfg, *args):
if isinstance(cfg, str):
fp = open(cfg, 'r')
self.cfg = json.load(fp)
fp.close()
elif isinstance(cfg, list):
self.cfg = cfg
self... | import json
import os
import importlib
class Config(object):
available_actions = {}
def __init__(self, cfg, *args):
if isinstance(cfg, str):
fp = open(cfg, 'r')
self.cfg = json.load(fp)
fp.close()
elif isinstance(cfg, list):
self.cfg = cfg
... | Use ~/.snakewatch/default.json if exists, fallback on built-in. | Use ~/.snakewatch/default.json if exists, fallback on built-in.
| Python | bsd-3-clause | asoc/snakewatch |
5f1632cf1f307688e4884988e03a1678557bb79c | erpnext/hr/doctype/training_feedback/training_feedback.py | erpnext/hr/doctype/training_feedback/training_feedback.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
... | Use event_status instead of status | fix(hr): Use event_status instead of status
Training Feedback DocType has event_status field (not status)
This was broken since PR #10379, PR #17197 made this failure explicit.
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
83938c9bf7aafc1f7a2a6b9594279600012ee7ef | setup.py | setup.py | # coding: utf-8
"""pypel setup file.
THIS SOFTWARE IS UNDER BSD LICENSE.
Copyright (c) 2012-2015 Daniele Tricoli <eriol@mornie.org>
Read LICENSE for more informations.
"""
import distutils.core
import os.path
from pypel import __version__
def read(filename):
"""Small tool function to read file content."""
... | # coding: utf-8
"""pypel setup file.
THIS SOFTWARE IS UNDER BSD LICENSE.
Copyright (c) 2012-2015 Daniele Tricoli <eriol@mornie.org>
Read LICENSE for more informations.
"""
import distutils.core
import os.path
from pypel import __version__
def read(filename):
"""Small tool function to read file content."""
... | Update Python supported versions classifiers | Update Python supported versions classifiers
| Python | bsd-3-clause | eriol/pypel |
f2399e49e657848a58022b63915fad7969841b62 | setup.py | setup.py | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-portfolio',
version='0.8.0',
description='Web Worker\'s Portfolio for Django.',
url='http://github.com/benspaulding/django-portfolio/',
author='Be... | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-portfolio',
version='0.8.0',
description='Web Worker\'s Portfolio for Django.',
url='http://github.com/benspaulding/django-portfolio/',
author='Be... | Add tests to package list. | Add tests to package list.
Missed this earlier. Oops. | Python | bsd-3-clause | blturner/django-portfolio,blturner/django-portfolio,benspaulding/django-portfolio |
6705b4eb603f69681357a5f71f02e81705ea5e17 | setup.py | setup.py | from distutils.core import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pymp4parse',
version='0.3.0',
packages=[''],
url='https://github.com/use-sparingly/pymp4parse... | from distutils.core import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pymp4parse',
version='0.3.0',
packages=[''],
url='https://github.com/use-sparingly/pymp4parse... | Add six as dependency to fix import issue | Add six as dependency to fix import issue | Python | mit | use-sparingly/pymp4parse |
bdeb28f2f7840c04dbf65b6c0771c121f229e59a | tests.py | tests.py | #!/usr/bin/env python
import sys
import os
import unittest
from straight.plugin.loader import StraightPluginLoader
class PluginTestCase(unittest.TestCase):
def setUp(self):
self.loader = StraightPluginLoader()
self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins')
... | #!/usr/bin/env python
import sys
import os
import unittest
from straight.plugin.loader import StraightPluginLoader
class PluginTestCase(unittest.TestCase):
def setUp(self):
self.loader = StraightPluginLoader()
sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins'))
... | Fix test case for multiple locations of a namespace | Fix test case for multiple locations of a namespace
| Python | mit | ironfroggy/straight.plugin,pombredanne/straight.plugin |
27967818b58b2630a6282999e7b39af618716f91 | scheduler.py | scheduler.py | import logging
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
from config import Config
_config = Config()
raven_client = RavenClient()
# When testing changes, set the "TEST_SCHEDULE" envvar to... | import logging
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
from config import Config
_config = Config()
raven_client = RavenClient()
# When testing changes, set the "TEST_SCHEDULE" envvar to... | Use RUN_ONCE to only run the destalinate job once immediately | Use RUN_ONCE to only run the destalinate job once immediately
| Python | apache-2.0 | TheConnMan/destalinator,TheConnMan/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator |
0e07e0127e359cbf6c97d6f470fb51d15d7544bc | scripts/utils.py | scripts/utils.py | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
# Default parameters for JSON input and output
def json_load(fn):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file)
def... | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSO... | Move JSON dump parameters to a global dictionary. | scripts: Move JSON dump parameters to a global dictionary.
| Python | unlicense | VBChunguk/thcrap,VBChunguk/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap |
66aa43a5e8963c440261128e5b317679d01917e6 | server/routes.py | server/routes.py | from __init__ import app, db
from subprocess import call
from models import User
from flask import request
from flask import abort
from flask import jsonify
@app.route('/register', methods=['POST'])
def register():
if not request.json or not 'guid' in request.json:
abort(400) # Malformed Packet
guid =... | from __init__ import app, db
from subprocess import call
from models import User
from flask import request
from flask import abort
from flask import jsonify
@app.route('/register', methods=['POST'])
def register():
if not request.json or not 'guid' in request.json:
abort(400) # Malformed Packet
guid =... | Return header fix and msg_to route | Return header fix and msg_to route
| Python | mit | stevex86/RandomActsOfKindness,stevex86/RandomActsOfKindness |
550fedc513aab5feec3aaf43a49df5082a1e5dda | incuna_test_utils/testcases/urls.py | incuna_test_utils/testcases/urls.py | import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLsMixinBase(object):
"""A TestCase Mixin with a check_url helper method for testing urls"""
def check_url(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
... | import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLTestMixin(object):
def assert_url_matches_view(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly ... | Add simple URLTestMixin and URLTestCase classes | Add simple URLTestMixin and URLTestCase classes
* Remove old mixins and testcases
| Python | bsd-2-clause | incuna/incuna-test-utils,incuna/incuna-test-utils |
e4ab52fc36b9d4e0805fb134d43bf63fb73a62d8 | shcol/cli.py | shcol/cli.py | from __future__ import print_function
import argparse
import shcol
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
parser.add_argument('items', nargs='... | from __future__ import print_function
import argparse
import shcol
import sys
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
parser.add_argument(
... | Read from Stdin when no items are passed. | Read from Stdin when no items are passed.
| Python | bsd-2-clause | seblin/shcol |
7a20ee42aae2d2a6f5766ab4ec1ee4ef33fe14c8 | madam_rest/__init__.py | madam_rest/__init__.py | from flask import Flask
from madam import Madam
app = Flask(__name__)
app.from_object('config')
asset_manager = Madam()
asset_storage = app.config['ASSET_STORAGE']
from madam_rest import views
| import madam
from flask import Flask
app = Flask(__name__)
app.from_object('config')
asset_manager = madam.Madam()
asset_storage = madam.core.ShelveStorage(app.config['ASSET_STORAGE_PATH'])
from madam_rest import views
| Create shelve asset storage by default. | Create shelve asset storage by default.
| Python | agpl-3.0 | eseifert/madam-rest |
5b931f92b0f8f65306ced9cf049e2d1089c43860 | fantail/tests/test_staticsite.py | fantail/tests/test_staticsite.py | """
Tests for staticsite.py - the static site generator
"""
import os.path
import pytest
from fantail.staticsite import StaticSite
def test_init(tmpdir, caplog):
# Verify path does not exist
path = str(tmpdir.join('test-site'))
assert not os.path.isdir(path)
# Create the site
site = StaticSite(p... | """
Tests for staticsite.py - the static site generator
"""
import os.path
import pytest
from fantail.staticsite import StaticSite
def test_init(tmpdir, caplog):
# Verify path does not exist
path = str(tmpdir.join('test-site'))
assert not os.path.isdir(path)
# Create the site
site = StaticSite(p... | Remove assertion in test that should not have made it in | Remove assertion in test that should not have made it in
| Python | bsd-2-clause | sjkingo/fantail,sjkingo/fantail,sjkingo/fantail |
d67257dfe124d74d40d1dbe8bf881df27a07bf2c | needlestack/connections.py | needlestack/connections.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from threading import local
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import utils
class ConnectionManager(object):
def __init__(self):
self._connections = local()
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from threading import local
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import utils
from . import base
class ConnectionManager(object):
def __init__(self):
self._connect... | Add helpers for obtain indexes to connection manager. | Add helpers for obtain indexes to connection manager.
| Python | bsd-3-clause | niwinz/needlestack |
a849544beed5b2ef717345c1de467382f95f804a | githubsetupircnotifications.py | githubsetupircnotifications.py | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | Add more events to listen to | Add more events to listen to
| Python | mit | kragniz/github-setup-irc-notifications |
777eeaf61c256f04031d87995b4bccd7a93f1182 | lg_mirror/test/test_mirror_scene.py | lg_mirror/test/test_mirror_scene.py | #!/usr/bin/env python
import rospy
from interactivespaces_msgs.msg import GenericMessage
DIRECTOR_MESSAGE = """
{
"description": "bogus",
"duration": 0,
"name": "test whatever",
"resource_uri": "bogus",
"slug": "test message",
"windows": [
{
"activity": "mirror",
"activity_config": {
... | #!/usr/bin/env python
import rospy
from interactivespaces_msgs.msg import GenericMessage
DIRECTOR_MESSAGE = """
{
"description": "bogus",
"duration": 0,
"name": "test whatever",
"resource_uri": "bogus",
"slug": "test message",
"windows": [
{
"activity": "mirror",
"activity_config": {
... | Update mirror test scene for single activity | Update mirror test scene for single activity
| Python | apache-2.0 | EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes |
13daca3feedd8df8803904a60199a9dfa47dad8d | fuel_test/cobbler/test_single.py | fuel_test/cobbler/test_single.py | import unittest
from fuel_test.cobbler.cobbler_test_case import CobblerTestCase
from fuel_test.manifest import Manifest
from fuel_test.settings import OPENSTACK_SNAPSHOT
class SingleTestCase(CobblerTestCase):
def test_single(self):
Manifest().write_openstack_single_manifest(
remote=self.remote(... | import unittest
from fuel_test.cobbler.cobbler_test_case import CobblerTestCase
from fuel_test.manifest import Manifest
from fuel_test.settings import OPENSTACK_SNAPSHOT
class SingleTestCase(CobblerTestCase):
def test_single(self):
Manifest().write_openstack_single_manifest(
remote=self.remote(... | Switch off quantum at single node in test | Switch off quantum at single node in test
| Python | apache-2.0 | huntxu/fuel-library,eayunstack/fuel-library,eayunstack/fuel-library,SmartInfrastructures/fuel-library-dev,SmartInfrastructures/fuel-library-dev,stackforge/fuel-library,huntxu/fuel-library,stackforge/fuel-library,zhaochao/fuel-library,xarses/fuel-library,SmartInfrastructures/fuel-library-dev,ddepaoli3/fuel-library-dev,z... |
f76a766f7be4936d34dc14e65a0f1fd974055b20 | fireplace/cards/tgt/paladin.py | fireplace/cards/tgt/paladin.py | from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ALL_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##
# Secrets
# Competitive Spirit
class A... | from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ENEMY_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##
# Secrets
# Competitive Spirit
class AT_073:
... | Fix Eadric the Pure's target selection | Fix Eadric the Pure's target selection
| Python | agpl-3.0 | liujimj/fireplace,beheh/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,amw2104/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,Ragowit/fireplace,amw2104/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace |
f7cc714a0ea6f9d33ac06c2460f8abbd5991e4ab | pi_gpio/handlers.py | pi_gpio/handlers.py | from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinManager
MANAGER = PinManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
... | from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinManager
MANAGER = PinManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
... | Add extra field to detail output | Add extra field to detail output
| Python | mit | thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server |
903c0d6a3bda96a0b193cc6efd2f8e868d4d82e2 | setuptools/tests/test_build_ext.py | setuptools/tests/test_build_ext.py | """build_ext tests
"""
import unittest
from distutils.command.build_ext import build_ext as distutils_build_ext
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give... | """build_ext tests
"""
import unittest
import distutils.command.build_ext as orig
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give back the same
# resu... | Use namespacing for easier reading | Use namespacing for easier reading
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
1c254d8869482241de14255c25edd875ca369e46 | fortuitus/frunner/factories.py | fortuitus/frunner/factories.py | import factory
from fortuitus.feditor.factories import TestProjectF
from fortuitus.frunner import models
class TestRunF(factory.Factory):
FACTORY_FOR = models.TestRun
project = factory.SubFactory(TestProjectF)
class TestCaseF(factory.Factory):
FACTORY_FOR = models.TestCase
testrun = factory.SubFa... | import factory
from fortuitus.feditor.factories import TestProjectF
from fortuitus.frunner import models
class TestRunF(factory.Factory):
FACTORY_FOR = models.TestRun
project = factory.SubFactory(TestProjectF)
base_url = 'http://api.example.com/'
class TestCaseF(factory.Factory):
FACTORY_FOR = mod... | Fix TestRun factory missing base_url | Fix TestRun factory missing base_url
| Python | mit | elegion/djangodash2012,elegion/djangodash2012 |
8ae66dc2f9b3dd58db0c41a4bf44229dff2dc652 | falmer/content/models/__init__.py | falmer/content/models/__init__.py | from falmer.content.models.core import ClickThrough
from .staff import StaffPage, StaffMemberSnippet
from .section_content import SectionContentPage
from .selection_grid import SelectionGridPage
from .officer_overview import OfficerOverviewPage
from .homepage import HomePage
from .freshers import FreshersHomepage
from ... | from falmer.content.models.core import ClickThrough
from .staff import StaffPage, StaffMemberSnippet
from .section_content import SectionContentPage
from .selection_grid import SelectionGridPage
from .officer_overview import OfficerOverviewPage, OfficersIndex
from .homepage import HomePage
from .freshers import Fresher... | Add officers index to contentmap | Add officers index to contentmap
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
8a3eb221f51850d8a97c6d72715e644f52346c9f | swish/client.py | swish/client.py | import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json)... | import json
import requests
from .environment import Environment
class SwishClient(object):
def __init__(self, environment, payee_alias, cert):
self.environment = Environment.parse_environment(environment)
self.payee_alias = payee_alias
self.cert = cert
def post(self, endpoint, json)... | Correct data in payment request | Correct data in payment request
| Python | mit | playing-se/swish-python |
5bf50c2f36e00004dac0bc9bd604ac99b77261df | rename_fotos/tests/test_rename_fotos.py | rename_fotos/tests/test_rename_fotos.py | import pytest
import ../__init__ as init
from selenium import webdriver
LOCAL_INSTANCE = "127.0.0.1:5000"
def test_is_running():
init.is_running()
# Firefox
driver = webdriver.Firefox()
driver.get(LOCAl_INSTANCE)
assert driver.body == "Flask is running"
| import pytest
import rename_fotos as rfapp
LOCAL_INSTANCE = "127.0.0.1:5000"
@pytest.fixture
def client():
rfapp.app.config['TESTING'] = True
with rfapp.app.test_client() as client:
with rfapp.app.app_context():
rfapp.init_db()
yield client
def test_is_run... | Switch to flask built in tests | Switch to flask built in tests
| Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various |
797786d53d525aabd9495ac68a8f319680e09f89 | src/syntax/infix_coordination.py | src/syntax/infix_coordination.py | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
# Break the tree
... | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
# Break the tree
... | Break infix coordination only if there is one | Break infix coordination only if there is one
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify |
6cabf9c03cd40ae748d03f1a2fd3f4f3db6c47a5 | protocols/models.py | protocols/models.py | from datetime import datetime
from django.db import models
class Topic(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
attachment = models.ManyToManyField('attachments.Attachment')
voted_for = models.PositiveIntegerField()
voted_against... | from datetime import datetime
from django.db import models
class Topic(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
attachment = models.ManyToManyField('attachments.Attachment')
voted_for = models.PositiveIntegerField(blank=True, null=Tr... | Add option for blank voting | Add option for blank voting
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
fc7ba9019b42f056713b81bfee70f9e780b4aab5 | models/rasmachine/twitter_client.py | models/rasmachine/twitter_client.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh.read... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import tweepy
def get_oauth_file(auth_file):
try:
fh = open(auth_file, 'rt')
except IOError:
print('Could not get Twitter credentials.')
return None
lines = [l.strip() for l in fh... | Implement dict credentials in Twitter client | Implement dict credentials in Twitter client
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/belpy,jmuhlich/indra,jmuhlich/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,pvtodorov/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra... |
fe9512de5e41a6892826e70543637b893f3bd6f5 | temba/msgs/migrations/0087_populate_broadcast_send_all.py | temba/msgs/migrations/0087_populate_broadcast_send_all.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
for chunk in chunk_li... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_count = len... | Print progress of data migration | Print progress of data migration
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro |
3dfb310fa4df74c89b46fabb8195eb62b53dc5be | optimisers.py | optimisers.py | import numpy as np
class Optimiser:
def __init__(self, network):
self.nn = network
self.step_sign = -1.0 # minimise by default
def step(self):
self.nn.forward()
self.nn.reset_gradients()
self.nn.backward()
self.update_params()
def update_params(se... | import numpy as np
class Optimiser:
def __init__(self, network):
self.nn = network
self.step_sign = -1.0 # minimise by default
def step(self):
self.nn.forward()
self.nn.reset_gradients()
self.nn.backward()
self.update_params()
def update_params(se... | Add GradientDescent with Momentum Optimiser. | Add GradientDescent with Momentum Optimiser.
| Python | mit | Hornobster/Numpy-Neural-Net |
34015dbc34b2f4e44b104070bae8c3d1956d7e12 | is_valid/wrapper_predicates.py | is_valid/wrapper_predicates.py | import json
def is_transformed(transform, predicate, *args, exceptions=[
Exception
], msg='data can\'t be transformed', **kwargs):
def is_valid(data, explain=False):
try:
data = transform(data, *args, **kwargs)
except Exception as e:
if not any(isinstance(e, exc) for ex... | import json
def is_transformed(transform, predicate, *args, exceptions=[
Exception
], msg='data can\'t be transformed', **kwargs):
def is_valid(data, explain=False, include=False):
try:
data = transform(data, *args, **kwargs)
except Exception as e:
if not any(isinstance... | Add include keyword arg to is_tranformed | Add include keyword arg to is_tranformed
| Python | mit | Daanvdk/is_valid |
f8d94b93427ff92ae6eed58a81058cce4e661cd2 | solum/tests/common/test_service.py | solum/tests/common/test_service.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Test service with Component instead of Plan db object | Test service with Component instead of Plan db object
Since plan db objects are getting removed in add-plan-in-swift,
we need to test service with another object.
Change-Id: I85537ef17f8c125d3de85ab3625ea91e9487376f
| Python | apache-2.0 | gilbertpilz/solum,ed-/solum,devdattakulkarni/test-solum,stackforge/solum,gilbertpilz/solum,openstack/solum,ed-/solum,devdattakulkarni/test-solum,ed-/solum,ed-/solum,gilbertpilz/solum,gilbertpilz/solum,openstack/solum,stackforge/solum |
1c4b3fe1204bfa40c1d7b6444ab645826e4c1d1f | Filter.py | Filter.py | # tcviz 1.2
#
# Licensed under the terms of the MIT/X11 license.
# Copyright (c) 2009-2013 Vita Smid <http://ze.phyr.us>
import textwrap
from Id import Id
class Filter:
COLOR = '#999999'
def __init__(self, spec=None):
self.__parent = None
self.__target = None
self.__params = []
... | # tcviz 1.2
#
# Licensed under the terms of the MIT/X11 license.
# Copyright (c) 2009-2013 Vita Smid <http://ze.phyr.us>
import textwrap
from Id import Id
class Filter:
COLOR = '#999999'
def __init__(self, spec=None):
self.__parent = None
self.__target = None
self.__params = []
... | Fix ValueError when flowid is ??? | Fix ValueError when flowid is ???
A filter like the following:
tc filter add dev srvif parent 1: protocol ip u32 match ip dst 1.2.3.4/32 action drop
is reported in "tc show filter" as:
filter parent 1: protocol ip [...] flowid ??? [..]
| Python | mit | ze-phyr-us/tcviz |
f69a9a3e49f6a242be2d0d8d9eb6ff104e25247b | pyvarnish/remote.py | pyvarnish/remote.py | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
sshconfig = SS... | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
s... | Add an exception if ssh not configured | Add an exception if ssh not configured
| Python | bsd-3-clause | redsnapper8t8/pyvarnish |
afbb9a9be46c6a9db02f6f3256c82b9939ce5c9e | src/rna_seq/forms.py | src/rna_seq/forms.py | from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import AbstractAnalysisCre... | from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import InlineField
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import (
AbstractAnalysisCreat... | Use analysis base class form helper and form building blocks | Use analysis base class form helper and form building blocks
| Python | mit | ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai |
44fbeeb82ce797f357de36979ff47f2dec9d70ca | graphene/commands/show_command.py | graphene/commands/show_command.py | from enum import Enum
from graphene.commands.command import Command
from graphene.utils import PrettyPrinter
class ShowCommand(Command):
class ShowType(Enum):
TYPES = 1
RELATIONS = 2
def __init__(self, show_type):
self.show_type = show_type
def execute(self, storage_manager):
... | from enum import Enum
from graphene.commands.command import Command
from graphene.utils import PrettyPrinter
class ShowCommand(Command):
class ShowType(Enum):
TYPES = 1
RELATIONS = 2
def __init__(self, show_type):
self.show_type = show_type
def execute(self, storage_manager):
... | Update SHOW TYPES command to handle no types being created | Update SHOW TYPES command to handle no types being created
| Python | apache-2.0 | PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene |
abf36e3a6ce9eb001b3501756b3d3d15bd49d5bc | jazzband/members/decorators.py | jazzband/members/decorators.py | from flask import flash, redirect
from flask_login import current_user
import wrapt
from ..account.views import default_url
def member_required(next_url=None, message=None):
if next_url is None:
next_url = default_url()
if message is None:
message = "Sorry but you're not a member of Jazzband ... | from flask import flash, redirect
from flask_login import current_user
import wrapt
from ..account.views import default_url
def member_required(next_url=None, message=None):
if message is None:
message = "Sorry but you're not a member of Jazzband at the moment."
@wrapt.decorator
def wrapper(wrap... | Fix import time issue with member_required decorator. | Fix import time issue with member_required decorator.
| Python | mit | jazzband/site,jazzband/jazzband-site,jazzband/jazzband-site,jazzband/website,jazzband/website,jazzband/site,jazzband/website,jazzband/website |
45896958badb2ff5f7c36a86a60fbdab80d2f618 | plots/urls.py | plots/urls.py | __author__ = 'ankesh'
from django.conf.urls import patterns, url
| __author__ = 'ankesh'
from django.conf.urls import patterns, url
from plots.views import rawdata, draw
urlpatterns = patterns('',
url(r'^(?P<type>[A-z]+)/$', draw, name='drawChart'),
url(r'^(?P<type>[A-z]+)/data/$', rawdata, name='rawdata'),
)
| Add the URL mappings for the plots app. | Add the URL mappings for the plots app.
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark |
ce5cc3d899ef6a07b46794bbcf689ca52e9d59ae | txircd/modules/core/channel_statuses.py | txircd/modules/core/channel_statuses.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class StatusReport(ModuleData):
implements(IPlugin, IModuleData)
name = "ChannelStatusReport"
core = True
def actions(self):
return [ ("channelstatuses", 1, self.statuses) ]
... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class StatusReport(ModuleData):
implements(IPlugin, IModuleData)
name = "ChannelStatusReport"
core = True
def actions(self):
return [ ("channelstatuses", 1, self.statuses) ]
... | Fix check on the user's status when retrieving it | Fix check on the user's status when retrieving it
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd |
199a64fbed87a8ae43469bb48f8a4e16579f0b64 | partner_coc/__openerp__.py | partner_coc/__openerp__.py | # -*- coding: utf-8 -*-
# Copyright 2018 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
'name': 'Partner CoC',
'summary': "Adds a field 'Chamber Of Commerce Registration Number' to "
"partner",
'version': '8.0.1.0.0',
'category': 'W... | # -*- coding: utf-8 -*-
# Copyright 2018 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
'name': 'Partner CoC',
'summary': "Adds a field 'Chamber Of Commerce Registration Number' to "
"partner",
'version': '8.0.1.0.0',
'category': 'W... | Set website in manifest to OCA repository | [FIX] Set website in manifest to OCA repository | Python | agpl-3.0 | acsone/partner-contact |
ecbdb0389feb18d30524ab071db69a184710954d | past/types/__init__.py | past/types/__init__.py | from past import utils
if utils.PY2:
import __builtin__
basestring = __builtin__.basestring
dict = __builtin__.dict
str = __builtin__.str
long = __builtin__.long
unicode = __builtin__.unicode
__all__ = []
else:
from .basestring import basestring
from .olddict import olddict as dict
... | from past import utils
if utils.PY2:
import __builtin__
basestring = __builtin__.basestring
dict = __builtin__.dict
str = __builtin__.str
long = __builtin__.long
unicode = __builtin__.unicode
__all__ = []
else:
from .basestring import basestring
from .olddict import olddict
from... | Fix imports of past.builtins types | Fix imports of past.builtins types
| Python | mit | michaelpacer/python-future,krischer/python-future,PythonCharmers/python-future,QuLogic/python-future,PythonCharmers/python-future,krischer/python-future,QuLogic/python-future,michaelpacer/python-future |
e86901ac2b074d42d2e388353bbe60fcdd8f0240 | wagtail/contrib/postgres_search/apps.py | wagtail/contrib/postgres_search/apps.py | from django.apps import AppConfig
from django.core.checks import Error, Tags, register
from .utils import get_postgresql_connections, set_weights
class PostgresSearchConfig(AppConfig):
name = 'wagtail.contrib.postgres_search'
def ready(self):
@register(Tags.compatibility, Tags.database)
def ... | from django.apps import AppConfig
from django.core.checks import Error, Tags, register
from .utils import get_postgresql_connections, set_weights
class PostgresSearchConfig(AppConfig):
name = 'wagtail.contrib.postgres_search'
default_auto_field = 'django.db.models.AutoField'
def ready(self):
@re... | Set default_auto_field in wagtail.contrib.postgres_search AppConfig | Set default_auto_field in wagtail.contrib.postgres_search AppConfig
Add default_auto_field = 'django.db.models.AutoField'
Co-authored-by: Nick Moreton <7f1a4658c80dbc9331efe1b3861c4063f4838748@torchbox.com> | Python | bsd-3-clause | jnns/wagtail,zerolab/wagtail,gasman/wagtail,gasman/wagtail,gasman/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,thenewguy/wagtail,thenewguy/wagtail,jnns/wagtail,jnns/wagtail,rsalmaso/wagtail,wagtail/wagtail,mixxorz/wagtail,torchbox/wagtail,jnns/wagtail,gasman/wagtail,thenewguy/wagtail,thenewguy/wagtail,wagtail/wagtail,mixx... |
fc60bdfe1ee3c4baef916532bb88aeb1787cd8c7 | molo/core/api/constants.py | molo/core/api/constants.py | from collections import namedtuple
CONTENT_TYPES = [
("core.ArticlePage", "Article"),
("core.SectionPage", "Section"),
]
ENDPOINTS = [
("page", "api/v1/pages")
]
SESSION_VARS = namedtuple(
"SESSION_VARS",
["first", "second", ]
)
ARTICLE_SESSION_VARS = SESSION_VARS(
first=("url", "article_con... | from collections import namedtuple
CONTENT_TYPES = [
("core.ArticlePage", "Article"),
("core.SectionPage", "Section"),
]
ENDPOINTS = [
("page", "api/v1/pages")
]
SESSION_VARS = namedtuple(
"SESSION_VARS",
["first", "second", ]
)
ARTICLE_SESSION_VARS = SESSION_VARS(
first=("url", "article_con... | Add section session varialbes to facilitate redirects | Add section session varialbes to facilitate redirects
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo |
cad23e7c73a8f33b7aa841d89d5311030d1c2262 | databridge/helpers.py | databridge/helpers.py | from requests.adapters import HTTPAdapter
RetryAdapter = HTTPAdapter(max_retries=5)
def create_db_url(username, passwd, host, port):
if username and passwd:
cr = '{}:{}@'.format(username, passwd)
else:
cr = ''
return 'http://{}{}:{}/'.format(
cr, host, port
)
... | from requests.adapters import HTTPAdapter
RetryAdapter = HTTPAdapter(max_retries=5,
pool_connections=100,
pool_maxsize=50)
def create_db_url(username, passwd, host, port):
if username and passwd:
cr = '{}:{}@'.format(username, passwd)
else:
... | Change adapter; fix filter func | Change adapter; fix filter func
| Python | apache-2.0 | yshalenyk/databridge |
3f325e7820661313b69f6e410987caaff1ac7d96 | python/VTK.py | python/VTK.py | """
VTK.py
An VTK module for python that includes:
Wrappers for all the VTK classes that are wrappable
A Tkinter vtkRenderWidget (works like the tcl vtkTkRenderWidget)
The vtkImageViewerWidget and vtkImageWindowWidget are coming soon.
Classes to assist in moving data between python and VTK.
"""
from vtkpython impo... | """
VTK.py
An VTK module for python that includes:
Wrappers for all the VTK classes that are wrappable
A Tkinter vtkRenderWidget (works like the tcl vtkTkRenderWidget)
The vtkImageViewerWidget and vtkImageWindowWidget are coming soon.
Classes to assist in moving data between python and VTK.
"""
from vtkpython impo... | Remove dependancy on vtkVersion Place a try/except around modules that required Numeric | FIX: Remove dependancy on vtkVersion
Place a try/except around modules that required Numeric
| Python | bsd-3-clause | sumedhasingla/VTK,aashish24/VTK-old,mspark93/VTK,hendradarwin/VTK,cjh1/VTK,gram526/VTK,SimVascular/VTK,demarle/VTK,Wuteyan/VTK,msmolens/VTK,SimVascular/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,ashray/VTK-EVM,SimVascular/VTK,biddisco/VTK,demarle/VTK,spthaolt/VTK,sumedhasingla/VTK,candy7393/VTK,mspark93... |
ef011470ad361ca50b638461935d344392976821 | pywwt/misc.py | pywwt/misc.py | from bs4 import BeautifulSoup
class WWTException(Exception):
pass
def handle_response(resp_str):
soup = BeautifulSoup(resp_str)
success = soup.layerapi.status.string
if success != "Success":
raise WWTException(success)
def parse_kwargs(params, kwargs):
if "date_time" in kwargs:
pa... | from bs4 import BeautifulSoup
class WWTException(Exception):
pass
def handle_response(resp_str):
soup = BeautifulSoup(resp_str)
try:
success = soup.layerapi.status.string
if success != "Success":
raise WWTException(success)
except AttributeError:
error = soup.html.b... | Handle other kinds of errors. | Handle other kinds of errors.
| Python | bsd-3-clause | jzuhone/pywwt,vga101/pywwt,vga101/pywwt,jzuhone/pywwt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.