commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
ddbf22b6e4d19c2b0c47543d6f4d7fe8fc704483
errors.py
errors.py
"""Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" ...
"""Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" ...
Make __str__ = to repr
Make __str__ = to repr
Python
bsd-3-clause
mmattice/TwistedSNMP
--- +++ @@ -18,4 +18,5 @@ self.errorCode, self.message, ) + __str__ = __repr__
73fad83b4c1d295611de23b300b67d80a39c9a13
bot/api/call/call.py
bot/api/call/call.py
from bot.api.call.params import ApiCallParams from bot.api.domain import ApiObject from bot.api.telegram import TelegramBotApiException from bot.multithreading.work import Work class ApiCall: def __init__(self, api_func: callable, name: str): self.api_func = api_func self.name = name def call...
from bot.api.call.params import ApiCallParams from bot.api.domain import ApiObject from bot.api.exceptions import ApiExceptionFactory from bot.api.telegram import TelegramBotApiException from bot.multithreading.work import Work class ApiCall: def __init__(self, api_func: callable, name: str): self.api_fun...
Convert TelegramBotApiException to a ApiException in ApiCall
Convert TelegramBotApiException to a ApiException in ApiCall
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
--- +++ @@ -1,5 +1,6 @@ from bot.api.call.params import ApiCallParams from bot.api.domain import ApiObject +from bot.api.exceptions import ApiExceptionFactory from bot.api.telegram import TelegramBotApiException from bot.multithreading.work import Work @@ -21,7 +22,8 @@ try: return self.__...
fa2e48566bf532a2c72f9863444f3c7cff23a1c4
github/commands/open_file_on_remote.py
github/commands/open_file_on_remote.py
from sublime_plugin import TextCommand from ...common.file_and_repo import FileAndRepo from ..github import open_file_in_browser class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo): """ Open a new browser window to the web-version of the currently opened (or specified) file. If `preselect` is `Tru...
from sublime_plugin import TextCommand from ...core.base_command import BaseCommand from ..github import open_file_in_browser class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand): """ Open a new browser window to the web-version of the currently opened (or specified) file. If `preselect` is `True`,...
Fix regression where unable to open file on remote.
Fix regression where unable to open file on remote.
Python
mit
divmain/GitSavvy,ddevlin/GitSavvy,ddevlin/GitSavvy,ypersyntelykos/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,ralic/GitSavvy,dreki/GitSavvy,ralic/GitSavvy,jmanuel1/GitSavvy,divmain/GitSavvy,stoivo/GitSavvy,dreki/GitSavvy,dvcrn/GitSavvy,asfaltboy/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,asfaltboy/GitSavvy,ddevlin/Git...
--- +++ @@ -1,10 +1,10 @@ from sublime_plugin import TextCommand -from ...common.file_and_repo import FileAndRepo +from ...core.base_command import BaseCommand from ..github import open_file_in_browser -class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo): +class GsOpenFileOnRemoteCommand(TextCommand, Ba...
ea875b1cecd154400381969c7c1b165dccd77db8
httpony/application.py
httpony/application.py
from __future__ import print_function from httpie.cli import parser from httpie.context import Environment from httpie.output import streams from requests.models import Request from werkzeug.wrappers import Response from werkzeug.wrappers import Request as WerkzeugRequest from httpony import __version__ def make_ap...
from __future__ import print_function from httpie.cli import parser from httpie.context import Environment from httpie.output import streams from requests.models import Request from werkzeug.wrappers import Response from werkzeug.wrappers import Request as WerkzeugRequest from httpony import __version__ def make_ap...
Delete CONTENT_LENGTH and CONTENT_TYPE if empty.
Delete CONTENT_LENGTH and CONTENT_TYPE if empty. For some reason, the WSGI server puts these things in the environment even when they were not in the request. Their presence messes up the output in those cases.
Python
bsd-2-clause
mblayman/httpony
--- +++ @@ -18,6 +18,13 @@ server = 'HTTPony/{0}'.format(__version__) def application(environ, start_response): + # The WSGI server puts content length and type in the environment + # even when not provided with the request. Drop them if they are empty. + if environ.get('CONTENT_LENGT...
1f105b7ecd6770ac0704329bda3f149c05878da3
tests/test_utilities/test_in2csv.py
tests/test_utilities/test_in2csv.py
#!/usr/bin/env python import unittest import StringIO from csvkit.utilities.in2csv import In2CSV from csvkit.utilities.csvstat import CSVStat class TestIn2CSV(unittest.TestCase): def test_convert_xls(self): args = ['-f', 'xls', 'examples/test.xls'] output_file = StringIO.StringIO() ...
#!/usr/bin/env python import unittest import StringIO from csvkit.utilities.in2csv import In2CSV class TestIn2CSV(unittest.TestCase): def test_convert_xls(self): args = ['-f', 'xls', 'examples/test.xls'] output_file = StringIO.StringIO() utility = In2CSV(args, output_file) ...
Remove extraneous import in test.
Remove extraneous import in test.
Python
mit
themiurgo/csvkit,barentsen/csvkit,matterker/csvkit,dannguyen/csvkit,tlevine/csvkit,wjr1985/csvkit,doganmeh/csvkit,bradparks/csvkit__query_join_filter_CSV_cli,cypreess/csvkit,KarrieK/csvkit,archaeogeek/csvkit,Jobava/csvkit,jpalvarezf/csvkit,unpingco/csvkit,nriyer/csvkit,arowla/csvkit,haginara/csvkit,Tabea-K/csvkit,snugg...
--- +++ @@ -4,7 +4,6 @@ import StringIO from csvkit.utilities.in2csv import In2CSV -from csvkit.utilities.csvstat import CSVStat class TestIn2CSV(unittest.TestCase): def test_convert_xls(self):
6f265e37361b1447cf55c5d79cfe3ba6b6047b57
tests/examples/helloworld/flows.py
tests/examples/helloworld/flows.py
from viewflow import flow, lock, views as flow_views from viewflow.base import this, Flow from viewflow.site import viewsite from .models import HelloWorldProcess from .tasks import send_hello_world_request class HelloWorldFlow(Flow): """ Hello world This process demonstrates hello world approval reque...
from viewflow import flow, lock, views as flow_views from viewflow.base import this, Flow from viewflow.site import viewsite from .models import HelloWorldProcess from .tasks import send_hello_world_request class HelloWorldFlow(Flow): """ Hello world This process demonstrates hello world approval reque...
Fix hello world sample flow
Fix hello world sample flow
Python
agpl-3.0
ribeiro-ucl/viewflow,ribeiro-ucl/viewflow,ribeiro-ucl/viewflow,codingjoe/viewflow,viewflow/viewflow,codingjoe/viewflow,codingjoe/viewflow,pombredanne/viewflow,pombredanne/viewflow,viewflow/viewflow,viewflow/viewflow
--- +++ @@ -27,7 +27,7 @@ approve = flow.View(flow_views.ProcessView, fields=['approved']) \ .Permission(auto_create=True) \ - .Next(this.send) + .Next(this.check_approve) check_approve = flow.If(cond=lambda p: p.approved) \ .OnTrue(this.send) \
710291dd51c0a2950d616579f2442e6a81ee1670
update.py
update.py
from datetime import datetime, timedelta import sys from icalendar import Calendar def data_for_vevent(ev): start_date, end_date = [ev[which].dt.replace(tzinfo=None) + timedelta(hours=-9) for which in ('DTSTART', 'DTEND')] # TODO: convert to PT return (start_date.date(), str(ev['SUMMARY']), start_date,...
from datetime import datetime, timedelta from pprint import pformat import sys from icalendar import Calendar def data_for_vevent(ev): start_date, end_date = [ev[which].dt.replace(tzinfo=None) + timedelta(hours=-9) for which in ('DTSTART', 'DTEND')] return (start_date.date(), str(ev['SUMMARY']), sta...
Write the formatted date data out as a module
Write the formatted date data out as a module
Python
mit
markpasc/isthereagiantsgame
--- +++ @@ -1,13 +1,13 @@ from datetime import datetime, timedelta +from pprint import pformat import sys from icalendar import Calendar def data_for_vevent(ev): - start_date, end_date = [ev[which].dt.replace(tzinfo=None) + timedelta(hours=-9) for which in ('DTSTART', 'DTEND')] - - # TODO: convert to ...
ac2be16f952a40710610e0368ce195b73b92b611
core/management/commands/ticker/exchangerate.py
core/management/commands/ticker/exchangerate.py
import decimal import logging import threading import requests logger = logging.getLogger('btc.priceticker.exchangerate') class ExchangeRate(threading.Thread): YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv" YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'} SLEEP...
import decimal import logging import sys import threading import requests logger = logging.getLogger('btc.priceticker.exchangerate') class ExchangeRate(threading.Thread): YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv" YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'...
Include more exception data on exchange rate failure
Include more exception data on exchange rate failure
Python
unlicense
kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no
--- +++ @@ -1,5 +1,6 @@ import decimal import logging +import sys import threading import requests @@ -31,6 +32,16 @@ name, rate, date, time = csv.split(',') self.rate = decimal.Decimal(rate) self.stop_event.wait(ExchangeRate.SLEEP_TIME) - except Exc...
f832c047acf95e4a9f426eb2e3a174db025325a4
test/runalltest.py
test/runalltest.py
import sys, os import unittest try: # use the 'installed' mpi4py import mpi4py except ImportError: # or the no yet installed mpi4py from distutils.util import get_platform plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) os.path.split(__file__)[0] path = os.path.join(os.path.split(__f...
import sys, os import unittest try: # use the 'installed' mpi4py import mpi4py except ImportError: # or the no yet installed mpi4py from distutils.util import get_platform plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) os.path.split(__file__)[0] path = os.path.join(os.path.split(__f...
Print test names when running full testsuite
Print test names when running full testsuite
Python
bsd-2-clause
pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,pressel/mpi4py,mpi4py/mpi4py
--- +++ @@ -14,6 +14,7 @@ import mpi4py from mpi4py import MPI +sys.stderr.flush() sys.stderr.write("mpi4py imported from '%s'\n" % mpi4py.__path__[0]) sys.stderr.flush() @@ -31,6 +32,9 @@ def runtests(*args, **kargs): for test in alltests: + sys.stderr.flush() + sys.stderr.write("\n...
2212d1b943987652f4a6a575e3e88dc3e174ce7c
eigen/3.2/conanfile.py
eigen/3.2/conanfile.py
from conans import ConanFile import os class EigenConan(ConanFile): name = "eigen" version = "3.2" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=True" exports = "eigen/*" url="https://github.com/jslee02/conan-dart/tree/master...
from conans import ConanFile import os class EigenConan(ConanFile): name = "eigen" version = "3.2" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=True" exports = "eigen/*" url="https://github.com/jslee02/conan-dart/tree/master...
Add --insecure option to hg clone to avoid self-assigned certificate issue
Add --insecure option to hg clone to avoid self-assigned certificate issue
Python
bsd-2-clause
jslee02/conan-dart,jslee02/conan-dart,jslee02/conan-dart
--- +++ @@ -11,7 +11,7 @@ url="https://github.com/jslee02/conan-dart/tree/master/eigen/3.2" def source(self): - self.run('hg clone https://bitbucket.org/eigen/eigen -u 3.2.7') + self.run('hg clone --insecure https://bitbucket.org/eigen/eigen -u 3.2.7') self.run('cd eigen') de...
33915344c52ba7ea95cbe56668f55b1ba520af10
fortuitus/fcore/models.py
fortuitus/fcore/models.py
from autoslug.fields import AutoSlugField from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save class Company(models.Model): """ Organization. """ slug = AutoSlugField(populate_from='name', unique=True) name = models.CharField(max_length=10...
from autoslug.fields import AutoSlugField from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver class Company(models.Model): """ Organization. """ slug = AutoSlugField(populate_from='name', unique...
Use receiver decorator instead of `signal.connect`
Use receiver decorator instead of `signal.connect` I've contributed to this decorator upstream! It should be used. :-)
Python
mit
elegion/djangodash2012,elegion/djangodash2012
--- +++ @@ -2,6 +2,7 @@ from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save +from django.dispatch.dispatcher import receiver class Company(models.Model): @@ -20,9 +21,8 @@ company = models.ForeignKey(Company, null=True, blank=True) +...
bd1346a318f8f8d553a3fbf0a353ef6d68102566
twitter/twitter_globals.py
twitter/twitter_globals.py
''' This module is automatically generated using `update.py` .. data:: POST_ACTIONS List of twitter method names that require the use of POST ''' POST_ACTIONS = [ # Status Methods 'update', 'retweet', # Direct Message Methods 'new', # Account Methods 'update_profile_image', ...
''' This module is automatically generated using `update.py` .. data:: POST_ACTIONS List of twitter method names that require the use of POST ''' POST_ACTIONS = [ # Status Methods 'update', 'retweet', # Direct Message Methods 'new', # Account Methods 'update_profile_image', ...
Use POST for all methods requiring it in specs
Use POST for all methods requiring it in specs Added all missing methods from https://dev.twitter.com/docs/api/1.1 Also included some of the streaming methods which work with both GET and POST but accept arguments like "track" which can quickly require POST. (Closes #187 #145 #188)
Python
mit
adonoho/twitter,Adai0808/twitter,jessamynsmith/twitter,hugovk/twitter,sixohsix/twitter,tytek2012/twitter,miragshin/twitter
--- +++ @@ -16,24 +16,29 @@ # Account Methods 'update_profile_image', 'update_delivery_device', 'update_profile', 'update_profile_background_image', 'update_profile_colors', - 'update_location', 'end_session', + 'update_location', 'end_session', 'settings', + 'update_profile_banner', 'remove_p...
2ae93662f9f978dfae98096701b8e2e2a135f5a5
rejected/__init__.py
rejected/__init__.py
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ __author__ = 'Gavin M. Roy <gavinmroy@gmail.com>' __since__ = "2009-09-10" __version__ = "3.4.2" from consumer import Consumer from consumer import PublishingConsumer from consumer import SmartConsumer from consumer import SmartPublishingC...
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ __author__ = 'Gavin M. Roy <gavinmroy@gmail.com>' __since__ = "2009-09-10" __version__ = "3.4.2" from consumer import Consumer from consumer import PublishingConsumer from consumer import SmartConsumer from consumer import SmartPublishingC...
Add an additional null handler
Add an additional null handler
Python
bsd-3-clause
gmr/rejected,gmr/rejected
--- +++ @@ -28,3 +28,4 @@ pass logging.getLogger('rejected').addHandler(NullHandler()) +logging.getLogger('rejected.consumer').addHandler(NullHandler())
b75153ad49280ce793a995fca4a34d0688d63cb4
tests/unit/checkout/mixins_tests.py
tests/unit/checkout/mixins_tests.py
import mock from django.test import TestCase from oscar.apps.checkout.mixins import OrderPlacementMixin class TestOrderPlacementMixin(TestCase): def test_returns_none_when_no_shipping_address_passed_to_creation_method(self): address = OrderPlacementMixin().create_shipping_address( user=mock...
import mock from django.test import TestCase from oscar.apps.checkout.mixins import CheckoutSessionMixin, OrderPlacementMixin from oscar.apps.checkout.exceptions import FailedPreCondition from oscar.test import factories from oscar.test.utils import RequestFactory class TestOrderPlacementMixin(TestCase): def t...
Add tests for CheckoutSessionMixin.check_basket_is_valid method.
Add tests for CheckoutSessionMixin.check_basket_is_valid method.
Python
bsd-3-clause
django-oscar/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sonofa...
--- +++ @@ -2,7 +2,10 @@ from django.test import TestCase -from oscar.apps.checkout.mixins import OrderPlacementMixin +from oscar.apps.checkout.mixins import CheckoutSessionMixin, OrderPlacementMixin +from oscar.apps.checkout.exceptions import FailedPreCondition +from oscar.test import factories +from oscar.test...
e066eae6bb0f9d555a53f9ee2901c77ffebd3647
tracer/cachemanager/cachemanager.py
tracer/cachemanager/cachemanager.py
import pickle import claripy import logging from ..simprocedures import receive l = logging.getLogger("tracer.cachemanager.CacheManager") class CacheManager(object): def __init__(self): self.tracer = None def set_tracer(self, tracer): self.tracer = tracer def cacher(self, simstate): ...
import pickle import claripy import logging from ..simprocedures import receive l = logging.getLogger("tracer.cachemanager.CacheManager") class CacheManager(object): def __init__(self): self.tracer = None def set_tracer(self, tracer): self.tracer = tracer def cacher(self, simstate): ...
Fix a bug in the cache manager
Fix a bug in the cache manager It is possible that the previous state is None
Python
bsd-2-clause
schieb/angr,schieb/angr,angr/angr,angr/angr,tyb0807/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,angr/tracer,f-prettyland/angr,f-prettyland/angr
--- +++ @@ -21,7 +21,10 @@ def _prepare_cache_data(self, simstate): - state = self.tracer.previous.state + if self.tracer.previous != None: + state = self.tracer.previous.state + else: + state = None ds = None try:
01983a9c8fab1556aac524e7b3000461ff7c0b5d
txircd/modules/core/channellevel.py
txircd/modules/core/channellevel.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ChannelLevel(ModuleData): implements(IModuleData) name = "ChannelLevel" core = True def actions(self): return [ ("checkchannellevel", 1, self.levelCheck), ("ch...
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ChannelLevel(ModuleData): implements(IPlugin, IModuleData) name = "ChannelLevel" core = True def actions(self): return [ ("checkchannellevel", 1, self.levelCheck), ...
Make ChannelLevel actually a valid module
Make ChannelLevel actually a valid module
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
--- +++ @@ -3,7 +3,7 @@ from zope.interface import implements class ChannelLevel(ModuleData): - implements(IModuleData) + implements(IPlugin, IModuleData) name = "ChannelLevel" core = True
6bf971e4248d480594bf10b8f446bf30a5b16072
scripts/cuba_enum_generator.py
scripts/cuba_enum_generator.py
from scripts.old_single_meta_class_generator import CUBA_DATA_CONTAINER_EXCLUDE class CUBAEnumGenerator(object): """Generator class for cuba.py enumeration. """ def generate(self, cuba_dict, simphony_metadata_dict, output): """Generates the cuba file from the yaml-extracted dictionary of ...
from scripts import utils class CUBAEnumGenerator(object): """Generator class for cuba.py enumeration. """ def generate(self, cuba_dict, simphony_metadata_dict, output): """Generates the cuba file from the yaml-extracted dictionary of cuba and simphony_metadata files. Writes the generated...
Put prefix to enum values. Removed old hack.
Put prefix to enum values. Removed old hack.
Python
bsd-2-clause
simphony/simphony-common
--- +++ @@ -1,4 +1,4 @@ -from scripts.old_single_meta_class_generator import CUBA_DATA_CONTAINER_EXCLUDE +from scripts import utils class CUBAEnumGenerator(object): @@ -26,8 +26,7 @@ cuba_dict['CUBA_KEYS']) | set(simphony_metadata_dict['CUDS_KEYS']) for keyword in sorted(list(all_keys)): ...
40b4e156a72dd09d752b6ba3adeec7e28ca127a8
crawler/collector.py
crawler/collector.py
#!/usr/bin/env python3 # chameleon-crawler # # Copyright 2015 ghostwords. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from time import sleep from .utils import ...
#!/usr/bin/env python3 # chameleon-crawler # # Copyright 2015 ghostwords. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from time import sleep from .utils import ...
Convert JSON blob to relational db structure.
Convert JSON blob to relational db structure.
Python
mpl-2.0
ghostwords/chameleon-crawler,ghostwords/chameleon-crawler,ghostwords/chameleon-crawler
--- +++ @@ -13,33 +13,55 @@ from .utils import DATABASE_URL import dataset -import json def collect(crawl_id, result_queue, log): - with dataset.connect(DATABASE_URL) as db: - while True: - if result_queue.empty(): - sleep(0.01) - continue + db = dataset....
fc9cd61f97924a1e3daf053319e9b49a73b58c80
dploy/__init__.py
dploy/__init__.py
""" dploy script is an attempt at creating a clone of GNU stow that will work on Windows as well as *nix """ import sys assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater" import dploy.main as main def stow(sources, dest): """ sub command stow """ main.Stow(sources, dest) # pylint: ...
""" dploy script is an attempt at creating a clone of GNU stow that will work on Windows as well as *nix """ import sys assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater" import dploy.main as main def stow(sources, dest, is_silent=True, is_dry_run=False): """ sub command stow """ ma...
Add is_silent & is_dry_run arguments to module API
Add is_silent & is_dry_run arguments to module API This way all the features of the command line commands is also in the module API
Python
mit
arecarn/dploy
--- +++ @@ -9,24 +9,21 @@ import dploy.main as main -def stow(sources, dest): +def stow(sources, dest, is_silent=True, is_dry_run=False): """ sub command stow """ + main.Stow(sources, dest, is_silent, is_dry_run) - main.Stow(sources, dest) # pylint: disable=protected-access - - -def unstow...
a5fa87d1dac36ae8a1e0939aaf7835aa39d5c153
jsonapi.py
jsonapi.py
from flask import Blueprint # Set up api Blueprint api = Blueprint('api', __name__) # API Post Route @api.route('/create', methods=['GET', 'POST']) def api_create(): return "Create JSON Blueprint!"
from flask import Blueprint, jsonify, request import MySQLdb, dbc # Set up api Blueprint api = Blueprint('api', __name__) # API Post Route @api.route('/create', methods=['GET', 'POST']) def api_create(): # Get URL and password from POST Request URL = request.form.get('url') password = request.form.get('pa...
Add jsonify to api returns
Add jsonify to api returns
Python
apache-2.0
kylefrost/frst.xyz,kylefrost/frst.xyz
--- +++ @@ -1,4 +1,5 @@ -from flask import Blueprint +from flask import Blueprint, jsonify, request +import MySQLdb, dbc # Set up api Blueprint api = Blueprint('api', __name__) @@ -6,4 +7,31 @@ # API Post Route @api.route('/create', methods=['GET', 'POST']) def api_create(): - return "Create JSON Blueprint!...
3347aaf8ad8fc1e016f1bf4159a91227cf8bc450
billjobs/tests/tests_user_admin_api.py
billjobs/tests/tests_user_admin_api.py
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST ...
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST ...
Test anonymous user do not access user list endpoint
Test anonymous user do not access user list endpoint
Python
mit
ioO/billjobs
--- +++ @@ -28,3 +28,9 @@ view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_anonymous_do_not_list_user(self): + request = self.factory.get('/billjobs/users/') + view = UserAdmin.as_view() ...
bef6e3b13c2e524f606d6ef4157df93933548c22
11_first-try-except.py
11_first-try-except.py
number = raw_input('Enter a number to find a square : ') try : actualNumber = int(number)**2 print 'Square of the number is', actualNumber except : print 'Instead of typing number you entered -', number
number = raw_input('Enter a number to find a square : ') try : # In order to accept floating numbers, we are converting the varibale to float. actualNumber = float(number)**2 print 'Square of the number is', actualNumber except : print 'Instead of typing number you entered -', number
Convert variable from int to float, in order to accept floating value as well
Convert variable from int to float, in order to accept floating value as well
Python
mit
rahulbohra/Python-Basic
--- +++ @@ -1,6 +1,7 @@ number = raw_input('Enter a number to find a square : ') try : - actualNumber = int(number)**2 - print 'Square of the number is', actualNumber + # In order to accept floating numbers, we are converting the varibale to float. + actualNumber = float(number)**2 + print 'Square of the...
6e9e7e87efd220bb4f45172388161a7fc6f6d4ed
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ethan Zimmerman,,, # Copyright (c) 2014 Ethan Zimmerman,,, # # License: MIT # """This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provid...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ethan Zimmerman,,, # Copyright (c) 2014 Ethan Zimmerman,,, # # License: MIT # """This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provid...
Update RAML Cop version requirement to 1.0.0
Update RAML Cop version requirement to 1.0.0
Python
mit
thebinarypenguin/SublimeLinter-contrib-raml-cop
--- +++ @@ -19,7 +19,7 @@ syntax = 'raml' cmd = 'raml-cop --no-color' - version_requirement = '>= 0.2.0' + version_requirement = '>= 1.0.0' regex = ( r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] ' r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
1bbb7d793b479e299f751e84a85f8bc9f40fc633
microbower/__init__.py
microbower/__init__.py
from subprocess import check_call import urllib import json import os import os.path def install(): with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) registry = 'https://bower.herokuapp.com' topdir = os.path.abspath(os.curdir) ...
from subprocess import check_call import urllib import json import os import os.path def install(): if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')): return with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(...
Check for the asset directory once at the beginning
Check for the asset directory once at the beginning
Python
isc
zenhack/microbower
--- +++ @@ -7,10 +7,15 @@ def install(): + if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')): + return with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) + + if not os.path.isdir(bowerrc['directory...
85384cb811c8e4cfdcaa1c207ac2274f352b86e9
tensorflow_tutorials/__init__.py
tensorflow_tutorials/__init__.py
""" [Tutorials] for [TensorFlow]. [Tutorials]: https://www.tensorflow.org/versions/r0.8/tutorials/index.html [TensorFLow]: https://www.tensorflow.org/ """ from .version import __version__ from .mnist import mnist __all__ = [ 'mnist' ]
""" [Tutorials] for [TensorFlow]. [Source on GitHub][source]. [source]: https://github.com/rxedu/tensorflow-tutorials [Tutorials]: https://www.tensorflow.org/versions/r0.8/tutorials/index.html [TensorFLow]: https://www.tensorflow.org/ """ from .version import __version__ from .mnist import mnist __all__ = [ 'mni...
Add source link to docstring
Add source link to docstring
Python
mit
rxedu/tensorflow-tutorials
--- +++ @@ -1,6 +1,9 @@ """ [Tutorials] for [TensorFlow]. +[Source on GitHub][source]. + +[source]: https://github.com/rxedu/tensorflow-tutorials [Tutorials]: https://www.tensorflow.org/versions/r0.8/tutorials/index.html [TensorFLow]: https://www.tensorflow.org/ """
c23f134cb8385919c8fe07136f978223ed229978
micawber/cache.py
micawber/cache.py
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): ...
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): ...
Fix PicleCache error on Python3
Fix PicleCache error on Python3
Python
mit
coleifer/micawber,coleifer/micawber
--- +++ @@ -26,14 +26,13 @@ def load(self): if os.path.exists(self.filename): - with closing(open(self.filename)) as fh: - contents = fh.read() - return pickle.loads(contents) + with closing(open(self.filename, 'rb')) as fh: + return p...
81d2882d1558ed52fc70927d745474aa46ac1f3b
jarbas/dashboard/admin.py
jarbas/dashboard/admin.py
from django.contrib import admin from jarbas.core.models import Reimbursement class SuspiciousListFilter(admin.SimpleListFilter): title = 'Is suspicious' parameter_name = 'is_suspicions' def lookups(self, request, model_admin): return ( ('yes', 'Yes'), ('no', 'No'), ...
from django.contrib import admin from jarbas.core.models import Reimbursement class SuspiciousListFilter(admin.SimpleListFilter): title = 'Is suspicious' parameter_name = 'is_suspicions' def lookups(self, request, model_admin): return ( ('yes', 'Yes'), ('no', 'No'), ...
Mark all fields as read only in the dashboard
Mark all fields as read only in the dashboard
Python
mit
datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor
--- +++ @@ -46,6 +46,7 @@ 'year', 'state', ) + readonly_fields = tuple(f.name for f in Reimbursement._meta.fields) def is_suspicious(self, obj): return obj.suspicions is not None
7d4d1afc5a42edb88f5cb8eb1347b79fdc131272
src/actions/client.py
src/actions/client.py
from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.application.internet import MulticastServer from BeautifulSoup import BeautifulSoup, SoupStrainer import requests fileserver = '' urls = [] def get_file_urls(self, url): f = requests.get("http://" + url) ...
from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.application.internet import MulticastServer from BeautifulSoup import BeautifulSoup, SoupStrainer import requests fileserver = '' urls = [] def get_file_urls(self, url): f = requests.get("http://" + url) ...
Stop reactor and find files
Stop reactor and find files
Python
mit
derwolfe/teiler,derwolfe/teiler
--- +++ @@ -11,8 +11,10 @@ def get_file_urls(self, url): f = requests.get("http://" + url) for link in BeautifulSoup(f, parseOnlyThese=SoupStrainer('a')): - self.urls.append(link) - print link + urls.append(link) + +def get_files(): + pass class MulticastClientUDP(DatagramProtoco...
c11d0ec668a0755a9c5db2cb4dd372d8ab3e8a0d
.circleci/get_repos.py
.circleci/get_repos.py
from __future__ import print_function import os import sys import subprocess as sp import pytest import yaml import requests import argparse import re from ggd import utils #--------------------------------------------------------------------- ## Clone repos #---------------------------------------------------------...
from __future__ import print_function import os import sys import subprocess as sp import pytest import yaml import requests import argparse import re from ggd import utils #--------------------------------------------------------------------- ## Clone repos #---------------------------------------------------------...
Update with new metadata file system (removing use of ggd repo cloning)
Update with new metadata file system (removing use of ggd repo cloning)
Python
mit
gogetdata/ggd-cli,gogetdata/ggd-cli
--- +++ @@ -15,14 +15,14 @@ ## Clone repos #--------------------------------------------------------------------- -## Update local repo -utils.update_local_repo() +## Update local genomic metadata files +utils.update_genome_metadata_files() -##Uupdate metadata repo -utils.update_metadata_local_repo() +##Update ...
90f306421f695a596bf4a0a2dce3b52c44145889
zilencer/migrations/0001_initial.py
zilencer/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] operations = [ migrations.CreateModel( name='Deployment', fields=[ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] operations = [ migrations.CreateModel( name='Deployment', fields=[ ...
Replace bytes by strings in zilencer/migrations.
Replace bytes by strings in zilencer/migrations.
Python
apache-2.0
timabbott/zulip,vabs22/zulip,reyha/zulip,grave-w-grave/zulip,zulip/zulip,rht/zulip,andersk/zulip,punchagan/zulip,niftynei/zulip,KingxBanana/zulip,susansls/zulip,jphilipsen05/zulip,jainayush975/zulip,SmartPeople/zulip,isht3/zulip,jphilipsen05/zulip,Galexrt/zulip,souravbadami/zulip,paxapy/zulip,synicalsyntax/zulip,brainw...
--- +++ @@ -19,7 +19,7 @@ ('api_key', models.CharField(max_length=32, null=True)), ('base_api_url', models.CharField(max_length=128)), ('base_site_url', models.CharField(max_length=128)), - ('realms', models.ManyToManyField(related_name=b'_deployments'...
1c727e878402ffacf14c2978860d7d555c5f4069
zoe_lib/predefined_apps/__init__.py
zoe_lib/predefined_apps/__init__.py
# Copyright (c) 2016, Daniele Venzano # # 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 w...
# Copyright (c) 2016, Daniele Venzano # # 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 w...
Fix import error due to wrong import line
Fix import error due to wrong import line
Python
apache-2.0
DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe
--- +++ @@ -14,7 +14,7 @@ # limitations under the License. from zoe_lib.predefined_apps.copier import copier_app -from zoe_lib.predefined_frameworks.jupyter_spark import spark_jupyter_notebook_app +from zoe_lib.predefined_apps.spark_interactive import spark_jupyter_notebook_app from zoe_lib.predefined_apps.eurec...
1c5af88a0689aadab4069f9f2ad16164791624b3
Discord/utilities/errors.py
Discord/utilities/errors.py
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoice...
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoice...
Remove no longer used Missing Capability error
[Discord] Remove no longer used Missing Capability error
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
--- +++ @@ -21,11 +21,6 @@ '''Missing Permissions''' pass -class MissingCapability(CommandError): - '''Missing Capability''' - def __init__(self, permissions): - self.permissions = permissions - class NotPermitted(CommandError): '''Not Permitted''' pass
fb5c2e5df4f700fb19663bbe96e7aa2710e627ca
osprey/execute_dump.py
osprey/execute_dump.py
from __future__ import print_function, absolute_import, division import csv import json from six.moves import cStringIO from .config import Config from .trials import Trial def execute(args, parser): config = Config(args.config, verbose=False) session = config.trials() columns = Trial.__mapper__.columns...
from __future__ import print_function, absolute_import, division import csv import json from six.moves import cStringIO from .config import Config from .trials import Trial def execute(args, parser): config = Config(args.config, verbose=False) session = config.trials() columns = Trial.__mapper__.columns...
Store hyperparameters with the other settings
Store hyperparameters with the other settings Instead of storing them in their own 'parameters' directory.
Python
apache-2.0
msmbuilder/osprey,msultan/osprey,pandegroup/osprey,msultan/osprey,msmbuilder/osprey,pandegroup/osprey
--- +++ @@ -15,7 +15,14 @@ if args.output == 'json': items = [curr.to_dict() for curr in session.query(Trial).all()] - value = json.dumps(items) + new_items = [] + # Instead of saving the parameters on their own nested dict, + # save them along the rest of elements + ...
0b13092a7854fe2d967d057221420a57b7a37b16
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """This module exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an inte...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to sty...
Change module docstring to make Travis CI build pass
Change module docstring to make Travis CI build pass
Python
mit
jackbrewer/SublimeLinter-contrib-stylint
--- +++ @@ -7,7 +7,7 @@ # # License: MIT -"""This module exports the Stylint plugin class.""" +"""Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util
9037c6c67add92304b6cfdbfb3a79ac1b3e9e64e
test/checker/test_checker_binary.py
test/checker/test_checker_binary.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals import itertools import pytest import six from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(ob...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals import itertools import pytest from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): ...
Fix test cases for Python2
Fix test cases for Python2
Python
mit
thombashi/typepy
--- +++ @@ -10,7 +10,6 @@ import itertools import pytest -import six from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode @@ -25,10 +24,16 @@ list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( - ...
8af1f7a0525f69a6e2ee6c5cfd7d6a923873a7ec
froide/helper/auth.py
froide/helper/auth.py
from django.contrib.auth.backends import ModelBackend from django.core.validators import email_re from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): if email_re.search(username...
from django.contrib.auth.backends import ModelBackend from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=...
Validate email the correct way
Validate email the correct way
Python
mit
catcosmo/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,...
--- +++ @@ -1,18 +1,22 @@ from django.contrib.auth.backends import ModelBackend -from django.core.validators import email_re +from django.core.exceptions import ValidationError +from django.core.validators import validate_email from django.contrib.auth import models, load_backend, login from django.conf import set...
4ced26baaf25df6211940fa87ce7eaa9eee776f4
src/judge/compiler.py
src/judge/compiler.py
import hashlib import os import subprocess class CompilationError(Exception): def __init__(self,e): self.e = e def __str__(self): return repr(self.e) def compile(f): filename_with_extension = os.path.basename(f) name_of_binary_executable = hashlib.md5(open(f,'r').read().encode('utf-8')...
Add basic compiling ability capable of throwing 'CompilationError'.
judge: Add basic compiling ability capable of throwing 'CompilationError'.
Python
mit
basu96/crux-judge,CRUx-BPHC/crux-judge,basu96/crux-judge,CRUx-BPHC/crux-judge,CRUx-BPHC/crux-judge,basu96/crux-judge,basu96/crux-judge,basu96/crux-judge
--- +++ @@ -0,0 +1,17 @@ +import hashlib +import os +import subprocess + +class CompilationError(Exception): + def __init__(self,e): + self.e = e + def __str__(self): + return repr(self.e) + +def compile(f): + filename_with_extension = os.path.basename(f) + name_of_binary_executable = hashli...
3e6798113d3f1ddc08f4db7d65f3130ea2211dd7
nursereg/admin.py
nursereg/admin.py
from django.contrib import admin from .models import NurseSource, NurseReg admin.site.register(NurseSource) admin.site.register(NurseReg)
from django.contrib import admin from control.utils import CsvExportAdminMixin from .models import NurseSource, NurseReg class NurseRegAdmin(CsvExportAdminMixin, admin.ModelAdmin): csv_header = [ 'cmsisdn', 'dmsisdn', 'rmsisdn', 'faccode', 'id_type', 'id_no', 'passport_origin', 'dob', 'nu...
Add export inline for Nurse Registrations
Add export inline for Nurse Registrations
Python
bsd-3-clause
praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control
--- +++ @@ -1,6 +1,24 @@ from django.contrib import admin +from control.utils import CsvExportAdminMixin from .models import NurseSource, NurseReg + +class NurseRegAdmin(CsvExportAdminMixin, admin.ModelAdmin): + csv_header = [ + 'cmsisdn', 'dmsisdn', 'rmsisdn', 'faccode', + 'id_type', 'id_no', ...
810450d36084094c633646b14e123be8ae0e3602
src/services/TemperatureMonitor/src/TemperatureMonitor.py
src/services/TemperatureMonitor/src/TemperatureMonitor.py
import time import requests class TemperatureMonitor: def __init__(self, temperature_sensor, interval=60, smoothing=5, observers=()): self.temperature_sensor = temperature_sensor self.interval = interval self.smoothing = smoothing self.observers = observers self.history = ...
import time import requests class TemperatureMonitor: def __init__(self, temperature_sensor, interval=60, smoothing=5, observers=()): self.temperature_sensor = temperature_sensor self.interval = interval self.smoothing = smoothing self.observers = observers self.history = ...
Add New Temps to Beginning
Add New Temps to Beginning
Python
mit
IAPark/PITherm
--- +++ @@ -18,7 +18,7 @@ def check_temp(self): self.history = self.history[:self.smoothing-1] - self.history.append(self.temperature_sensor.get_temp()) + self.history.insert(0,self.temperature_sensor.get_temp()) sum = 0.0 for temp in self.history:
8bd3b1eb25d2207e33cd8970ac2cf739c983e191
properties/__init__.py
properties/__init__.py
"""Properties Giving structure (and documentation!) to the properties you use in your code avoids confusion and allows users to interact flexibly and provide multiple styles of input, have those inputs validated, and allow you as a developer to set expectations for what you want to work with. import properties class ...
"""Properties Giving structure (and documentation!) to the properties you use in your code avoids confusion and allows users to interact flexibly and provide multiple styles of input, have those inputs validated, and allow you as a developer to set expectations for what you want to work with. import properties class ...
Modify init to only import available modules
Modify init to only import available modules
Python
mit
aranzgeo/properties,3ptscience/properties
--- +++ @@ -7,8 +7,7 @@ import properties class Profile(properties.HasProperties): - name = properties.String('What is your name!', required=True) - + name = properties.String('What is your name?') """ from __future__ import absolute_import from __future__ import division @@ -21,6 +20,7 @@ List, ...
6cac0b8531297dab6bdaff2959646d5a8a90dd01
parse_vcfFile.py
parse_vcfFile.py
import pandas def read_vcf(filename): """ Reads an input VCF file containing lines for each SNP and columns with genotype info for each sample. :param filename: Path to VCF file :return: Pandas DataFrame representing VCF file with rows as SNPs and columns with info and samples """ vcf = open(...
import pandas def read_vcf(filename): """ Reads an input VCF file containing lines for each SNP and columns with genotype info for each sample. :param filename: Path to VCF file :return: Pandas DataFrame representing VCF file with columns as SNPs and rows with samples """ vcf = open(filename)...
Update VCF parsing to output SNP-column sample-row DataFrame
Update VCF parsing to output SNP-column sample-row DataFrame
Python
mit
NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop,NCBI-Hackathons/Network_Stats_Acc_Interop
--- +++ @@ -6,7 +6,7 @@ Reads an input VCF file containing lines for each SNP and columns with genotype info for each sample. :param filename: Path to VCF file - :return: Pandas DataFrame representing VCF file with rows as SNPs and columns with info and samples + :return: Pandas DataFrame representi...
72bb5cb08d7d0b708b9078b49b8ca8a068d514b9
account_verification_flask/config.py
account_verification_flask/config.py
class DefaultConfig(object): SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+' SQLALCHEMY_DATABASE_URI = 'sqlite://' class DevelopmentConfig(DefaultConfig): AUTHY_KEY = 'your_authy_key' TWILIO_ACCOUNT_SID = 'your_twilio_account_sid' TWILIO_AUTH_TOKEN = 'your_twilio_auth_toke...
class DefaultConfig(object): SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+' SQLALCHEMY_DATABASE_URI = 'sqlite://' class DevelopmentConfig(DefaultConfig): AUTHY_KEY = 'your_authy_key' TWILIO_ACCOUNT_SID = 'your_twilio_account_sid' TWILIO_AUTH_TOKEN = 'your_twilio_auth_toke...
Set default Db to inmemory storage
Set default Db to inmemory storage
Python
mit
TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask
--- +++ @@ -9,7 +9,7 @@ TWILIO_AUTH_TOKEN = 'your_twilio_auth_token' TWILIO_NUMBER = 'your_twilio_phone_number' - SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db' + SQLALCHEMY_DATABASE_URI = 'sqlite://' DEBUG = True class TestConfig(DefaultConfig):
08dcf4de96c6f8890e467e4d17c9449bae8064be
plugins/debug.py
plugins/debug.py
import time class Plugin: def __call__(self, bot): bot.on_respond(r"ping$", lambda bot, msg, reply: reply("PONG")) bot.on_respond(r"echo (.*)$", lambda bot, msg, reply: reply(msg["match"][0])) bot.on_respond(r"time$", lambda bot, msg, reply: reply(time.time())) bot.on_help("debug", ...
import time class Plugin: def __call__(self, bot): bot.on_respond(r"ping$", lambda bot, msg, reply: reply("PONG")) bot.on_respond(r"(?:echo|say) (.*)$", lambda bot, msg, reply: reply(msg["match"][0])) bot.on_respond(r"time$", lambda bot, msg, reply: reply(time.time())) bot.on_help("...
Add say alias to echo
Add say alias to echo
Python
mit
tomleese/smartbot,Cyanogenoid/smartbot,Muzer/smartbot,thomasleese/smartbot-old
--- +++ @@ -3,7 +3,7 @@ class Plugin: def __call__(self, bot): bot.on_respond(r"ping$", lambda bot, msg, reply: reply("PONG")) - bot.on_respond(r"echo (.*)$", lambda bot, msg, reply: reply(msg["match"][0])) + bot.on_respond(r"(?:echo|say) (.*)$", lambda bot, msg, reply: reply(msg["match"]...
38b4af0b3c1c6105d68ff453d86107758ef9d751
preconditions.py
preconditions.py
class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format...
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Python
mit
nejucomo/preconditions
--- +++ @@ -1,8 +1,23 @@ +import inspect + + class PreconditionError (TypeError): pass def preconditions(*precs): + + precinfo = [] + for p in precs: + spec = inspect.getargspec(p) + if spec.varargs or spec.keywords: + raise PreconditionError( + 'Precondition {...
634442dc25385831ce8f165ab8d9d58493a1979a
pinry/pins/views.py
pinry/pins/views.py
from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib import messages from django.utils.functional import lazy from django.views.generic.base import TemplateView from django.views.generic import CreateView from .forms import PinForm from .models import Pin reve...
from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib import messages from django.utils.functional import lazy from django.views.generic.base import TemplateView from django.views.generic import CreateView from .forms import PinForm from .models import Pin reve...
Fix a small styling error in the lazy_resolve definition
Fix a small styling error in the lazy_resolve definition
Python
bsd-2-clause
QLGu/pinry,MSylvia/pinry,Stackato-Apps/pinry,pinry/pinry,MSylvia/pinry,lapo-luchini/pinry,supervacuo/pinry,dotcom900825/xishi,lapo-luchini/pinry,lapo-luchini/pinry,Stackato-Apps/pinry,dotcom900825/xishi,wangjun/pinry,lapo-luchini/pinry,supervacuo/pinry,wangjun/pinry,pinry/pinry,MSylvia/pinry,pinry/pinry,rafirosenberg/p...
--- +++ @@ -9,7 +9,7 @@ from .models import Pin -reverse_lazy = lambda name=None, *args : lazy(reverse, str)(name, args=args) +reverse_lazy = lambda name=None, *args: lazy(reverse, str)(name, args=args) class RecentPins(TemplateView):
af56e9e9935b2caafe2b13eff3e2dd0d0eb5d980
pysis/util/__init__.py
pysis/util/__init__.py
# -*- coding: utf-8 -*- """ Utilities to help with common Isis patterns. """ __all__ = [ 'write_file_list', 'file_variations', 'ImageName', ] from file_manipulation import write_file_list, file_variations, ImageName
# -*- coding: utf-8 -*- """ Utilities to help with common Isis patterns. """ __all__ = [ 'write_file_list', 'file_variations', 'ImageName', ] from .file_manipulation import write_file_list, file_variations, ImageName
Use relative import for file manipulation module.
Use relative import for file manipulation module.
Python
bsd-3-clause
wtolson/pysis,wtolson/pysis,michaelaye/Pysis,michaelaye/Pysis
--- +++ @@ -11,4 +11,4 @@ ] -from file_manipulation import write_file_list, file_variations, ImageName +from .file_manipulation import write_file_list, file_variations, ImageName
fc74e6a4bc9992647abbb9f92a7e5880e5c29506
models.py
models.py
from django.db import models # Create your models here. class User(models.Model): display_name = models.CharField(max_length=64) auth_key = models.CharField(max_length=64) class Post(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=4000) class Comment(models.Model): user = model...
from django.db import models # Create your models here. class User(models.Model): display_name = models.CharField(max_length=64) auth_key = models.CharField(max_length=64) class Post(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=4000) last_modified = models.DateTimeField() cl...
Add 'last modified' field to Post model
Add 'last modified' field to Post model
Python
mit
SyntaxBlitz/bridie,SyntaxBlitz/bridie
--- +++ @@ -9,6 +9,7 @@ class Post(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=4000) + last_modified = models.DateTimeField() class Comment(models.Model): user = models.ForeignKey(User)
6989e6b2308cbe496857b5f911c136fcf3043444
zeus/api/resources/user_token.py
zeus/api/resources/user_token.py
from flask import Response from sqlalchemy.exc import IntegrityError from zeus import auth from zeus.config import db from zeus.models import UserApiToken from .base import Resource from ..schemas import TokenSchema token_schema = TokenSchema(strict=True) class UserTokenResource(Resource): def dispatch_request...
from sqlalchemy.exc import IntegrityError from zeus import auth from zeus.config import db from zeus.models import UserApiToken from .base import Resource from ..schemas import TokenSchema token_schema = TokenSchema(strict=True) class UserTokenResource(Resource): def get(self): """ Return the A...
Fix user token endpoint authorization
fix(token): Fix user token endpoint authorization
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
--- +++ @@ -1,4 +1,3 @@ -from flask import Response from sqlalchemy.exc import IntegrityError from zeus import auth @@ -12,27 +11,28 @@ class UserTokenResource(Resource): - def dispatch_request(self, *args, **kwargs) -> Response: + def get(self): + """ + Return the API token for the user....
a8e2f3e00145f56429eb3d01aa08efe329191b18
src/proposals/admin.py
src/proposals/admin.py
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): m...
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): m...
Make submitter a raw_id_field to prevent long select tag
Make submitter a raw_id_field to prevent long select tag
Python
mit
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
--- +++ @@ -23,6 +23,7 @@ 'detailed_description', 'outline', 'supplementary', 'recording_policy', 'slide_link', 'cancelled', ] + raw_id_fields = ['submitter'] search_fields = ['title', 'abstract'] inlines = [AdditionalSpeakerInline]
43696b102bada7408c5c8151e4ae87e5a2855337
ds_binary_tree_ft.py
ds_binary_tree_ft.py
def binary_tree(r): pass def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function def binary_tree(r): """Binary tree using list of list.""" return [r, [], []] def insert_left(root, new_branch): left_tree = root.pop(1) if len(left_tree) > 1: root.insert(1, [new_bran...
Complete ds: binary_tree using ls of ls
Complete ds: binary_tree using ls of ls
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -1,10 +1,73 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + def binary_tree(r): - pass + """Binary tree using list of list.""" + return [r, [], []] + + +def insert_left(root, new_branch): + left_tree = root.pop(1) + if len(...
6c78f66cda7842894ba11109bee602633edd87b5
symposion/reviews/forms.py
symposion/reviews/forms.py
from django import forms from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": MarkEdit()} def __init__(self,...
from django import forms from django.forms import Textarea from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": M...
Make review feedback not a Markdown widget
Make review feedback not a Markdown widget Review feedback wasn't supposed to be in markdown. Change the widget to a regular text area.
Python
bsd-3-clause
pyconjp/pyconjp-website,Diwahars/pycon,PyCon/pycon,njl/pycon,njl/pycon,PyCon/pycon,Diwahars/pycon,osmfj/sotmjp-website,smellman/sotmjp-website,smellman/sotmjp-website,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,Diwahars/pycon,njl/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,pyconjp/pyconjp-website,sm...
--- +++ @@ -1,4 +1,5 @@ from django import forms +from django.forms import Textarea from markedit.widgets import MarkEdit @@ -30,7 +31,7 @@ class Meta: model = ProposalMessage fields = ["message"] - widgets = {"message": MarkEdit()} + widgets = {"message": Textarea(attrs={'c...
3d0d917aed8aa73f8f73601666141b9acf72120e
server.py
server.py
import StringIO import base64 import signal from flask import Flask, render_template, request, make_response from quiver.plotter import FieldPlotter app = Flask(__name__) @app.route('/') def quiver(): '''Route for homepage''' return render_template('quiver.html') @app.route('/plot/', methods=['GET',]) def ...
import StringIO import base64 import signal import flask from quiver.plotter import FieldPlotter app = flask.Flask(__name__) @app.route('/') def quiver(): '''Route for homepage''' return flask.render_template('quiver.html') @app.route('/plot/', methods=['GET',]) def plot(): equation_string = flask.requ...
Change import level of flask.
Change import level of flask.
Python
mit
davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver
--- +++ @@ -2,20 +2,20 @@ import base64 import signal -from flask import Flask, render_template, request, make_response +import flask from quiver.plotter import FieldPlotter -app = Flask(__name__) +app = flask.Flask(__name__) @app.route('/') def quiver(): '''Route for homepage''' - return render_...
742f4a4e97caa32483d65244b7e7a705763c67bf
TestRig/TestProgram/DetectPlatform.py
TestRig/TestProgram/DetectPlatform.py
import subprocess import time import glob def detectPlatform(): data = [] proc = subprocess.Popen(["uname"], stdout=subprocess.PIPE, stdin=subprocess.PIPE) while True: read = proc.stdout.readline() #block / wait if not read: break data.append(read) if data[0] == 'Darwin\n': return "D...
import subprocess import time import glob def detectPlatform(): data = [] proc = subprocess.Popen(["uname"], stdout=subprocess.PIPE, stdin=subprocess.PIPE) while True: read = proc.stdout.readline() #block / wait if not read: break data.append(read) if data[0] == 'Darwin\n': return "D...
Add support for FTDI devices under linux
Add support for FTDI devices under linux
Python
apache-2.0
Blinkinlabs/BlinkyTape,Blinkinlabs/BlinkyTape,Blinkinlabs/BlinkyTape
--- +++ @@ -23,9 +23,10 @@ platform = detectPlatform() if platform == 'Darwin': - SERIAL_DEVICE_PATH = "/dev/cu.usb*" + ports = glob.glob("/dev/cu.usb*") else: # TODO: linux? - SERIAL_DEVICE_PATH = "/dev/ttyACM*" + ports = glob.glob("/dev/ttyACM*") + ports.extend(glob.glob("/d...
82eb7a69ccb88d27141aeb483e4482041108723f
app/Display/display.py
app/Display/display.py
import sys ESC = chr(27) CLEAR = ESC + "[2J" MOVE_HOME = ESC + "[H" ERASE = CLEAR + MOVE_HOME LINES = 24 COLS = 80 class Display: def __init__(self, title): self.title = title def clear(self): sys.stdout.write(ERASE) def show_properties(self, properties, names=None): ...
import sys ESC = chr(27) CSI = ESC + "[" CLEAR = CSI + "2J" MOVE_HOME = CSI + "H" ERASE = CLEAR + MOVE_HOME MOVE_TO = CSI + "{0};{1}H" LINES = 24 COLS = 80 class Display: def __init__(self, title, info=None): self.title = title self.info = info def clear(self): ...
Add support for cursor position, centered title, and an info bar
Add support for cursor position, centered title, and an info bar
Python
mit
gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x
--- +++ @@ -1,20 +1,28 @@ import sys ESC = chr(27) -CLEAR = ESC + "[2J" -MOVE_HOME = ESC + "[H" +CSI = ESC + "[" +CLEAR = CSI + "2J" +MOVE_HOME = CSI + "H" ERASE = CLEAR + MOVE_HOME +MOVE_TO = CSI + "{0};{1}H" LINES = 24 COLS = 80 class Display: - def __init__(self, title): ...
fe4f2697afdc280e0158aad1acf9613d1decb32d
project_template.py
project_template.py
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): def run(self): # Check whether the folder is open only one in the current window. folders = self.window.folders() msg = None if len(folders) == 0: msg = "No floder opened i...
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.fol...
Implement checking the format of settings
Implement checking the format of settings
Python
mit
autopp/SublimeProjectTemplate,autopp/SublimeProjectTemplate
--- +++ @@ -3,6 +3,9 @@ class ProjectTemplateCommand(sublime_plugin.WindowCommand): + + SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' + TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. @@ -16,5 +19,21 @@ sub...
a08bd02fcd255d19991398444a5d1ec0d11409d2
test/test_featurecounts.py
test/test_featurecounts.py
import sequana.featurecounts as fc from sequana import sequana_data def test_featurecounts(): RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0" RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1" RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2" RNASEQ_DIR_undef = sequana_data...
import sequana.featurecounts as fc from sequana import sequana_data def test_featurecounts(): RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0" RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1" RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2" RNASEQ_DIR_undef = sequana_data...
Fix syntax in featureCounts test
Fix syntax in featureCounts test
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
--- +++ @@ -13,12 +13,12 @@ assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_1, tolerance=0.1) == "1" assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_2, tolerance=0.1) == "2" - try: - assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_undef, tolerance=0.1) == "NA" + assert...
c38b9f378f7dbf968ee6bcb7b3f0625a1993d61d
tests/core/test_history.py
tests/core/test_history.py
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), A...
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), A...
Use assertIn instead of assertTrue to test membership.
Use assertIn instead of assertTrue to test membership.
Python
apache-2.0
swak/mopidy,ali/mopidy,mokieyue/mopidy,tkem/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,tkem/mopidy,bacontext/mopidy,adamcik/mopidy,glogiotatidis/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,mopidy/mopidy,bencevans/mopidy,bacontext/mopidy,jcass77/mopidy,jodal/mopidy,diandiankan/mopidy,vrs01/mopidy,bencevans/mopidy,p...
--- +++ @@ -35,7 +35,7 @@ stored_history = self.history.get_history() track_ref = stored_history[0][1] self.assertEqual(track_ref.uri, track.uri) - self.assertTrue(track.name in track_ref.name) + self.assertIn(track.name, track_ref.name) if track.artists: ...
92da4abbcf1551d87192b627b3c5f44f2fe82e91
quickplots/textsize.py
quickplots/textsize.py
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return 10
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return int(height)
Make very basic font size calculator
Make very basic font size calculator
Python
mit
samirelanduk/quickplots
--- +++ @@ -1,4 +1,4 @@ """Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): - return 10 + return int(height)
e3287b9669e07dc4265efe768ba2b4c3351839d3
base_geoengine/geo_db.py
base_geoengine/geo_db.py
# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). """Helper to setup Postgis""" import logging from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS suppo...
# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). """Helper to setup Postgis""" import logging from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis ...
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Python
agpl-3.0
OCA/geospatial,OCA/geospatial,OCA/geospatial
--- +++ @@ -3,6 +3,7 @@ """Helper to setup Postgis""" import logging +from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') @@ -32,12 +33,15 @@ """) except Exception: raise MissingError( - "Error, can not automatically initialize ...
aa436864f53a4c77b4869baabfb1478d7fea36f0
tests/products/__init__.py
tests/products/__init__.py
""" Test utilities for ensuring the correctness of products """ import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': str, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': str, 'instrument': str, 'bounds': BoundingBox, 'bands': [Ba...
""" Test utilities for ensuring the correctness of products """ import arrow import six from tilezilla.core import BoundingBox, Band MAPPING = { 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, 'platform': six.string_types, 'instrument': six.string_types, ...
Allow str type comparison in py2/3
Allow str type comparison in py2/3
Python
bsd-3-clause
ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tiles,ceholden/tilezilla,ceholden/landsat_tile
--- +++ @@ -7,11 +7,11 @@ MAPPING = { - 'timeseries_id': str, + 'timeseries_id': six.string_types, 'acquired': arrow.Arrow, 'processed': arrow.Arrow, - 'platform': str, - 'instrument': str, + 'platform': six.string_types, + 'instrument': six.string_types, 'bounds': BoundingBox, ...
f2bf7807754d13c92bd2901072dd804dda61805f
cla_public/apps/contact/constants.py
cla_public/apps/contact/constants.py
# -*- coding: utf-8 -*- "Contact constants" from flask.ext.babel import lazy_gettext as _ DAY_TODAY = 'today' DAY_SPECIFIC = 'specific_day' DAY_CHOICES = ( (DAY_TODAY, _('Call me today at')), (DAY_SPECIFIC, _('Call me in the next week on')) )
# -*- coding: utf-8 -*- "Contact constants" from flask.ext.babel import lazy_gettext as _ DAY_TODAY = 'today' DAY_SPECIFIC = 'specific_day' DAY_CHOICES = ( (DAY_TODAY, _('Call me today at')), (DAY_SPECIFIC, _('Call me in on')) )
Update button label (call back time picker)
FE: Update button label (call back time picker)
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
--- +++ @@ -8,5 +8,5 @@ DAY_SPECIFIC = 'specific_day' DAY_CHOICES = ( (DAY_TODAY, _('Call me today at')), - (DAY_SPECIFIC, _('Call me in the next week on')) + (DAY_SPECIFIC, _('Call me in on')) )
74d6b8bf119eca7e3f8f1d49f3c8d82b726f3062
faq/search_indexes.py
faq/search_indexes.py
# -*- coding: utf-8 -*- from haystack import indexes from haystack.sites import site from faq.settings import SEARCH_INDEX from faq.models import Topic, Question class FAQIndexBase(SEARCH_INDEX): text = indexes.CharField(document=True, use_template=True) url = indexes.CharField(model_attr='get_absolute_url...
# -*- coding: utf-8 -*- """ Haystack SearchIndexes for FAQ objects. Note that these are compatible with both Haystack 1.0 and Haystack 2.0-beta. The super class for these indexes can be customized by using the ``FAQ_SEARCH_INDEX`` setting. """ from haystack import indexes from faq.settings import SEARCH_INDEX fro...
Add compatibility for Haystack 2.0.
Add compatibility for Haystack 2.0.
Python
bsd-3-clause
benspaulding/django-faq
--- +++ @@ -1,10 +1,28 @@ # -*- coding: utf-8 -*- +""" +Haystack SearchIndexes for FAQ objects. + +Note that these are compatible with both Haystack 1.0 and Haystack 2.0-beta. + +The super class for these indexes can be customized by using the +``FAQ_SEARCH_INDEX`` setting. + +""" + from haystack import indexes -...
f1cf2af003f7d8686a8b54ca822ff9aaa7fcc96b
clifford/_version.py
clifford/_version.py
# Package versioning solution originally found here: # http://stackoverflow.com/q/458550 # Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module __version__ = '1.3.0dev0'
# Package versioning solution originally found here: # http://stackoverflow.com/q/458550 # Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module __version__ = '1.3.0dev1'
Create a pre-release version for PyPI, to test tweaks to readme and setup.py.
Create a pre-release version for PyPI, to test tweaks to readme and setup.py.
Python
bsd-3-clause
arsenovic/clifford,arsenovic/clifford
--- +++ @@ -5,4 +5,4 @@ # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module -__version__ = '1.3.0dev0' +__version__ = '1.3.0dev1'
6e77aff69adba0ded366a704bdafb601514faf5d
salt/thorium/runner.py
salt/thorium/runner.py
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
Fix local opts from CLI
Fix local opts from CLI
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -42,7 +42,7 @@ func = name local_opts = {} local_opts.update(__opts__) - local_opts['async'] = True # ensure this will be run async + local_opts['asynchronous'] = True # ensure this will be run asynchronous local_opts.update({ 'fun': func, 'arg': arg,
2cb406cac1a6faf1f2f79c1376ceac39871fb96e
pony_barn/build-django.py
pony_barn/build-django.py
import os import sys from base import BaseBuild from pony_build import client as pony class DjangoBuild(BaseBuild): def __init__(self): super(DjangoBuild, self).__init__() self.directory = os.path.dirname(os.path.abspath(__file__)) self.repo_url = 'git://github.com/django/django.git' ...
import os import sys from base import BaseBuild from pony_build import client as pony class DjangoBuild(BaseBuild): def __init__(self): super(DjangoBuild, self).__init__() self.directory = os.path.dirname(os.path.abspath(__file__)) self.repo_url = 'git://github.com/django/django.git' ...
Make it so that django build actually uses it's own code.
Make it so that django build actually uses it's own code.
Python
mit
ericholscher/pony_barn,ericholscher/pony_barn
--- +++ @@ -14,7 +14,7 @@ def define_commands(self): self.commands = [ pony.GitClone(self.repo_url), - pony.TestCommand([self.context.python, '../tests/runtests.py', '--settings', 'django_pony_test_settings'], name='run tests', run_cwd='django') + pony....
3b9105868cdeac3647aa9052532ce55d7c9b8dcd
bureaucrate/__main__.py
bureaucrate/__main__.py
from sys import argv from os.path import expanduser, join from argparse import ArgumentParser from . import __version__ from .bureaucrate import init from .utils import Config def process_account(conf: Config, account: str): acc = init(join(conf.get("base_path"), account)) for mailbox in conf.get_mailboxes(a...
from sys import argv from os.path import expanduser, join from argparse import ArgumentParser import logging from . import __version__ from .bureaucrate import init from .utils import Config def process_account(conf: Config, account: str): acc = init(join(conf.get("base_path"), account)) for mailbox in conf...
Add debug flag, printing debug info
Add debug flag, printing debug info
Python
mit
paulollivier/bureaucrate
--- +++ @@ -1,6 +1,8 @@ from sys import argv from os.path import expanduser, join from argparse import ArgumentParser + +import logging from . import __version__ from .bureaucrate import init @@ -20,9 +22,15 @@ parser.add_argument('-a', '--account', help="Restrict to an account") parser.add_argument(...
d4dc4effd92196e9ff18c04f217ded3cf1352103
project/api/forms.py
project/api/forms.py
# Django from django import forms # Local from .models import User class UserCreationForm(forms.ModelForm): class Meta: model = User fields = '__all__' def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['person'].email.lower() ...
# Django from django import forms # Local from .models import User class UserCreationForm(forms.ModelForm): class Meta: model = User fields = '__all__' def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['person'].email.lower() ...
Fix 'add user' form in Admin
Fix 'add user' form in Admin
Python
bsd-2-clause
barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api
--- +++ @@ -14,7 +14,7 @@ def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['person'].email.lower() - user.name = self.cleaned_data['name'].name + user.name = self.cleaned_data['person'].name user.set_password(None) if ...
0dc217bd0cec8a0321dfc38b88696514179bf833
editorconfig/__init__.py
editorconfig/__init__.py
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "development") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename"...
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" ...
Upgrade version to 0.11.3 final
Upgrade version to 0.11.3 final
Python
bsd-2-clause
VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,pocke/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,VictorBjelkholm/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,benjifishe...
--- +++ @@ -2,7 +2,7 @@ from editorconfig.versiontools import join_version -VERSION = (0, 11, 3, "development") +VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions']
574dd4ef0aa0d6381938a0638e497374434cb75e
lilkv/columnfamily.py
lilkv/columnfamily.py
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
Store rows as dictionaries of lists.
Store rows as dictionaries of lists.
Python
mit
pgorla/lil-kv
--- +++ @@ -16,7 +16,9 @@ def __init__(self, name, data_dir='data'): self.name = name - self.ROWS = set() + # A row consists of: + # {'rowkey': [col1, col2, col3]} + self.ROWS = dict() def insert(self, column): return self._insert(column) @@ -31,8 +33,10 @@ ...
3ce3e00b0ad3910c99e6d42b21e8d6839b4a2214
sympy/sets/condset.py
sympy/sets/condset.py
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import d...
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import d...
Fix property name in CondSet
Fix property name in CondSet Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>
Python
bsd-3-clause
oliverlee/sympy,Vishluck/sympy,skidzo/sympy,drufat/sympy,sampadsaha5/sympy,chaffra/sympy,souravsingh/sympy,AkademieOlympia/sympy,kaichogami/sympy,grevutiu-gabriel/sympy,ga7g08/sympy,pandeyadarsh/sympy,mcdaniel67/sympy,jerli/sympy,AkademieOlympia/sympy,ahhda/sympy,emon10005/sympy,mafiya69/sympy,jerli/sympy,rahuldan/symp...
--- +++ @@ -28,7 +28,7 @@ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) - cond = property(lambda self: self.args[0]) + lamda = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self):
780a224f055fef4aba302334050c7679b4e675f2
sanitize.py
sanitize.py
#!/usr/bin/env python """ This script cleans and processes JSON data scraped, using Scrapy, from workabroad.ph. """ import argparse import json import sys def main(): parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data") parser.add_argument("export", help="Export file format, 'cs...
#!/usr/bin/env python """ This script cleans and processes JSON data scraped, using Scrapy, from workabroad.ph. """ import argparse import codecs import os import json import sys def main(): parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data") parser.add_argument("export", help=...
Read JSON file to be processed
Read JSON file to be processed
Python
mit
staceytay/workabroad-scraper
--- +++ @@ -5,6 +5,8 @@ """ import argparse +import codecs +import os import json import sys @@ -19,6 +21,13 @@ global args args = parser.parse_args() + file_path = os.path.dirname(os.path.abspath(__file__)) + '/' + args.inputfile + + with codecs.open(file_path, 'r', 'utf-8') as json_data: +...
b573936d30840e8173d5ca59117a45ceae8dc2e6
hoomd/_operations.py
hoomd/_operations.py
import hoomd._integrator class Operations: def __init__(self, simulation=None): self.simulation = None self._auto_schedule = False self._compute = list() def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._set_integrator(op) else: ...
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._auto_schedule = False self._compute = list() def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: ...
Fix typo in constructor and remove set_integrator method
Fix typo in constructor and remove set_integrator method
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
--- +++ @@ -1,21 +1,18 @@ -import hoomd._integrator +import hoomd.integrate class Operations: def __init__(self, simulation=None): - self.simulation = None + self.simulation = simulation self._auto_schedule = False self._compute = list() def add(self, op): if ...
188fcafc6855da9cb7f946b3605ddca2bd20a0b8
qiprofile_rest/routers.py
qiprofile_rest/routers.py
from rest_framework import routers from .views import (UserViewSet, SubjectViewSet, SubjectDetailViewSet, SessionDetailViewSet) router = routers.SimpleRouter() router.register(r'user', UserViewSet) router.register(r'subjects', SubjectViewSet) router.register(r'subject_detail', SubjectDetailViewSet)...
from rest_framework import routers from .views import (UserViewSet, SubjectViewSet, SubjectDetailViewSet, SessionDetailViewSet) router = routers.SimpleRouter() router.register(r'user', UserViewSet) router.register(r'subjects', SubjectViewSet) router.register(r'subject[_-]detail', SubjectDetailViewS...
Allow underscore or dash in URL.
Allow underscore or dash in URL.
Python
bsd-2-clause
ohsu-qin/qiprofile-rest,ohsu-qin/qirest
--- +++ @@ -5,5 +5,5 @@ router = routers.SimpleRouter() router.register(r'user', UserViewSet) router.register(r'subjects', SubjectViewSet) -router.register(r'subject_detail', SubjectDetailViewSet) -router.register(r'session_detail', SessionDetailViewSet) +router.register(r'subject[_-]detail', SubjectDetailViewSet)...
dba0a9b80eb5dd90bcf1184fabe998973fbd2393
pacasus.py
pacasus.py
#!/usr/bin/python import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__)) +"/pypaswas") from pacasus.pacasusall import Pacasus import logging if __name__ == '__main__': try: ppw = Pacasus() ppw.run() except Exception as exception: # Show complete exception whe...
#!/usr/bin/python import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__)) +"/pypaswas") from pacasus.pacasusall import Pacasus import logging if __name__ == '__main__': try: ppw = Pacasus() ppw.run() except Exception as exception: # Show complete exception whe...
Print exception when no other info on exception is available
Print exception when no other info on exception is available
Python
mit
swarris/Pacasus
--- +++ @@ -17,5 +17,9 @@ getattr(logging, 'DEBUG') == ppw.logger.getEffectiveLevel()): ppw.logger.exception(str(exception)) else: - print('Program ended. The message was: ', ','.join(exception.args)) + if len(exception.args) > 0: + print('Progra...
ee5de7b17aea09bf06da3e79bc21cde4473969f9
nethud/proto/telnet.py
nethud/proto/telnet.py
from __future__ import print_function from twisted.internet import reactor, protocol, threads, defer from twisted.protocols.basic import LineReceiver from nethud.proto.client import NethackFactory class TelnetConnection(LineReceiver): def __init__(self, users): self.users = users self.uname = ''...
from __future__ import print_function from twisted.internet import reactor, protocol, threads, defer from twisted.protocols.basic import LineReceiver from nethud.proto.client import NethackFactory class TelnetConnection(LineReceiver): def __init__(self, users): self.users = users self.uname = ''...
Define class with `class`, not `def`
Define class with `class`, not `def` I don't make calsses much, can you tell?
Python
mit
ryansb/netHUD
--- +++ @@ -39,7 +39,7 @@ -def TelnetFactory(protocol.Factory): +class TelnetFactory(protocol.Factory): def __init__(self): self.users = {}
8915729158c9b5c22d16a4c2deee66f79a8276b9
apps/local_apps/account/middleware.py
apps/local_apps/account/middleware.py
from django.utils.cache import patch_vary_headers from django.utils import translation from account.models import Account class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context depending on ...
from django.utils.cache import patch_vary_headers from django.utils import translation from account.models import Account class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context depending on ...
Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
Python
mit
ingenieroariel/pinax,ingenieroariel/pinax
--- +++ @@ -16,7 +16,7 @@ try: account = Account.objects.get(user=request.user) return account.language - except (Account.DoesNotExist, Account.MultipleObjectsReturned): + except Account.DoesNotExist: pass return translatio...
b8d0398f5c134c3457f9b09c3457e0f882b75732
lutrisweb/settings/production.py
lutrisweb/settings/production.py
import os from base import * # noqa DEBUG = False MEDIA_URL = '//lutris.net/media/' FILES_ROOT = '/srv/files' ALLOWED_HOSTS = ['.lutris.net', '.lutris.net.', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lutris', 'USER': 'lutris', 'PASS...
import os from base import * # noqa DEBUG = False MEDIA_URL = '//lutris.net/media/' FILES_ROOT = '/srv/files' ALLOWED_HOSTS = ['.lutris.net', '.lutris.net.', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lutris', 'USER': 'lutris', 'PASS...
Store sessions in cache + database
Store sessions in cache + database
Python
agpl-3.0
lutris/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website
--- +++ @@ -30,6 +30,8 @@ )), ) +SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' + CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
f4d703fb38c8d4efbff709a6e3c7478b7cf96db2
code/conditional_switch_as_else_if.py
code/conditional_switch_as_else_if.py
score = 76 if score < 60: grade = 'F' elif score < 70: grade = 'D' elif score < 80: grade = 'C' elif score < 90: grade = 'B' else: grade = 'A' print(grade)
score = 76 grades = [ (60, 'F'), (70, 'D'), (80, 'C'), (90, 'B'), ] print(next((g for x, g in grades if score < x), 'A'))
Replace swith statement with a mapping
Replace swith statement with a mapping Official Python documentation explains [1], that switch statement can be replaced by `if .. elif .. else` or by a mapping. In first example with varying condtitions `if .. elif .. else` was used, and in this example a mapping is much better fitted way of doing a switch statement...
Python
mit
evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare
--- +++ @@ -1,12 +1,8 @@ score = 76 -if score < 60: - grade = 'F' -elif score < 70: - grade = 'D' -elif score < 80: - grade = 'C' -elif score < 90: - grade = 'B' -else: - grade = 'A' -print(grade) +grades = [ + (60, 'F'), + (70, 'D'), + (80, 'C'), + (90, 'B'), +] +print(next((g for x, g in...
4583c9949143e58bf400fc86e27d634aa382f605
tests/test_expanded.py
tests/test_expanded.py
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """-[ RECORD 0 ] name | hello age | 123 -[ RECORD 1 ] name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"])
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """***************************[ 1. row ]*************************** name | hello age | 123 ***************************[ 2. row ]*************************** name | world ag...
Update expanded tests to match mysql style.
Update expanded tests to match mysql style.
Python
bsd-3-clause
oguzy/mycli,chenpingzhao/mycli,ZuoGuocai/mycli,evook/mycli,jinstrive/mycli,j-bennet/mycli,danieljwest/mycli,suzukaze/mycli,thanatoskira/mycli,chenpingzhao/mycli,j-bennet/mycli,brewneaux/mycli,webwlsong/mycli,MnO2/rediscli,brewneaux/mycli,shoma/mycli,mdsrosa/mycli,oguzy/mycli,danieljwest/mycli,jinstrive/mycli,thanatoski...
--- +++ @@ -3,10 +3,10 @@ def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] - expected = """-[ RECORD 0 ] + expected = """***************************[ 1. row ]*************************** name | hello age | 123 --[ RECORD 1 ] +***************************[ 2. row ]************...
e09b8488b14cac72a8724a72b44e272df5a52db4
tests/test_pyserial.py
tests/test_pyserial.py
from __future__ import (absolute_import, print_function, unicode_literals) import os import sys lib_path = os.path.abspath('../') sys.path.append(lib_path) import io import struct import unittest import threading import time import serial try: import unittest2 as unittest except ImportError: import unittest ...
from __future__ import (absolute_import, print_function, unicode_literals) import os import sys lib_path = os.path.abspath('../') sys.path.append(lib_path) import io import struct import unittest import threading import time import serial try: import unittest2 as unittest except ImportError: import unittest ...
Convert 'comports' to a list before getting its length (the value may be a generator).
Convert 'comports' to a list before getting its length (the value may be a generator).
Python
agpl-3.0
makerbot/s3g,Jnesselr/s3g,makerbot/s3g,makerbot/s3g,Jnesselr/s3g,makerbot/s3g
--- +++ @@ -35,7 +35,7 @@ scan = lp.list_ports_by_vid_pid print('autograbbing a port') comports = lp.comports() - if( len(comports) < 1): + if( len(list(comports)) < 1): print('no comport availabe') self.assertFalse(True, "no comports, cannot execute test") portname = compo...
56b23bc44655e4a965939ceb5908cd84cfd9de88
src/room.py
src/room.py
class Room(object): """ This class is responsible for managing the people in a room """
class Room(object): """ This class is responsible for managing the people in a room """ def __init__(self, room_type, room_name): self.residents = [] self.room_name = room_name self.room_type =room_type if room_type == "office": self.maximum_no_of_people = 6 ...
Add init method to class Room
Add init method to class Room
Python
mit
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
--- +++ @@ -1,4 +1,12 @@ class Room(object): """ This class is responsible for managing the people in a room """ + def __init__(self, room_type, room_name): + self.residents = [] + self.room_name = room_name + self.room_type =room_type + if room_type == "office": + se...
a72a13aa89c11c4d9a2bad48b67abdf352989981
parsley/decorators.py
parsley/decorators.py
from django import forms def parsleyfy(klass): class ParsleyClass(klass): def __init__(self, *args, **kwargs): super(ParsleyClass, self).__init__(*args, **kwargs) for key, val in self.fields.items(): if val.required: val.widget.attrs.update({"data...
from django import forms def parsleyfy(klass): class ParsleyClass(klass): def __init__(self, *args, **kwargs): super(ParsleyClass, self).__init__(*args, **kwargs) for key, val in self.fields.items(): if val.required: val.widget.attrs.update({"dat...
Change type comparisions with isinstance
Change type comparisions with isinstance
Python
bsd-3-clause
agiliq/Django-parsley,jproffitt/Django-parsley,jproffitt/Django-parsley,agiliq/Django-parsley,Tivix/Django-parsley,Tivix/Django-parsley,agiliq/Django-parsley,jproffitt/Django-parsley
--- +++ @@ -1,4 +1,5 @@ from django import forms + def parsleyfy(klass): class ParsleyClass(klass): @@ -7,22 +8,19 @@ for key, val in self.fields.items(): if val.required: val.widget.attrs.update({"data-required": "true"}) - if type(val) == fo...
5cf8088d1cd808a31a38c776fd4668858205ddf2
openedx/features/job_board/views.py
openedx/features/job_board/views.py
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobsListView(ListView): model = Job context_object_name = 'jobs_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] def...
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobsListView(ListView): model = Job context_object_name = 'jobs_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] def...
Change job_count var name to total_job_count
Change job_count var name to total_job_count
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
--- +++ @@ -14,7 +14,7 @@ def get_context_data(self, **kwargs): context = super(JobsListView, self).get_context_data(**kwargs) - context['job_count'] = Job.objects.all().count() + context['total_job_count'] = Job.objects.all().count() return context
e0d4defa7bc7cd3ac70d77040c00150215ca251f
gavel/controllers/csrf_protection.py
gavel/controllers/csrf_protection.py
from gavel import app import gavel.utils as utils from flask import abort, request, session @app.before_request def csrf_protect(): if request.method == "POST": token = session.pop('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): abort(403) def generate_cs...
from gavel import app import gavel.utils as utils from flask import abort, request, session @app.before_request def csrf_protect(): if request.method == "POST": token = session.get('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): abort(403) def generate_cs...
Switch CSRF token from per-request to per-session
Switch CSRF token from per-request to per-session This patch switches the CSRF token handling from per-request to per-session. The per-request behavior was overly aggressive, and it restricted parallel browsing (e.g. multiple open browser tabs).
Python
agpl-3.0
anishathalye/gavel,anishathalye/gavel,anishathalye/gavel
--- +++ @@ -5,7 +5,7 @@ @app.before_request def csrf_protect(): if request.method == "POST": - token = session.pop('_csrf_token', None) + token = session.get('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): abort(403)
370e00e40012b4a99ccb9ec6e67e6a6b45a7f661
common/rc_sensor_cli.py
common/rc_sensor_cli.py
#!/usr/bin/env python import pexpect import os import re path = os.path.dirname(__file__) class RcSensor(object): def __init__(self, gpio, cycles=200, discharge_delay=10): if gpio is None: raise ValueError("Must supply gpio value") self.gpio = gpio self.cycles = cycles ...
#!/usr/bin/env python import pexpect import os import re path = os.path.dirname(__file__) class RcSensor(object): def __init__(self, gpio, cycles=200, discharge_delay=10): if gpio is None: raise ValueError("Must supply gpio value") self.gpio = gpio self.cycles = cycles ...
Increase timeout on RC sensor readings
Increase timeout on RC sensor readings
Python
mit
mecworks/garden_pi,mecworks/garden_pi,mecworks/garden_pi,mecworks/garden_pi
--- +++ @@ -24,7 +24,7 @@ :return: int """ - m = self.rcsense_re.match(pexpect.run(self.rcsensor_cmd, timeout=150)) + m = self.rcsense_re.match(pexpect.run(self.rcsensor_cmd, timeout=180)) count = int(m.groups()[0]) return count
316d9557002c54c5dd03f2a740367946b997d06a
src/foremast/utils/generate_encoded_user_data.py
src/foremast/utils/generate_encoded_user_data.py
"""Generate base64 encoded User Data.""" import base64 from ..utils import get_template def generate_encoded_user_data(env='dev', region='us-east-1', app_name='', group_name=''): r"""Generate base64 encoded User Data. ...
"""Generate base64 encoded User Data.""" import base64 from .get_template import get_template def generate_encoded_user_data(env='dev', region='us-east-1', app_name='', group_name=''): r"""Generate base64 encoded User Da...
Use new relative import within directory
fix: Use new relative import within directory See also: PSOBAT-1197
Python
apache-2.0
gogoair/foremast,gogoair/foremast
--- +++ @@ -1,7 +1,7 @@ """Generate base64 encoded User Data.""" import base64 -from ..utils import get_template +from .get_template import get_template def generate_encoded_user_data(env='dev',
76551f7a05506a872ec6535eb3263710650ea8ce
glue/core/data_factories/__init__.py
glue/core/data_factories/__init__.py
from .helpers import * from .gridded import * from .pandas import * from .excel import * from .image import * from .dendrogram import * from .tables import *
from .helpers import * from .gridded import * from .pandas import * from .excel import * from .image import * from .tables import * from .dendrogram import *
Order of import matters for disambiguation, but this should be fixed later to avoid this.
Order of import matters for disambiguation, but this should be fixed later to avoid this.
Python
bsd-3-clause
saimn/glue,stscieisenhamer/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue
--- +++ @@ -3,5 +3,5 @@ from .pandas import * from .excel import * from .image import * +from .tables import * from .dendrogram import * -from .tables import *
21a7e7557b8e02ef448bcc46a63e983f48cafe38
tests/test_endpoint.py
tests/test_endpoint.py
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'...
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'...
Test Endpoint.endpoints has all endpoints
Test Endpoint.endpoints has all endpoints
Python
mit
acuros/noopy
--- +++ @@ -20,4 +20,6 @@ from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints - assert set(endpoints.keys()) == {('/foo', methods.GET)} + foo_endpoint = Endpoint('/foo', methods.GET) + assert set(endpoints.keys()) == {foo_endpoint} + assert endpoints[foo_endpoint] == sample_view
6130d6d20992dff449696094790a4177302aae9a
tests/unit/conftest.py
tests/unit/conftest.py
from random import randint import pytest import dataactcore.config from dataactcore.scripts.databaseSetup import ( createDatabase, dropDatabase, runMigrations) from dataactvalidator.interfaces.interfaceHolder import InterfaceHolder @pytest.yield_fixture(scope='module') def database(): """Sets up a clean dat...
from random import randint import pytest import dataactcore.config from dataactcore.scripts.databaseSetup import ( createDatabase, dropDatabase, runMigrations) from dataactvalidator.interfaces.interfaceHolder import InterfaceHolder @pytest.yield_fixture(scope='session') def database(): """Sets up a clean da...
Set up the database once for all unittests
Set up the database once for all unittests Resolves an error with a static pointer to a dead database and speeds up tests
Python
cc0-1.0
chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend
--- +++ @@ -8,7 +8,7 @@ from dataactvalidator.interfaces.interfaceHolder import InterfaceHolder -@pytest.yield_fixture(scope='module') +@pytest.yield_fixture(scope='session') def database(): """Sets up a clean database, yielding a relevant interface holder""" rand_id = str(randint(1, 9999))
b203f5ebbec108da7abffc3c5ef3a8a2d0334837
planet_alignment/app/app_factory.py
planet_alignment/app/app_factory.py
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunc...
""" .. module:: app_factory :platform: linux :synopsis: The class factory to create the application App. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface impo...
Add doc synopsis for the app factory.
Add doc synopsis for the app factory.
Python
mit
paulfanelli/planet_alignment
--- +++ @@ -1,7 +1,7 @@ """ .. module:: app_factory :platform: linux - :synopsis: + :synopsis: The class factory to create the application App. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com>
1e001eb11938bd5c613e655f86943167cd945d50
local_sync_client.py
local_sync_client.py
# -*- coding: utf-8 -*- import os class LocalSyncClient(object): def __init__(self, local_dir): self.local_dir = local_dir def get_object_timestamp(self, key): object_path = os.path.join(self.local_dir, key) if os.path.exists(object_path): return os.stat(object_path).st_m...
# -*- coding: utf-8 -*- import os class LocalSyncClient(object): def __init__(self, local_dir): self.local_dir = local_dir def get_object_timestamp(self, key): object_path = os.path.join(self.local_dir, key) if os.path.exists(object_path): return os.stat(object_path).st_m...
Fix bug which caused put_object in LocalSyncClient to fail on create
Fix bug which caused put_object in LocalSyncClient to fail on create
Python
mit
MichaelAquilina/s3backup,MichaelAquilina/s3backup
--- +++ @@ -27,10 +27,16 @@ def put_object(self, key, fp, timestamp): object_path = os.path.join(self.local_dir, key) - object_stat = os.stat(object_path) + + object_stat = None + if os.path.exists(object_path): + object_stat = os.stat(object_path) + with open(...
8c2ebccac0f633b3d2198a6a9d477ac4b8a620df
koztumize/application.py
koztumize/application.py
"""Declare the Koztumize application using Pynuts.""" import ldap from pynuts import Pynuts class Koztumize(Pynuts): """The class which open the ldap.""" @property def ldap(self): """Open the ldap.""" if 'LDAP' not in self.config: # pragma: no cover self.config['LDAP'] = ldap...
"""Declare the Koztumize application using Pynuts.""" import os import ldap from pynuts import Pynuts class Koztumize(Pynuts): """The class which open the ldap.""" @property def ldap(self): """Open the ldap.""" if 'LDAP' not in self.config: # pragma: no cover self.config['LDA...
Use an environment variable as config file
Use an environment variable as config file
Python
agpl-3.0
Kozea/Koztumize,Kozea/Koztumize,Kozea/Koztumize
--- +++ @@ -1,5 +1,6 @@ """Declare the Koztumize application using Pynuts.""" +import os import ldap from pynuts import Pynuts @@ -14,5 +15,6 @@ return self.config['LDAP'] -app = Koztumize( - __name__, config_file='config/config.cfg') # pylint: disable=C0103 +app = Koztumize( # pylint: disabl...
e08be68c9a998678edbb24620518fad7d02582b6
lib/datasets/__init__.py
lib/datasets/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from .imdb import imdb from .pascal_voc import pascal_voc from . import...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from .imdb import imdb from .pascal_voc import pascal_voc from . import...
Use matlab.exe instead of matlab in Windows
Use matlab.exe instead of matlab in Windows
Python
mit
only4hj/fast-rcnn,only4hj/fast-rcnn,only4hj/fast-rcnn
--- +++ @@ -15,7 +15,9 @@ # We assume your matlab binary is in your path and called `matlab'. # If either is not true, just add it to your path and alias it as matlab, or # you could change this file. -MATLAB = 'matlab' + +#MATLAB = 'matlab' +MATLAB = 'matlab.exe' # http://stackoverflow.com/questions/377017/tes...
83863677227436572be18e76803ee6f2ada24f8a
version.py
version.py
# -*- coding: utf-8 -*- import platform name = "Fourth Evaz" version = (0, 9, 2) source = "https://github.com/shacknetisp/fourthevaz" def versionstr(): return "%d.%d.%d" % (version[0], version[1], version[2]) def pythonversionstr(): return '{t[0]}.{t[1]}.{t[2]}'.format(t=platform.python_version_tuple()) d...
# -*- coding: utf-8 -*- import platform name = "Fourth Evaz" version = (0, 1, 2) source = "https://github.com/shacknetisp/fourthevaz" def versionstr(): return "%d.%d.%d" % (version[0], version[1], version[2]) def pythonversionstr(): return '{t[0]}.{t[1]}.{t[2]}'.format(t=platform.python_version_tuple()) d...
Change 0.9.2 to 0.1.2 (Kind of silly to have 0.9 just 3 weeks after starting...)
Change 0.9.2 to 0.1.2 (Kind of silly to have 0.9 just 3 weeks after starting...)
Python
mit
shacknetisp/fourthevaz,shacknetisp/fourthevaz,shacknetisp/fourthevaz
--- +++ @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import platform name = "Fourth Evaz" -version = (0, 9, 2) +version = (0, 1, 2) source = "https://github.com/shacknetisp/fourthevaz"
f8ccb67ad9775fa1babe79640d4db46027531046
examples/async_step/features/steps/async_dispatch_steps.py
examples/async_step/features/steps/async_dispatch_steps.py
from behave import given, then, step from behave.api.async_step import use_or_create_async_context, AsyncContext from hamcrest import assert_that, equal_to, empty import asyncio @asyncio.coroutine def async_func(param): yield from asyncio.sleep(0.2) return str(param).upper() @given('I dispatch an async-call w...
# -*- coding: UTF-8 -*- # REQUIRES: Python >= 3.5 from behave import given, then, step from behave.api.async_step import use_or_create_async_context, AsyncContext from hamcrest import assert_that, equal_to, empty import asyncio @asyncio.coroutine def async_func(param): yield from asyncio.sleep(0.2) return str(...
Add encoding hint (and which python version is required).
Add encoding hint (and which python version is required).
Python
bsd-2-clause
jenisys/behave,jenisys/behave
--- +++ @@ -1,3 +1,5 @@ +# -*- coding: UTF-8 -*- +# REQUIRES: Python >= 3.5 from behave import given, then, step from behave.api.async_step import use_or_create_async_context, AsyncContext from hamcrest import assert_that, equal_to, empty
1c516e64518597404e3928d445fb3239748a4861
performanceplatform/collector/logging_setup.py
performanceplatform/collector/logging_setup.py
from logstash_formatter import LogstashFormatter import logging import os import pdb import sys import traceback def get_log_file_handler(path): handler = logging.FileHandler(path) handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)s] -> %(message)s")) return handler def get_json_...
from logstash_formatter import LogstashFormatter import logging import os import pdb import sys import traceback def get_log_file_handler(path): handler = logging.FileHandler(path) handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)s] -> %(message)s")) return handler def get_json_...
Add `json_fields` parameter to set_up_logging
Add `json_fields` parameter to set_up_logging This will allow the main function to add extra fields to JSON log messages, for example to pass through command-line arguments. See https://www.pivotaltracker.com/story/show/70748012
Python
mit
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector
--- +++ @@ -13,10 +13,11 @@ return handler -def get_json_log_handler(path, app_name): +def get_json_log_handler(path, app_name, json_fields): handler = logging.FileHandler(path) formatter = LogstashFormatter() formatter.defaults['@tags'] = ['collector', app_name] + formatter.defaults.update...
a102731c88f496b557dedd4024fb9b82801d134a
oauthlib/__init__.py
oauthlib/__init__.py
""" oauthlib ~~~~~~~~ A generic, spec-compliant, thorough implementation of the OAuth request-signing logic. :copyright: (c) 2011 by Idan Gazit. :license: BSD, see LICENSE for details. """ __author__ = 'The OAuthlib Community' __version__ = '2.1.0' import logging try: # Python 2.7+ fro...
""" oauthlib ~~~~~~~~ A generic, spec-compliant, thorough implementation of the OAuth request-signing logic. :copyright: (c) 2011 by Idan Gazit. :license: BSD, see LICENSE for details. """ import logging from logging import NullHandler __author__ = 'The OAuthlib Community' __version__ = '2.1....
Remove Python 2.6 compatibility code.
Remove Python 2.6 compatibility code.
Python
bsd-3-clause
idan/oauthlib,oauthlib/oauthlib
--- +++ @@ -8,18 +8,10 @@ :copyright: (c) 2011 by Idan Gazit. :license: BSD, see LICENSE for details. """ +import logging +from logging import NullHandler __author__ = 'The OAuthlib Community' __version__ = '2.1.0' - -import logging -try: # Python 2.7+ - from logging import NullHandler -except Im...
bbba3cdedaa536e11691275abb60964b5afd2ffe
obuka/__openerp__.py
obuka/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Add depends in our addon
Add depends in our addon
Python
mit
gdamjan/openerp-training
--- +++ @@ -26,7 +26,7 @@ "description": "test test some description", 'website': 'http://damjan.softver.org.mk', 'init_xml': [], - "depends" : [], + "depends" : ['base'], 'update_xml': ['obuka_view.xml'], 'demo_xml': [], 'test': [],
8a7fd251454026baf3cf7a0a1aa0300a0f3772bc
pycanvas/assignment.py
pycanvas/assignment.py
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): # pragma: no cover return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/...
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ ...
Remove no-cover from __str__ method
Remove no-cover from __str__ method
Python
mit
ucfopen/canvasapi,ucfopen/canvasapi,ucfopen/canvasapi
--- +++ @@ -4,7 +4,7 @@ class Assignment(CanvasObject): - def __str__(self): # pragma: no cover + def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self):
75fd199b239c23d7396bd3b5803d3c6007361b5a
test/repsitory_test.py
test/repsitory_test.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2017, Fabian Greif # All Rights Reserved. # # The file is part of the lbuild project and is released under the # 2-clause BSD license. See the file `LICENSE.txt` for the full license # governing this code. import os import io import sys import unittest ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2017, Fabian Greif # All Rights Reserved. # # The file is part of the lbuild project and is released under the # 2-clause BSD license. See the file `LICENSE.txt` for the full license # governing this code. import os import sys import unittest # Hack to ...
Fix repository import test for Python < 3.6
Fix repository import test for Python < 3.6 Check for broader range of exceptions.
Python
bsd-2-clause
dergraaf/library-builder,dergraaf/library-builder
--- +++ @@ -9,7 +9,6 @@ # governing this code. import os -import io import sys import unittest @@ -32,7 +31,7 @@ with self.assertRaises(lbuild.exception.BlobForwardException) as cm: self.parser.parse_repository(self._get_path("invalid_import.lb")) - self.assertEqual(ModuleNotFou...