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 |
|---|---|---|---|---|---|---|---|---|---|---|
e779a66c29ecb389b03357ca2e2ccb88752072b7 | test/selenium/src/lib/constants/ux.py | test/selenium/src/lib/constants/ux.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
MAX_USER_WAIT_SECONDS = 10
MAX_ALERT_WAIT = 1
ELEMENT_MOVING_TIMEOUT = 5
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
MAX_USER_WAIT_SECONDS = 60
MAX_ALERT_WAIT = 1
ELEMENT_MOVING_TIMEOUT = 5
| Increase wait time for element loading from 10s to 1min | Increase wait time for element loading from 10s to 1min
| Python | apache-2.0 | j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,AleksNeStu/... | ---
+++
@@ -3,6 +3,6 @@
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
-MAX_USER_WAIT_SECONDS = 10
+MAX_USER_WAIT_SECONDS = 60
MAX_ALERT_WAIT = 1
ELEMENT_MOVING_TIMEOUT = 5 |
80bbff0511e47fbb3b9ed7774942ef5f9880a9c3 | plugins/Views/WireframeView/WireframeView.py | plugins/Views/WireframeView/WireframeView.py | from Cura.View.View import View
from Cura.View.Renderer import Renderer
from Cura.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
class WireframeView(View):
def __init__(self):
super().__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getR... | from Cura.View.View import View
from Cura.View.Renderer import Renderer
from Cura.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
class WireframeView(View):
def __init__(self):
super().__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getR... | Use the new wireframe mode to render the Wireframe view correctly | Use the new wireframe mode to render the Wireframe view correctly
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -13,5 +13,5 @@
for node in DepthFirstIterator(scene.getRoot()):
if not node.render(renderer):
if node.getMeshData():
- renderer.renderMesh(node.getGlobalTransformation(), node.getMeshData(), Renderer.RenderLines)
+ renderer.render... |
82cc087e5dc39201444e19ce305a44aea8c4b3d1 | nailgun/nailgun/extrasettings.py | nailgun/nailgun/extrasettings.py | import os
import os.path
LOGPATH = "/var/log/nailgun"
LOGFILE = os.path.join(LOGPATH, "nailgun.log")
LOGLEVEL = "DEBUG"
CELERYLOGFILE = os.path.join(LOGPATH, "celery.log")
CELERYLOGLEVEL = "DEBUG"
PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa")
PATH_TO_BOOTSTRAP_SSH_KEY = os.path.join(os.getenv("H... | import os
import os.path
LOGPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
LOGFILE = os.path.join(LOGPATH, "nailgun.log")
LOGLEVEL = "DEBUG"
CELERYLOGFILE = os.path.join(LOGPATH, "celery.log")
CELERYLOGLEVEL = "DEBUG"
PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa")
PATH_TO_B... | Set LOGPATH to nailgun folder by default | Set LOGPATH to nailgun folder by default
| Python | apache-2.0 | dancn/fuel-main-dev,koder-ua/nailgun-fcert,huntxu/fuel-web,SergK/fuel-main,dancn/fuel-main-dev,AnselZhangGit/fuel-main,huntxu/fuel-main,eayunstack/fuel-web,ddepaoli3/fuel-main-dev,nebril/fuel-web,eayunstack/fuel-main,zhaochao/fuel-main,Fiware/ops.Fuel-main-dev,Fiware/ops.Fuel-main-dev,prmtl/fuel-web,prmtl/fuel-web,nebr... | ---
+++
@@ -1,7 +1,7 @@
import os
import os.path
-LOGPATH = "/var/log/nailgun"
+LOGPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
LOGFILE = os.path.join(LOGPATH, "nailgun.log")
LOGLEVEL = "DEBUG"
CELERYLOGFILE = os.path.join(LOGPATH, "celery.log") |
cc3b82a943baf42f78b131d3218ad5eb748a11ce | test_proj/urls.py | test_proj/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'do... | try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),... | Support for Django > 1.4 for test proj | Support for Django > 1.4 for test proj
| Python | mit | husbas/django-admin-tools,husbas/django-admin-tools,husbas/django-admin-tools | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import *
+try:
+ from django.conf.urls import patterns, url, include
+except ImportError: # django < 1.4
+ from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
|
fc3e823b6bf1b5c7de62a55f4b5459bbc0c9a4c3 | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
'''
General-purpose fixtures for vdirsyncer's testsuite.
'''
import logging
import os
import click_log
from hypothesis import HealthCheck, Verbosity, settings
import pytest
@pytest.fixture(autouse=True)
def setup_logging():
click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG)
... | # -*- coding: utf-8 -*-
'''
General-purpose fixtures for vdirsyncer's testsuite.
'''
import logging
import os
import click_log
from hypothesis import HealthCheck, Verbosity, settings
import pytest
@pytest.fixture(autouse=True)
def setup_logging():
click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG)
... | Use os.environ instead of getenv | Use os.environ instead of getenv
None.lower() fails too, but KeyError() is a nicer errormessage
| Python | mit | hobarrera/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,hobarrera/vdirsyncer | ---
+++
@@ -41,7 +41,7 @@
derandomize=True,
))
-if os.getenv('DETERMINISTIC_TESTS').lower() == 'true':
+if os.environ['DETERMINISTIC_TESTS'].lower() == 'true':
settings.load_profile("deterministic")
-elif os.getenv('CI').lower() == 'true':
+elif os.environ['CI'].lower() == 'true':
settings.load_prof... |
0ba616bbd037a1c84f20221a95a623d853da9db9 | garfield/sims/tests.py | garfield/sims/tests.py | from mock import patch
from sms.tests.test_sms import GarfieldTwilioTestCase
from sms.tests.test_sms import GarfieldTwilioTestClient
class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase):
@patch('sms.tasks.save_sms_message.apply_async')
def test_sim_receive_sms(self, mock_save_sms_message):
res... | from django.test import override_settings
from mock import patch
from sms.tests.test_sms import GarfieldTwilioTestCase
from sms.tests.test_sms import GarfieldTwilioTestClient
@override_settings(TWILIO_PHONE_NUMBER="+15558675309")
class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase):
@patch('sms.tasks.sav... | Add override settings for CI without local settings. | Add override settings for CI without local settings.
| Python | mit | RobSpectre/garfield,RobSpectre/garfield | ---
+++
@@ -1,9 +1,12 @@
+from django.test import override_settings
+
from mock import patch
from sms.tests.test_sms import GarfieldTwilioTestCase
from sms.tests.test_sms import GarfieldTwilioTestClient
+@override_settings(TWILIO_PHONE_NUMBER="+15558675309")
class GarfieldTestSimSmsCaseNewJohn(GarfieldTwili... |
f5faf9c90b2671f7d09e1a4f21c036737bd039ef | echo/tests/test_response.py | echo/tests/test_response.py | import json
from echo.response import EchoResponse, EchoSimplePlainTextResponse
from echo.tests import BaseEchoTestCase
class TestEchoSimplePlainTextResponse(BaseEchoTestCase):
def test_populates_text_in_response(self):
"""The Plain text response should populate the outputSpeech"""
expected = "Th... | import json
from echo.response import EchoResponse, EchoSimplePlainTextResponse
from echo.tests import BaseEchoTestCase
class TestEchoSimplePlainTextResponse(BaseEchoTestCase):
def test_populates_text_in_response(self):
"""The Plain text response should populate the outputSpeech"""
expected = "Th... | Fix response tests in py3 | Fix response tests in py3
| Python | mit | bunchesofdonald/django-echo | ---
+++
@@ -9,7 +9,7 @@
"""The Plain text response should populate the outputSpeech"""
expected = "This is the text"
response = EchoSimplePlainTextResponse(expected)
- data = json.loads(response.content)
+ data = json.loads(response.content.decode())
assert data['re... |
32388a96b848629bf8f4b7d7ea832fca8c3dccd9 | fabfile/templates/collector_haproxy.py | fabfile/templates/collector_haproxy.py | import string
template = string.Template("""#contrail-collector-marker-start
listen contrail-collector-stats :5938
mode http
stats enable
stats uri /
stats auth $__contrail_hap_user__:$__contrail_hap_passwd__
frontend contrail-analytics-api *:8081
default_backend contrail-analytics-api
backend co... | import string
template = string.Template("""#contrail-collector-marker-start
listen contrail-collector-stats :5938
mode http
stats enable
stats uri /
stats auth $__contrail_hap_user__:$__contrail_hap_passwd__
frontend contrail-analytics-api *:8081
default_backend contrail-analytics-api
backend co... | Remove tcp-check connect option for redis on haproxy | Remove tcp-check connect option for redis on haproxy
tcp-check connect option for redis on haproxy.cfg causes the client
connections in the redis-server to grow continuously and reaches the max
limit resulting in connection failure/response error for requests from
collector and other analytics services to redis.
Chan... | Python | apache-2.0 | Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils | ---
+++
@@ -12,10 +12,8 @@
backend contrail-analytics-api
option nolinger
+ timeout server 3m
balance roundrobin
- option tcp-check
- tcp-check connect port 6379
- default-server error-limit 1 on-error mark-down
$__contrail_analytics_api_backend_servers__
#contrail-collector-marker-en... |
8c1ab6a774b380fdbb571818e68b375e25909bff | pdf_parser/filters/filters/lzw_and_flate.py | pdf_parser/filters/filters/lzw_and_flate.py | """
Compression filters
"""
from ..stream_filter import StreamFilter
from io import BytesIO
import zlib
class LZWDecode(StreamFilter):
"""LZW compression"""
filter_name = 'LZWDecode'
EOD = None
@staticmethod
def decode_data(data, **kwargs):
"""Based on code from http://rosettacod... | """
Compression filters
"""
from ..stream_filter import StreamFilter
from io import BytesIO
import zlib
class LZWDecode(StreamFilter):
"""LZW compression"""
filter_name = 'LZWDecode'
EOD = None
@staticmethod
def decode_data(data, **kwargs):
"""Based on code from http://rosettacod... | Add encode method to flat filter | Add encode method to flat filter
| Python | mit | ajmarks/gymnast,ajmarks/gymnast | ---
+++
@@ -47,7 +47,11 @@
EOD = None
@staticmethod
- def decode_data(data, CloseTarget=False, Predictor=None,
- Columns=None, BitsPerComponent=None):
+ def decode_data(data, **kwargs):
#TODO: use these parameters
return zlib.decompress(data)
+
+ @stat... |
d792f82ea6e59b0e998d023fdbc24b0829e2d0e7 | pythran/tests/openmp/omp_parallel_copyin.py | pythran/tests/openmp/omp_parallel_copyin.py | #threadprivate supprimé, est ce que c'est grave?
def omp_parallel_copyin():
sum = 0
sum1 = 7
num_threads = 0
if 'omp parallel copyin(sum1) private(i)':
'omp for'
for i in xrange(1, 1000):
sum1 += i
if 'omp critical':
sum += sum1
num_threads +=... | #unittest.skip threadprivate not supported
def omp_parallel_copyin():
sum = 0
sum1 = 7
num_threads = 0
if 'omp parallel copyin(sum1) private(i)':
'omp for'
for i in xrange(1, 1000):
sum1 += i
if 'omp critical':
sum += sum1
num_threads += 1
... | Disable an OpenMP test that requires threadprivate | Disable an OpenMP test that requires threadprivate
| Python | bsd-3-clause | pbrunet/pythran,artas360/pythran,pbrunet/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,hainm/pythran,pombredanne/pythran,artas360/pythran,serge-sans-paille/pythran,pombredanne/pythran,pbrunet/pythran | ---
+++
@@ -1,4 +1,4 @@
-#threadprivate supprimé, est ce que c'est grave?
+#unittest.skip threadprivate not supported
def omp_parallel_copyin():
sum = 0
sum1 = 7 |
83908d3d8d3de0db5f8af26155137bf382afa24a | lettuce_webdriver/django.py | lettuce_webdriver/django.py | """
Django-specific extensions
"""
def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s' % socket.gethostname()
if server.port is not 80:
base_url += ':%d' % server.port
return urlparse.urljoin(base_url, url)
@step(r'I visit site page "([^"]*)"')
def visit_pag... | """
Django-specific extensions
"""
import socket
import urlparse
from lettuce import step
from lettuce.django import server
# make sure the steps are loaded
import lettuce_webdriver.webdriver # pylint:disable=unused-import
def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s'... | Fix bugs with lettuce-webdriver Django steps | Fix bugs with lettuce-webdriver Django steps
| Python | mit | infoxchange/lettuce_webdriver,infoxchange/lettuce_webdriver,aloetesting/aloe_webdriver,infoxchange/aloe_webdriver,koterpillar/aloe_webdriver,macndesign/lettuce_webdriver,ponsfrilus/lettuce_webdriver,aloetesting/aloe_webdriver,ponsfrilus/lettuce_webdriver,bbangert/lettuce_webdriver,aloetesting/aloe_webdriver,bbangert/le... | ---
+++
@@ -1,6 +1,15 @@
"""
Django-specific extensions
"""
+
+import socket
+import urlparse
+
+from lettuce import step
+from lettuce.django import server
+
+# make sure the steps are loaded
+import lettuce_webdriver.webdriver # pylint:disable=unused-import
def site_url(url):
@@ -16,9 +25,9 @@
@step(r... |
39ea336297b0479abb29a70f831b2a02a01fcc18 | portas/portas/utils.py | portas/portas/utils.py | import contextlib
import functools
import logging
import sys
import webob.exc
LOG = logging.getLogger(__name__)
def http_success_code(code):
"""Attaches response code to a method.
This decorator associates a response code with a method. Note
that the function attributes are directly manipulated; the m... | import logging
LOG = logging.getLogger(__name__)
# def verify_tenant(func):
# @functools.wraps(func)
# def __inner(self, req, tenant_id, *args, **kwargs):
# if hasattr(req, 'context') and tenant_id != req.context.tenant:
# LOG.info('User is not authorized to access this tenant.')
# ... | Remove unnecessary blocks of code | Remove unnecessary blocks of code
| Python | apache-2.0 | Bloomie/murano-agent,openstack/python-muranoclient,ativelkov/murano-api,sajuptpm/murano,NeCTAR-RC/murano,satish-avninetworks/murano,satish-avninetworks/murano,openstack/murano,openstack/murano-agent,openstack/murano-agent,telefonicaid/murano,satish-avninetworks/murano,DavidPurcell/murano_temp,openstack/murano-agent,ser... | ---
+++
@@ -1,66 +1,24 @@
-import contextlib
-import functools
import logging
-import sys
-
-import webob.exc
LOG = logging.getLogger(__name__)
-def http_success_code(code):
- """Attaches response code to a method.
+# def verify_tenant(func):
+# @functools.wraps(func)
+# def __inner(self, req, tena... |
6eff6622457b619f36404957968f30e3b1944362 | openfisca_country_template/__init__.py | openfisca_country_template/__init__.py | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be chan... | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from openfisca_country_template import entities
from openfisca_country_template.situation_examples import couple
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits fr... | Define which examples to use in OpenAPI | Define which examples to use in OpenAPI
| Python | agpl-3.0 | openfisca/country-template,openfisca/country-template | ---
+++
@@ -4,7 +4,8 @@
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
-from . import entities
+from openfisca_country_template import entities
+from openfisca_country_template.situation_examples import couple
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -23,3 +24,10 @@
... |
edd096abfa3c304b49fe94155a64fc2371a3084a | py/linhomy/matrices.py | py/linhomy/matrices.py | '''
>>> IC_FLAG[2]
array([[1, 3],
[1, 4]])
>>> IC_FLAG[3]
array([[1, 4, 6],
[1, 5, 8],
[1, 6, 9]])
'''
# For Python2 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__metaclass__... | '''
>>> FLAG_from_IC[2]
array([[1, 1],
[3, 4]])
The flag vector of ICC is [1, 6, 9].
>>> numpy.dot(FLAG_from_IC[3], [0, 0, 1])
array([1, 6, 9])
>>> FLAG_from_IC[3]
array([[1, 1, 1],
[4, 5, 6],
[6, 8, 9]])
'''
# For Python2 compatibility
from __future__ import absolute_import
from __future__ i... | Rewrite to replace IC_FLAG by FLAG_from_IC. | Rewrite to replace IC_FLAG by FLAG_from_IC.
| Python | mit | jfine2358/py-linhomy | ---
+++
@@ -1,15 +1,18 @@
'''
->>> IC_FLAG[2]
-array([[1, 3],
- [1, 4]])
+>>> FLAG_from_IC[2]
+array([[1, 1],
+ [3, 4]])
+The flag vector of ICC is [1, 6, 9].
+>>> numpy.dot(FLAG_from_IC[3], [0, 0, 1])
+array([1, 6, 9])
->>> IC_FLAG[3]
-array([[1, 4, 6],
- [1, 5, 8],
- [1, 6, 9]])
+>>... |
3e3e4b88692922fe3182e4db1db60e8a60ced8e4 | apps/user/admin.py | apps/user/admin.py | # -*- coding: utf-8 -*-
#
# defivelo-intranet -- Outil métier pour la gestion du Défi Vélo
# Copyright (C) 2015 Didier Raboud <me+defivelo@odyx.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software ... | # -*- coding: utf-8 -*-
#
# defivelo-intranet -- Outil métier pour la gestion du Défi Vélo
# Copyright (C) 2015 Didier Raboud <me+defivelo@odyx.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software ... | Drop the hurtinq username patching of username that also affects edition | Drop the hurtinq username patching of username that also affects edition
| Python | agpl-3.0 | defivelo/db,defivelo/db,defivelo/db | ---
+++
@@ -26,25 +26,3 @@
admin.site.register(UserProfile)
admin.site.register(UserManagedState)
-
-# Monkey-patch the get_username, mostly for the admin
-
-
-def get_user_model_safe():
- """
- Get the user model before it is loaded, but after the app registry
- is populated
- """
- app_label, mod... |
8c64757759e69f7aff84065db8da604dd43faded | pyrsss/usarray/info.py | pyrsss/usarray/info.py | import pandas as PD
INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt'
"""Full URL link to USArray MT site information text file."""
HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT'
"""Header line of data file."""
def get_info_map(info_link=INFO_LIN... | import pandas as PD
INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt'
"""Full URL link to USArray MT site information text file."""
HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT'
"""Header line of data file."""
def get_info_map(info_link=INFO_LIN... | Change of function name due to deprecation. | Change of function name due to deprecation.
| Python | mit | butala/pyrsss | ---
+++
@@ -15,21 +15,21 @@
*info_link*, a link to a tab delineated text file containing
information for each USArray MT site.
"""
- df = PD.read_table(info_link,
- sep='\t',
- skiprows=1,
- names=['vnet',
- ... |
fba4801ce64853db37af01b08e1533719425118d | repovisor/repovisor.py | repovisor/repovisor.py | from git import Repo
from git.exc import InvalidGitRepositoryError
import os
def reposearch(*folders):
for folder in folders:
for dir, subdirs, files in os.walk(folder):
try:
yield dict(vcs='git', pntr=Repo(dir), folder=dir)
subdirs[:] = []
contin... | from git import Repo
from git.exc import InvalidGitRepositoryError
import os
import warnings
vcs_statechecker = {'git': None}
def reposearch(*folders):
for folder in folders:
for dir, subdirs, files in os.walk(folder):
try:
yield dict(vcs='git', pntr=Repo(dir), folder=dir)
... | Add repocheck looper, git checker | Add repocheck looper, git checker
| Python | bsd-3-clause | gjcooper/repovisor,gjcooper/repovisor | ---
+++
@@ -1,6 +1,10 @@
from git import Repo
from git.exc import InvalidGitRepositoryError
import os
+import warnings
+
+vcs_statechecker = {'git': None}
+
def reposearch(*folders):
for folder in folders:
@@ -12,3 +16,37 @@
except InvalidGitRepositoryError:
pass
+
+def repo... |
256c0f9cfd1ca0c5982ac9ab001c5ced84a02c32 | src/bots/inputs/malwaredomains/feed.py | src/bots/inputs/malwaredomains/feed.py | #!/usr/bin/python
import sys
from lib.bot import *
from lib.utils import *
from lib.event import *
from lib.cache import *
import time
class MalwareDomainsBot(Bot):
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 1638... | #!/usr/bin/python
import sys
from lib.bot import *
from lib.utils import *
from lib.event import *
from lib.cache import *
import time
class MalwareDomainsBot(Bot):
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 1638... | Comment added to create generic decode method | Comment added to create generic decode method
| Python | agpl-3.0 | aaronkaplan/intelmq-old,s4n7h0/intelmq,Phantasus/intelmq,aaronkaplan/intelmq-old,aaronkaplan/intelmq-old | ---
+++
@@ -12,8 +12,9 @@
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 16384)
- rep_ascii = report.decode('ascii', 'ignore')
-# print report
+
+ rep_ascii = report.decode('ascii','ignore')
+# [FIXME] ... |
31ad44a9ea518a6ced7d1bd938cec1ee215fefac | pyexp/string_permu_check.py | pyexp/string_permu_check.py | '''Module to solve the algoritm question:
Given a string S, how to count how many permutations
of S is in a longer string L, assuming, of course, that
permutations of S must be in contagious blocks in L.
I will solve it in O(len(L)) time.
For demonstration purpose, let's assume the characters
are ASCII lowercase lette... | '''Module to solve the algoritm question:
Given a string S, how to count how many permutations
of S is in a longer string L, assuming, of course, that
permutations of S must be in contagious blocks in L.
I will solve it in O(len(L)) time.
For demonstration purpose, let's assume the characters
are ASCII lowercase lette... | Add documentation for the hash function. | Add documentation for the hash function.
| Python | mit | nguyentu1602/pyexp | ---
+++
@@ -25,6 +25,11 @@
return chr(num + SHIFT)
def string_permu_hash(in_str):
+ '''hash a string based on the numbers of each char
+ in the string. So 2 permutations of a string give
+ the same hash. You can decompose this hash to get
+ back the number of each char.
+ '''
base = len(in... |
57376590aec0db20a8046deaee86d035c8963a40 | readthedocs/builds/admin.py | readthedocs/builds/admin.py | """Django admin interface for `~builds.models.Build` and related models.
"""
from django.contrib import admin
from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult
from guardian.admin import GuardedModelAdmin
class BuildCommandResultInline(admin.TabularInline):
model = BuildComm... | """Django admin interface for `~builds.models.Build` and related models.
"""
from django.contrib import admin
from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult
from guardian.admin import GuardedModelAdmin
class BuildCommandResultInline(admin.TabularInline):
model = BuildComm... | Include output in result inline | Include output in result inline
| Python | mit | tddv/readthedocs.org,espdev/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,rtfd/readthedocs.org,espdev/readthedocs.org,david... | ---
+++
@@ -9,11 +9,11 @@
class BuildCommandResultInline(admin.TabularInline):
model = BuildCommandResult
- fields = ('command', 'exit_code')
+ fields = ('command', 'exit_code', 'output')
class BuildAdmin(admin.ModelAdmin):
- fields = ('project', 'version', 'type', 'error', 'state', 'success', '... |
47269f733427fef34e4f43c2652eda79aa3e5e0d | test/test_util/test_StopWatch.py | test/test_util/test_StopWatch.py | # -*- encoding: utf-8 -*-
"""Created on Dec 16, 2014.
@author: Katharina Eggensperger
@projekt: AutoML2015
"""
from __future__ import print_function
import time
import unittest
from autosklearn.util import StopWatch
class Test(unittest.TestCase):
_multiprocess_can_split_ = True
def test_stopwatch_overhea... | # -*- encoding: utf-8 -*-
"""Created on Dec 16, 2014.
@author: Katharina Eggensperger
@projekt: AutoML2015
"""
from __future__ import print_function
import time
import unittest
import unittest.mock
from autosklearn.util import StopWatch
class Test(unittest.TestCase):
_multiprocess_can_split_ = True
def t... | TEST potentially fix brittle stopwatch test | TEST potentially fix brittle stopwatch test
| Python | bsd-3-clause | automl/auto-sklearn,automl/auto-sklearn | ---
+++
@@ -9,6 +9,7 @@
from __future__ import print_function
import time
import unittest
+import unittest.mock
from autosklearn.util import StopWatch
@@ -17,29 +18,24 @@
_multiprocess_can_split_ = True
def test_stopwatch_overhead(self):
- # CPU overhead
- start = time.clock()
+
+ ... |
2a3a5fba536877c0ba735244a986e49605ce3fc0 | tests/test_schematics_adapter.py | tests/test_schematics_adapter.py | from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
def test_object_conversion():
adapter = SchematicsSerializerAdapter(... | import pytest
from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
@pytest.fixture
def adapter():
return SchematicsSerial... | Convert the adapter into a pytest fixture | Convert the adapter into a pytest fixture
| Python | mit | kalasjocke/hyp | ---
+++
@@ -1,3 +1,4 @@
+import pytest
from schematics.models import Model
from schematics.types import IntType
@@ -13,11 +14,15 @@
id = IntType()
-def test_object_conversion():
- adapter = SchematicsSerializerAdapter(Simple)
+@pytest.fixture
+def adapter():
+ return SchematicsSerializerAdapter(Sim... |
a8c7a6d6cd87f057fbd03c41cec41dba35e6bdf6 | unittesting/test_color_scheme.py | unittesting/test_color_scheme.py | import sublime
from sublime_plugin import ApplicationCommand
from .mixin import UnitTestingMixin
from .const import DONE_MESSAGE
try:
from ColorSchemeUnit.lib.runner import ColorSchemeUnit
except Exception:
print('ColorSchemeUnit runner could not be imported')
class UnitTestingColorSchemeCommand(ApplicationC... | import sublime
from sublime_plugin import ApplicationCommand
from .mixin import UnitTestingMixin
from .const import DONE_MESSAGE
try:
from ColorSchemeUnit.lib.runner import ColorSchemeUnit
except Exception:
print('ColorSchemeUnit runner could not be imported')
class UnitTestingColorSchemeCommand(ApplicationC... | Use ColorSchemeunit new run with package API | Use ColorSchemeunit new run with package API
Re: https://github.com/gerardroche/sublime-color-scheme-unit/issues/18
The new API allows to run with package name so Unittesting doesn't need
to open any files before running the tests.
I also added an async parameter which allows to run the tests in non
async mode and g... | Python | mit | randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting | ---
+++
@@ -19,8 +19,6 @@
settings = self.load_unittesting_settings(package, **kargs)
stream = self.load_stream(package, settings["output"])
- # Make sure at least one file from the
- # package opened for ColorSchemeUnit.
tests = sublime.find_resources("color_scheme_test*")
... |
1667e4c28d969af615d028a4b828cc2c868957bc | tests/git_code_debt/list_metrics_test.py | tests/git_code_debt/list_metrics_test.py |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.mark.integration
def test_list_metricssmoke():
# This test is just to make sure... |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.yield_fixture
def print_mock():
with mock.patch.object(__builtin__, 'print', au... | Add integration test for --color never. | Add integration test for --color never.
| Python | mit | Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt | ---
+++
@@ -10,12 +10,25 @@
from git_code_debt.list_metrics import NORMAL
+@pytest.yield_fixture
+def print_mock():
+ with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
+ yield print_mock
+
+
@pytest.mark.integration
-def test_list_metricssmoke():
+def test_list_metrics_smoke(p... |
14be519ba4bb09957865f1810c88c02f6b359c48 | tests/utilities/test_customtreeview.py | tests/utilities/test_customtreeview.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.utilities.customtreeview import CustomizedTreeView
class CustomTreeViewTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
def tearDown(self):
s... | from __future__ import absolute_import, print_function
import pytest
from addie.utilities.customtreeview import CustomizedTreeView
@pytest.fixture
def custom_tree_view(qtbot):
return CustomizedTreeView(None)
def test_get_selected_items(qtbot, custom_tree_view):
"""Test get_selected_items in tree of Customiz... | Refactor CustomTreeView test to use pytest-qt | Refactor CustomTreeView test to use pytest-qt
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR | ---
+++
@@ -1,19 +1,15 @@
from __future__ import absolute_import, print_function
-import unittest
-from qtpy.QtWidgets import QApplication
+import pytest
from addie.utilities.customtreeview import CustomizedTreeView
-class CustomTreeViewTests(unittest.TestCase):
- def setUp(self):
- self.main_window =... |
f3763c417d745463361b054fd4ffa0ddf35833eb | src/server/Universe.py | src/server/Universe.py | class Universe:
def __init__(self, height=100000000, width=100000000):
self.entities = []
self.height = height
self.width = width
self.teams = []
self.state = []
def add(self, entity):
self.entities.append(entity)
def remove(self, entity):
self.entities.remove(entity)
... | class Universe:
def __init__(self, height=100000000, width=100000000):
self.entities = []
self.height = height
self.width = width
self.teams = []
self.state = []
self.maxID = 0
def add(self, entity):
maxID += 1
entity.id = maxID
self.entities.append(entity)
def remove... | Add ID to Entity upon creation | Add ID to Entity upon creation
| Python | mit | cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim | ---
+++
@@ -5,8 +5,11 @@
self.width = width
self.teams = []
self.state = []
+ self.maxID = 0
def add(self, entity):
+ maxID += 1
+ entity.id = maxID
self.entities.append(entity)
def remove(self, entity): |
79d868ed68148b1e8f7c046b1ae9bb4b5a413c99 | base/components/accounts/admin.py | base/components/accounts/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
... | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form,... | Move the super() up on ContributorMixin. | Move the super() up on ContributorMixin.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | ---
+++
@@ -7,11 +7,11 @@
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
+ super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
... |
1da9b6538294744aa1d68ec6f48bebbbf5d714bb | bot/action/standard/admin/fail.py | bot/action/standard/admin/fail.py | from bot.action.core.action import Action
class FailAction(Action):
def process(self, event):
raise NotARealError("simulated error")
class NotARealError(Exception):
pass
| from bot.action.core.action import Action
class FailAction(Action):
def process(self, event):
if event.command_args == "fatal":
raise NotARealFatalError("simulated fatal error")
raise NotARealError("simulated error")
class NotARealError(Exception):
pass
class NotARealFatalError... | Allow to simulate fatal errors | Allow to simulate fatal errors
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -3,8 +3,14 @@
class FailAction(Action):
def process(self, event):
+ if event.command_args == "fatal":
+ raise NotARealFatalError("simulated fatal error")
raise NotARealError("simulated error")
class NotARealError(Exception):
pass
+
+
+class NotARealFatalError(Ba... |
f0d629ae8b4568b2aceaf38779c8b07832e860b0 | teamspeak_web_utils.py | teamspeak_web_utils.py | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | Clean string returned by website | Clean string returned by website
=> remove newline-characters and strip
| Python | mit | Thor77/TeamspeakIRC | ---
+++
@@ -21,4 +21,8 @@
def search(search_string):
return soup.find_all(text=re.compile(search_string))[0].parent.\
find(class_='version').text
- return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
+
+ def clean(s):
+ return s.replace('\n', '').strip()
+ retu... |
75eb6f93fff381953788a98aac8ee61bbf36c900 | apps/storybase/templatetags/verbatim.py | apps/storybase/templatetags/verbatim.py | """
Handlebars templates use constructs like:
{{if condition}} print something{{/if}}
This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.
Wrap {% verbatim %} and {% endverbatim %} around those
blocks of Handlebars templates and this will try its best
to output ... | """
Handlebars templates use constructs like:
{{if condition}} print something{{/if}}
This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.
Wrap {% verbatim %} and {% endverbatim %} around those
blocks of Handlebars templates and this will try its best
to output ... | Move register outside of guard | Move register outside of guard
Even if we don't load the ``verbatim`` tag backbport, the module
still needs to have a ``register`` variable.
Addresses #660
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase | ---
+++
@@ -13,10 +13,10 @@
from django import template
+register = template.Library()
+
# For Django >= 1.5, use the default verbatim tag implementation
if not hasattr(template.defaulttags, 'verbatim'):
- register = template.Library()
-
class VerbatimNode(template.Node):
def __init__(self, ... |
d7b532e83b30e429a9c87b52799c30dda6c4628c | plasmapy/physics/tests/test_dimensionless.py | plasmapy/physics/tests/test_dimensionless.py | from plasmapy.physics.dimensionless import (beta)
import astropy.units as u
B = 1.0 * u.T
n_i = 5e19 * u.m ** -3
T_e = 1e6 * u.K
def test_beta():
# Check that beta is dimensionless
float(beta(T_e, n_i, B))
| from plasmapy.physics.dimensionless import (beta)
import astropy.units as u
import numpy as np
B = 1.0 * u.T
n = 5e19 * u.m ** -3
T = 1e6 * u.K
def test_beta_dimensionless():
# Check that beta is dimensionless
float(beta(T, n, B))
def quantum_theta_dimensionless():
# Check that quantum theta is dimens... | Add test for beta passing through nans | Add test for beta passing through nans
| Python | bsd-3-clause | StanczakDominik/PlasmaPy | ---
+++
@@ -1,12 +1,27 @@
from plasmapy.physics.dimensionless import (beta)
import astropy.units as u
+import numpy as np
B = 1.0 * u.T
-n_i = 5e19 * u.m ** -3
-T_e = 1e6 * u.K
+n = 5e19 * u.m ** -3
+T = 1e6 * u.K
-def test_beta():
+def test_beta_dimensionless():
# Check that beta is dimensionless
- ... |
4bfa6627b14c3e00e32b10a2806f02d4fafd6509 | chipy_org/libs/social_auth_pipelines.py | chipy_org/libs/social_auth_pipelines.py | from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with this email already exists. If they do, don't cr... | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | Fix false positive for the social login | Fix false positive for the social login
| Python | mit | brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.or... | ---
+++
@@ -1,3 +1,4 @@
+from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
@@ -6,12 +7,17 @@
def associate_by_email... |
02095500794565fc84aee8272bfece1b39bc270f | examples/example_architecture_upload.py | examples/example_architecture_upload.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localhost:8080"
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localhost:8080"
... | Update example for architecture upload | Update example for architecture upload
| Python | apache-2.0 | cqse/teamscale-client-python | ---
+++
@@ -12,11 +12,11 @@
TEAMSCALE_URL = "http://localhost:8080"
USERNAME = "admin"
-PASSWORD = "admin"
+PASSWORD = "F0VzQ_2Q2wqGmBFBrI6EIVWVK4QxR55o"
PROJECT_NAME = "test"
if __name__ == '__main__':
client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME)
- client.upload_archi... |
f9c98ff2c5166f113918f9dc575abcad781bce01 | tests/test-vext-api.py | tests/test-vext-api.py | import unittest
from vext.env import findsyspy, in_venv
class TestVextAPI(unittest.TestCase):
def test_findsyspy(self):
# Stub test, checks no exceptions are thrown.
findsyspy()
def test_invenv(self):
# Stub test, checks no exceptions are thrown.
in_venv()
if __name__ == "_... | import os
import unittest
from vext.env import findsyspy, in_venv
class TestVextAPI(unittest.TestCase):
def test_findsyspy(self):
# Stub test, checks no exceptions are thrown.
findsyspy()
def test_invenv(self):
# Stub test, checks no exceptions are thrown.
# TODO, fake runni... | Revert trying to test in virtualenv for now. | Revert trying to test in virtualenv for now.
| Python | mit | stuaxo/vext | ---
+++
@@ -1,3 +1,4 @@
+import os
import unittest
from vext.env import findsyspy, in_venv
@@ -10,6 +11,8 @@
def test_invenv(self):
# Stub test, checks no exceptions are thrown.
+
+ # TODO, fake running inside and outside an virtualenv and actually check the return value
in_venv()
... |
dfa144f02ac43012ea51f24b9752eabe8a1ef9b5 | opps/images/templatetags/images_tags.py | opps/images/templatetags/images_tags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | Fix rules x,y on image_obj Coordinates for manual cropping. The first pair are X and Y coordinates, for the left, top point and the second pair are X and Y coordinates, for the right, bottom point (thus forming the square to crop); | Fix rules x,y on image_obj
Coordinates for manual cropping. The first pair are X and Y coordinates,
for the left, top point and the second pair are X and Y coordinates, for
the right, bottom point (thus forming the square to crop);
| Python | mit | williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps | ---
+++
@@ -28,8 +28,8 @@
if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \
image.crop_y2 > 0:
- new['crop'] = ((image.crop_x1, image.crop_x2),
- (image.crop_y1, image.crop_y2))
+ new['crop'] = ((image.crop_x1, image.crop_y1),
+ ... |
e93c29e7d3bbb66da000ec46e1908b36c2c497e1 | lab_assistant/storage/__init__.py | lab_assistant/storage/__init__.py | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_op... | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_op... | Store results under correct experiment key | Store results under correct experiment key
| Python | mit | joealcorn/lab_assistant | ---
+++
@@ -31,7 +31,7 @@
def store(result, storage=None):
- storage = storage or get_storage()
+ storage = storage or get_storage(name=result.experiment.name)
key = simpleflake()
storage.set(key, result)
return key |
77f4fca43b1d4be85894ad565801d8a333008fdc | Lib/test/test_pep263.py | Lib/test/test_pep263.py | #! -*- coding: koi8-r -*-
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
u"\".e... | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\x... | Add a comment explaining -kb. | Add a comment explaining -kb.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,5 @@
#! -*- coding: koi8-r -*-
+# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support |
aaad392fedca6b3f9879240591877f6a64d907c3 | wordcloud/wordcloud.py | wordcloud/wordcloud.py | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... | Make maximum number of words a parameter | Make maximum number of words a parameter
| Python | agpl-3.0 | geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola | ---
+++
@@ -10,7 +10,7 @@
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
-def popular_words(max_entries=20):
+def popular_words(max_entries=20, max_words=25):
sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')
cloudlist = []
@@ -35... |
baaa7e4818ac71898ff3b601d006f5e23d444bee | pyes/exceptions.py | pyes/exceptions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... | Add exception type for script_fields related errors | Add exception type for script_fields related errors | Python | bsd-3-clause | jayzeng/pyes,rookdev/pyes,haiwen/pyes,mavarick/pyes,haiwen/pyes,mouadino/pyes,haiwen/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes,mavarick/pyes,aparo/pyes,aparo/pyes,mouadino/pyes,Fiedzia/pyes,mavarick/pyes,HackLinux/pyes,aparo/pyes,rookdev/pyes,Fiedzia/pyes,jayzeng/pyes,HackLinux/pyes | ---
+++
@@ -12,6 +12,7 @@
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
+ "ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
@@ -34,6 +35,8 @@
class Que... |
032256c7e13cd6630b7c6da16c083ad5b622aa64 | pynuts/__init__.py | pynuts/__init__.py | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... | Add views in Pynuts init | Add views in Pynuts init
| Python | bsd-3-clause | Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts | ---
+++
@@ -24,6 +24,7 @@
self.config.update(config or {})
self.db = SQLAlchemy(self)
self.documents = {}
+ self.views = {}
if reflect:
self.db.metadata.reflect(bind=self.db.get_engine(self))
|
0de68abab608680d4ef390fea572828fb12b6abd | rounding/common.py | rounding/common.py | '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
def _get_fract... | '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
self.count = 0
... | Add average_roundoff to rounding base class. | Add average_roundoff to rounding base class.
| Python | apache-2.0 | dmaust/rounding | ---
+++
@@ -17,6 +17,7 @@
'''
self.precision = precision
self.cumulative_error = 0
+ self.count = 0
def _get_fraction(self, x):
@@ -27,7 +28,12 @@
def _record_roundoff_error(self, x, result):
self.cumulative_error += result - x
+ se... |
b6a3890efc1716877eff7cce7f451df82cc3ca5c | services/heroku.py | services/heroku.py | import foauth.providers
class Heroku(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://heroku.com/'
docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference'
category = 'Code'
# URLs to interact with the API
authorize_url = 'https://id.heroku.... | import foauth.providers
class Heroku(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://heroku.com/'
docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference'
category = 'Code'
# URLs to interact with the API
authorize_url = 'https://id.heroku.... | Rewrite Heroku's scope handling a bit to better match reality | Rewrite Heroku's scope handling a bit to better match reality
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -13,13 +13,19 @@
api_domain = 'api.heroku.com'
available_permissions = [
- ('identity', 'read your account information'),
+ (None, 'read your account information'),
('read', 'read all of your apps and resources, excluding configuration values'),
('write', 'write ... |
c8422778e31888cbc02dc764af875114916e5f88 | smsviewer/views.py | smsviewer/views.py | from pyramid.view import view_config
from lxml import etree
@view_config(route_name='index', renderer='index.mako')
def my_view(request):
smsfile = "sms.xml"
with open(smsfile) as f:
tree = etree.parse(f)
root = tree.getroot()
return {"messages": sorted([e for e in root if e.get("contact_nam... | from pyramid.view import view_config
from lxml import etree
@view_config(route_name='index', renderer='index.mako')
def my_view(request):
smsfile = "sms.xml"
with open(smsfile) as f:
tree = etree.parse(f)
root = tree.getroot()
els = root.xpath("*[@contact_name='Lacey Shankle']")
return ... | Use xpath to find messages instead of a loop | Use xpath to find messages instead of a loop
| Python | mit | spiffytech/smsviewer,spiffytech/smsviewer | ---
+++
@@ -10,5 +10,6 @@
root = tree.getroot()
- return {"messages": sorted([e for e in root if e.get("contact_name") == "Lacey Shankle"], key=lambda message: message.get("date"))}
- return {'project': 'smsviewer'}
+ els = root.xpath("*[@contact_name='Lacey Shankle']")
+
+ return {"messages": so... |
dea4ed78fef278c2cb87b052c98a67940339835a | tagalog/_compat.py | tagalog/_compat.py | try:
from urlparse import urlparse
except ImportError: # Python3
from urllib import parse as urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| try:
from urlparse import urlparse
except ImportError: # Python3
from urllib.parse import urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| Fix compat module for Python 3 | Fix compat module for Python 3
| Python | mit | nickstenning/tagalog,alphagov/tagalog,alphagov/tagalog,nickstenning/tagalog | ---
+++
@@ -1,7 +1,7 @@
try:
from urlparse import urlparse
except ImportError: # Python3
- from urllib import parse as urlparse
+ from urllib.parse import urlparse
try:
_xrange = xrange |
aa78db30ad56262e7961013b523e69dacec26d60 | tests/util_test.py | tests/util_test.py | #!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
longMessage = True
def test_power_of_two(self):
self.assertFalse(util.power_of_two(None))
self.assertFalse(util.power_of_two("not a number"))
self.assertFalse(uti... | #!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
# Disable this warning, which will only be triggered on python3. For
# python2, the default is False.
longMessage = True # pylint: disable=pointless-class-attribute-override
... | Disable a pointless override warning. | Disable a pointless override warning.
This is a valid warning, but only on python3. On python2, the default
is False. I don't want to crud up the code with a bunch of conditionals
for stuff like this.
| Python | lgpl-2.1 | AdamWill/blivet,vpodzime/blivet,rvykydal/blivet,dwlehman/blivet,dwlehman/blivet,jkonecny12/blivet,rhinstaller/blivet,vpodzime/blivet,rhinstaller/blivet,rvykydal/blivet,vojtechtrefny/blivet,jkonecny12/blivet,vojtechtrefny/blivet,AdamWill/blivet | ---
+++
@@ -7,7 +7,9 @@
class MiscTest(unittest.TestCase):
- longMessage = True
+ # Disable this warning, which will only be triggered on python3. For
+ # python2, the default is False.
+ longMessage = True # pylint: disable=pointless-class-attribute-override
def test_power_of_two(self):... |
8670dc8d6c0c920f21598b132250537a744eeebc | tweepy/__init__.py | tweepy/__init__.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy Twitter API library
"""
__version__ = '3.1.0'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category
from tweepy.erro... | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy Twitter API library
"""
__version__ = '3.1.0'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category
from tweepy.erro... | Fix tweepy.debug() by using six's module helpers. | Fix tweepy.debug() by using six's module helpers.
| Python | mit | tweepy/tweepy,bconnelly/tweepy,kylemanna/tweepy,yared-bezum/tweepy,conversocial/tweepy,vikasgorur/tweepy,atomicjets/tweepy,iamjakob/tweepy,robbiewoods05/tweepy,arunxarun/tweepy,tsablic/tweepy,kcompher/tweepy,rudraksh125/tweepy,svven/tweepy,srimanthd/tweepy,vishnugonela/tweepy,truekonrads/tweepy,IsaacHaze/tweepy,awangga... | ---
+++
@@ -21,6 +21,5 @@
api = API()
def debug(enable=True, level=1):
- pass
- # import http.client
- # http.client.HTTPConnection.debuglevel = level
+ from six.moves.http_client import HTTPConnection
+ HTTPConnection.debuglevel = level |
1d9b0ac91bca0dd19f83507f9e27414334fdb756 | bin/commands/restash.py | bin/commands/restash.py | """Restash changes."""
import re
import sys
from subprocess import check_output, PIPE, Popen
from utils.messages import error
def restash(stash='stash@{0}'):
"""Restashes a stash reference."""
if re.match('^stash@{.*}$', stash) is None:
error('{} is not a valid stash reference'.format(stash))
... | """Restash changes."""
import os
import re
import sys
from subprocess import check_output, PIPE, Popen
from utils.messages import error
def _is_valid_stash(stash):
"""Determines if a stash reference is valid."""
if re.match('^stash@{.*}$', stash) is None:
return False
with open(os.devnull, 'w'... | Fix error messages for bad stash references | Fix error messages for bad stash references
| Python | mit | Brickstertwo/git-commands | ---
+++
@@ -1,5 +1,6 @@
"""Restash changes."""
+import os
import re
import sys
from subprocess import check_output, PIPE, Popen
@@ -7,10 +8,21 @@
from utils.messages import error
+def _is_valid_stash(stash):
+ """Determines if a stash reference is valid."""
+
+ if re.match('^stash@{.*}$', stash) is N... |
c7f7337b8f86786cd74f46cee9cff7f6d8eb8ec3 | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
import subprocess
import sys
import shlex
def run_tests(env):
subprocess.call(shlex.split(env.get('TEST_COMMAND')))
sys.exit(0)
def generate(env):
env.CBAddVariables(('TEST_COMMAND', 'Command to run for `test` target',
'tests/testHarness -C tests --no-c... | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
subprocess.call(shlex.split(env.get('TEST_COMMAND')))
sys.exit(0)
def generate(env):
import os
cmd = 'tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-fa... | Use color output for tests outside of dockbot | Use color output for tests outside of dockbot
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang | ---
+++
@@ -1,19 +1,24 @@
from SCons.Script import *
-import subprocess
-import sys
-import shlex
def run_tests(env):
+ import shlex
+ import subprocess
+ import sys
+
subprocess.call(shlex.split(env.get('TEST_COMMAND')))
sys.exit(0)
def generate(env):
- env.CBAddVariables(('TEST_COMM... |
8639f4e32be8e264cca0831ecacec2d4a177cceb | citrination_client/models/design/target.py | citrination_client/models/design/target.py | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min")
"""
def __init__(self, name, objective):
"""
Co... | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min")
"""
def __init__(self, name, objective):
"""
Co... | Fix docstring for Target values | Fix docstring for Target values
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | ---
+++
@@ -14,8 +14,7 @@
:param name: The name of the target output column
:type name: str
- :param objective: The optimization objective; either "Min"
- or "Max"
+ :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0")
:typ... |
ce04fc96bf6653419acb81db0f1894934517f33b | fireplace/cards/blackrock/collectible.py | fireplace/cards/blackrock/collectible.py | from ..utils import *
##
# Minions
# Flamewaker
class BRM_002:
events = [
OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2)
]
# Imp Gang Boss
class BRM_006:
events = [
Damage(SELF).on(Summon(CONTROLLER, "BRM_006t"))
]
##
# Spells
# Solemn Vigil
class BRM_001:
action = [Draw(CONTROLLER) * 2]
def c... | from ..utils import *
##
# Minions
# Flamewaker
class BRM_002:
events = [
OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2)
]
# Imp Gang Boss
class BRM_006:
events = [
Damage(SELF).on(Summon(CONTROLLER, "BRM_006t"))
]
# Dark Iron Skulker
class BRM_008:
action = [Hit(ENEMY_MINIONS - DAMAGED, 2)]
# ... | Implement Dark Iron Skulker and Volcanic Lumberer | Implement Dark Iron Skulker and Volcanic Lumberer
| Python | agpl-3.0 | oftc-ftw/fireplace,NightKev/fireplace,Meerkov/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,Ragowit/fireplace,Meerkov/fireplace,amw2104/fireplace,amw2104/fireplace,jleclanche/fireplace,liujimj/fireplace,beheh/fireplace,butozerca/fireplace,butozerca/fi... | ---
+++
@@ -16,6 +16,17 @@
events = [
Damage(SELF).on(Summon(CONTROLLER, "BRM_006t"))
]
+
+
+# Dark Iron Skulker
+class BRM_008:
+ action = [Hit(ENEMY_MINIONS - DAMAGED, 2)]
+
+
+# Volcanic Lumberer
+class BRM_009:
+ def cost(self, value):
+ return value - self.game.minionsKilledThisTurn
## |
87b5fe729ef398722c2db1c8eb85a96f075ef82c | examples/GoBot/gobot.py | examples/GoBot/gobot.py | from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
import math
import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r... | """
GoBot Example
"""
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
"""
GoBot
"""
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN... | Fix linting errors in GoBot | Fix linting errors in GoBot
| Python | apache-2.0 | cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot | ---
+++
@@ -1,14 +1,18 @@
+"""
+GoBot Example
+"""
+
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
-
-import math
-import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
+ """
+ GoBot
+ """
def __init__(self):
... |
b7438eb833887c207cc8b848e549a30c7a981373 | polling_stations/apps/data_finder/forms.py | polling_stations/apps/data_finder/forms.py | from django import forms
from localflavor.gb.forms import GBPostcodeField
class PostcodeLookupForm(forms.Form):
postcode = GBPostcodeField(label="Enter your postcode")
class AddressSelectForm(forms.Form):
address = forms.ChoiceField(
choices=(),
label="",
initial="",
widget=... | from django import forms
from django.utils.translation import gettext_lazy as _
from localflavor.gb.forms import GBPostcodeField
class PostcodeLookupForm(forms.Form):
postcode = GBPostcodeField(label=_("Enter your postcode"))
class AddressSelectForm(forms.Form):
address = forms.ChoiceField(
choices... | Mark "Enter your postcode" for translation in a form field label | Mark "Enter your postcode" for translation in a form field label
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -1,10 +1,11 @@
from django import forms
+from django.utils.translation import gettext_lazy as _
from localflavor.gb.forms import GBPostcodeField
class PostcodeLookupForm(forms.Form):
- postcode = GBPostcodeField(label="Enter your postcode")
+ postcode = GBPostcodeField(label=_("Enter your po... |
bb82e3a8519009311ede80f877844565c49384b4 | examples/qidle/qidle.py | examples/qidle/qidle.py | #! /usr/bin/python3
# -*- coding: utf-8 -*-
from qidle import main
import logging
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
main()
| #! /usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from qidle import main
import logging
if __name__ == '__main__':
filename = None
if sys.platform == 'win32':
filename = 'qidle.log'
logging.basicConfig(level=logging.INFO, filename=filename)
main()
| Add a log file on windows | Add a log file on windows
| Python | mit | pyQode/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python,mmolero/pyqode.python | ---
+++
@@ -1,8 +1,12 @@
#! /usr/bin/python3
# -*- coding: utf-8 -*-
+import sys
from qidle import main
import logging
if __name__ == '__main__':
- logging.basicConfig(level=logging.INFO)
+ filename = None
+ if sys.platform == 'win32':
+ filename = 'qidle.log'
+ logging.basicConfig(level=log... |
e1f15a29bb947666740ec250120e3bdf451f0477 | pythonwarrior/towers/beginner/level_006.py | pythonwarrior/towers/beginner/level_006.py | # --------
# |C @ S aa|
# --------
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.")
level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.")
level... | # --------
# |C @ S aa|
# --------
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.")
level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a ... | Update description of the level 06 | Update description of the level 06 | Python | mit | arbylee/python-warrior | ---
+++
@@ -3,7 +3,7 @@
# --------
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.")
-level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.")
... |
72358efa2bf9ff45377ef8ab3478b9433c67c574 | candidates/feeds.py | candidates/feeds.py | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/chan... | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/chan... | Remove IP address from feed description | Remove IP address from feed description
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yourn... | ---
+++
@@ -23,10 +23,9 @@
description = """
{0}
- Updated by {1} at {2}
+ Updated at {1}
""".format(
item.source,
- item.ip_address,
str(item.updated),
)
|
20cc6c1edca69c946261c6bd8587d6cf5bb7a6e8 | tests/core/eth-module/test_eth_contract.py | tests/core/eth-module/test_eth_contract.py | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... | Replace duplicate test with valid address kwarg | Replace duplicate test with valid address kwarg
| Python | mit | pipermerriam/web3.py | ---
+++
@@ -16,7 +16,7 @@
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
- ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
+ ((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
) |
16765ebf41e2c7adea3ed1c1021bf1ca9db83d15 | fmn/lib/__init__.py | fmn/lib/__init__.py | """ fedmsg-notifications internal API """
import fmn.lib.models
import logging
log = logging.getLogger(__name__)
def recipients(session, config, valid_paths, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"... | """ fedmsg-notifications internal API """
import fmn.lib.models
import inspect
import logging
log = logging.getLogger(__name__)
def recipients(session, config, valid_paths, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of re... | Use inspect to get the list of arguments each filter accepts | Use inspect to get the list of arguments each filter accepts | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | ---
+++
@@ -2,6 +2,7 @@
import fmn.lib.models
+import inspect
import logging
log = logging.getLogger(__name__)
@@ -48,6 +49,7 @@
if not callable(obj):
continue
log.info("Found filter %r %r" % (name, obj))
- filters[name] = obj
+
+ filters[name] = {'func': obj, 'ar... |
cbe773d051168e05118774708ff7a0ce881617f4 | ganglia/settings.py | ganglia/settings.py | DEBUG = True
GANGLIA_PATH = '/usr/local/etc' # where gmetad.conf is located
API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted
BASE_URL = '/ganglia/api/v2'
LOGFILE = '/var/log/ganglia-api.log'
PIDFILE = '/var/run/ganglia-api.pid'
| DEBUG = True
GANGLIA_PATH = '/etc/ganglia' # where gmetad.conf is located
API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted
BASE_URL = '/ganglia/api/v2'
LOGFILE = '/var/log/ganglia-api.log'
PIDFILE = '/var/run/ganglia-api.pid'
| Make GANGLIA_PATH default to /etc/ganglia | Make GANGLIA_PATH default to /etc/ganglia
| Python | apache-2.0 | guardian/ganglia-api | ---
+++
@@ -1,6 +1,6 @@
DEBUG = True
-GANGLIA_PATH = '/usr/local/etc' # where gmetad.conf is located
+GANGLIA_PATH = '/etc/ganglia' # where gmetad.conf is located
API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted
BASE_URL = '/ganglia/api/v2' |
bab17ba4b22192848ab7e2b9649b6e83f0d947ac | src/load_remote_data.py | src/load_remote_data.py | #!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
with open(os.path.join(remote_... | #!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
with open(os.path.join(remote_... | Fix encoding after fetching remote data | Fix encoding after fetching remote data
Adds opening of csv file in binary format, plus conversion of fetched data to utf-8. This
resolves a UnicodeEncodeError exception.
| Python | mit | devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring | ---
+++
@@ -12,7 +12,7 @@
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
-with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'w') as f:
+with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error... |
09db47bd68f71560cde9509472b114c9ed5a6d54 | kolibri/__init__.py | kolibri/__init__.py | from __future__ import absolute_import, print_function, unicode_literals
# NB! This is not necessarily the version scheme we want, however having a good
# tracking of releases once we start doing lots of pre-releases is essential.
from .utils.version import get_version
#: This may not be the exact version as it's sub... | from __future__ import absolute_import, print_function, unicode_literals
# NB! This is not necessarily the version scheme we want, however having a good
# tracking of releases once we start doing lots of pre-releases is essential.
from .utils.version import get_version
#: This may not be the exact version as it's sub... | Develop branch bumped to 0.6.0dev with new versioning mechanism introduced | Develop branch bumped to 0.6.0dev with new versioning mechanism introduced
| Python | mit | jonboiser/kolibri,mrpau/kolibri,lyw07/kolibri,DXCanas/kolibri,lyw07/kolibri,DXCanas/kolibri,indirectlylit/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,christianmemije/koli... | ---
+++
@@ -6,7 +6,7 @@
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
-VERSION = (0, 4, 0, 'beta', 10)
+VERSION = (0, 6, 0, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.o... |
0d8a9a83fdd896aa5690c1c32db1d1658748a94a | tests/test_schemaorg.py | tests/test_schemaorg.py | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | Add test coverage for expected nutrient retrieval behaviour | Add test coverage for expected nutrient retrieval behaviour
| Python | mit | hhursev/recipe-scraper | ---
+++
@@ -25,6 +25,13 @@
del self.schema.data["totalTime"]
self.assertEqual(self.schema.total_time(), 0)
+ def test_nutrient_retrieval(self):
+ expected_nutrients = {
+ "calories": "240 calories",
+ "fatContent": "9 grams fat",
+ }
+ self.assertEqual... |
1f3f0b50d8cd740e09983b3dbd8796f1e4afa66c | linkatos/message.py | linkatos/message.py | import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is not None:
answer = answer.group(1).strip()
return ans... | import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
purge_re = re.compile("(purge) (\d+)")
list_re = re.compile("list")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is... | Change location of regex compilation | refactor: Change location of regex compilation
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -1,7 +1,8 @@
import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
-
+purge_re = re.compile("(purge) (\d+)")
+list_re = re.compile("list")
def extract_url(message):
"""
@@ -24,14 +25,12 @@
def is_list_request(message):
- list_re = re.compile("list")
list... |
e5c8379c987d2d7ae60d5f9321bb96f278549167 | apel/parsers/__init__.py | apel/parsers/__init__.py | '''
Copyright (C) 2012 STFC
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 writi... | '''
Copyright (C) 2012 STFC
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 writi... | Add HTCondorParser to init imports | Add HTCondorParser to init imports
| Python | apache-2.0 | apel/apel,tofu-rocketry/apel,tofu-rocketry/apel,stfc/apel,apel/apel,stfc/apel | ---
+++
@@ -22,6 +22,7 @@
from parser import Parser
from blah import BlahParser
+from htcondor import HTCondorParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser |
fdcc7f0e45fe5f0d284f47941238a92cbe9a1b36 | attest/tests/__init__.py | attest/tests/__init__.py | from attest import Tests
suite = lambda mod: 'attest.tests.' + mod + '.suite'
all = Tests([suite('asserts'),
suite('collections'),
suite('classy'),
suite('reporters'),
suite('eval'),
])
| from attest import Tests
all = Tests('.'.join((__name__, mod, 'suite'))
for mod in ('asserts',
'collections',
'classy',
'reporters',
'eval'))
| Simplify our own test suite | Simplify our own test suite
| Python | bsd-2-clause | dag/attest | ---
+++
@@ -1,11 +1,8 @@
from attest import Tests
-
-suite = lambda mod: 'attest.tests.' + mod + '.suite'
-
-all = Tests([suite('asserts'),
- suite('collections'),
- suite('classy'),
- suite('reporters'),
- suite('eval'),
- ])
+all = Tests('.'.join((__name... |
f096b5d2944dc19de8aa79696c137fe3f45927da | sistr/src/logger.py | sistr/src/logger.py | import logging
LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
def init_console_logger(logging_verbosity=3):
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
if logging_verbosity > len(logging_levels):
logging_verbosity = 3
lvl = loggin... | import logging
LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
def init_console_logger(logging_verbosity=3):
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
if logging_verbosity > (len(logging_levels) - 1):
logging_verbosity = 3
lvl = ... | Fix verbose level index out of range error | Fix verbose level index out of range error
| Python | apache-2.0 | peterk87/sistr_cmd | ---
+++
@@ -4,7 +4,7 @@
def init_console_logger(logging_verbosity=3):
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
- if logging_verbosity > len(logging_levels):
+ if logging_verbosity > (len(logging_levels) - 1):
logging_verbosity = 3
lvl = logging_levels[log... |
1ed1ac9a9a07a4b43ed1e96060a40b1ffd3fe97d | src/hunter/const.py | src/hunter/const.py | import os
import site
import sys
import this
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKA... | import os
import site
import sys
import stat
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKA... | Use stat instead of this. | Use stat instead of this.
| Python | bsd-2-clause | ionelmc/python-hunter | ---
+++
@@ -1,7 +1,7 @@
import os
import site
import sys
-import this
+import stat
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
@@ -20,7 +20,7 @@
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
- os.path.dirname(this.__file__),
+ os.path.dirname(sta... |
4219cb35c877d7838ed5ff4483a028f05f8433bd | testapp/__init__.py | testapp/__init__.py | __author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-And-Redis test project'
__license__ = 'BSD License'
__version__ = '0.2.3'
| Add metadata to ``testapp`` package. | Add metadata to ``testapp`` package.
| Python | bsd-3-clause | playpauseandstop/Flask-And-Redis,playpauseandstop/Flask-And-Redis | ---
+++
@@ -0,0 +1,4 @@
+__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
+__description__ = 'Flask-And-Redis test project'
+__license__ = 'BSD License'
+__version__ = '0.2.3' | |
012f93ae03aded72b64ac9bbfb6d2995199d4d8f | tests/test_api_views.py | tests/test_api_views.py | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequ... | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList, status
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory =... | Add test for status view | Add test for status view
| Python | apache-2.0 | erinspace/scrapi,erinspace/scrapi,felliott/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi | ---
+++
@@ -5,7 +5,7 @@
from django.test import TestCase
from rest_framework.test import APIRequestFactory
-from api.webview.views import DocumentList
+from api.webview.views import DocumentList, status
django.setup()
@@ -41,3 +41,12 @@
response = view(request)
self.assertEqual(response.s... |
0168836c6bb2c04ac7a9d4ac6682fca47512ea4c | tests/test_cli_parse.py | tests/test_cli_parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix, sample):
runner = CliRunner()
with tempfile.NamedTempor... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom'])
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefi... | Add tests for parse CLI with pos_kind | Add tests for parse CLI with pos_kind
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels | ---
+++
@@ -9,19 +9,21 @@
from tbmodels._cli import cli
+@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom'])
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
-def test_cli_parse(models_equal, prefix, sample):
+def test_cli_parse(models_equal, prefix, sample, pos_kind):
runner = CliRunner... |
b1a91fc4e843197a12be653aa60d5cdf32f31423 | tests/test_recursion.py | tests/test_recursion.py | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
assert uwhois.get_registrar_w... | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
server, port = uwhois.get_who... | Fix test for the fork | Fix test for the fork
| Python | mit | Rafiot/uwhoisd,Rafiot/uwhoisd | ---
+++
@@ -7,4 +7,6 @@
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
- assert uwhois.get_registrar_whois_server('com', transcript) == expected
+ server, port = uwhois.get_whois_server('com'... |
754d2949ce0c2fa2b36615af755b3b8aaf9876b5 | tests/test_resources.py | tests/test_resources.py | import pytest
from micromanager.resources import Resource
from micromanager.resources import BQDataset
from micromanager.resources import Bucket
from micromanager.resources import SQLInstance
test_cases = [
(
{'resource_kind': 'storage#bucket'},
Bucket
),
(
{'resource_kind': 'sql#i... | import pytest
from .util import load_test_data
from .util import discovery_cache
from .mock import HttpMockSequenceEx
from googleapiclient.http import HttpMockSequence
from micromanager.resources import Resource
from micromanager.resources.gcp import GcpBigqueryDataset
from micromanager.resources.gcp import GcpComp... | Update tests after lots of work on Resources | Update tests after lots of work on Resources
| Python | apache-2.0 | forseti-security/resource-policy-evaluation-library | ---
+++
@@ -1,34 +1,57 @@
import pytest
+from .util import load_test_data
+from .util import discovery_cache
+
+from .mock import HttpMockSequenceEx
+
+from googleapiclient.http import HttpMockSequence
+
from micromanager.resources import Resource
-from micromanager.resources import BQDataset
-from micromanager.r... |
0b32ae7a09dd961f379104b6628eaf5700cca785 | tests/test_unlocking.py | tests/test_unlocking.py | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2018
# License: 3-clause BSD, see LICENSE file
import unittest
from secretstorage import dbus_init, get_any_collection
from secretstorage.util import BUS_NAME
from secretstorage.exceptions import LockedException
@unittest.skipIf(BUS_NAME == "org.freedesktop.secre... | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2018
# License: 3-clause BSD, see LICENSE file
import unittest
from secretstorage import dbus_init, Collection
from secretstorage.util import BUS_NAME
from secretstorage.exceptions import LockedException
@unittest.skipIf(BUS_NAME == "org.freedesktop.secrets",
... | Add test coverage for Item.ensure_not_locked() method | Add test coverage for Item.ensure_not_locked() method
| Python | bsd-3-clause | mitya57/secretstorage | ---
+++
@@ -4,7 +4,7 @@
import unittest
-from secretstorage import dbus_init, get_any_collection
+from secretstorage import dbus_init, Collection
from secretstorage.util import BUS_NAME
from secretstorage.exceptions import LockedException
@@ -14,12 +14,16 @@
class LockingUnlockingTest(unittest.TestCase):
... |
d59635e9542ca54b39eaa10f31b53da46df68e61 | neutron/plugins/ml2/drivers/mlnx/config.py | neutron/plugins/ml2/drivers/mlnx/config.py | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Remove extra space in help string | Remove extra space in help string
Extra spaces make the openstack-manuals tests fail with a niceness
error. This patch removes an extra space at the end of a help string.
Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2
| Python | apache-2.0 | gkotton/vmware-nsx,gkotton/vmware-nsx | ---
+++
@@ -25,7 +25,7 @@
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
- help=_("Enable server compatibility with old nova ")),
+ help=_("Enable server compatibility with old nova")),
]
|
aa3029f962e47a6c0cd3023192616acb8eff5b75 | third_party/__init__.py | third_party/__init__.py | import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
| import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
| Insert third_party into the second slot of sys.path rather than the last slot | Insert third_party into the second slot of sys.path rather than the last slot
| Python | apache-2.0 | protron/namebench,google/namebench,rogers0/namebench,google/namebench,google/namebench | ---
+++
@@ -2,4 +2,4 @@
import sys
# This bit of evil should inject third_party into the path for relative imports.
-sys.path.append(os.path.dirname(__file__))
+sys.path.insert(1, os.path.dirname(__file__)) |
bbeb9b780908cf1322722669f1c68259345fe261 | readthedocs/v3/routers.py | readthedocs/v3/routers.py | from rest_framework.routers import DefaultRouter
from rest_framework_extensions.routers import NestedRouterMixin
class DefaultRouterWithNesting(NestedRouterMixin, DefaultRouter):
pass
| from rest_framework.routers import DefaultRouter, APIRootView
from rest_framework_extensions.routers import NestedRouterMixin
class DocsAPIRootView(APIRootView):
# Overridden only to add documentation for BrowsableAPIRenderer.
"""
Read the Docs APIv3 root endpoint.
Full documentation at [https://do... | Add documentation to the root view of BrowsableAPI | Add documentation to the root view of BrowsableAPI
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | ---
+++
@@ -1,6 +1,21 @@
-from rest_framework.routers import DefaultRouter
+from rest_framework.routers import DefaultRouter, APIRootView
from rest_framework_extensions.routers import NestedRouterMixin
+class DocsAPIRootView(APIRootView):
+
+ # Overridden only to add documentation for BrowsableAPIRenderer.
+
... |
20696d6f236afc1bc0e2b3db570363540e70ca84 | test/test_serve.py | test/test_serve.py | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run()
class TestServe(unittest.TestCase):
def test_simple(self):
... | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run(host='127.0.0.1')
class TestServe(unittest.TestCase):
def test_sim... | Use ip instead of localhost for travis | Use ip instead of localhost for travis
| Python | mit | witchard/grole | ---
+++
@@ -14,7 +14,7 @@
def hello(env, req):
return 'Hello, World!'
- app.run()
+ app.run(host='127.0.0.1')
class TestServe(unittest.TestCase):
@@ -22,16 +22,16 @@
p = multiprocessing.Process(target=simple_server)
p.start()
time.sleep(0.1)
- with urllib.r... |
5e0e22eb6e709eb5291ac50a28b96c2c05909a2d | src/artgraph/miner.py | src/artgraph/miner.py | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... | Return value of get_result is a pair of (task, result data) | Return value of get_result is a pair of (task, result data) | Python | mit | dMaggot/ArtistGraph | ---
+++
@@ -18,7 +18,7 @@
def mine(self, artist):
self.mine_internal(Node(artist, NodeTypes.ARTIST))
- new_relationships = self.master.get_result()
+ (finished_task, new_relationships) = self.master.get_result()
while new_relationships:
for n in new_relati... |
bfbb1e4fb8324df9a039c18359c053190f9e7e64 | dusty/commands/manage_config.py | dusty/commands/manage_config.py | import textwrap
from prettytable import PrettyTable
from ..config import get_config, save_config_value
from .. import constants
from ..log import log_to_client
def _eligible_config_keys_for_setting():
config = get_config()
return [key for key in sorted(constants.CONFIG_SETTINGS.keys())
if key ... | import textwrap
from prettytable import PrettyTable
from ..config import get_config, save_config_value
from .. import constants
from ..log import log_to_client
def _eligible_config_keys_for_setting():
config = get_config()
return [key for key in sorted(constants.CONFIG_SETTINGS.keys())
if key ... | Make config list able to handle long values | Make config list able to handle long values
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty | ---
+++
@@ -15,7 +15,9 @@
config = get_config()
table = PrettyTable(['Key', 'Description', 'Value'])
for key, description in constants.CONFIG_SETTINGS.iteritems():
- table.add_row([key, '\n'.join(textwrap.wrap(description, 80)), config.get(key)])
+ table.add_row([key,
+ ... |
d34fbc70d5873d159c311caed41b745b05534ce9 | lib/solution.py | lib/solution.py | class Solution:
def __init__(self, nr):
self.nr = nr
self.test = False
self.input = ""
self.solution = ["(not calculated)", "(not calculated)"]
self.calculated = [False, False]
def __str__(self):
return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], se... | class Solution:
def __init__(self, nr):
self.nr = nr
self.test = False
self.input = ""
self.solution = ["(not calculated)", "(not calculated)"]
self.calculated = [False, False]
def __str__(self):
return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], se... | Read Input: Read file complete or by lines | Read Input: Read file complete or by lines
| Python | mit | unstko/adventofcode2016 | ---
+++
@@ -25,6 +25,9 @@
if nr in [1, 2]:
return self.calculated[nr-1]
- def read_input(self):
+ def read_input(self, lines=False):
with open(self.nr+"/input.txt", "r") as f:
- self.input = f.read()
+ if lines:
+ self.input = f.readlines()
+... |
0f8b6f4a12c23e5498e8135a3f39da40c4333788 | tests/hexdumper.py | tests/hexdumper.py | # This hack by: Raymond Hettinger
class hexdumper:
"""Given a byte array, turn it into a string. hex bytes to stdout."""
def __init__(self):
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
def dump(self, src, length=8):
result=[]
for i in xrange(0, len(src... | # This hack by: Raymond Hettinger
class hexdumper:
"""Given a byte array, turn it into a string. hex bytes to stdout."""
def __init__(self):
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
# pretty dumping hate machine.
def dump(self, src, length=8):
re... | Add a function which allows packet dumps to be produced easily for inserting into regression tests. | Add a function which allows packet dumps to be produced
easily for inserting into regression tests.
| Python | bsd-3-clause | gvnn3/PCS,gvnn3/PCS | ---
+++
@@ -5,6 +5,7 @@
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
+ # pretty dumping hate machine.
def dump(self, src, length=8):
result=[]
for i in xrange(0, len(src), length):
@@ -14,3 +15,15 @@
result.append("%04X %-*s %s\n" % \
... |
06e84c25bb783490c963963ccb44cf07d521a197 | spam_lists/exceptions.py | spam_lists/exceptions.py | # -*- coding: utf-8 -*-
class SpamBLError(Exception):
''' Base exception class for spambl module '''
class UnknownCodeError(SpamBLError):
''' Raise when trying to use an unexpected value of dnsbl return code '''
class UnathorizedAPIKeyError(SpamBLError):
''' Raise when trying to use an unathorize... | # -*- coding: utf-8 -*-
class SpamBLError(Exception):
'''There was an error during testing a url or host'''
class UnknownCodeError(SpamBLError):
'''The classification code from the service was not recognized'''
class UnathorizedAPIKeyError(SpamBLError):
'''The API key used to query the service wa... | Reword docstrings for exception classes | Reword docstrings for exception classes
| Python | mit | piotr-rusin/spam-lists | ---
+++
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
class SpamBLError(Exception):
- ''' Base exception class for spambl module '''
+ '''There was an error during testing a url or host'''
class UnknownCodeError(SpamBLError):
- ''' Raise when trying to use an unexpected value of dnsbl return code '''
... |
4ca292e53710dd4ef481e7fa5965e22d3f94e65b | l10n_br_account_payment_order/models/cnab_return_move_code.py | l10n_br_account_payment_order/models/cnab_return_move_code.py | # Copyright 2020 Akretion
# @author Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, api, fields
class CNABReturnMoveCode(models.Model):
"""
CNAB return code, each Bank can has a list of Codes
"""
_name = 'cnab.retu... | # Copyright 2020 Akretion
# @author Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, api, fields
class CNABReturnMoveCode(models.Model):
"""
CNAB return code, each Bank can has a list of Codes
"""
_name = 'cnab.retu... | Index and code improve cnab.return.move.code | [REF] Index and code improve cnab.return.move.code
Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil | ---
+++
@@ -12,19 +12,33 @@
_name = 'cnab.return.move.code'
_description = 'CNAB Return Move Code'
- name = fields.Char(string='Name')
- code = fields.Char(string='Code')
+ name = fields.Char(
+ string='Name',
+ index=True,
+ )
+ code = fields.Char(
+ string='Code',
+ ... |
f0766ff22a7ee7c3e9a48c468f7e1f41e9d7e92c | vizier/__init__.py | vizier/__init__.py | """Init file."""
import os
import sys
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
PROTO_ROOT = os.path.realpath(os.path.join(THIS_DIR, "service"))
sys.path.append(PROTO_ROOT)
__version__ = "0.0.3.alpha"
| """Init file."""
import os
import sys
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
PROTO_ROOT = os.path.realpath(os.path.join(THIS_DIR, "service"))
sys.path.append(PROTO_ROOT)
__version__ = "0.0.5.dev"
| Update repo version to v0.0.5.dev | Update repo version to v0.0.5.dev
PiperOrigin-RevId: 471307548
| Python | apache-2.0 | google/vizier,google/vizier | ---
+++
@@ -7,4 +7,4 @@
sys.path.append(PROTO_ROOT)
-__version__ = "0.0.3.alpha"
+__version__ = "0.0.5.dev" |
1891469e5d3eb34efbe3c5feed1f7770e680120e | automata/nfa.py | automata/nfa.py | #!/usr/bin/env python3
import automata.automaton as automaton
class NFA(automaton.Automaton):
"""a deterministic finite automaton"""
def validate_automaton(self):
"""returns True if this NFA is internally consistent;
raises the appropriate exception if this NFA is invalid"""
for sta... | #!/usr/bin/env python3
import automata.automaton as automaton
class NFA(automaton.Automaton):
"""a nondeterministic finite automaton"""
def validate_automaton(self):
"""returns True if this NFA is internally consistent;
raises the appropriate exception if this NFA is invalid"""
for ... | Fix incorrect docstring for NFA class | Fix incorrect docstring for NFA class
| Python | mit | caleb531/automata | ---
+++
@@ -4,7 +4,7 @@
class NFA(automaton.Automaton):
- """a deterministic finite automaton"""
+ """a nondeterministic finite automaton"""
def validate_automaton(self):
"""returns True if this NFA is internally consistent; |
440fcebdcc06c0fbb26341764a0df529cec6587d | flask_wiki/frontend/frontend.py | flask_wiki/frontend/frontend.py | from flask import Flask, render_template, abort, redirect, url_for
from flask.ext.script import Manager
from jinja2 import TemplateNotFound
app = Flask(__name__)
app.config['TESTING'] = True
manager = Manager(app)
@app.route('/', endpoint='frontend-index')
def root():
# Redirect Base URL for the real Index Page... | from flask import Flask, render_template, abort, redirect, url_for
from flask.ext.script import Manager
from jinja2 import TemplateNotFound
app = Flask(__name__)
app.config['TESTING'] = True
manager = Manager(app)
@app.route('/', endpoint='frontend-index')
def root():
# Redirect Base URL for the real Index Page.... | Support for angular + API added. | Support for angular + API added.
| Python | bsd-2-clause | gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki | ---
+++
@@ -1,6 +1,5 @@
from flask import Flask, render_template, abort, redirect, url_for
from flask.ext.script import Manager
-
from jinja2 import TemplateNotFound
app = Flask(__name__)
@@ -22,7 +21,7 @@
:return: template.
"""
try:
- return render_template('pages/%s.html' % page)
+ ... |
fb6e5b11492675b7a7c94424737c91acbb541d69 | tests/test_message_body.py | tests/test_message_body.py | from tddcommitmessage.messagebody import MessageBody
from tddcommitmessage import Kind
def test_message_is_wrapped_in_quotes():
msg = MessageBody(Kind.red, 'Forty-two')
assert str(msg) == '"RED Forty-two"'
def test_message_with_double_quote_is_wrapped_with_single():
msg = MessageBody(Kind.red, 'But what a... | from tddcommitmessage.messagebody import MessageBody
from tddcommitmessage import Kind
def test_message_is_wrapped_in_quotes():
msg = MessageBody(Kind.red, 'Forty-two')
assert str(msg) == '"RED Forty-two"'
def test_first_letter_capitalised():
msg = MessageBody(Kind.red, 'forty-two')
assert str(msg) ==... | REFACTOR Change order of tests. | REFACTOR Change order of tests.
| Python | mit | matatk/tdd-bdd-commit,matatk/tdd-bdd-commit | ---
+++
@@ -5,10 +5,10 @@
msg = MessageBody(Kind.red, 'Forty-two')
assert str(msg) == '"RED Forty-two"'
+def test_first_letter_capitalised():
+ msg = MessageBody(Kind.red, 'forty-two')
+ assert str(msg) == '"RED Forty-two"'
+
def test_message_with_double_quote_is_wrapped_with_single():
msg = M... |
ef617d4e98d9c029225a32098cc81aeab1d6deb5 | genes/gnu_coreutils/commands.py | genes/gnu_coreutils/commands.py | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
... | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
... | Add link to gnu coreutils | Add link to gnu coreutils | Python | mit | hatchery/Genepool2,hatchery/genepool | ---
+++
@@ -20,6 +20,11 @@
@only_posix()
+def ln(*args):
+ run(['ln'] + list(*args))
+
+
+@only_posix()
def mkdir(path, mode=None):
if mode:
run(['mkdir', '-m', mode, path]) |
8ac142af2afc577a47197fe9bc821cb796883f38 | virtual_machine.py | virtual_machine.py | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
se... | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
se... | Check for autoincrement before executing the instruction | Check for autoincrement before executing the instruction
| Python | bsd-3-clause | darbaga/simple_compiler | ---
+++
@@ -24,7 +24,8 @@
def run(self):
while self.executing:
+ increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
- if self.bytecodes[self.pc].autoincrement:
+ if increment:
self.pc += 1
|
450b72dd97534c7317a6256ec2b2cd30bc0a0e59 | ocookie/httplibadapter.py | ocookie/httplibadapter.py | from . import CookieParser, CookieDict
def parse_cookies(httplib_headers):
cookies = [
CookieParser.parse_set_cookie_value(
header[1]
) for header in httplib_headers if header[0].lower() == 'set-cookie'
]
return cookies
| from . import CookieParser, CookieDict
def parse_cookies(httplib_set_cookie_headers):
cookies = []
for header in httplib_set_cookie_headers:
header = header.strip()
name, value = header.split(' ', 1)
value = value.strip()
cookie = CookieParser.parse_set_cookie_value(value)
... | Change API for parsing httplib cookies | Change API for parsing httplib cookies
| Python | bsd-2-clause | p/ocookie | ---
+++
@@ -1,9 +1,27 @@
from . import CookieParser, CookieDict
-def parse_cookies(httplib_headers):
- cookies = [
- CookieParser.parse_set_cookie_value(
- header[1]
- ) for header in httplib_headers if header[0].lower() == 'set-cookie'
- ]
+def parse_cookies(httplib_set_cookie_heade... |
de60844c82c9b569228aa830d36235b5a377859d | rpath_tools/client/sysdisco/descriptors.py | rpath_tools/client/sysdisco/descriptors.py | #!/usr/bin/python
from xml.etree import cElementTree as etree
from conary import conarycfg
from conary import conaryclient
from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache
class Descriptors(object):
def __init__(self):
self.cfg = conarycfg.ConaryConfiguration(True)
... | #!/usr/bin/python
from xml.etree import cElementTree as etree
from conary import conarycfg
from conary import conaryclient
from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache
class Descriptors(object):
def __init__(self):
self.cfg = conarycfg.ConaryConfiguration(True)
... | Fix descriptor module to support assimilation | Fix descriptor module to support assimilation
| Python | apache-2.0 | sassoftware/rpath-tools,sassoftware/rpath-tools | ---
+++
@@ -12,11 +12,13 @@
self.client = conaryclient.ConaryClient(self.cfg)
def gather(self):
- group = [ x for x in self.client.getUpdateItemList()
- if x[0].startswith('group-') and
- x[0].endswith('-appliance') ][0]
-
- desc = ConfigDescriptorC... |
3c218dff3e00ece3a84de727fa217d2d7d01b82d | wger/email/urls.py | wger/email/urls.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | Add 'gym' prefix to URL in email app | Add 'gym' prefix to URL in email app
The email app is supposed to be used in other parts of the application,
not only in the gym.
| Python | agpl-3.0 | wger-project/wger,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,wger-project/wger,rolandgeider/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,wger-project/wger,DeveloperMal/wger,rolan... | ---
+++
@@ -22,10 +22,10 @@
# sub patterns for email lists
patterns_email = [
- url(r'^overview/(?P<gym_pk>\d+)$',
+ url(r'^overview/gym/(?P<gym_pk>\d+)$',
email_lists.EmailLogListView.as_view(),
name='overview'),
- url(r'^add/(?P<gym_pk>\d+)$',
+ url(r'^add/gym/(?P<gym_pk>\d+)$',
... |
853744e82f2740a47a3f36e003ea8d2784bafff6 | accelerator/tests/factories/user_deferrable_modal_factory.py | accelerator/tests/factories/user_deferrable_modal_factory.py | import swapper
from datetime import (
datetime,
timedelta,
)
from factory import SubFactory
from factory.django import DjangoModelFactory
from simpleuser.tests.factories.user_factory import UserFactory
from .deferrable_modal_factory import DeferrableModalFactory
UserDeferrableModal = swapper.load_model('accel... | import swapper
from datetime import (
datetime,
timedelta,
)
from factory import SubFactory
from factory.django import DjangoModelFactory
from pytz import utc
from simpleuser.tests.factories.user_factory import UserFactory
from .deferrable_modal_factory import DeferrableModalFactory
UserDeferrableModal = swa... | Fix bare datetime.now() in factory | [AC-8673] Fix bare datetime.now() in factory
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -6,6 +6,8 @@
)
from factory import SubFactory
from factory.django import DjangoModelFactory
+from pytz import utc
+
from simpleuser.tests.factories.user_factory import UserFactory
from .deferrable_modal_factory import DeferrableModalFactory
@@ -20,4 +22,4 @@
user = SubFactory(UserFactory)
... |
e0b7217caaf4b94c879f43f2ee95584c469687db | csrv/model/read_o8d.py | csrv/model/read_o8d.py | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... | Fix o8d importer to read card IDs to make the sanitized cards | Fix o8d importer to read card IDs to make the sanitized cards
| Python | apache-2.0 | mrroach/CentralServer,mrroach/CentralServer,mrroach/CentralServer | ---
+++
@@ -16,5 +16,6 @@
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
- dest.append(card.text)
+ # Read the last 5 digits of card#id
+ dest.append("Card{}".format(card.get('id')[-5:]))
return (identity[0], cards) |
eac2211956d49d9da957492bbac1bcdc85b1e40d | openprescribing/frontend/management/commands/load_development_data.py | openprescribing/frontend/management/commands/load_development_data.py | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in local development'
def handle(self, *args, **options):
... | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.models import ImportLog, PPUSaving
from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in lo... | Add extra development data so the All England page loads | Add extra development data so the All England page loads
Previously the absence of the PPU ImportLog entry caused the page to
throw an error.
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing | ---
+++
@@ -1,7 +1,8 @@
from django.core.management import call_command
from django.core.management.base import BaseCommand
-from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
+from frontend.models import ImportLog, PPUSaving
+from frontend.tests.test_api_spending import ApiTestBase, TestAP... |
13c1745e73b7d3be162ce228d6c6ccf53f2438eb | syncplay/__init__.py | syncplay/__init__.py | version = '1.6.6'
revision = ' beta 2'
milestone = 'Yoitsu'
release_number = '89'
projectURL = 'https://syncplay.pl/'
| version = '1.6.6'
revision = ''
milestone = 'Yoitsu'
release_number = '90'
projectURL = 'https://syncplay.pl/'
| Mark build 90 as 1.6.6 final | Mark build 90 as 1.6.6 final
| Python | apache-2.0 | alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay | ---
+++
@@ -1,5 +1,5 @@
version = '1.6.6'
-revision = ' beta 2'
+revision = ''
milestone = 'Yoitsu'
-release_number = '89'
+release_number = '90'
projectURL = 'https://syncplay.pl/' |
fa2ecdc0bcb30415699baf4f014b390d4473d43c | photutils/psf/__init__.py | photutils/psf/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains tools to perform point-spread-function (PSF)
photometry.
"""
from .epsf import * # noqa
from .epsf_stars import * # noqa
from .groupstars import * # noqa
from .matching import * # noqa
from .models import * # noqa
from .p... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains tools to perform point-spread-function (PSF)
photometry.
"""
from . import epsf
from .epsf import * # noqa
from . import epsf_stars
from .epsf_stars import * # noqa
from . import groupstars
from .groupstars import * # noqa
... | Fix Sphinx warnings about duplicate objects | Fix Sphinx warnings about duplicate objects
| Python | bsd-3-clause | astropy/photutils,larrybradley/photutils | ---
+++
@@ -4,10 +4,24 @@
photometry.
"""
+from . import epsf
from .epsf import * # noqa
+from . import epsf_stars
from .epsf_stars import * # noqa
+from . import groupstars
from .groupstars import * # noqa
from .matching import * # noqa
+from . import models
from .models import * # noqa
+from . import ... |
a80b1292e9c9a29921a3e42c7c60d861b4bf7965 | tests/testwith.py | tests/testwith.py | import sys
if sys.version_info[:2] > (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '_... | import sys
if sys.version_info[:2] >= (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '... | Enable with statement tests for Python 2.5 | Enable with statement tests for Python 2.5
| Python | bsd-2-clause | frankier/mock,dannybtran/mock,testing-cabal/mock,sorenh/mock,scorphus/mock,nett55/mock,rbtcollins/mock,fladi/mock,OddBloke/mock,derwiki-adroll/mock,kostyll/mock,pypingou/mock,lord63-forks/mock,johndeng/mock | ---
+++
@@ -1,6 +1,6 @@
import sys
-if sys.version_info[:2] > (2, 5):
+if sys.version_info[:2] >= (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2 |
6055b7eb6b34ed22eb3c7cd17a975d4728be1360 | msmbuilder/tests/test_sampling.py | msmbuilder/tests/test_sampling.py | import numpy as np
from msmbuilder.decomposition import tICA
from msmbuilder.io.sampling import sample_dimension
def test_sample_dimension():
np.random.seed(42)
X = np.random.randn(500, 5)
data = [X, X, X]
tica = tICA(n_components=2, lag_time=1).fit(data)
tica_trajs = {k: tica.partial_transform(... | import numpy as np
from msmbuilder.decomposition import tICA
from msmbuilder.io.sampling import sample_dimension
def test_sample_dimension():
np.random.seed(42)
X = np.random.randn(500, 5)
data = [X, X, X]
tica = tICA(n_components=2, lag_time=1).fit(data)
tica_trajs = {k: tica.partial_transform(... | Add test for new edge sampling | Add test for new edge sampling
I think it would've failed before | Python | lgpl-2.1 | Eigenstate/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,brookehus/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbui... | ---
+++
@@ -15,3 +15,15 @@
res2 = sample_dimension(tica_trajs, 1, 10, scheme="linear")
assert len(res) == len(res2) == 10
+
+def test_sample_dimension_2():
+ np.random.seed(42)
+ X = np.random.randn(500, 5)
+ data = [X, X, X]
+
+ tica = tICA(n_components=2, lag_time=1).fit(data)
+ tica_traj... |
cebd4f1ee9a87cc2652ebf8981df20121ec257b2 | steel/fields/numbers.py | steel/fields/numbers.py | import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # lon... | import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # lon... | Raise ValueError instead of struct.error | Raise ValueError instead of struct.error
The protocol for field encoding and decoding is to raise ValueError, so this is a necessary translation.
| Python | bsd-3-clause | gulopine/steel-experiment | ---
+++
@@ -20,8 +20,14 @@
self.format_code = endianness + self.size_formats[self.size]
def encode(self, value):
- return struct.pack(self.format_code, value)
+ try:
+ return struct.pack(self.format_code, value)
+ except struct.error as e:
+ raise ValueError(... |
32f99cd7a9f20e2c8d7ebd140c23ac0e43b1284c | pulldb/users.py | pulldb/users.py | # Copyright 2013 Russell Heilling
import logging
from google.appengine.api import users
from pulldb import base
from pulldb import session
from pulldb.models.users import User
class Profile(session.SessionHandler):
def get(self):
app_user = users.get_current_user()
template_values = self.base_template_valu... | # Copyright 2013 Russell Heilling
import logging
from google.appengine.api import users
from pulldb import base
from pulldb import session
from pulldb.models.users import User
class Profile(session.SessionHandler):
def get(self):
app_user = users.get_current_user()
template_values = self.base_template_valu... | Add logging to track down a bug | Add logging to track down a bug
| Python | mit | xchewtoyx/pulldb | ---
+++
@@ -18,6 +18,7 @@
self.response.write(template.render(template_values))
def user_key(app_user=users.get_current_user(), create=True):
+ logging.debug("Looking up user key for: %r", app_user)
key = None
user = User.query(User.userid == app_user.user_id()).get()
if user: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.