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 |
|---|---|---|---|---|---|---|---|---|---|---|
fe6e24d3cadd71b7c613926f7baa26947f6caadd | webmention_plugin.py | webmention_plugin.py | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
info = UrlInfo(url)
in_reply_to = info.inReplyTo()
if url and in_reply_to:
sender = WebmentionSend(url, in_reply_to, verify=False)
... | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
in_reply_to = post.in_reply_to
if url and in_reply_to:
print "Sending webmention {} to {}".format(url, in_reply_to)
sender = WebmentionSend(... | Update webmention plugin to new version | Update webmention plugin to new version
| Python | bsd-2-clause | thedod/redwind,Lancey6/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind | ---
+++
@@ -3,9 +3,9 @@
def handle_new_or_edit(post):
url = post.permalink_url
- info = UrlInfo(url)
- in_reply_to = info.inReplyTo()
-
+ in_reply_to = post.in_reply_to
if url and in_reply_to:
- sender = WebmentionSend(url, in_reply_to, verify=False)
- sender.send()
+ ... |
1bc674ea94209ff20a890b9743a28bc0b9d8cb89 | motels/serializers.py | motels/serializers.py | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M')
class Meta:
model = Comment
fields = ('id', 'motel', 'bo... | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False)
class Meta:
model = Comment
fields = ('i... | Fix bug with comment POST (created_date was required) | Fix bug with comment POST (created_date was required)
| Python | mit | amartinez1/5letrasAPI | ---
+++
@@ -4,7 +4,7 @@
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
- created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M')
+ created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False)
class Meta:
model = Com... |
11f6f98753eae023da73afa111403d34ca818df0 | armet/attributes/decimal.py | armet/attributes/decimal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import six
from .attribute import Attribute
import decimal
class DecimalAttribute(Attribute):
type = decimal.Decimal
def prepare(self, value):
if value is None:
return None
return six.text... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import six
from .attribute import Attribute
import decimal
class DecimalAttribute(Attribute):
type = decimal.Decimal
def prepare(self, value):
if value is None:
return None
return six.text... | Convert to float then to text. | Convert to float then to text.
| Python | mit | armet/python-armet | ---
+++
@@ -13,7 +13,7 @@
if value is None:
return None
- return six.text_type(value)
+ return six.text_type(float(value))
def clean(self, value):
if isinstance(value, decimal.Decimal): |
a4dda07a7c1c8883a8828f43abae51826711b33e | test/343-winter-sports-resorts.py | test/343-winter-sports-resorts.py | assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
'sort_key': 27 })
| assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
'sort_key': 33 })
| Sort keys changed, update test. | Sort keys changed, update test.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -1,4 +1,4 @@
assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
- 'sort_key': 27 })
+ 'sort_key': 33 }) |
7c425075280fea87b1c8dd61b43f51e19e84b770 | astropy/utils/exceptions.py | astropy/utils/exceptions.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, pri... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, pri... | Remove DeprecationWarning superclass for AstropyDeprecationWarning | Remove DeprecationWarning superclass for AstropyDeprecationWarning
we do this because in py2.7, DeprecationWarning and subclasses are hidden by default, but we want astropy's deprecations to get shown by default
| Python | bsd-3-clause | bsipocz/astropy,astropy/astropy,funbaker/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,larrybradley/astropy,lpsinger/astropy,dhomeier/astropy,funbaker/astropy,MSeifert04/astropy,stargaser/astropy,dhomeier/astropy,mhvk/astropy,AustereCuriosity/astropy,saimn/astropy,pllim/astropy,larrybradley/astropy,joergdie... | ---
+++
@@ -24,7 +24,7 @@
"""
-class AstropyDeprecationWarning(DeprecationWarning, AstropyWarning):
+class AstropyDeprecationWarning(AstropyWarning):
"""
A warning class to indicate a deprecated feature.
""" |
a8e96366a55684c14835a3ef183708fa7177bd67 | server/lib/python/cartodb_services/setup.py | server/lib/python/cartodb_services/setup.py | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.19.1',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data... | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.20.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data... | Bump for the python library version | Bump for the python library version
| Python | bsd-3-clause | CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api | ---
+++
@@ -10,7 +10,7 @@
setup(
name='cartodb_services',
- version='0.19.1',
+ version='0.20.0',
description='CartoDB Services API Python Library',
|
e0719d89d00471168ae65891a1024608ff5ea608 | settings_example.py | settings_example.py | """
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServe... | """
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServe... | Fix logging format settings example | Fix logging format settings example
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | ---
+++
@@ -35,7 +35,7 @@
'''.strip()
LOGGING_KWARGS = dict(
- fromat=LOGGING_FORMAT,
+ format=LOGGING_FORMAT,
level=logging.DEBUG
)
|
98ab2a2ac0279f504195e49d55ff7be817592a75 | kirppu/app/checkout/urls.py | kirppu/app/checkout/urls.py | from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(func.url, func.name, name=func.view_name)
for func in AJAX_FUNCTIONS.itervalues()
])
urlpatterns = patterns('kirppu.app.checko... | from django.conf import settings
from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
if settings.KIRPPU_CHECKOUT_ACTIVE:
# Only activate API when checkout is active.
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(... | Fix access to checkout API. | Fix access to checkout API.
Prevent access to checkout API urls when checkout is not activated by
not creating urlpatterns.
| Python | mit | mniemela/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu | ---
+++
@@ -1,12 +1,19 @@
+from django.conf import settings
from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
-_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
-_urls.extend([
- url(func.url, func.name, name=func.view_name)
- for func in AJ... |
535b07758a16dec2ce79781f19b34a96044b99d3 | fluent_contents/conf/plugin_template/models.py | fluent_contents/conf/plugin_template/models.py | from django.db import models
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
@python_2_unicode_compatible
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models... | from django.db import models
from django.utils.translation import gettext_lazy as _
from fluent_contents.models import ContentItem
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models.CharField(_("Title"), max_length=200)
class Meta:
verbose_name = _("{{ mo... | Update plugin_template to Python 3-only standards | Update plugin_template to Python 3-only standards
| Python | apache-2.0 | edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents | ---
+++
@@ -1,11 +1,9 @@
from django.db import models
-from django.utils.six import python_2_unicode_compatible
-from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import gettext_lazy as _
from fluent_contents.models import ContentItem
-@python_2_unicode_compatible
class {... |
505f7f6b243502cb4d6053ac7d54e0ecad15c557 | functional_tests/test_question_page.py | functional_tests/test_question_page.py | from selenium import webdriver
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(... | from selenium import webdriver
from hamcrest import *
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.b... | Test for submitting and viewing questions. | Test for submitting and viewing questions.
| Python | agpl-3.0 | bjaress/shortanswer | ---
+++
@@ -1,4 +1,5 @@
from selenium import webdriver
+from hamcrest import *
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
@@ -22,6 +23,29 @@
self.browser.get(SERVER_URL+"/question")
submit_button = self.browser.find_element_by_css_selector("input[typ... |
20b0e705fe6eedb05a94a3e9cb978b65a525fe91 | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.3"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | Bump version: 0.0.2 -> 0.0.3 | Bump version: 0.0.2 -> 0.0.3
[ci skip]
| Python | mit | polysquare/sanitize-target-cmake | ---
+++
@@ -2,7 +2,7 @@
from conans.tools import download, unzip
import os
-VERSION = "0.0.2"
+VERSION = "0.0.3"
class SanitizeTargetCMakeConan(ConanFile): |
8b1818aefd6180548cf3b9770eb7a4d93e827fd7 | alignak_app/__init__.py | alignak_app/__init__.py | #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str... | #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VER... | Remove import of all Class app | Remove import of all Class app
| Python | agpl-3.0 | Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app | ---
+++
@@ -6,9 +6,6 @@
This module is an Alignak App Indicator
"""
-
-# Specific Application
-from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0) |
f5747773e05fc892883c852e495f9e166888d1ea | rapt/connection.py | rapt/connection.py | import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url)... | import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url)... | Set the hostname when it localhost | Set the hostname when it localhost
| Python | bsd-3-clause | yougov/rapt,yougov/rapt | ---
+++
@@ -16,6 +16,7 @@
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
+ os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname
password = keyring.get_password(hostname, username)
if not password: |
4a0491fb018cd96e510f25141dda5e7ceff423b4 | client/test/server_tests.py | client/test/server_tests.py | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = ... | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = ... | Remove tearDown not used method | Remove tearDown not used method
| Python | mit | CaminsTECH/owncloud-test | ---
+++
@@ -24,9 +24,6 @@
self.server = Server('')
self.server._requests = mock()
- def tearDown(self):
- pass
-
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get() |
a0863e53ccc8f548486eaa5f3e1f79774dea4b75 | tests/api/views/clubs/list_test.py | tests/api/views/clubs/list_test.py | from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aach... | from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
... | Use `pytest-voluptuous` to simplify JSON compare code | api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code
| Python | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines | ---
+++
@@ -1,32 +1,35 @@
+from pytest_voluptuous import S
+from voluptuous.validators import ExactSequence
+
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
- sfn = clubs.sfn()
- lva = clubs.lva()
- add_fixtures(db_session, sfn, lva)
+ add_fixtures(db_session, club... |
b74ae3ddba11ddc785da3a94bfff8f964d7c4ac6 | tests/test_run_ccoverage.py | tests/test_run_ccoverage.py | # coding=utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Test the run_ccoverage.py file."""
from __future__ import absolute_import, division, print_functio... | # coding=utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Test the run_ccoverage.py file."""
from __future__ import absolute_import, division, print_functio... | Revert "Re-activate code coverage test." | Revert "Re-activate code coverage test."
This reverts commit 9a5d5122139aedddbbcea169525e924269f6c20a.
| Python | mpl-2.0 | nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,nth10sd/funfuzz | ---
+++
@@ -11,6 +11,8 @@
import logging
import unittest
+import pytest
+
import funfuzz
FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test")
@@ -20,6 +22,7 @@
class RunCcoverageTests(unittest.TestCase):
""""TestCase class for functions in run_ccoverage.py"""
+ @pytest.mark.skip(reason="disab... |
93e447512b32e61ce41d25e73bb1592a3f8ac556 | gitfs/views/history.py | gitfs/views/history.py | from .view import View
class HistoryView(View):
pass
| from datetime import datetime
from errno import ENOENT
from stat import S_IFDIR
from pygit2 import GIT_SORT_TIME
from gitfs import FuseOSError
from log import log
from .view import View
class HistoryView(View):
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to th... | Add minimal working version for HistoryView (to be refactored). | Add minimal working version for HistoryView (to be refactored).
| Python | apache-2.0 | ksmaheshkumar/gitfs,rowhit/gitfs,bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs | ---
+++
@@ -1,5 +1,67 @@
+from datetime import datetime
+from errno import ENOENT
+from stat import S_IFDIR
+from pygit2 import GIT_SORT_TIME
+
+from gitfs import FuseOSError
+from log import log
from .view import View
class HistoryView(View):
- pass
+ def getattr(self, path, fh=None):
+ '''
+ ... |
267dfd75fa601b44b965d6df1d4440002f542638 | robert/__init__.py | robert/__init__.py | """
Entry point and the only view we have.
"""
from .article_utils import get_articles
from flask import Flask, render_template
from os import path
app = Flask(__name__)
config_path = path.abspath(path.join(path.dirname(__file__), 'config.py'))
app.config.from_pyfile(config_path)
@app.route('/')
def frontpage... | """
Entry point and the only view we have.
"""
from .article_utils import get_articles
from flask import Flask, render_template
from os import path
app = Flask(__name__)
config_path = path.abspath(path.join(path.dirname(__file__), 'config.py'))
app.config.from_pyfile(config_path)
@app.route('/')
def frontpage... | Change URL of about page -> /about.html | Change URL of about page -> /about.html
Since we can't control the web server serving this at GitHub Pages, we
can't setup proper URL rewriting to get rid of the extension. Ugly, but
keeps us from moving back to self-hosted site.
| Python | mit | thusoy/robertblag,thusoy/robertblag,thusoy/robertblag | ---
+++
@@ -23,7 +23,7 @@
return render_template('home.html', **context)
-@app.route('/about')
+@app.route('/about.html')
def about():
return render_template('about.html', title="Robert :: About")
|
4811de79c618134cec922e401ec447ef156ffc78 | scripts/pystart.py | scripts/pystart.py | import os,sys,re
from time import sleep
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran pystart and did import os... | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran... | Add pprint to default python includes | Add pprint to default python includes
| Python | mit | jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir | ---
+++
@@ -1,5 +1,6 @@
import os,sys,re
from time import sleep
+from pprint import pprint
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
@@ -8,4 +9,4 @@
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
-print ("Ran pystart a... |
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a | deen/main.py | deen/main.py | import sys
import logging
import pathlib
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def mai... | import sys
import logging
import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
de... | Use os.path instead of pathlib | Use os.path instead of pathlib
| Python | apache-2.0 | takeshixx/deen,takeshixx/deen | ---
+++
@@ -1,13 +1,13 @@
import sys
import logging
-import pathlib
+import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
-ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
+ICON = os.path.dirname(os.path.abspath(__file__)) + '/ic... |
47530321c413976241e0d4e314f2a8e1532f38c9 | hackarena/utilities.py | hackarena/utilities.py | # -*- coding: utf-8 -*-
class Utilities(object):
def get_session_string(self, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
def get_session_middle_part(self, original_session_string):
return... | # -*- coding: utf-8 -*-
class Utilities(object):
@classmethod
def get_session_string(cls, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
@classmethod
def get_session_middle_part(cls, origina... | Fix classmethods on utility class | Fix classmethods on utility class
| Python | mit | verekia/hackarena,verekia/hackarena,verekia/hackarena,verekia/hackarena | ---
+++
@@ -2,13 +2,12 @@
class Utilities(object):
- def get_session_string(self, original_session_string):
+
+ @classmethod
+ def get_session_string(cls, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attr... |
b2155e167b559367bc24ba614f51360793951f12 | mythril/support/source_support.py | mythril/support/source_support.py | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... | Remove meta from source class (belongs to issue not source) | Remove meta from source class (belongs to issue not source)
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | ---
+++
@@ -29,4 +29,3 @@
else:
assert False # Fail hard
- self.meta = "" |
356891c9b0fbf1d57f67a22ca977d3d1016e5dc1 | numpy/array_api/_set_functions.py | numpy/array_api/_set_functions.py | from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :p... | from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :p... | Fix the array API unique() function | Fix the array API unique() function
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -12,4 +12,8 @@
See its docstring for more information.
"""
- return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
+ res = np.unique(x._array, return_counts=return_counts,
+ return_index=return_inde... |
09d356f7b124368ac2ca80efa981d115ea847196 | django_ethereum_events/web3_service.py | django_ethereum_events/web3_service.py | from django.conf import settings
from web3 import Web3, RPCProvider
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given `RPCProvider`."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
... | from django.conf import settings
from web3 import Web3
try:
from web3 import HTTPProvider
RPCProvider = None
except ImportError:
from web3 import RPCProvider
HTTPProvider = None
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the give... | Support for Web3 4.0beta: HTTPProvider | Support for Web3 4.0beta: HTTPProvider
In Web3 3.16 the class is called RPCProvider, but in the
upcoming 4.0 series it's replaced with HTTPProvider.
This commit ensures both versions are supported in this regard.
| Python | mit | artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events | ---
+++
@@ -1,5 +1,11 @@
from django.conf import settings
-from web3 import Web3, RPCProvider
+from web3 import Web3
+try:
+ from web3 import HTTPProvider
+ RPCProvider = None
+except ImportError:
+ from web3 import RPCProvider
+ HTTPProvider = None
from .singleton import Singleton
@@ -15,11 +21,24 ... |
3039b00e761f02eb0586dad51049377a31329491 | reggae/reflect.py | reggae/reflect.py | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... | Use absolute paths for dependencies | Use absolute paths for dependencies
| Python | bsd-3-clause | atilaneves/reggae-python | ---
+++
@@ -24,7 +24,8 @@
finder = ModuleFinder()
finder.run_script(module)
- all_module_paths = [m.__file__ for m in finder.modules.values()]
+ all_module_paths = [os.path.abspath(m.__file__) for
+ m in finder.modules.values() if m.__file__ is not None]
def is_in_same_... |
827bc2751add4905b3fca57568c879e7cb8e70a0 | django_tml/inline_translations/middleware.py | django_tml/inline_translations/middleware.py | from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... | # encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... | Delete cookie on reset inline mode | Delete cookie on reset inline mode
| Python | mit | translationexchange/tml-python,translationexchange/tml-python | ---
+++
@@ -1,3 +1,4 @@
+# encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
@@ -25,7 +26,10 @@
def process_response(self, request, response):
""" Set/reset cookie for inline tranlations """
if _.save:
- response.set_signed_cookie(self.cooki... |
8284a8e61ed6c4e6b3402c55d2247f7e468a6872 | tests/test_integrations/test_get_a_token.py | tests/test_integrations/test_get_a_token.py | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
... | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
@unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret
... | Add unittest skip for CI | Add unittest skip for CI
| Python | isc | bretth/auth0plus | ---
+++
@@ -11,6 +11,7 @@
class TestGetAToken(unittest.TestCase):
+ @unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret |
08bd3801c0ecc3d4ef9720094bcbf67acaf1b67b | Instanssi/admin_base/views.py | Instanssi/admin_base/views.py | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/files/")
@login_required(login_url='/control/auth/login/')
def eventchange... | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchang... | Fix default refirect when url is /control/ | admin_base: Fix default refirect when url is /control/
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -5,7 +5,7 @@
@login_required(login_url='/control/auth/login/')
def index(request):
- return HttpResponseRedirect("/control/files/")
+ return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id): |
557d536aebe40bb115d2f0056aaaddf450ccc157 | test/params/test_arguments_parsing.py | test/params/test_arguments_parsing.py | import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args("")
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argum... | import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args([])
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argum... | Test for parsing argument parameters | Test for parsing argument parameters
| Python | mit | gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer | ---
+++
@@ -6,7 +6,14 @@
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
- argument = parse_args("")
+ argument = parse_args([])
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argument.oa... |
07b81828c100879795b629185bcc68bd69d30748 | setup.py | setup.py | from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
... | from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
... | Add more libraries that are used at runtime | Add more libraries that are used at runtime
| Python | agpl-3.0 | abadger/stellarmagnate | ---
+++
@@ -28,5 +28,5 @@
],
packages=['magnate', 'magnate.ui'],
scripts=['bin/magnate'],
- install_requires=['ConfigObj', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'],
+ install_requires=['ConfigObj', 'PyYaml', 'attrs', 'jsonschema', 'kitchen', 'pubmarine >= 0.3... |
98ca83d54eab97c81c5df86b415eb9ff0b201902 | src/__init__.py | src/__init__.py | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | Fix starting inet client when should use unix socket instead. Fix port to be int. | Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg | ---
+++
@@ -20,7 +20,7 @@
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
- address != gethostbyname(gethostname()):
+ address.split(':')[0] != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
... |
d90544ad2051e92a63da45d7270c7f66545edb82 | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_rem... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scra... | Migrate correctly from scratch also | Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a se... | Python | agpl-3.0 | Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform | ---
+++
@@ -1,8 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-from django.db import migrations, models, OperationalError, connection
-from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
+from django.db import migrations, models, connection
+
+def table_de... |
9c4bdeae651dd38801b980b4d06edcb8872cd5fa | Lib/test/test_gzip.py | Lib/test/test_gzip.py |
import sys, os
import gzip, tempfile
filename = tempfile.mktemp()
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"""
data2 = """/* zlibmodule.c -- gzip-compatible data compression */
/* See http://www.cdrom.com/pub/infozip/zlib/ */... |
import sys, os
import gzip, tempfile
filename = tempfile.mktemp()
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"""
data2 = """/* zlibmodule.c -- gzip-compatible data compression */
/* See http://www.cdrom.com/pub/infozip/zlib/ */... | Use binary mode for all gzip files we open. | Use binary mode for all gzip files we open.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -16,15 +16,15 @@
/* See http://www.winimage.com/zLibDll for Windows */
"""
-f = gzip.GzipFile(filename, 'w') ; f.write(data1) ; f.close()
+f = gzip.GzipFile(filename, 'wb') ; f.write(data1) ; f.close()
-f = gzip.GzipFile(filename, 'r') ; d = f.read() ; f.close()
+f = gzip.GzipFile(filename, 'rb') ; d... |
577da237d219aacd4413cb789fb08c76ca218223 | ws/plugins/accuweather/__init__.py | ws/plugins/accuweather/__init__.py |
import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
print(mydir)
lookupmatrix = pickle.load(open( \
mydir +'/accuweather_location_codes.dump','rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
... | import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
... | Use os.path.join() to join paths | Use os.path.join() to join paths
| Python | bsd-3-clause | BCCN-Prog/webscraping | ---
+++
@@ -1,4 +1,3 @@
-
import numpy as np
import pickle
import os
@@ -6,23 +5,17 @@
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
-
-print(mydir)
-
-lookupmatrix = pickle.load(open( \
- mydir +'/accuweather_location_codes.dump','rb'))
-
+lookupmatrix =... |
d84e37089a287fd151824f0b48624f243fdded09 | d1lod/tests/test_dataone.py | d1lod/tests/test_dataone.py | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod.dataone import extractIdentifierFromFullURL as extract
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert extract('asdf') is None
assert extract(1) is None
assert extract('1') is None
assert extract... | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod import dataone
def test_parsing_resource_map():
pid = 'resourceMap_df35d.3.2'
aggd_pids = dataone.getAggregatedIdentifiers(pid)
assert len(aggd_pids) == 7
def test_extracting_identifiers_from_urls():
# Returns None when it should
... | Change imports in dataone test and add test for resource map parsing | Change imports in dataone test and add test for resource map parsing
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod | ---
+++
@@ -3,18 +3,25 @@
Test the DataOne utility library.
"""
-from d1lod.dataone import extractIdentifierFromFullURL as extract
+from d1lod import dataone
+
+def test_parsing_resource_map():
+ pid = 'resourceMap_df35d.3.2'
+
+ aggd_pids = dataone.getAggregatedIdentifiers(pid)
+
+ assert len(aggd_pids)... |
fd4f6fb2eef3fd24d427836023918103bac08ada | acme/acme/__init__.py | acme/acme/__init__.py | """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://github.com/ietf-wg-acme/acme/
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://ietf-wg-acme.github.io/acme
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| Use GH pages for IETF spec repo link | Use GH pages for IETF spec repo link
| Python | apache-2.0 | mitnk/letsencrypt,mitnk/letsencrypt,twstrike/le_for_patching,DavidGarciaCat/letsencrypt,kuba/letsencrypt,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,jsha/letsencrypt,thanatos/lets-encrypt-preview,TheBoegl/letsencrypt,kuba/letsencrypt,brentdax/letsencrypt,wteiken/letsencrypt,brentdax/letsencrypt,jtl999/certbot,Vl... | ---
+++
@@ -3,10 +3,10 @@
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
-.. _`ACME protocol`: https://github.com/ietf-wg-acme/acme/
+
+.. _`ACME protocol`: https://ietf-wg-acme.github.io/acme
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-ac... |
091b1f5eb7c999a8d9b2448c1ca75941d2efb926 | opentaxii/auth/sqldb/models.py | opentaxii/auth/sqldb/models.py | import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integer, primary_ke... | import hmac
import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integ... | Use constant time string comparison for password checking | Use constant time string comparison for password checking
| Python | bsd-3-clause | EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII | ---
+++
@@ -1,3 +1,5 @@
+import hmac
+
import bcrypt
from sqlalchemy.schema import Column
@@ -10,6 +12,7 @@
MAX_STR_LEN = 256
+
class Account(Base):
__tablename__ = 'accounts'
@@ -18,7 +21,6 @@
username = Column(String(MAX_STR_LEN), unique=True)
password_hash = Column(String(MAX_STR_LEN))... |
2bc2f7e077ad46903688aababa51d37853746231 | bmi_ilamb/bmi_ilamb.py | bmi_ilamb/bmi_ilamb.py | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name... | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name... | Change component name to 'ILAMB' | Change component name to 'ILAMB'
This currently conflicts with the component name for the NCL
version of ILAMB; however, I'll change its name to 'ILAMBv1'.
The current version of ILAMB should take the correct name.
| Python | mit | permamodel/bmi-ilamb | ---
+++
@@ -16,7 +16,7 @@
return [self._command] + (self._args or [])
def get_component_name(self):
- return 'ILAMB v2'
+ return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg'] |
2faca854148a0661946ac944e4b8aa0684c773f6 | request.py | request.py | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callba... | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callba... | Add get param as int | Add get param as int
| Python | bsd-3-clause | Sendhub/flashk_util | ---
+++
@@ -21,3 +21,14 @@
else:
return func(*args, **kwargs)
return decorated_function
+
+
+def getParamAsInt(request, key, default):
+ """
+ Safely pulls a key from the request and converts it to an integer
+ @param request: The HttpRequest object
+ @param key: The key from re... |
6c351939243f758119ed91de299d6d37dc305359 | application/main/routes/__init__.py | application/main/routes/__init__.py | # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0... | # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0... | Expand class name routing target | Expand class name routing target
| Python | bsd-3-clause | p22co/edaemon,paulsnar/edaemon,p22co/edaemon,p22co/edaemon,paulsnar/edaemon,paulsnar/edaemon | ---
+++
@@ -9,5 +9,5 @@
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate),
- (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass),
+ (r'/changes/for_class/(.+)', ChangesForClass),
] |
0bbe6a915f8c289a9960f3cba9354955a19854f4 | inpassing/pass_util.py | inpassing/pass_util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... | Fix bug in user pass code | Fix bug in user pass code
The functions to query user and org passes return non-verified passes when
verified=None, which was not intended.
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend | ---
+++
@@ -12,7 +12,7 @@
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
- elif not verified:
+ elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
... |
7439a2c4b73707dc301117d3d8d368cfc31bc774 | akanda/rug/api/keystone.py | akanda/rug/api/keystone.py | # Copyright (c) 2015 Akanda, Inc. 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 applicable la... | # Copyright (c) 2015 Akanda, Inc. 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 applicable la... | Use KSC auth's register_conf_options instead of oslo.cfg import | Use KSC auth's register_conf_options instead of oslo.cfg import
A newer keystoneclient is not happy with simply using oslo_config to
import the config group. Instead, use register_conf_options()
from keystoneclient.auth.
Change-Id: I798dad7ad5bd90362e1fa10c2eecb3e1d5bade71
| Python | apache-2.0 | openstack/akanda-rug,openstack/akanda-rug,stackforge/akanda-rug,stackforge/akanda-rug | ---
+++
@@ -19,13 +19,13 @@
CONF = cfg.CONF
-CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token')
class KeystoneSession(object):
def __init__(self):
self._session = None
self.region_name = CONF.auth_region
+ ksauth.register_conf_options(CONF, 'keystone_autht... |
9d0ba593ae5f7e23a1bd32573ad8e80dac6eb845 | stalkr/cache.py | stalkr/cache.py | import os
import requests
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
self.directory = directory
if not os.path.isdir(directory):
os.mkdir(directory)
def get(self, key):
for extension in self.extensions:
filename =... | import os
import requests
class UnknownExtensionException:
def __init__(self, extension):
self.extension = extension
def __str__(self):
return repr("{0}: unknown extension".format(self.extension))
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
... | Raise exception if the image file extension is unknown | Raise exception if the image file extension is unknown
| Python | isc | helderm/stalkr,helderm/stalkr,helderm/stalkr,helderm/stalkr | ---
+++
@@ -1,5 +1,12 @@
import os
import requests
+
+class UnknownExtensionException:
+ def __init__(self, extension):
+ self.extension = extension
+
+ def __str__(self):
+ return repr("{0}: unknown extension".format(self.extension))
class Cache:
extensions = ["gif", "jpeg", "jpg", "png... |
5c5956dc11bbe9e65f6b9403cf0dbe5470eab257 | iterm2_tools/images.py | iterm2_tools/images.py | from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename... | from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in t... | Add a docstring to image_bytes | Add a docstring to image_bytes
| Python | mit | asmeurer/iterm2-tools | ---
+++
@@ -8,6 +8,12 @@
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
+ """
+ Display the image given by the bytes b in the terminal.
+
+ If filename=None the filename defaults to "Unnamed file".
+
+ """
data = {
... |
eba55b9b4eb59af9a56965086aae240c6615ba1f | author/urls.py | author/urls.py | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.contrib.auth.views import l... | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import per... | Fix bug with author permission check | Fix bug with author permission check
| Python | bsd-3-clause | stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3 | ---
+++
@@ -2,8 +2,6 @@
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
-from django.contrib.contenttypes.models import ContentType
-from django.contrib.auth.models import Permission
from django.contrib.auth.views import login
... |
ca9c4f7c3f1f7690395948b9dcdfd917cc33bfa8 | array/sudoku-check.py | array/sudoku-check.py | # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
... | # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
... | Add create sub grid method | Add create sub grid method
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -37,3 +37,18 @@
else:
ref_check[square] = 1
return True
+
+def check_sub_grid(grid):
+ sub_grid = []
+ for row in range(0, 9, 3):
+ for i in range(0, 9, 3):
+ a = []
+ for j in range(row, row + 3):
+ for column in range(i, i + 3):
+ a.append(grid[j][column])
+ sub_grid.append(a)
+
... |
b1dfc01eadd9420d5e20c5f3437e04505d77df13 | autocloud/__init__.py | autocloud/__init__.py | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT)
if not os.path.exists(name):
name = '/etc/autocloud/autocloud.cfg'
conf... | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
raise Exception('Please add a proper cofig file under /etc/autocloud/')
config.read(name)
KOJI_SERVER_URL = config.get('autocloud', ... | Read the config file only from /etc/autocloud/autocloud.cfg file. | Read the config file only from /etc/autocloud/autocloud.cfg file.
| Python | agpl-3.0 | maxamillion/autocloud,maxamillion/autocloud,kushaldas/autocloud,maxamillion/autocloud,maxamillion/autocloud,kushaldas/autocloud,kushaldas/autocloud,kushaldas/autocloud | ---
+++
@@ -5,12 +5,9 @@
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
-config = ConfigParser.RawConfigParser()
-name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
- PROJECT_ROOT=PROJECT_ROOT)
-
+name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
- name = '/etc/autocloud/... |
dba22abf151ddee20aeb886e2bca6401a17d7cea | properties/spatial.py | properties/spatial.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | Improve vector property error message | Improve vector property error message
| Python | mit | aranzgeo/properties,3ptscience/properties | ---
+++
@@ -39,7 +39,8 @@
try:
return vmath.Vector(value)
except Exception:
- raise ValueError('{} must be a Vector'.format(self.name))
+ raise ValueError('{}: must be Vector with '
+ '3 elements'.format(self.name))
def from_json(... |
b0b067c70d3bfc8fb599bd859116cce60f6759da | examples/dft/12-camb3lyp.py | examples/dft/12-camb3lyp.py | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
The default XC functional library (libxc) supports the energy and nuclear
gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
need xcfun library. See also example 32-xcfun_as_default.py for how to set
xcfun library a... | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''Density functional calculations can be run with either the default
backend library, libxc, or an alternative library, xcfun. See also
example 32-xcfun_as_default.py for how to set xcfun as the default XC
functional library.
'''
from pyscf impor... | Update the camb3lyp example to libxc 5 series | Update the camb3lyp example to libxc 5 series
| Python | apache-2.0 | sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf | ---
+++
@@ -3,36 +3,42 @@
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
-'''
-The default XC functional library (libxc) supports the energy and nuclear
-gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
-need xcfun library. See also example 32-xcfun_as_default.py for how to set
-xcf... |
35aec417f31fce87ff31f255b0781352def48217 | examples/generate_images.py | examples/generate_images.py | from __future__ import print_function
import subprocess
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path t... | from subprocess import run
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path to ImageMagick's convert.exe>
... | Refactor examples generation to Python 3 | Refactor examples generation to Python 3
| Python | mit | mp4096/blockschaltbilder | ---
+++
@@ -1,5 +1,4 @@
-from __future__ import print_function
-import subprocess
+from subprocess import run
# Compile examples and export them as images
@@ -16,7 +15,7 @@
# Compile the LaTeX document with examples
num_runs = 2
for i in range(num_runs):
- subprocess.run(["pdflatex", "--interaction=nonstop... |
76be04b7474d9a12d45256c3f31719e3b2ac425d | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/data/TestSwiftFoundationTypeData.py | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/data/TestSwiftFoundationTypeData.py | # TestSwiftFoundationValueTypes.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swif... | # TestSwiftFoundationValueTypes.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swif... | Revert "Skip an x-failed test due to an unexpected assert" | Revert "Skip an x-failed test due to an unexpected assert"
This reverts commit b04c3edb7a8bcb5265a1ea4265714dcb8d1b185a.
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | ---
+++
@@ -12,9 +12,7 @@
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
-# https://bugs.swift.org/browse/SR-3320
-# This test fails with an assertion error with stdlib resilience enabled:
-# https://github.com/apple/swift/pull/13573
lldbinline.MakeInlineTest(
... |
3974d63721c49564be638c9912ee3e940ca2695d | decisiontree/tasks.py | decisiontree/tasks.py | from threadless_router.router import Router
from decisiontree.models import Session
from celery.task import Task
from celery.registry import tasks
import logging
logger = logging.getLogger()
logging.getLogger().setLevel(logging.DEBUG)
class PeriodicTask(Task):
"""celery task to notice when we haven't gotten a ... | from celery.task import task
from decisiontree.models import Session
@task
def check_for_session_timeout():
"""
Check sessions and send a reminder if they have not responded in
the given threshold.
Note: this requires the threadless router to run.
"""
from threadless_router.router import Rou... | Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router. | Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router.
| Python | bsd-3-clause | caktus/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app | ---
+++
@@ -1,24 +1,18 @@
-from threadless_router.router import Router
+from celery.task import task
from decisiontree.models import Session
-from celery.task import Task
-from celery.registry import tasks
-import logging
-logger = logging.getLogger()
+@task
+def check_for_session_timeout():
+ """
+ Chec... |
cb8fe795aff58078a16ae1fac655c04762145abd | subscription/api.py | subscription/api.py | from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):... | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResou... | Add filter for getting user subs: | Add filter for getting user subs:
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control | ---
+++
@@ -1,5 +1,5 @@
from tastypie import fields
-from tastypie.resources import ModelResource
+from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
@@... |
934ec1300e70be518021d5851bdc380fef844393 | billjobs/tests/tests_export_account_email.py | billjobs/tests/tests_export_account_email.py | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account expor... | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account expor... | Add comment and reformat code | Add comment and reformat code
| Python | mit | ioO/billjobs | ---
+++
@@ -15,7 +15,7 @@
self.query_set = User.objects.all()
def test_method_is_avaible(self):
- """ Test admin can select the action in dropdown list """
+ """ Test UserAdmin class has method export_email """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_... |
ebd829a4939a524283d5603ed86a916c7bf88bb9 | regcore/db/storage.py | regcore/db/storage.py | from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django OR... | from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django OR... | Fix error during merge commit | Fix error during merge commit
| Python | cc0-1.0 | cmc333333/regulations-core,18F/regulations-core,eregs/regulations-core | ---
+++
@@ -9,7 +9,7 @@
class_str = settings.BACKENDS.get(
data_type,
'regcore.db.django_models.DM' + data_type.capitalize())
- return import_string(class_str)
+ return import_string(class_str)()
for_regulations = select_for('regulations')
for_layers = select_for('layers') |
b35befc9677541295609f4e55eea6fc2c4d7ab08 | office365/runtime/odata/odata_path_parser.py | office365/runtime/odata/odata_path_parser.py | from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_p... | from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_p... | Add more OData parameter format escapes | Add more OData parameter format escapes
| Python | mit | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client | ---
+++
@@ -26,7 +26,19 @@
@staticmethod
def encode_method_value(value):
if isinstance(value, basestring):
- value = "'{0}'".format(value.replace("'", "''"))
+ value = value.replace("'", "''")
+
+ # Same replacements as SQL Server
+ # https://web.archive.... |
b5601797b0e734514e5958be64576abe9fe684d7 | src/cli.py | src/cli.py | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, o... | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
if len(args.strip()) > 0:
for g in self.explorer.list_groups(args):
print(g+"/")
for ds in self.explorer.list_dataset... | Allow ls to pass arguments | Allow ls to pass arguments
| Python | mit | ksunden/h5cli | ---
+++
@@ -6,11 +6,18 @@
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
- for g in self.explorer.list_groups():
- print(g+"/")
-
- for ds in self.explorer.list_datasets():
- print(ds)
+ if len(args.strip()) > 0:
+ for g in self.explorer.lis... |
c01b01bd8ab640f74da0796ac1b6f05f5dc3ebc1 | pytest_cram/tests/test_options.py | pytest_cram/tests/test_options.py | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_cramignore(testdir):
testdir.makeini("""
[pytest]
cramignore =
sub/a*.t
a.t
c*.t
""")
testdir.tmpdir.ensure("sub/a.t")
testdir.tmpdir.en... | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_nocram(testdir):
"""Ensure that --nocram collects .py but not .t files."""
testdir.makefile('.t', " $ true")
testdir.makepyfile("def test_(): assert True")
result = testdir.runpytest("--n... | Test the --nocram command line option | Test the --nocram command line option
| Python | mit | tbekolay/pytest-cram,tbekolay/pytest-cram | ---
+++
@@ -7,7 +7,17 @@
assert pytest_cram.__version__
+def test_nocram(testdir):
+ """Ensure that --nocram collects .py but not .t files."""
+ testdir.makefile('.t', " $ true")
+ testdir.makepyfile("def test_(): assert True")
+ result = testdir.runpytest("--nocram")
+ assert result.ret == 0... |
15c51102f8e9f37bb08f9f6c04c7da2d75250cd2 | cabot/cabot_config.py | cabot/cabot_config.py | import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.env... | import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.env... | Convert *_INTERVAL variables to int | Convert *_INTERVAL variables to int
ALERT_INTERVAL and NOTIFICATION_INTERVAL are now converted to
numbers. This allows user-defined ALERT_INTERVAL and
NOTIFICATION_INTERVAL env variables to work without throwing
TypeErrors:
return self.run(*args, **kwargs)
File "/cabot/cabot/cabotapp/tasks.py", line 68, in upda... | Python | mit | arachnys/cabot,reddit/cabot,cmclaughlin/cabot,cmclaughlin/cabot,bonniejools/cabot,dever860/cabot,lghamie/cabot,jdycar/cabot,jdycar/cabot,movermeyer/cabot,xinity/cabot,lghamie/cabot,dever860/cabot,lghamie/cabot,dever860/cabot,cmclaughlin/cabot,arachnys/cabot,maks-us/cabot,mcansky/cabotapp,xinity/cabot,cmclaughlin/cabot,... | ---
+++
@@ -10,8 +10,8 @@
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
-ALERT_INTERVAL = os.environ.get('ALERT_INTERVAL', 10)
-NOTIFICATION_INTERVAL = os.environ.get('NOTIFICATION_INTERVAL', 120)
+ALERT_IN... |
8753b17e4583ca84249234fa09c5669df7a9d6ff | txnats/_meta.py | txnats/_meta.py | version_info = (0, 5, 1)
version = '.'.join(map(str, version_info))
| version_info = (0, 5, 2)
version = '.'.join(map(str, version_info))
| Increment version because bad release | Increment version because bad release
| Python | mit | johnwlockwood/txnats | ---
+++
@@ -1,2 +1,2 @@
-version_info = (0, 5, 1)
+version_info = (0, 5, 2)
version = '.'.join(map(str, version_info)) |
b0c27402da5522db7d8e1b65c81a28b3a19500b0 | pyinfra/modules/virtualenv.py | pyinfra/modules/virtualenv.py | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_c... | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_c... | Fix relying on pyinfra generator unroll | Fix relying on pyinfra generator unroll
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | ---
+++
@@ -30,8 +30,7 @@
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
- for cmd in files.directory(state, host, path, present=False):
- yield cmd
+ yield files.directory(state, host, path, p... |
0ebac1925b3d4b32188a6f2c9e40760b21d933ce | backend/uclapi/dashboard/app_helpers.py | backend/uclapi/dashboard/app_helpers.py | from binascii import hexlify
import os
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_key += char
final = "uclapi" + dashes... | from binascii import hexlify
from random import choice
import os
import string
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_k... | Add helpers to the dashboard code to generate OAuth keys | Add helpers to the dashboard code to generate OAuth keys
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | ---
+++
@@ -1,5 +1,8 @@
from binascii import hexlify
+from random import choice
+
import os
+import string
def generate_api_token():
@@ -21,3 +24,15 @@
final = "A" + key
return final
+
+def generate_app_client_id():
+ client_id = ''.join(random.choice(string.digits, k=16))
+ client_id += "."
... |
63f650855dfc707c6850add17d9171ba003bebcb | ckeditor_demo/urls.py | ckeditor_demo/urls.py | from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VER... | from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VERSION >= (1, 8):
urlpatterns = [
... | Fix media handling in demo application. | Fix media handling in demo application.
| Python | bsd-3-clause | MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,zatarus/django-ckeditor,Josephpaik/django-ckeditor,MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,MarcJoan/django-ck... | ---
+++
@@ -3,7 +3,6 @@
import django
from django.conf import settings
from django.conf.urls import include, url
-from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
@@ -15,6 +14,9 @@
url(r'^admin/', include(admin.site.urls)),
... |
412e672ea12c691b423acfa1b67a7a2626d91b0d | openslides/default.settings.py | openslides/default.settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Global settings file.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
# Django settings for openslides project.
from openslides_se... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Global Django settings file for OpenSlides.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides_settings import *
# Us... | Set default language for model/form translation strings. Have to changed for English installation! (Template strings are translated automatically by selected browser language) | Set default language for model/form translation strings. Have to changed for English installation!
(Template strings are translated automatically by selected browser language)
| Python | mit | emanuelschuetze/OpenSlides,jwinzer/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,boehlke/OpenSlides,boehlke/OpenSlides,CatoTH/OpenSlides,normanjaeckel/OpenSlides,normanjaeckel/OpenSlides,ostcar/OpenSlides,jwinzer/OpenSlides,rolandgeider/OpenSlides,rolandgeider/OpenSlides,emanuelschuetze/OpenSlides,jwinzer/OpenSlides,... | ---
+++
@@ -4,19 +4,21 @@
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Global settings file.
+ Global Django settings file for OpenSlides.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
-
-# Django settings for o... |
543509e991f88ecad7e5ed69db6d3b175fe44351 | tests/constants.py | tests/constants.py | TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_GROUP = ''
TEST_BAD_USER = '1234'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3... | TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_BAD_USER = '1234'
TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID ... | Add a test group key | Add a test group key
| Python | mit | scolby33/pushover_complete | ---
+++
@@ -1,7 +1,7 @@
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
-TEST_GROUP = ''
TEST_BAD_USER = '1234'
+TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "... |
07598bf67c3771391a5f3e287aab4b2c49180a05 | tests/test_tests.py | tests/test_tests.py | """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
c... | """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
c... | Remove an unused variable from TestTests. | Remove an unused variable from TestTests.
| Python | mit | s3rvac/retdec-python | ---
+++
@@ -31,5 +31,5 @@
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
- with self.assertRaises(AuthenticationError) as cm:
+ with self.assertRaises(AuthenticationError):
test.auth() |
8e0f2271b19504886728ccf5d060778c027c79ca | ide/views.py | ide/views.py | import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_al... | import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_al... | Check if project exists inside ProjectConverter. | Check if project exists inside ProjectConverter.
| Python | apache-2.0 | Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide | ---
+++
@@ -21,7 +21,10 @@
class ProjectConverter(BaseConverter):
def to_python(self, value):
- return Project(value)
+ project = Project(value)
+ if not project.exists():
+ abort(404)
+ return project
def to_url(self, value):
return BaseConverter.to_url(... |
5eb96c599dbbef56853dfb9441ab2eb54d36f9b7 | ckanext/syndicate/tests/test_plugin.py | ckanext/syndicate/tests/test_plugin.py | from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
... | from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
... | Add test for notify dataset/delete | Add test for notify dataset/delete
| Python | agpl-3.0 | aptivate/ckanext-syndicate,aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues,sorki/ckanext-redmine-autoissues | ---
+++
@@ -27,3 +27,9 @@
self.plugin.notify(self.entity, DomainObjectOperation.changed)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/update')
+
+ def test_syndicates_task_for_dataset_delete(self):
+ with self.syndicate_p... |
70c61b734940aed0ed4a491bc1169e1320d02998 | docs/conf.py | docs/conf.py | import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping ... | import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping ... | Fix zero-length field error when building docs in Python 2.6 | Fix zero-length field error when building docs in Python 2.6
| Python | bsd-3-clause | Intelworks/libtaxii,stkyle/libtaxii,TAXIIProject/libtaxii | ---
+++
@@ -24,7 +24,7 @@
master_doc = 'index'
rst_prolog = """
-**Version**: {}
+**Version**: {0}
""".format(release)
exclude_patterns = ['_build'] |
c9631819179eb99728c0ad7f3d6b46aef6dea079 | polygraph/types/object_type.py | polygraph/types/object_type.py | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | Fix ObjectType name and description attributes | Fix ObjectType name and description attributes
| Python | mit | polygraph-python/polygraph | ---
+++
@@ -10,7 +10,7 @@
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
self.name = getattr(meta, 'name', None)
- self.description = getattr(meta, 'name', None)
+ self.description = getattr(meta, 'description', None)
class ObjectType(Schema):
@... |
ac5b9765d69139915f06bd52d96b1abaa3d41331 | scuole/districts/views.py | scuole/districts/views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().select_related('county__name')
class DistrictDetailView(DetailView):
query... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().defer('shape')
class DistrictDetailView(DetailView):
queryset = District.o... | Remove unused select_related, defer the loading of shape for speed | Remove unused select_related, defer the loading of shape for speed
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | ---
+++
@@ -7,7 +7,7 @@
class DistrictListView(ListView):
- queryset = District.objects.all().select_related('county__name')
+ queryset = District.objects.all().defer('shape')
class DistrictDetailView(DetailView): |
924be2b545a4d00b9eacc5aa1c974e8ebf407c2f | shade/tests/unit/test_shade.py | shade/tests/unit/test_shade.py | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | Add basic unit test for shade.openstack_cloud | Add basic unit test for shade.openstack_cloud
Just getting basic minimal surface area unit tests to help when making
changes. This exposed some python3 incompatibilities in
os-client-config, which is why the change Depends on
Ia78bd8edd17c7d2360ad958b3de734503d400774.
Change-Id: I9cf5082d01861a0b6b372728a33ce9df9ee8d... | Python | apache-2.0 | stackforge/python-openstacksdk,openstack-infra/shade,openstack/python-openstacksdk,openstack/python-openstacksdk,openstack-infra/shade,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,jsmartin/shade,jsmartin/shade | ---
+++
@@ -12,17 +12,11 @@
# License for the specific language governing permissions and limitations
# under the License.
-"""
-test_shade
-----------------------------------
-
-Tests for `shade` module.
-"""
-
+import shade
from shade.tests import base
class TestShade(base.TestCase):
- def test_somet... |
437d495ba310ab2deee4a5c0f81e61228f2b6503 | yunity/resources/tests/integration/test_chat__rename_chat_succeeds/response.py | yunity/resources/tests/integration/test_chat__rename_chat_succeeds/response.py | from .initial_data import users
from yunity.utils.tests.comparison import DeepMatcher
response = {
"http_status": 201,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name",
"message": {
"content": "Hello user 1",
... | from .initial_data import users
from yunity.utils.tests.comparison import DeepMatcher
response = {
"http_status": 200,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name",
"message": {
"content": "Hello user 1",
... | Update expected http status code in test | Update expected http status code in test
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend | ---
+++
@@ -2,7 +2,7 @@
from yunity.utils.tests.comparison import DeepMatcher
response = {
- "http_status": 201,
+ "http_status": 200,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name", |
3f29248fc8159030417750e900a0e4c940883b4e | conf/models.py | conf/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneT... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneT... | Add verbose name to Conf model. | Add verbose name to Conf model.
| Python | bsd-2-clause | overshard/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,muhleder/timestrap,cdubz/timestrap | ---
+++
@@ -13,8 +13,12 @@
on_delete=models.CASCADE)
color = models.CharField(max_length=5, blank=True)
+ class Meta:
+ verbose_name = 'Configuration'
+ verbose_name_plural = 'Configuration'
+
def __str__(self):
- return 'Configuration'
+ ret... |
5536a2f330861631e411a064c9544ab732f0917a | dataproperty/_align.py | dataproperty/_align.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align:
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align(object):
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
... | Change old style class defined to new style class definition | Change old style class defined to new style class definition
| Python | mit | thombashi/DataProperty | ---
+++
@@ -7,7 +7,7 @@
from __future__ import unicode_literals
-class Align:
+class Align(object):
class __AlignData(object):
|
b9b4089fcd7f26ebf339c568ba6454d538a1813e | zk_shell/cli.py | zk_shell/cli.py | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | Handle IOError in run_once mode so paging works | Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <f25f6873bbbde69f1fe653b3e6bd40d543b8d0e0@itevenworks.net>
| Python | apache-2.0 | harlowja/zk_shell,harlowja/zk_shell,rgs1/zk_shell,rgs1/zk_shell | ---
+++
@@ -24,7 +24,10 @@
setup_readline=params.run_once == "")
if params.run_once != "":
- sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ try:
+ sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ except IOError:
+ ... |
623b170985a69a713db2d3c4887ed3b2ed8dc368 | feincms_extensions/content_types.py | feincms_extensions/content_types.py | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs)... | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs)... | Add id to json content types | Add id to json content types
Tests will probably fail! | Python | bsd-2-clause | incuna/feincms-extensions,incuna/feincms-extensions | ---
+++
@@ -9,7 +9,11 @@
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
- return {'content_type': 'rich-text', 'html': self.text}
+ return {
+ 'content_type': 'rich-text',
+ 'html': self.text,
+ 'id': self.pk... |
45ee26fae4a8d31b66e3307c0ab4aed21678b4b6 | scrubadub/filth/named_entity.py | scrubadub/filth/named_entity.py | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | Revert NamedEntityFilth name because it was a bad idea | Revert NamedEntityFilth name because it was a bad idea
| Python | mit | deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub | ---
+++
@@ -9,4 +9,4 @@
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
- self.type = "{}_{}".format(self.type, label).lower()
+ self.label = label.lower() |
6c0e6e79c05b95001ad4c7c1f6ab3b505ffbd6a5 | examples/comparator_example.py | examples/comparator_example.py | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['file_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexOb... | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['full_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexOb... | Change comparison parameter in example | Change comparison parameter in example
| Python | bsd-3-clause | MAECProject/python-maec | ---
+++
@@ -2,12 +2,12 @@
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
-match_on_dictionary = {'FileObjectType': ['file_name'],
+match_on_dictionary = {'FileObjectType': ['full_name'],
'WindowsRegistryKeyObjec... |
c3e034de03ee45bb161c06bcff870839f9ed4d4b | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import patterns, url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | Remove reference to deprecated "patterns" function. | Remove reference to deprecated "patterns" function.
This function is no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | ---
+++
@@ -1,4 +1,4 @@
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
|
18fec1124bb86f90183350e7b9c86eb946a01884 | whatchanged/main.py | whatchanged/main.py | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if sys.argv < 3:
print('Usage: %s <module1> <... | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if len(sys.argv) < 3:
print('Usage: %s <packa... | Fix minor bug in length comparison. | Fix minor bug in length comparison.
| Python | bsd-2-clause | punchagan/what-changed | ---
+++
@@ -14,8 +14,8 @@
def main():
import sys
- if sys.argv < 3:
- print('Usage: %s <module1> <module2>' % sys.argv[0])
+ if len(sys.argv) < 3:
+ print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3] |
2a08a8a6d5cdac0ddcbaf34977c119c5b75bbe8d | wtforms_webwidgets/__init__.py | wtforms_webwidgets/__init__.py | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
# from .common import *
from .common import CustomWidgetMixin, custom_widget_wrapper, FieldRender... | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
from .common import *
| Revert "Possible fix for docs not rendering auto" | Revert "Possible fix for docs not rendering auto"
This reverts commit 88c3fd3c4b23b12f4b68d3f5a13279870486d4b2.
| Python | mit | nickw444/wtforms-webwidgets | ---
+++
@@ -11,5 +11,4 @@
"""
-# from .common import *
-from .common import CustomWidgetMixin, custom_widget_wrapper, FieldRenderer, MultiField
+from .common import * |
a73dd1859dd21ede778a5404ca073ade0d5ef17c | src/greenmine/urls/__init__.py | src/greenmine/urls/__init__.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.... | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.... | Remove redis cache stats url. | Remove redis cache stats url.
| Python | bsd-3-clause | niwinz/Green-Mine,niwinz/Green-Mine,niwinz/Green-Mine,niwinz/Green-Mine | ---
+++
@@ -7,7 +7,7 @@
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.main', namespace='web')),
- url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
+ #url(r'^redis/status/', include('redis_... |
0e7edc1359726ce3257cf67dbb88408979be6a0b | doc/quickstart/testlibs/LoginLibrary.py | doc/quickstart/testlibs/LoginLibrary.py | import os
import sys
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, pass... | import os
import sys
import subprocess
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('creat... | Use subprocess isntead of popen to get Jython working too | Use subprocess isntead of popen to get Jython working too
| Python | apache-2.0 | ldtri0209/robotframework,ldtri0209/robotframework,waldenner/robotframework,waldenner/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,fiuba08/robotframework,fiu... | ---
+++
@@ -1,5 +1,6 @@
import os
import sys
+import subprocess
class LoginLibrary:
@@ -24,7 +25,9 @@
% (expected_status, self._status))
def _run_command(self, command, *args):
- command = '"%s" %s %s' % (self._sut_path, command, ' '.join(args))
- process... |
ea3f4934ffa8b88d8716f6550134c37e300c4003 | sqlitebiter/_const.py | sqlitebiter/_const.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "table not found in {}"
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "convertible table not found in {}"
| Modify a log message template | Modify a log message template
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter | ---
+++
@@ -11,4 +11,4 @@
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
-TABLE_NOT_FOUND_MSG_FORMAT = "table not found in {}"
+TABLE_NOT_FOUND_MSG_FORMAT = "convertible table not found in {}" |
df6375c952f0681a3f66596ca77701db8a193b6b | flake8/tests/test_mccabe.py | flake8/tests/test_mccabe.py | import unittest
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # NOQA
from flake8.mccabe import get_code_complexity
_GLOBAL = """\
for i in range(10):
pass
def a():
def b():
def c():
pass
c()
b()
"""
class McCabeTest(... | import unittest
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # NOQA
from flake8.mccabe import get_code_complexity
_GLOBAL = """\
for i in range(10):
pass
def a():
def b():
def c():
pass
c()
b()
"""
class McCabeTest(... | Fix the codes in the tests | Fix the codes in the tests
| Python | mit | wdv4758h/flake8,lericson/flake8 | ---
+++
@@ -36,6 +36,6 @@
self.assertEqual(get_code_complexity(_GLOBAL, 1), 2)
self.out.seek(0)
res = self.out.read().strip().split('\n')
- wanted = ["stdin:5:1: W901 'a' is too complex (4)",
- "stdin:2:1: W901 'Loop 2' is too complex (2)"]
+ wanted = ["stdin:... |
15490a05696e5e37aa98af905669967fe406eb1d | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
R... | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
| Python | mit | simonluijk/django-localeurl,jmagnusson/django-localeurl | ---
+++
@@ -10,6 +10,7 @@
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
+ 'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
) |
4e6ee7ed1d0e6cc105dad537dc79e12bdcbe9a40 | geozones/factories.py | geozones/factories.py | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... | Fix location factory field name | Fix location factory field name
| Python | mit | sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa | ---
+++
@@ -22,5 +22,5 @@
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
- name = factory.Sequence(lambda n: "Location_%s" % n)
- regionId = factory.SubFactory(RegionFactory)
+ description = factory.Sequence(lambda n: "Location_%s" % n)
+ region = factory.SubF... |
989abb47041e6a172765453c750c31144a92def5 | doc/rst2html-manual.py | doc/rst2html-manual.py | #!/usr/bin/env python3
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
import locale
from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directi... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice ... | Switch rst2html to HTML5 builder | Switch rst2html to HTML5 builder
This gives a prettier output and every browser in widespread usage has
supported it for years. The license, which was previously missing, is
added.
Signed-off-by: Stephen Finucane <06fa905d7f2aaced6dc72e9511c71a2a51e8aead@that.guru>
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf | ---
+++
@@ -1,12 +1,23 @@
#!/usr/bin/env python3
+# -*- coding: utf8 -*-
+# :Copyright: © 2015 Günter Milde.
+# :License: Released under the terms of the `2-Clause BSD license`_, in short:
+#
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty ... |
8244b6196ce84949e60174f844f80357c8a23478 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocke... | Migrate from Folly Format to fmt | Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
| Python | apache-2.0 | facebook/wangle,facebook/wangle,facebook/wangle | ---
+++
@@ -7,6 +7,7 @@
import specs.folly as folly
import specs.fizz as fizz
+import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
@@ -22,7 +23,7 @@
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
- 'depends_o... |
18818a8dfebcc44f9e8b582c15d6185f9a7a0c45 | minicms/templatetags/cms.py | minicms/templatetags/cms.py | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks ... | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks ... | Allow "Home" to be active menu item | Allow "Home" to be active menu item
| Python | bsd-3-clause | adieu/allbuttonspressed,adieu/allbuttonspressed | ---
+++
@@ -29,17 +29,19 @@
pass
# Mark the best-matching URL as active
- if request.path != '/':
- active = None
- active_len = 0
+ active = None
+ active_len = 0
+ # Normalize path
+ path = request.path.rstrip('/') + '/'
+ for item in menu:
# Normalize path
-... |
1b63781465abcc19df053a283148ea48436b8152 | mint/django_rest/rbuilder/inventory/views.py | mint/django_rest/rbuilder/inventory/views.py | #
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#
from django.http import HttpResponse
from django_restapi import resource
from mint.django_rest.deco import requires
from mint.django_rest.rbuilder.inventory import models
from mint.django_rest.rbuilder.inventory import systemdbmgr
MANAGER_CLASS = systemdbm... | #
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#
from django.http import HttpResponse
from django_restapi import resource
from mint.django_rest.deco import requires
from mint.django_rest.rbuilder.inventory import models
from mint.django_rest.rbuilder.inventory import systemdbmgr
MANAGER_CLASS = systemdbm... | Fix reference to model name | Fix reference to model name
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -30,7 +30,7 @@
resp = [str((s.id, s.registrationDate)) for s in systems]
return HttpResponse(str(resp))
- @requires('system', models.ManagedSystem)
+ @requires('system', models.managed_system)
def create(self, request, system):
return self.sysMgr.registerSystem(s... |
658587192ad4dbd56a655015bb4225cb965e60fa | neutron_fwaas/tests/tempest_plugin/plugin.py | neutron_fwaas/tests/tempest_plugin/plugin.py | # Copyright (c) 2015 Midokura SARL
# 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 require... | # Copyright (c) 2015 Midokura SARL
# 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 require... | Fix TempestPlugin to fix gate failure | Fix TempestPlugin to fix gate failure
Currently, tempest plugin for FWaaS is failing due to a wrong
function signature. This patch fixes the function.
Reference:
http://logs.openstack.org/75/247375/5/check/gate-congress-dsvm-api/1c5ed1f/logs/tempest.txt.gz?level=ERROR
Change-Id: Ifb8a0d50a88218b39274798cf8a82dc6f30a... | Python | apache-2.0 | openstack/neutron-fwaas,openstack/neutron-fwaas | ---
+++
@@ -32,5 +32,5 @@
'neutron_fwaas/tests/tempest_plugin/tests')
return (test_dir, top_level_dir)
- def register_opts(self):
+ def register_opts(self, conf):
return |
2efff9eb852ec2a8f38b4c21ecc6e62898891901 | test/run_tests.py | test/run_tests.py | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path... | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
"""
Note: This runs all of the tests. Maybe
this will be removed eventually?
"""
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfu... | Add quick comment to explain test_runner.py | Add quick comment to explain test_runner.py
| Python | apache-2.0 | ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/monary | ---
+++
@@ -1,5 +1,10 @@
# Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
+
+"""
+Note: This runs all of the tests. Maybe
+ this will be removed eventually?
+"""
import os
from os import listdir |
473e0536f388846fccf48ad75100f9e09b574610 | src/texas_choropleth/settings/local.py | src/texas_choropleth/settings/local.py | from .base import *
from .pipeline import *
# Debug Settings
DEBUG = True
TEMPLATE_DEBUG = True
STATIC_ROOT = os.path.join(BASE_DIR, 'static_final')
# TMP Dir for Choropleth Screenshots
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
INVITE_SIGNUP_SUCCESS_URL = "/"
INSTALLED_APPS += (
'debug_toolbar',
)
INT... | from .base import *
from .pipeline import *
# Debug Settings
DEBUG = True
TEMPLATE_DEBUG = True
STATIC_ROOT = os.path.join(BASE_DIR, 'static_final')
# TMP Dir for Choropleth Screenshots
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
INVITE_SIGNUP_SUCCESS_URL = "/"
INSTALLED_APPS += (
'debug_toolbar',
)
INT... | Add comment to clarify the pipeline settings. | Add comment to clarify the pipeline settings. | Python | bsd-3-clause | unt-libraries/texas-choropleth,damonkelley/texas-choropleth,unt-libraries/texas-choropleth,unt-libraries/texas-choropleth,unt-libraries/texas-choropleth,damonkelley/texas-choropleth,damonkelley/texas-choropleth,damonkelley/texas-choropleth | ---
+++
@@ -40,6 +40,8 @@
PIPELINE_ENABLED = False
+# This allows us to "test" the pipeline configuration
+# just by flipping the PIPELINE_ENABLED constant above.
if PIPELINE_ENABLED:
# Let Pipeline find Compressed files
STATICFILES_FINDERS = ( |
3db1ba530ea21baac3f42f56a2a49e85d8d9d18f | machete/issues/tests/test_create.py | machete/issues/tests/test_create.py |
from machete.issues.models import Issue
import unittest
class CreateTest(unittest.TestCase):
pass
| from machete.issues.models import Issue, Severity, Caliber, AssignedTo
import unittest
class CreateTest(unittest.TestCase):
"""Unit-tests around the creation of issues"""
def setUp(self):
super(CreateTest, self).setUp()
def test_should_be_able_to_create_new_issue(self):
"""Should be... | Add Unit-Tests Around Issue and Severity Creation and Association | Add Unit-Tests Around Issue and Severity Creation and Association
| Python | bsd-3-clause | rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete | ---
+++
@@ -1,8 +1,21 @@
-
-from machete.issues.models import Issue
+from machete.issues.models import Issue, Severity, Caliber, AssignedTo
import unittest
-class CreateTest(unittest.TestCase):
- pass
+class CreateTest(unittest.TestCase):
+ """Unit-tests around the creation of issues"""
+
+ def setUp(... |
f2703d18fc758033e7df582772b3abb973497562 | message/serializers.py | message/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon =... | # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon =... | Add message type field for api serializer | Add message type field for api serializer
| Python | mit | sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness | ---
+++
@@ -16,4 +16,4 @@
class Meta:
model = Message
- fields = ['id', 'title', 'lat', 'lon',]
+ fields = ['id', 'title', 'lat', 'lon', 'messageType'] |
03d4c298add892e603e48ca35b1a5070f407d6ff | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp:... | """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip f... | Remove only those files that were stored 5 minutes ago. | Remove only those files that were stored 5 minutes ago.
[https://cloudbolt.atlassian.net/browse/DEV-12629]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | ---
+++
@@ -4,13 +4,14 @@
from common.methods import set_progress
import glob
import os
+import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_l... |
617919d11722e2cc191f3dcecabfbe08f5d93caf | lib/utils.py | lib/utils.py | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(lst, basestring):
# Convert list to proper format for URL para... | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(input_lst, basestring):
# Convert list to proper format ... | Fix issue where last email was truncated | Fix issue where last email was truncated
| Python | unlicense | CodingAnarchy/Amon | ---
+++
@@ -8,19 +8,19 @@
logger = logging.getLogger(__name__)
-def comma_sep_list(lst):
+def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
- if not isinstance(lst, basestring):
+ if not isinstance(input_lst, basestring):
# Convert list to proper format f... |
c79e6b16e29dc0c756bfe82d62b9e01a5702c47f | testanalyzer/pythonanalyzer.py | testanalyzer/pythonanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]",
content))
def get_function_count(self, content):
ret... | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content)
matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
ret... | Fix counter to ignore quoted lines | Fix counter to ignore quoted lines
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | ---
+++
@@ -4,10 +4,11 @@
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
- return len(
- re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]",
- content))
+ matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.