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 |
|---|---|---|---|---|---|---|---|---|---|---|
7ff1f860f9cff5dcec86588485b9f2ce992fdd7c | widget.py | widget.py | #!/usr/bin/env python3
from config import colors, icons
# TODO properties instead of GETs/SETs
class Widget:
'''
Abstrac class for all lemonbar widgets.
'''
def __init__(self, name):
'''
Params:
bg: background color
fg: foreground color
icon: icon
... | #!/usr/bin/env python3
from config import colors, icons
# TODO properties instead of GETs/SETs
class Widget:
'''
Abstrac class for all lemonbar widgets.
'''
def __init__(self, name):
'''
Params:
bg: background color
fg: foreground color
icon: icon
... | Add bg and fg function. | Add bg and fg function.
| Python | mit | alberand/lemonbar,alberand/lemonbar,alberand/lemonbar | ---
+++
@@ -38,10 +38,23 @@
'''
Implement if widget should execute any aciont, commands, programs...
'''
- pass
+
+ def set_action(self, string)
+ return '%{{A{1}:{2}:}}{0}%{{A}}'.format(string, button, action)
+
+ def set_bg(self, string):
+ return '%{{B{1}}}{0}%... |
89b23ce8abd259ace055c35b0da47428bdcbc37a | scripts/server/client_example.py | scripts/server/client_example.py | #!/usr/bin/env python
from __future__ import print_function, unicode_literals, division
import sys
import time
import argparse
from websocket import create_connection
def translate(batch, port=8080):
ws = create_connection("ws://localhost:{}/translate".format(port))
#print(batch.rstrip())
ws.send(batch... | #!/usr/bin/env python
from __future__ import print_function, unicode_literals, division
import sys
import time
import argparse
from websocket import create_connection
def translate(batch, port=8080):
ws = create_connection("ws://localhost:{}/translate".format(port))
#print(batch.rstrip())
ws.send(batch... | Fix decoding error with python2 | Fix decoding error with python2
| Python | mit | marian-nmt/marian-train,emjotde/amunn,amunmt/marian,emjotde/amunmt,emjotde/amunmt,emjotde/amunmt,marian-nmt/marian-train,marian-nmt/marian-train,marian-nmt/marian-train,amunmt/marian,amunmt/marian,emjotde/amunn,emjotde/amunn,marian-nmt/marian-train,emjotde/amunmt,emjotde/amunn,emjotde/Marian,emjotde/Marian | ---
+++
@@ -32,7 +32,7 @@
batch = ""
for line in sys.stdin:
count += 1
- batch += line
+ batch += line.decode('utf-8') if sys.version_info < (3, 0) else line
if count == args.batch_size:
translate(batch, port=args.port)
count = 0 |
e0e222420242deba4e5ec8b9ddb931ba06728b23 | apps/podcast-transcribe-episode/tests/python/random_gcs_prefix.py | apps/podcast-transcribe-episode/tests/python/random_gcs_prefix.py | import abc
import datetime
from podcast_transcribe_episode.config import (
AbstractGCBucketConfig,
RawEnclosuresBucketConfig,
TranscodedEpisodesBucketConfig,
TranscriptsBucketConfig,
)
class RandomGCSPrefixMixin(AbstractGCBucketConfig, metaclass=abc.ABCMeta):
"""
Generates a random path prefi... | import abc
import datetime
from mediawords.util.text import random_string
from podcast_transcribe_episode.config import (
AbstractGCBucketConfig,
RawEnclosuresBucketConfig,
TranscodedEpisodesBucketConfig,
TranscriptsBucketConfig,
)
class RandomGCSPrefixMixin(AbstractGCBucketConfig, metaclass=abc.ABC... | Make random string a bit more random | Make random string a bit more random
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | ---
+++
@@ -1,5 +1,7 @@
import abc
import datetime
+
+from mediawords.util.text import random_string
from podcast_transcribe_episode.config import (
AbstractGCBucketConfig,
@@ -25,7 +27,7 @@
date = datetime.datetime.utcnow().isoformat()
date = date.replace(':', '_')
- self.__rando... |
929909513e71282de388cf4e93476ba614e6c0c5 | Malcom/feeds/malwaredomains.py | Malcom/feeds/malwaredomains.py | import urllib2
import re
from Malcom.model.datatypes import Hostname, Evil
from feed import Feed
import Malcom.auxiliary.toolbox as toolbox
class MalwareDomains(Feed):
def __init__(self, name):
super(MalwareDomains, self).__init__(name)
self.source = "http://mirror1.malwaredomains.com/files/domains.txt"
self.de... | import urllib2
import re
from Malcom.model.datatypes import Hostname, Evil
from feed import Feed
import Malcom.auxiliary.toolbox as toolbox
class MalwareDomains(Feed):
def __init__(self, name):
super(MalwareDomains, self).__init__(name)
self.source = "http://mirror1.malwaredomains.com/files/domains.txt"
self.de... | Deal with MalwareDomains non-ASCII characters | Deal with MalwareDomains non-ASCII characters
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti | ---
+++
@@ -27,7 +27,7 @@
if hostname['value'] == None: return # hostname not found
evil = Evil()
evil['value'] = "Malware domain blocklist (%s)" % hostname['value']
- evil['tags'] = ['malwaredomains', splitted_mdl[3]]
+ evil['tags'] = ['malwaredomains', re.sub(r'[^\w]', '', splitted_mdl[3])]
evil['refe... |
2804ac090444e20f1a4899234a49cae8c3142003 | simuvex/procedures/libc___so___6/__init__.py | simuvex/procedures/libc___so___6/__init__.py |
#
# offsets in struct _IO_FILE
#
_IO_FILE = {
'X86': {
'fd': 0x38,
},
'X64': {
'fd': 0x70,
},
} |
#
# offsets in struct _IO_FILE
#
_IO_FILE = {
'X86': {
'fd': 0x38,
},
'AMD64': {
'fd': 0x70,
},
} | Rename X64 to AMD64 in libc SimProcedures to be consistent with architecture names in archinfo | Rename X64 to AMD64 in libc SimProcedures to be consistent with architecture names in archinfo
| Python | bsd-2-clause | tyb0807/angr,angr/angr,axt/angr,f-prettyland/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,axt/angr,chubbymaggie/simuvex,axt/angr,iamahuman/angr,chubbymaggie/angr,chubbymaggie/angr,angr/angr,f-prettyland/angr,schieb/angr,angr/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/simuvex,iamahuman/angr,schie... | ---
+++
@@ -6,7 +6,7 @@
'X86': {
'fd': 0x38,
},
- 'X64': {
+ 'AMD64': {
'fd': 0x70,
},
} |
c9449516bc3bfd15873347d1233001c51939a5e6 | pipeline/utils/backend_helper.py | pipeline/utils/backend_helper.py | """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard config... | """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard config... | Fix the bad jobboard path. | Fix the bad jobboard path.
Change-Id: I3281babfa835d7d4b76f7f299887959fa5342e85
| Python | apache-2.0 | ethanbao/artman,ethanbao/artman,googleapis/artman,googleapis/artman,shinfan/artman,googleapis/artman | ---
+++
@@ -13,7 +13,7 @@
JB_CONF = {
'hosts': ZK_HOST,
'board': 'zookeeper',
- 'path': '/taskflow/99-bottles-demo',
+ 'path': '/taskflow/dev',
}
# Default persistence configuration. |
f8e89b105a69e624ef853d102310284f5441bae5 | QuantifiedDevOpenDashboardCommand.py | QuantifiedDevOpenDashboardCommand.py | import sublime, sublime_plugin, webbrowser
QD_URL = "http://app.quantifieddev.org"
class GoToQuantifiedDevDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "QuantifiedDev.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
... | import sublime, sublime_plugin, webbrowser
QD_URL = "https://app.quantifieddev.org"
class GoToQuantifiedDevDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "QuantifiedDev.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
... | Use https dashboard url when using 'Go to dashboard' | Use https dashboard url when using 'Go to dashboard'
| Python | apache-2.0 | 1self/sublime-text-plugin,1self/sublime-text-plugin,1self/sublime-text-plugin | ---
+++
@@ -1,7 +1,7 @@
import sublime, sublime_plugin, webbrowser
-QD_URL = "http://app.quantifieddev.org"
+QD_URL = "https://app.quantifieddev.org"
class GoToQuantifiedDevDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit): |
df638a33d6f0812a22bb775fded2d1790bd1e409 | router/config/settings.py | router/config/settings.py | import os
import sys
from salmon.server import SMTPReceiver, LMTPReceiver
sys.path.append('..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
# where to listen for incoming messages
if settings.SALMON_SERVER["type"] == "lmtp":
receiver = LMTPReceiver(socket=settings.SALMON_S... | import os
import sys
from salmon.server import SMTPReceiver, LMTPReceiver
sys.path.append('..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
import django
django.setup()
# where to listen for incoming messages
if settings.SALMON_SERVER["type"] == "lmtp":
receiver = LMTPRec... | Call `django.setup()` in router app | Call `django.setup()` in router app
This should have been there before, but somehow we managed to get away
without it :)
fixes #99
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen | ---
+++
@@ -7,6 +7,9 @@
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
+import django
+
+django.setup()
# where to listen for incoming messages
if settings.SALMON_SERVER["type"] == "lmtp": |
6590f92c1423ab37570857e2c6cc726e1a7fede7 | _setup_database.py | _setup_database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_player_data
from ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_p... | Introduce command line parameters for database setup script | Introduce command line parameters for database setup script
| Python | mit | leaffan/pynhldb | ---
+++
@@ -1,5 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+
+import argparse
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
@@ -13,13 +15,27 @@
if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description='Setup script ... |
4a6ccb58bade2cefc7baa9424f1747275adaa166 | antxetamedia/archive/filtersets.py | antxetamedia/archive/filtersets.py | from django_filters import FilterSet
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so be inclusive and always
# make gte and lte lookups instead of using gt or... | from django.utils.translation import ugettext_lazy as _
from django_filters import FilterSet, DateTimeFilter
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so ... | Add labels to the pub_date__lte pub_date__gte filters | Add labels to the pub_date__lte pub_date__gte filters
| Python | agpl-3.0 | GISAElkartea/amv2,GISAElkartea/amv2,GISAElkartea/amv2 | ---
+++
@@ -1,4 +1,6 @@
-from django_filters import FilterSet
+from django.utils.translation import ugettext_lazy as _
+
+from django_filters import FilterSet, DateTimeFilter
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
@@ -10,24 +12,21 @@
class NewsPodc... |
4375e1d72832f9672eaba87019be9b769eb69e78 | alg_hash_string.py | alg_hash_string.py | from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for c in a_str:
sum += ord(c)
return sum % table_siz... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size. ... | Add importing absolute_import & division from Prague | Add importing absolute_import & division from Prague
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -1,3 +1,5 @@
+from __future__ import absolute_import
+from __future__ import division
from __future__ import print_function
|
9a49ce93428d6e7bdfeebbed906a1868dd844169 | anycluster/urls.py | anycluster/urls.py | from django.conf.urls import patterns, url
from anycluster import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^grid/(\d+)/(\d+)/$', views.getGrid, name='getGrid'),
url(r'^kmeans/(\d+)/(\d+)/$', views.getPins, name='getPins'),
url(r'^getClusterContent/(\d+)/(\d+)/$', views.getClu... | from django.conf.urls import url
from anycluster import views
from django.conf import settings
urlpatterns = [
url(r'^grid/(\d+)/(\d+)/$', views.getGrid, name='getGrid'),
url(r'^kmeans/(\d+)/(\d+)/$', views.getPins, name='getPins'),
url(r'^getClusterContent/(\d+)/(\d+)/$', views.getClusterContent, name='ge... | Update url format to support Django 1.10 | Update url format to support Django 1.10 | Python | mit | biodiv/anycluster,biodiv/anycluster,biodiv/anycluster,biodiv/anycluster,biodiv/anycluster | ---
+++
@@ -1,10 +1,10 @@
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from anycluster import views
from django.conf import settings
-urlpatterns = patterns('',
+urlpatterns = [
url(r'^grid/(\d+)/(\d+)/$', views.getGrid, name='getGrid'),
url(r'^kmeans/(\d+)/(\d+)/$', vie... |
c5d4c0cbfced859407c5569d879cfb7b9815eb57 | alerts/lib/alert_plugin_set.py | alerts/lib/alert_plugin_set.py | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summa... | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summa... | Convert debug message into unicode string | Convert debug message into unicode string
| Python | mpl-2.0 | Phrozyn/MozDef,mozilla/MozDef,gdestuynder/MozDef,mozilla/MozDef,Phrozyn/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,gdestuynder/Mo... | ---
+++
@@ -10,7 +10,7 @@
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summary' in message:
- message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
+ ... |
aa8611e43d31e07b9105cca13e4cb9c80479679b | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | Implement UpperCamelCase name check for structs | Implement UpperCamelCase name check for structs
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor | ---
+++
@@ -14,7 +14,7 @@
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
- pass
+ self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ct... |
7106dd7d9fb9a4df94ac6694cf52f16a5b6677e7 | apps/feeds/models.py | apps/feeds/models.py | import datetime
from django.contrib import admin
from django.db import models
from django.db.models.signals import post_save
from activity.models import broadcast
class Entry(models.Model):
title = models.CharField(max_length=100)
published = models.DateTimeField(default=datetime.datetime.now())
url = m... | import datetime
from django.contrib import admin
from django.db import models
from django.db.models.signals import post_save
from activity.models import broadcast
class Entry(models.Model):
title = models.CharField(max_length=100)
published = models.DateTimeField(default=datetime.datetime.now())
url = m... | Remove errant reference to old link field | Remove errant reference to old link field
| Python | bsd-3-clause | mozilla/mozilla-ignite,mozilla/betafarm,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/mozilla-ignite | ---
+++
@@ -18,7 +18,7 @@
verbose_name_plural = u'entries'
def __unicode__(self):
- return u'%s -> %s' % (self.title, self.link)
+ return u'%s -> %s' % (self.title, self.url)
@property
def project(self): |
fe0867e5499b627e776d132d300d17b40858dcab | line_profiler.py | line_profiler.py | from cProfile import label
import marshal
from _line_profiler import LineProfiler as CLineProfiler
class LineProfiler(CLineProfiler):
""" A subclass of the C version solely to provide a decorator since Cython
does not have closures.
"""
def __call__(self, func):
""" Decorate a function to st... | from cProfile import label
import marshal
from _line_profiler import LineProfiler as CLineProfiler
class LineProfiler(CLineProfiler):
""" A subclass of the C version solely to provide a decorator since Cython
does not have closures.
"""
def __call__(self, func):
""" Decorate a function to st... | Add the typical run/runctx/runcall methods. | ENH: Add the typical run/runctx/runcall methods.
| Python | bsd-3-clause | amegianeg/line_profiler,jstasiak/line_profiler,dreampuf/lprofiler,dreampuf/lprofiler,eblur/line_profiler,jstasiak/line_profiler,ymero/line_profiler,eblur/line_profiler,certik/line_profiler,certik/line_profiler,amegianeg/line_profiler,Doctorhoenikker/line_profiler,jsalva/line_profiler,Doctorhoenikker/line_profiler,ymero... | ---
+++
@@ -37,3 +37,29 @@
finally:
f.close()
+ def run(self, cmd):
+ """ Profile a single executable statment in the main namespace.
+ """
+ import __main__
+ dict = __main__.__dict__
+ return self.runctx(cmd, dict, dict)
+
+ def runctx(self, cmd, glob... |
117e8c717e4555aa9ee015336c36af186c1b0a85 | src/ocspdash/web/blueprints/ui.py | src/ocspdash/web/blueprints/ui.py | # -*- coding: utf-8 -*-
# import nacl.exceptions
# import nacl.signing
from flask import Blueprint, current_app, render_template
"""The OCSPdash homepage UI blueprint."""
# from nacl.encoding import URLSafeBase64Encoder
# from nacl.signing import VerifyKey
__all__ = [
'ui',
]
ui = Blueprint('ui', __name__)
@u... | # -*- coding: utf-8 -*-
"""The OCSPdash homepage UI blueprint."""
from flask import Blueprint, current_app, render_template
__all__ = [
'ui',
]
ui = Blueprint('ui', __name__)
@ui.route('/')
def home():
"""Show the user the home view."""
payload = current_app.manager.get_payload()
return render_tem... | Remove unused imports from UI blueprint | Remove unused imports from UI blueprint
| Python | mit | scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash | ---
+++
@@ -1,12 +1,8 @@
# -*- coding: utf-8 -*-
-# import nacl.exceptions
-# import nacl.signing
-from flask import Blueprint, current_app, render_template
"""The OCSPdash homepage UI blueprint."""
-# from nacl.encoding import URLSafeBase64Encoder
-# from nacl.signing import VerifyKey
+from flask import Bluepr... |
5c0937993fdf34c96ccde3226c8e2a81efb381ce | troposphere/views/allocations.py | troposphere/views/allocations.py |
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missin... |
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missin... | Fix theme asset pathing in "no allocation" | Fix theme asset pathing in "no allocation"
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend | ---
+++
@@ -16,7 +16,7 @@
# populate with values `site_metadata` in the future
template_params = {}
- template_params['THEME_URL'] = "/themes/%s" % settings.THEME_NAME
+ template_params['THEME_URL'] = "/assets/theme"
template_params['ORG_NAME'] = settings.ORG_NAME
if hasattr(settings, "B... |
a86ca24eba556580a68695f4e0c2a55c8f5f3df1 | s3authbasic/views.py | s3authbasic/views.py | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... | Set the correct content type according to the amazon metadata | Set the correct content type according to the amazon metadata
| Python | mit | ant30/s3authbasic | ---
+++
@@ -16,6 +16,6 @@
s3file = request.s3.get_file(request.path)
if s3file is None:
return HTTPNotFound()
- response = Response(content_type='text/html')
+ response = Response(content_type=s3file.content_type)
response.app_iter = s3file
return response |
01eece3984534dcd124df5d753f461f276fd6b53 | ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py | ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py | """Tests for plugin.py."""
import pytest
from ckan.tests import factories
import ckan.tests.helpers as helpers
from ckan.plugins.toolkit import NotAuthorized
@pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes')
@pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context')
class Apicatalog_Rout... | """Tests for plugin.py."""
import pytest
from ckan.tests import factories
import ckan.tests.helpers as helpers
from ckan.plugins.toolkit import NotAuthorized
@pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes')
@pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context')
class ApicatalogRoute... | Fix some parameters for pytest to pickup the test | Fix some parameters for pytest to pickup the test
| Python | mit | vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog | ---
+++
@@ -7,7 +7,8 @@
@pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes')
@pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context')
-class Apicatalog_Routes_Tests():
+class ApicatalogRoutesTests(object):
+
def non_sysadmins_should_not_be_able_to_delete_subsystems(self):
... |
4ea0cb50353b3d7cb7ee3dd4d16397db95d75223 | salt/states/rsync.py | salt/states/rsync.py | # -*- coding: utf-8 -*-
'''
Operations with Rsync.
'''
import salt.utils
def __virtual__():
'''
Only if Rsync is available.
:return:
'''
return salt.utils.which('rsync') and 'rsync' or False
def synchronized(name, source, delete=False, force=False, update=False,
passwordfile=N... | # -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#
# 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 agr... | Add license and SUSE copyright | Add license and SUSE copyright
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -1,4 +1,18 @@
# -*- coding: utf-8 -*-
+#
+# Copyright 2015 SUSE LLC
+#
+# 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
+#
+# Un... |
1c057c8ea1e75909e90992784cff177ea1cb294b | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb'
| #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '607907aed2c1dcdd3b5968a756a990ba3f47bca7'
| Update libchromiumcontent for iframe sandbox. | Update libchromiumcontent for iframe sandbox.
| Python | mit | leolujuyi/electron,Zagorakiss/electron,noikiy/electron,the-ress/electron,Neron-X5/electron,JussMee15/electron,Jacobichou/electron,iftekeriba/electron,webmechanicx/electron,michaelchiche/electron,bobwol/electron,mjaniszew/electron,aliib/electron,trankmichael/electron,saronwei/electron,xiruibing/electron,jjz/electron,lee... | ---
+++
@@ -2,4 +2,4 @@
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb'
+LIBCHROMIUMCONTENT_COMMIT = '607907aed2c1dcdd3b5968a756a990ba3f47bca7' |
d874ba80db5bedb67b0b50cea431321c77b10f5d | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'ea1a7e85a3de1878e5656110c76f4d2d8af41c6e'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '2cf80c1743e370c12eb7bf078eb425f3cc355383'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Upgrade libchromiumcontent for gin headers. | Upgrade libchromiumcontent for gin headers.
| Python | mit | icattlecoder/electron,ervinb/electron,pandoraui/electron,jlord/electron,Rokt33r/electron,fireball-x/atom-shell,michaelchiche/electron,gamedevsam/electron,tonyganch/electron,noikiy/electron,nicobot/electron,leftstick/electron,bobwol/electron,maxogden/atom-shell,bobwol/electron,GoooIce/electron,soulteary/electron,jcblw/e... | ---
+++
@@ -5,7 +5,7 @@
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = 'ea1a7e85a3de1878e5656110c76f4d2d8af41c6e'
+LIBCHROMIUMCONTENT_COMMIT = '2cf80c1743e370c12eb7bf078eb425f3cc355383'
ARCH = {
'cygwin': '32bit', |
e3079cdf31f6fb13ca9d91de313301c8a76d3cd8 | backend/unichat/models/user.py | backend/unichat/models/user.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unich... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unich... | Decrease cookie length in User model from 255 to 100 chars | Decrease cookie length in User model from 255 to 100 chars
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | ---
+++
@@ -43,7 +43,7 @@
cookie = models.CharField(
default='',
- max_length=255,
+ max_length=100,
db_index=True,
help_text=("The user's active cookie.")
) |
4953021eedbd73dc3d66455c5dff352a852d6474 | test/test_integration.py | test/test_integration.py | import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response = connRoute... | import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 404)
... | Add debug info to the test | Add debug info to the test | Python | apache-2.0 | dhiaayachi/dynx,dhiaayachi/dynx | ---
+++
@@ -5,7 +5,6 @@
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
- connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(respon... |
0ec2c192a3f8428bb487add6a70aef100f02c036 | segpy/portability.py | segpy/portability.py | import os
import sys
EMPTY_BYTE_STRING = b'' if sys.version_info >= (3, 0) else ''
if sys.version_info >= (3, 0):
long_int = int
else:
long_int = long
if sys.version_info >= (3, 0):
def byte_string(integers):
return bytes(integers)
else:
def byte_string(integers):
return EMPTY_BYTE_... | import os
import sys
EMPTY_BYTE_STRING = b'' if sys.version_info >= (3, 0) else ''
if sys.version_info >= (3, 0):
def byte_string(integers):
return bytes(integers)
else:
def byte_string(integers):
return EMPTY_BYTE_STRING.join(chr(i) for i in integers)
if sys.version_info >= (3, 0):
imp... | Remove Python 2.7 crutch for int/long | Remove Python 2.7 crutch for int/long
| Python | agpl-3.0 | hohogpb/segpy,abingham/segpy,kjellkongsvik/segpy,Kramer477/segpy,kwinkunks/segpy,stevejpurves/segpy,asbjorn/segpy | ---
+++
@@ -2,12 +2,6 @@
import sys
EMPTY_BYTE_STRING = b'' if sys.version_info >= (3, 0) else ''
-
-
-if sys.version_info >= (3, 0):
- long_int = int
-else:
- long_int = long
if sys.version_info >= (3, 0): |
da86340568ff03c6e612aa68a5cd9f275cbf3375 | coda/coda_replication/factories.py | coda/coda_replication/factories.py | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.QueueEntry
ark = factory.Sequence(lambda n: 'ark:/00001/id{... | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n))
bytes = fuzzy.FuzzyInteger(100000... | Move the QueueEntryFactory Meta class definition below the attributes per the Django code style guide. | Move the QueueEntryFactory Meta class definition below the attributes per the Django code style guide.
| Python | bsd-3-clause | unt-libraries/coda,unt-libraries/coda,unt-libraries/coda,unt-libraries/coda | ---
+++
@@ -10,10 +10,6 @@
class QueueEntryFactory(factory.django.DjangoModelFactory):
-
- class Meta:
- model = models.QueueEntry
-
ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n))
bytes = fuzzy.FuzzyInteger(100000000)
files = fuzzy.FuzzyInteger(50, 500)
@@ -22,3 +18,6 @@
... |
72ec6a22f94ca1744d2241202f33c0bc777521ca | supplements/fixtures/factories.py | supplements/fixtures/factories.py | # making a bet that factory_boy will pan out as we get more data
import factory
from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement
DEFAULT_INGREDIENT_NAME = 'Leucine'
DEFAULT_INGREDIENT_HL_MINUTE = 50
DEFAULT_MEASUREMENT_NAME = 'milligram'
DEFAULT_MEASUREMENT_SHORT_NAME = 'mg'
... | # making a bet that factory_boy will pan out as we get more data
import factory
from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement
DEFAULT_INGREDIENT_NAME = 'Leucine'
DEFAULT_INGREDIENT_HL_MINUTE = 50
DEFAULT_MEASUREMENT_NAME = 'milligram'
DEFAULT_MEASUREMENT_SHORT_NAME = 'mg'
... | Swap out native factory.Factory with Django specific factory .... now all factory() calls actually save versus ... before nasty assumption | Swap out native factory.Factory with Django specific factory .... now all factory() calls actually save versus ... before nasty assumption
| Python | mit | jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself | ---
+++
@@ -12,7 +12,7 @@
DEFAULT_SUPPLEMENT_NAME = 'BCAA'
-class IngredientFactory(factory.Factory):
+class IngredientFactory(factory.DjangoModelFactory):
class Meta:
model = Ingredient
@@ -20,14 +20,14 @@
half_life_minutes = DEFAULT_INGREDIENT_HL_MINUTE
-class MeasurementFactory(factor... |
3e1f1e515b4392d98fe221ce4c14daefc531a1fe | tests/test_compatibility/tests.py | tests/test_compatibility/tests.py | """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class ... | """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class ... | Test for compatibility of primary key AutoField | Test for compatibility of primary key AutoField
| Python | mit | philchristensen/django-salesforce,hynekcer/django-salesforce,django-salesforce/django-salesforce,chromakey/django-salesforce,philchristensen/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromak... | ---
+++
@@ -21,3 +21,13 @@
repr(test_lead.__dict__)
finally:
test_lead.delete()
+
+
+class DjangoCompatibility(TestCase):
+ def test_autofield_compatible(self):
+ """Test that the light weigh AutoField is compatible in all Django ver."""
+ primary_key = [x for x in Lead._meta.fields if x.primary_key][0]
... |
20fce7b482fd11a65494014e14aabecbe4e87683 | src/cmt/standard_names/snbuild.py | src/cmt/standard_names/snbuild.py | #! /usr/bin/env python
"""
Example usage:
snbuild data/models.yaml data/scraped.yaml \
> standard_names/data/standard_names.yaml
"""
import os
from . import (from_model_file, FORMATTERS, Collection)
def main():
"""
Build a list of CSDMS standard names for YAML description files.
"""
i... | #! /usr/bin/env python
"""
Example usage:
snbuild data/models.yaml data/scraped.yaml \
> standard_names/data/standard_names.yaml
"""
import os
from . import (from_model_file, FORMATTERS, Collection)
from .io import from_list_file
def main():
"""
Build a list of CSDMS standard names for YAML d... | Read names line-by-line from a plain text file. | Read names line-by-line from a plain text file.
| Python | mit | csdms/standard_names,csdms/standard_names | ---
+++
@@ -7,6 +7,7 @@
import os
from . import (from_model_file, FORMATTERS, Collection)
+from .io import from_list_file
def main():
@@ -23,7 +24,7 @@
names = Collection()
for model_file in args.file:
- names |= from_model_file(model_file)
+ names |= from_list_file(model_file)
... |
4b8fbe2914aec5ddcf7f63c6b7ca2244ec022084 | tests/test_crossbuild.py | tests/test_crossbuild.py | from mock import patch
from unittest import TestCase
from crossbuild import (
main,
)
class CrossBuildTestCase(TestCase):
def test_main_setup(self):
with patch('crossbuild.setup_cross_building') as mock:
main(['-d', '-v', 'setup', '--build-dir', './foo'])
args, kwargs = mock.call... | from mock import patch
from unittest import TestCase
from crossbuild import (
main,
)
class CrossBuildTestCase(TestCase):
def test_main_setup(self):
with patch('crossbuild.setup_cross_building') as mock:
main(['-d', '-v', 'setup', '--build-dir', './foo'])
args, kwargs = mock.call... | Add main osx-client command test. | Add main osx-client command test. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -15,9 +15,23 @@
self.assertEqual(('./foo', ), args)
self.assertEqual({'dry_run': True, 'verbose': True}, kwargs)
+ def test_main_osx_clientt(self):
+ with patch('crossbuild.build_osx_client') as mock:
+ main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']... |
abdfef81c3146b720c561eaedf8592cd640262a0 | falcom/table.py | falcom/table.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | Split input text on init | Split input text on init
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -9,11 +9,13 @@
def __init__ (self, tab_separated_text = None):
if tab_separated_text:
- self.text = tab_separated_text.rstrip("\n")
+ self.text = tab_separated_text
self.__raise_error_if_carriage_returns()
else:
self.text = tab_sepa... |
4d0e6265911199b1376d0f52e249625180a0500d | third_party/py/gflags/__init__.py | third_party/py/gflags/__init__.py | # gflags raises DuplicateFlagError when defining default flags from packages
# with different names, so this pseudo-package must mimic the core gflags
# package name.
__name__ += ".gflags" # i.e. "third_party.py.gflags.gflags"
from gflags import *
| from __future__ import absolute_import
from gflags import *
| Use PEP 328 absolute import for third_party python gflags. | Use PEP 328 absolute import for third_party python gflags.
Commit d926bc40260549b997a6a5a1e82d9e7999dbb65e fixed a bug (#4206, #4208) in
the third_party python gflags pseudo-package but added excessive runtime
warnings (see #4212). Using the python PEP 328 (absolute import) implementation
eliminates these warnings whi... | Python | apache-2.0 | meteorcloudy/bazel,perezd/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,akira-baruah/bazel,davidzchen/bazel,akira-baruah/bazel,ulfjack/bazel,twitter-forks/bazel,safarmer/bazel,aehlig/bazel,dslomov/bazel-windows,katre/bazel,bazelbuild/bazel,twitter-forks/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,ButterflyNetwork/b... | ---
+++
@@ -1,6 +1,2 @@
-# gflags raises DuplicateFlagError when defining default flags from packages
-# with different names, so this pseudo-package must mimic the core gflags
-# package name.
-__name__ += ".gflags" # i.e. "third_party.py.gflags.gflags"
-
+from __future__ import absolute_import
from gflags import ... |
ab14f4c86fca6daab9d67cc9b4c3581d76d5635a | foster/utils.py | foster/utils.py | import os.path
import shutil
from string import Template
PIKE_DIR = os.path.dirname(__file__)
SAMPLES_DIR = os.path.join(PIKE_DIR, 'samples')
def sample_path(sample):
path = os.path.join(SAMPLES_DIR, sample)
return os.path.realpath(path)
def copy_sample(sample, target):
source = os.path.join(SAMPLES_DIR... | import os.path
import shutil
from string import Template
PIKE_DIR = os.path.dirname(__file__)
SAMPLES_DIR = os.path.join(PIKE_DIR, 'samples')
def sample_path(sample):
path = os.path.join(SAMPLES_DIR, sample)
return os.path.realpath(path)
def copy_sample(sample, target):
source = os.path.join(SAMPLES_D... | Fix whitespace in foster/util.py to better comply with PEP8 | Fix whitespace in foster/util.py to better comply with PEP8
| Python | mit | hugollm/foster,hugollm/foster | ---
+++
@@ -6,13 +6,16 @@
PIKE_DIR = os.path.dirname(__file__)
SAMPLES_DIR = os.path.join(PIKE_DIR, 'samples')
+
def sample_path(sample):
path = os.path.join(SAMPLES_DIR, sample)
return os.path.realpath(path)
+
def copy_sample(sample, target):
source = os.path.join(SAMPLES_DIR, sample)
shu... |
26ffa0cdd1389e2a364531cd20e9f37ee1565cce | base/view_utils.py | base/view_utils.py | # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
... | # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
... | Use 'o' as the order by parameter in clean_query_string | Use 'o' as the order by parameter in clean_query_string
| Python | mit | magnet-cl/django-project-template-py3,Angoreher/xcero,Angoreher/xcero,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,Angoreher/xcero,Angoreher/xcero | ---
+++
@@ -24,7 +24,7 @@
clean_query_set = request.GET.copy()
clean_query_set = dict(
- (k, v) for k, v in request.GET.items() if not k.startswith('o')
+ (k, v) for k, v in request.GET.items() if k != 'o'
)
try: |
e3505746e0f09c103fd875a24ded85290272cfb9 | django_local_apps/management/commands/docker_exec.py | django_local_apps/management/commands/docker_exec.py | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | Print execution result for docker. | Print execution result for docker.
| Python | bsd-3-clause | weijia/django-local-apps,weijia/django-local-apps | ---
+++
@@ -23,7 +23,7 @@
print(self.options["path_and_params"])
client = docker.from_env()
container = client.containers.get(self.options["container_id"][0])
- container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])
+ print(container.ex... |
c83e2383ea38dc8a0b5ce8e24bdfc2e9c2ba62bd | concourse/scripts/build_with_orca.py | concourse/scripts/build_with_orca.py | #!/usr/bin/python2
import optparse
import subprocess
import sys
from gporca import GporcaCommon
def make():
return subprocess.call(["make",
"-j" + str(num_cpus())], cwd="gpdb_src")
def install(output_dir):
subprocess.call(["make", "install"], cwd="gpdb_src")
subprocess.call("m... | #!/usr/bin/python2
import optparse
import subprocess
import sys
from gporca import GporcaCommon
def make():
ciCommon = GporcaCommon()
return subprocess.call(["make",
"-j" + str(ciCommon.num_cpus())], cwd="gpdb_src")
def install(output_dir):
subprocess.call(["make", "install"],... | Fix councourse script for gpdb | Fix councourse script for gpdb
| Python | apache-2.0 | ashwinstar/gpdb,kaknikhil/gpdb,xuegang/gpdb,kaknikhil/gpdb,xinzweb/gpdb,lisakowen/gpdb,ahachete/gpdb,randomtask1155/gpdb,janebeckman/gpdb,CraigHarris/gpdb,kaknikhil/gpdb,Chibin/gpdb,tangp3/gpdb,lpetrov-pivotal/gpdb,janebeckman/gpdb,rvs/gpdb,royc1/gpdb,chrishajas/gpdb,ashwinstar/gpdb,0x0FFF/gpdb,50wu/gpdb,zaksoup/gpdb,g... | ---
+++
@@ -6,8 +6,9 @@
from gporca import GporcaCommon
def make():
+ ciCommon = GporcaCommon()
return subprocess.call(["make",
- "-j" + str(num_cpus())], cwd="gpdb_src")
+ "-j" + str(ciCommon.num_cpus())], cwd="gpdb_src")
def install(output_dir):
... |
d3bcd6426bc323a876ffab6ac46fe117f9e5ab13 | opps/__init__.py | opps/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"... | Remove django installed apps init opps | Remove django installed apps init opps
| Python | mit | YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps | ---
+++
@@ -1,6 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-from django.conf import settings
VERSION = (0, 1, 2)
@@ -13,13 +12,3 @@
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"
__copyright__ = u"Copyright 2013, YACOWS"
-
-settings.INSTALLED_APPS += ('opps.article',
- ... |
cf5b3e76f89e2430fa482a1fb4a163e6b367928f | opps/__init__.py | opps/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pkg_resources
pkg_resources.declare_namespace(__name__)
VERSION = (0, 2, 0)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Open Source Content Management Platform - CMS for the "
u"magazines, newspappers websites and porta... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pkg_resources
pkg_resources.declare_namespace(__name__)
VERSION = (0, 2, 1)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Open Source Content Management Platform - CMS for the "
u"magazines, newspappers websites and porta... | Set new developer version 0.2.1 | Set new developer version 0.2.1
| Python | mit | williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps | ---
+++
@@ -4,7 +4,7 @@
pkg_resources.declare_namespace(__name__)
-VERSION = (0, 2, 0)
+VERSION = (0, 2, 1)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development" |
2a80bcdc9fd7ad85888ac9edf53ece8d784db632 | c10kdemo/settings.py | c10kdemo/settings.py | # Django settings for c10kdemo project.
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = True
INSTALLED_APPS = (
'c10ktools',
'gameoflife',
'django.contrib.staticfiles',
)
LOGGING = {
'version': 1,
'handlers': ... | # Django settings for c10kdemo project.
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = True
INSTALLED_APPS = (
'c10ktools',
'gameoflife',
'django.contrib.staticfiles',
)
LOGGING = {
'disable_existing_loggers': Fa... | Make it easier to debug with logging. | Make it easier to debug with logging.
| Python | bsd-3-clause | aaugustin/django-c10k-demo,gogobook/django-c10k-demo,phamvanhung2e123/django-c10k-demo,phamvanhung2e123/django-c10k-demo,gogobook/django-c10k-demo,aaugustin/django-c10k-demo,aaugustin/django-c10k-demo,gogobook/django-c10k-demo,phamvanhung2e123/django-c10k-demo | ---
+++
@@ -18,6 +18,7 @@
)
LOGGING = {
+ 'disable_existing_loggers': False,
'version': 1,
'handlers': {
'console': { |
b973c6abe4d325b08278822f85f72ebc1761a825 | changes/constants.py | changes/constants.py | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
errored = 4
aborted = 5
ti... | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
aborted = 5
timedout = 6
... | Remove errored state (lets rely on a single failure state) | Remove errored state (lets rely on a single failure state)
| Python | apache-2.0 | bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes | ---
+++
@@ -17,7 +17,6 @@
passed = 1
failed = 2
skipped = 3
- errored = 4
aborted = 5
timedout = 6
@@ -51,7 +50,6 @@
Result.passed: 'Passed',
Result.failed: 'Failed',
Result.skipped: 'Skipped',
- Result.errored: 'Errored',
Result.aborted: 'Aborted',
Result.tim... |
b16e9e2f3a349b53505a3f60409b65e139c62356 | alg_prim_minimum_spanning_tree.py | alg_prim_minimum_spanning_tree.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim():
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim(w_graph_d):
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E... | Write init setting and pick a start | Write init setting and pick a start
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -7,11 +7,23 @@
from ds_min_priority_queue_tuple import MinPriorityQueue
-def prim():
+def prim(w_graph_d):
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|).
"""
+ min_pq = MinPriorityQueue()
+
+ key_d = {v: np.inf for v in w_... |
31df2bef09c151479b53ed514c55a600a3862b46 | storage/elasticsearch_storage.py | storage/elasticsearch_storage.py | from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
self.password = config_dict['password']... | import json
from storage import Storage
TASKS = [
{'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
{'task_id': 2, 'task_status': 'Pending', 'report_id': None},
]
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163... | Add mocks for es storage | Add mocks for es storage
| Python | mpl-2.0 | mitre/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,awest1339/multiscanner,mitre/multiscanner,mitre/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner | ---
+++
@@ -1,4 +1,15 @@
+import json
from storage import Storage
+
+TASKS = [
+ {'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
+ {'task_id': 2, 'task_status': 'Pending', 'report_id': None},
+]
+REPORTS = [
+ {'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6... |
294f5331a2a6d1f4cd55b87df4409672c6b2c652 | storage/elasticsearch_storage.py | storage/elasticsearch_storage.py | from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
self.password = config_dict['password']... | import json
from storage import Storage
TASKS = [
{'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
{'task_id': 2, 'task_status': 'Pending', 'report_id': None},
]
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163... | Add mocks for es storage | Add mocks for es storage
| Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,mitre/multiscanner,MITRECND/multiscanner,awest1339/multiscanner | ---
+++
@@ -1,4 +1,15 @@
+import json
from storage import Storage
+
+TASKS = [
+ {'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
+ {'task_id': 2, 'task_status': 'Pending', 'report_id': None},
+]
+REPORTS = [
+ {'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6... |
0207b0ea61050d8728e084277b14015bd92a8beb | tests/integration/test_kinesis.py | tests/integration/test_kinesis.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | Switch kinesis integ tests over to client interface | Switch kinesis integ tests over to client interface
| Python | apache-2.0 | pplu/botocore,boto/botocore | ---
+++
@@ -10,9 +10,7 @@
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
-
from tests import unittest
-import itertools
import botocore.session
@... |
fba94685ed3934196c4c36557578849aa2c7aeb0 | app.py | app.py | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... | Convert all the ids to strings | Convert all the ids to strings
| Python | mit | nickfrostatx/infection,nickfrostatx/infection | ---
+++
@@ -15,10 +15,10 @@
if json_users is None:
raise BadRequest('You need to supply a JSON user graph.')
try:
- users = dict((id, User(id)) for id in json_users)
+ users = dict((str(id), User(str(id))) for id in json_users)
for id in json_users:
for adjacent_... |
b32602f4af337ce9952288fd7080d7f189440f0d | sweettooth/review/urls.py | sweettooth/review/urls.py |
from django.conf.urls.defaults import patterns, url
from django.views.generic import ListView
from review import views
from extensions.models import ExtensionVersion, STATUS_LOCKED
urlpatterns = patterns('',
url(r'^$', ListView.as_view(queryset=ExtensionVersion.objects.filter(status=STATUS_LOCKED),
... |
from django.conf.urls.defaults import patterns, url
from django.views.generic import ListView
from review import views
from extensions.models import ExtensionVersion, STATUS_LOCKED
urlpatterns = patterns('',
url(r'^$', ListView.as_view(queryset=ExtensionVersion.objects.filter(status=STATUS_LOCKED),
... | Use raw strings for regexp URLs. | Use raw strings for regexp URLs.
| Python | agpl-3.0 | GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,magcius/sweettooth,GNOME/extensions-web | ---
+++
@@ -10,7 +10,7 @@
context_object_name="versions",
template_name="review/list.html"), name='review-list'),
- url('^ajax/v/(?P<pk>\d+)', views.AjaxGetFilesView.as_view(), name='review-ajax-files'),
- url('^submit/(?P<pk>\d+)', views.Submi... |
ffe584928616607be9685e1df4437a9715ce68be | bot.py | bot.py | #!/usr/bin/env python
from ConfigParser import ConfigParser
import logging
import getpass
from bot.bot import Bot
logging.basicConfig(level=logging.DEBUG,
format=u'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if __name__ == '__main__':
config_file = u'config.ini'
config = Conf... | #!/usr/bin/env python
from ConfigParser import ConfigParser
import logging
import getpass
import os
from bot.bot import Bot
logging.basicConfig(level=logging.DEBUG,
format=u'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if __name__ == '__main__':
config_file = u'config.ini'
con... | Enable passing password through env variable | Enable passing password through env variable
| Python | mit | LipuFei/team-hipchat-bot,LipuFei/team-hipchat-bot | ---
+++
@@ -2,6 +2,7 @@
from ConfigParser import ConfigParser
import logging
import getpass
+import os
from bot.bot import Bot
@@ -15,9 +16,12 @@
config = ConfigParser()
config.read([config_file])
- # get password
- print u"Please input your Hipchat password:"
- password = getpass.getpass... |
5c9b98319b3537ef6287bc28353cd72748f9e1a8 | profile_collection/startup/99-bluesky.py | profile_collection/startup/99-bluesky.py | # Configure bluesky default detectors with this:
# These are the new "default detectors"
gs.DETS = [em_ch1, em_ch2, em_ch3, em_ch4]
| # Configure bluesky default detectors with this:
# These are the new "default detectors"
gs.DETS = [em]
gs.TABLE_COLS.append('em_chan21')
gs.PLOT_Y = 'em_ch1'
gs.TEMP_CONTROLLER = cs700
gs.TH_MOTOR = th
gs.TTH_MOTOR = tth
import time as ttime
# We probably already have these imports, but we use them below
# so I'm im... | Add multiple settings for bluesky | Add multiple settings for bluesky
- Define a data validator to run at the end of a scan.
- Set up default detectors and plot and table settles for SPEC API.
| Python | bsd-2-clause | NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd | ---
+++
@@ -1,3 +1,45 @@
# Configure bluesky default detectors with this:
# These are the new "default detectors"
-gs.DETS = [em_ch1, em_ch2, em_ch3, em_ch4]
+gs.DETS = [em]
+gs.TABLE_COLS.append('em_chan21')
+gs.PLOT_Y = 'em_ch1'
+gs.TEMP_CONTROLLER = cs700
+gs.TH_MOTOR = th
+gs.TTH_MOTOR = tth
+
+
+import time as... |
55d0fa9b834e6400d48293c80e557c27f5cc4181 | yowsup/structs/protocolentity.py | yowsup/structs/protocolentity.py | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, ... | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, ... | Print protocoltreenode on assertion failure | Print protocoltreenode on assertion failure
| Python | mit | biji/yowsup,ongair/yowsup | ---
+++
@@ -38,5 +38,11 @@
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
- self.assertEqual(entity.toProtocolTreeNode(), self.node)
+ try:
+ self.assertEqual(entity.toProtocolTreeNode(), self.node)
+ except:
+ print(e... |
6ec4307173f3eafa87fd063978914bf5816ecb0a | reports/utils.py | reports/utils.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemF... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemF... | Increase default top margin to account for two line graph titles. | Increase default top margin to account for two line graph titles.
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy | ---
+++
@@ -15,7 +15,7 @@
'"Segoe UI Symbol"',
'size': 14,
},
- 'margin': {'b': 40, 't': 40},
+ 'margin': {'b': 40, 't': 80},
'xaxis': {
'titlefont': {
'color': 'rgba(0, 0, 0, 0.54)' |
24c5497b0c91ce032fb4cf99e79fffc5fa27cb84 | push/management/commands/startbatches.py | push/management/commands/startbatches.py | # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Comma... | # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Comma... | Update batch execute for conditions | Update batch execute for conditions
| Python | apache-2.0 | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas | ---
+++
@@ -13,7 +13,7 @@
def handle(self, *args, **kwargs):
now = '{0:%Y/%m/%d %H:%M}'.format(datetime.now())
- notifications = NotificationModel.objects.filter(execute_datetime = now)
+ notifications = NotificationModel.objects.filter(execute_datetime = now, is_sent = False)
... |
056cb6d5dff67fe029a080abeaba36faee5cff60 | lib/test_util.py | lib/test_util.py | from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
def fetch_documents_from_url(url):
'''
Retrieve newebe documents from a givent url
'''... | from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
class NewebeClient(HTTPClient):
'''
Tornado client wrapper to write POST, PUT and delete request faster.
'''... | Make newebe HTTP client for easier requesting | Make newebe HTTP client for easier requesting
| Python | agpl-3.0 | gelnior/newebe,gelnior/newebe,gelnior/newebe,gelnior/newebe | ---
+++
@@ -4,20 +4,36 @@
from newebe.settings import TORNADO_PORT
-client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
-def fetch_documents_from_url(url):
+class NewebeClient(HTTPClient):
'''
- Retrieve newebe documents from a givent url
+ Tornado client wrapper to write POST, P... |
be0ca3d4a1759fd68f0360fb3b6fe06cdc4cf7ea | test/test_blacklist_integrity.py | test/test_blacklist_integrity.py | #!/usr/bin/env python3
from glob import glob
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file, lineno)))
... | #!/usr/bin/env python3
from glob import glob
def test_blacklist_integrity():
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
seen = dict()
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
... | Check blacklist against duplicate entries as well | Check blacklist against duplicate entries as well
Additionally, refactor into a def test_* to run like the other unit tests.
| Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | ---
+++
@@ -2,12 +2,19 @@
from glob import glob
-for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
- with open(bl_file, 'r') as lines:
- for lineno, line in enumerate(lines, 1):
- if line.endswith('\r\n'):
- raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file... |
c5e47e61a6b51da99126a9faa4064a621acf017c | tests/handhistory/speed_tests.py | tests/handhistory/speed_tests.py | from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from handhistory import PokerStarsHandHistory; "
f"from stars_hands import HAND{hand... | from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from poker.room.pokerstars import PokerStarsHandHistory; "
f"from tests.handhistory.... | Make handhistory speed test work from root dir | Make handhistory speed test work from root dir
| Python | mit | pokerregion/poker | ---
+++
@@ -5,12 +5,12 @@
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
- setup="from handhistory import PokerStarsHandHistory; "
- f"from stars_hands import HAND{handnr}")
+ setup="from po... |
221bb27796036b348c5cf0fd06a0d57984b3591c | tests/integ/test_basic.py | tests/integ/test_basic.py | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | Rename integration test model names for debugging in console | Rename integration test model names for debugging in console
| Python | mit | numberoverzero/bloop,numberoverzero/bloop | ---
+++
@@ -35,21 +35,21 @@
def test_projection_overlap(engine):
- class Model(BaseModel):
+ class ProjectionOverlap(BaseModel):
hash = Column(Integer, hash_key=True)
range = Column(Integer, range_key=True)
other = Column(Integer)
by_other = GlobalSecondaryIndex(projec... |
c33b876c664178de92099b6553a6030789bdaaa4 | app/v2/templates/get_templates.py | app/v2/templates/get_templates.py | from flask import jsonify, request
from jsonschema.exceptions import ValidationError
from app import api_user
from app.dao import templates_dao
from app.schema_validation import validate
from app.v2.templates import v2_templates_blueprint
from app.v2.templates.templates_schemas import get_all_template_request
@v2_te... | from flask import jsonify, request
from jsonschema.exceptions import ValidationError
from app import api_user
from app.dao import templates_dao
from app.schema_validation import validate
from app.v2.templates import v2_templates_blueprint
from app.v2.templates.templates_schemas import get_all_template_request
@v2_te... | Remove get all template print | Remove get all template print
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -14,8 +14,6 @@
templates = templates_dao.dao_get_all_templates_for_service(api_user.service_id)
- print(templates)
-
return jsonify(
templates=[template.serialize() for template in templates]
), 200 |
f364b55a643c2768f80cb559eb0ec1988aa884c8 | tests/htmlgeneration_test.py | tests/htmlgeneration_test.py | from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
do... | from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
... | Add test just for paragraph HTML generation | Add test just for paragraph HTML generation
| Python | bsd-2-clause | mwilliamson/wordbridge | ---
+++
@@ -5,7 +5,6 @@
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
-generator = HtmlGenerator()
html = HtmlBuilder()
@istest
@@ -26,4 +25,18 @@
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
+
+ ... |
f1dd26bfb449f8bba69f93cae02ab904e0a9cba0 | tasks/hello_world.py | tasks/hello_world.py | import json
import pystache
class HelloWorld():
def __init__(self):
with open('models/hello_world.json') as config_file:
self.config = json.load(config_file)
self.message = self.config['message']
def process(self):
renderer = pystache.Renderer(search_dirs='templates')
... | import json
import pystache
class HelloWorld():
def __init__(self):
with open('models/hello_world.json') as config_file:
# Map JSON properties to this object
self.__dict__.update(json.load(config_file))
def process(self):
renderer = pystache.Renderer(search_dirs='templ... | Copy config settings to task object automatically | Copy config settings to task object automatically
| Python | mit | wpkita/automation-station,wpkita/automation-station,wpkita/automation-station | ---
+++
@@ -5,8 +5,8 @@
class HelloWorld():
def __init__(self):
with open('models/hello_world.json') as config_file:
- self.config = json.load(config_file)
- self.message = self.config['message']
+ # Map JSON properties to this object
+ self.__dict__.update(j... |
3f5a6d6cbf959cccddd2cb944eb93cd8f963f4a4 | tools/cr/cr/actions/linux.py | tools/cr/cr/actions/linux.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux pl... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux pl... | Fix the run command on Linux | cr: Fix the run command on Linux
TEST=cr run chrome
NOTRY=true
Review URL: https://codereview.chromium.org/105313004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@240638 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | PeterWangIntel/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/c... | ---
+++
@@ -22,7 +22,7 @@
print '**WARNING** Kill not yet implemented on linux'
def Run(self, context, target, arguments):
- cr.Host.Execute(target, ['{CR_BINARY}', '{CR_RUN_ARGUMENTS}'] + arguments)
+ cr.Host.Execute(target, '{CR_BINARY}', '{CR_RUN_ARGUMENTS}', *arguments)
def Test(self, context... |
556054ecbaa265b8e734860f3393acf3bc3e840e | Lib/importlib/test/import_/util.py | Lib/importlib/test/import_/util.py | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._... | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._... | Use the public API, not a private one. | Use the public API, not a private one.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -12,7 +12,7 @@
if using___import__:
return __import__(*args, **kwargs)
else:
- return importlib._bootstrap.__import__(*args, **kwargs)
+ return importlib.__import__(*args, **kwargs)
importlib_only = unittest.skipIf(using___import__, "importlib-specific test") |
44f56e0c6b53849f7cb97c595e844b706864a780 | ui/tcmui/debug/middleware.py | ui/tcmui/debug/middleware.py | import logging
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpResponse
log = logging.getLogger("tcmui.core.middleware.RequestLogMiddleware")
class RequestLogMiddleware(object):
def process_request(self, request):
log.debug(
... | import logging
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpResponse
log = logging.getLogger("tcmui.core.middleware.RequestLogMiddleware")
class RequestLogMiddleware(object):
def process_request(self, request):
log.debug(
... | Make debug AJAX tracebacks more readable in HTML. | Make debug AJAX tracebacks more readable in HTML.
| Python | bsd-2-clause | bobsilverberg/moztrap,mozilla/moztrap,shinglyu/moztrap,shinglyu/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,bobsilverberg/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mozilla/moztrap,mccarrmb/moztrap,mozilla/moztrap... | ---
+++
@@ -32,4 +32,4 @@
def process_exception(self, request, *args, **kwargs):
if request.is_ajax():
import traceback
- return HttpResponse(traceback.format_exc())
+ return HttpResponse(traceback.format_exc().replace("\n", "<br>\n")) |
6dfed291a253174672d7003700ab770aabcacae4 | backend/breach/models/__init__.py | backend/breach/models/__init__.py | from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| __all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| Add __all__ to models init file | Add __all__ to models init file
| Python | mit | dimriou/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dion... | ---
+++
@@ -1,3 +1,4 @@
+__all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round |
9ee87588b2d6694cafea6415af50110ba5263d3e | bitbots_body_behaviour/src/bitbots_body_behaviour/body/actions/wait.py | bitbots_body_behaviour/src/bitbots_body_behaviour/body/actions/wait.py | # -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
from bitbots_stackmachine.abstract_action_module import Abstra... | # -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
from bitbots_stackmachine.abstract_action_module import Abstra... | Fix Bug in Wait logic | Fix Bug in Wait logic
| Python | bsd-3-clause | bit-bots/bitbots_behaviour | ---
+++
@@ -24,5 +24,5 @@
connector.blackboard.set_head_duty(HeadMode.BALL_MODE)
self.push(Stand)
- if self.time > rospy.get_time():
+ if self.time < rospy.get_time():
self.pop() |
df7c783937d90b74c9b477b100709ed04ac0133e | monolithe/vanilla/sphinx/conf.py | monolithe/vanilla/sphinx/conf.py | # -*- coding: utf-8 -*-
import sys
import os
import sphinx_rtd_theme
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon']
add_module_names = False
source_suffix = '.rst'
master_doc = 'index'
project = u'vspk'
copyright = u'2015, Nuage Networks'
version = ''
release = ''
exclude_pattern... | # -*- coding: utf-8 -*-
import sys
import os
import sphinx_rtd_theme
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon']
add_module_names = False
source_suffix = '.rst'
master_doc = 'index'
project = u'vspk'
copyright = u'2015, Nuage Networks'
version = ''
release = ''
exclude_patterns =... | Use new import for napolean | Use new import for napolean
| Python | bsd-3-clause | nuagenetworks/monolithe,little-dude/monolithe,little-dude/monolithe,nuagenetworks/monolithe,little-dude/monolithe,nuagenetworks/monolithe | ---
+++
@@ -3,7 +3,7 @@
import os
import sphinx_rtd_theme
-extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon']
+extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon']
add_module_names = False
source_suffix = '.rst'
master_doc = 'index' |
c301e99bbf5b32e3c66d68f422fdfc271390adf4 | txircd/modules/cmode_s.py | txircd/modules/cmode_s.py | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"] = {}
# other +s stuff is hiding in other modules.
cla... | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
... | Make +s actually definitely clear the cdata dictionary | Make +s actually definitely clear the cdata dictionary
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd | ---
+++
@@ -6,7 +6,7 @@
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
- data["cdata"] = {}
+ data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object): |
dc884cfd49133a9a25cc5ba6276b94dd44d18729 | test/test_general.py | test/test_general.py | import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hi... | import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hi... | Add jobs to second test queen, add assertions | Add jobs to second test queen, add assertions
| Python | bsd-3-clause | iansmcf/busybees | ---
+++
@@ -20,10 +20,13 @@
apiary.start_queen('A1')
apiary.start_queen('A2')
- jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110",
+ job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st ... |
6d118fed4df334e093840d0bcaad98a06214793b | week1/the_real_deal/sum_matrix.py | week1/the_real_deal/sum_matrix.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def sum_matrix(n):
""" Returns a sum of all elements in a
given matrix """
p = [sum(x) for x in n]
print (len(p))
return sum(p)
if __name__ == '__main__':
print (sum_matrix([[0, 3, 0], [0, 4, 0], [0, 13, 0]]))
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def sum_matrix(n):
""" Returns a sum of all elements in a
given matrix """
return sum([sum(x) for x in n])
if __name__ == '__main__':
print (sum_matrix([[0, 3, 0], [0, 4, 0], [0, 13, 0]]))
| Make it look more pythonic | Make it look more pythonic
| Python | bsd-3-clause | sevgo/Programming101 | ---
+++
@@ -5,9 +5,8 @@
def sum_matrix(n):
""" Returns a sum of all elements in a
given matrix """
- p = [sum(x) for x in n]
- print (len(p))
- return sum(p)
+
+ return sum([sum(x) for x in n])
if __name__ == '__main__': |
b66d8c2d43a28ce6e0824543bd879dc3528e3509 | rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py | rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
numbers = client.available_p... | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
numbers = client.available_p... | Add a comment about purchasing the phone number | Add a comment about purchasing the phone number | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | ---
+++
@@ -10,6 +10,7 @@
.local \
.list(area_code="510")
+# Purchase the phone number
number = client.incoming_phone_numbers \
.create(phone_number=numbers[0].phone_number)
|
3b7dcc4d2a19b5ac03eebae35600c25dd038fe33 | tests/test_server.py | tests/test_server.py | import hashlib
import json
from unittest.mock import Mock
from unittest.mock import ANY
from queue_functions import do_work
from server import handle_post
from uploaders.s3 import get_url
from uploaders.s3 import upload
def test_post():
q = Mock()
filename = 'afakefilename'
files = {'file': [{'body': b'a... | import hashlib
import json
from unittest.mock import Mock
from unittest.mock import ANY
from queue_functions import do_work
from server import handle_post
from uploaders.s3 import get_url
from uploaders.s3 import upload
def test_post():
q = Mock()
filename = 'afakefilename'
files = {'file': [{'body': b'a... | Test against dictionary, not a string | Test against dictionary, not a string
| Python | bsd-2-clause | algorithmic-music-exploration/amen-server,algorithmic-music-exploration/amen-server | ---
+++
@@ -18,7 +18,7 @@
analysis_filename = audio_filename + '.analysis.json'
expected = {'analysis': get_url(analysis_filename), 'audio': get_url(audio_filename)}
- actual = json.reads(handle_post(q, files, get_url, upload))
+ actual = json.loads(handle_post(q, files, get_url, upload))
q.e... |
ca8600faac6b10f5e1bda42d74208f3189efe529 | bin/debug/load_timeline_for_day_and_user.py | bin/debug/load_timeline_for_day_and_user.py | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | Add option to print debug statements at regular intervals | Add option to print debug statements at regular intervals
Useful to track the progress of the load. This was a change copied from the
production server.
| Python | bsd-3-clause | shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server | ---
+++
@@ -14,6 +14,9 @@
parser.add_argument("-n", "--make_new", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
+ parser.add_argument("-v", "--verbose",
+ help="after how many lines we should print a status message.")
+
... |
249a49d2f174571db22860ebfffc37637cacd9be | xmantissa/plugins/hyperbolaoff.py | xmantissa/plugins/hyperbolaoff.py | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... | Revert 5505 - introduced numerous regressions into the test suite | Revert 5505 - introduced numerous regressions into the test suite | Python | mit | twisted/hyperbola,twisted/hyperbola | ---
+++
@@ -27,7 +27,7 @@
),
benefactorFactories = (hyperbolaer,),
- loginInterfaces = (),
+
themes = (HyperbolaTheme('base', 0),)
)
|
389d7e5d131188d5b8a3f9111d9a6a7a96ce8af8 | dmoj/executors/ICK.py | dmoj/executors/ICK.py | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | Make Intercal executor not fail to start at times. | Make Intercal executor not fail to start at times.
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | ---
+++
@@ -31,4 +31,8 @@
'''
def get_compile_args(self):
- return [self.get_command(), '-O', self._code]
+ flags = [self.get_command(), '-O', self._code]
+ if self.problem == self.test_name:
+ # Do not fail self-test to random compiler bug.
+ flags.insert(1, '-b')
+... |
34e78e686b967bbc6d3cc64786b5d12757210e87 | Function_blocks_Advanced/EPC_Email_Notification/email_notification.py | Function_blocks_Advanced/EPC_Email_Notification/email_notification.py | #!/usr/bin/python
import smtplib
#SMTP server settings
SMTP_SERVER = 'smtp.server.com' #e.g. smtp.gmail.com
SMTP_PORT = 587
SMTP_USERNAME = 'yourname@server.com' #your login name, e.g. yourname@gmail.com
SMTP_PASSWORD = 'yourpassword' #CAUTION: This is stored in plain text!
#notification recipient and content
recipie... | #!/usr/bin/python
import smtplib
#SMTP server settings
SMTP_SERVER = 'smtp.server.com' #e.g. smtp.gmail.com
SMTP_PORT = 587
SMTP_USERNAME = 'yourname@server.com' #your login name, e.g. yourname@gmail.com
SMTP_PASSWORD = 'yourpassword' #CAUTION: This is stored in plain text!
#notification recipient and content
recipie... | Fix in EPC example - incorrect variable name. | Fix in EPC example - incorrect variable name.
| Python | mit | rexcontrols/REXexamples,rexcontrols/REXexamples,rexcontrols/REXexamples,rexcontrols/REXexamples,rexcontrols/REXexamples,rexcontrols/REXexamples,rexcontrols/REXexamples | ---
+++
@@ -14,7 +14,7 @@
emailText = "" + emailText + ""
-headers = ["From: " + MAIL_USERNAME,
+headers = ["From: " + SMTP_USERNAME,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0", |
435cdbda7d93287db6dcd652a79324a86becd9b8 | bytecode.py | bytecode.py | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... | Edit arithmetic operators to use the underlying vm directly | Edit arithmetic operators to use the underlying vm directly
| Python | bsd-3-clause | darbaga/simple_compiler | ---
+++
@@ -21,24 +21,24 @@
class Add(BytecodeBase):
def execute(self, machine):
- a = Pop().execute(machine)
- b = Pop().execute(machine)
+ a = machine.pop()
+ b = machine.pop()
machine.push(a+b)
class Sub(BytecodeBase):
def execute(self, machine):
- a = Po... |
3b14ed7d9ec092baaf10c9f81955dda28508db35 | tests/test_basics.py | tests/test_basics.py | import unittest
from phaseplot import phase_portrait
import matplotlib
class TestBasics(unittest.TestCase):
"""A collection of basic tests with no particular theme"""
def test_retval(self):
"""phase_portrait returns an AxesImage instance"""
def somefun(z): return z*z + 1
retval = p... | import unittest
from phaseplot import phase_portrait
import matplotlib
from matplotlib import pyplot as plt
class TestBasics(unittest.TestCase):
"""A collection of basic tests with no particular theme"""
def test_retval(self):
"""phase_portrait returns an AxesImage instance"""
def somefun(... | Add test for correct image extent | Add test for correct image extent
| Python | mit | rluce/python-phaseplot | ---
+++
@@ -1,6 +1,7 @@
import unittest
from phaseplot import phase_portrait
import matplotlib
+from matplotlib import pyplot as plt
class TestBasics(unittest.TestCase):
"""A collection of basic tests with no particular theme"""
@@ -10,3 +11,19 @@
def somefun(z): return z*z + 1
retval = p... |
233e5b2f48ae567f50843dc3b8b4301a21c12b71 | cloud_notes/templatetags/markdown_filters.py | cloud_notes/templatetags/markdown_filters.py | from django import template
import markdown as md
import bleach
import copy
register = template.Library()
def markdown(value):
"""convert to markdown"""
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
return bleach.clean(md.markdown(value), tags = allowed_tags)
... | from django import template
import markdown as md
import bleach
import copy
register = template.Library()
def markdown(value):
"""convert to markdown"""
allowed_tags = bleach.ALLOWED_TAGS + ['blockquote', 'pre', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
return bleach.clean(md.markdown(value), t... | Add pre tag to cloud notes | Add pre tag to cloud notes
| Python | apache-2.0 | kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2 | ---
+++
@@ -7,7 +7,7 @@
def markdown(value):
"""convert to markdown"""
- allowed_tags = bleach.ALLOWED_TAGS + ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
+ allowed_tags = bleach.ALLOWED_TAGS + ['blockquote', 'pre', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
return bleach.clean(m... |
c82a6a9dce1036c94a6e4ac9d09196822935116f | doc/conf.py | doc/conf.py | # -*- coding: utf-8 -*-
import sys, os
import pyudev
needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinxcontrib.pyqt4', 'sphinxcontrib.issuetracker']
master_doc = 'index'
exclude_patterns = ['_build/*']
source_suffix = '.rst'
project = u'pyudev'
copyright = u'2... | # -*- coding: utf-8 -*-
import sys, os
import pyudev
needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinxcontrib.pyqt4', 'sphinxcontrib.issuetracker']
master_doc = 'index'
exclude_patterns = ['_build/*']
source_suffix = '.rst'
project = u'pyudev'
copyright = u'2... | Use only the python module index, but not the one from the (broken) pyqt4 extension | Use only the python module index, but not the one from the (broken) pyqt4 extension
| Python | lgpl-2.1 | mulkieran/pyudev,mulkieran/pyudev,deepakkapoor624/pyudev,deepakkapoor624/pyudev,pyudev/pyudev,mulkieran/pyudev | ---
+++
@@ -20,6 +20,7 @@
html_theme = 'default'
html_static_path = []
+html_domain_indices = ['py-modindex']
intersphinx_mapping = {'python': ('http://docs.python.org/', None)}
|
7dacd28007097f83713b08d8b768d8ba8f6629d2 | src/unittest/python/stack_configuration/stack_configuration_tests.py | src/unittest/python/stack_configuration/stack_configuration_tests.py | import unittest2
from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException
class ConfigTests(unittest2.TestCase):
def test_properties_parsing(self):
config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'foo': {'template-url': 'foo.json'}}})
self.assertEqual('eu-w... | import unittest2
from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException
class ConfigTests(unittest2.TestCase):
def test_properties_parsing(self):
config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url': 'foo.json', 'tags': {'any-tag': 'any-ta... | Make test variables more descriptive | refactor: Make test variables more descriptive
| Python | apache-2.0 | ImmobilienScout24/cfn-sphere,cfn-sphere/cfn-sphere,marco-hoyer/cfn-sphere,cfn-sphere/cfn-sphere,cfn-sphere/cfn-sphere | ---
+++
@@ -5,15 +5,17 @@
class ConfigTests(unittest2.TestCase):
def test_properties_parsing(self):
- config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'foo': {'template-url': 'foo.json'}}})
+ config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url... |
5c60aad725b0b98008ee467c5130931339c12d48 | os_client_config/cloud_config.py | os_client_config/cloud_config.py | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Add an equality method for CloudConfig | Add an equality method for CloudConfig
In order to track if a config has changed, we need to be able to compare
the CloudConfig objects for equality.
Change-Id: Icdd9acede81bc5fba60d877194048e24a62c9e5d
| Python | apache-2.0 | stackforge/python-openstacksdk,redhat-openstack/os-client-config,openstack/python-openstacksdk,dtroyer/python-openstacksdk,openstack/os-client-config,dtroyer/os-client-config,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,switch-ch/os-client-config | ---
+++
@@ -32,3 +32,7 @@
def __iter__(self):
return self.config.__iter__()
+
+ def __eq__(self, other):
+ return (self.name == other.name and self.region == other.region
+ and self.config == other.config) |
f879bf6304fcd31e32b55c40462dce06ff859410 | turbasen/settings.py | turbasen/settings.py | import os
from .cache import DummyCache
class Settings:
ENDPOINT_URL = os.environ.get('ENDPOINT_URL', 'https://api.nasjonalturbase.no')
LIMIT = 20
CACHE = DummyCache()
CACHE_LOOKUP_PERIOD = 60 * 60 * 24
CACHE_GET_PERIOD = 60 * 60 * 24 * 30
ETAG_CACHE_PERIOD = 60 * 60
API_KEY = os.environ.g... | import os
from .cache import DummyCache
class MetaSettings(type):
"""Implements reprentation for the Settings singleton, displaying all settings and values"""
def __repr__(cls):
settings = [
'%s=%s' % (name, getattr(cls, name))
for name in dir(cls)
if not name.start... | Implement repr for Settings class | Implement repr for Settings class
| Python | mit | Turbasen/turbasen.py | ---
+++
@@ -2,7 +2,17 @@
from .cache import DummyCache
-class Settings:
+class MetaSettings(type):
+ """Implements reprentation for the Settings singleton, displaying all settings and values"""
+ def __repr__(cls):
+ settings = [
+ '%s=%s' % (name, getattr(cls, name))
+ for nam... |
02d971ae2533336ba0625561a70c968b9d71b936 | PublicWebServicesAPI_AND_servercommandScripts/addInfoToCSVreport.py | PublicWebServicesAPI_AND_servercommandScripts/addInfoToCSVreport.py | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not loca... | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not loca... | Fix incorrect wording in addInfoToCSVReport.py | Update: Fix incorrect wording in addInfoToCSVReport.py
| Python | mit | PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples | ---
+++
@@ -17,7 +17,7 @@
context = create_default_context(Purpose.CLIENT_AUTH))#Create new ServerProxy Instance
# #TODO open and manipulate CSV
-csv_reader = reader(stdin, delimiter=',') #Read in standard data
+csv_reader = reader(stdin, delimiter=',') #Read in standard input
line_count = 0
for row in ... |
1272a93f4ea5b35b9b4030d984264b7e7fb7969e | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google 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 law or a... | # Copyright 2017 Google 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 law or a... | Update dsub version to 0.2.5. | Update dsub version to 0.2.5.
PiperOrigin-RevId: 232755945
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.2.5.dev0'
+DSUB_VERSION = '0.2.5' |
b7bdd73fdfe0036ceb0a423e3d2619a8a4a35a1f | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google 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 law or a... | # Copyright 2017 Google 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 law or a... | Update dsub version to 0.4.7 | Update dsub version to 0.4.7
PiperOrigin-RevId: 449501976
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.7.dev0'
+DSUB_VERSION = '0.4.7' |
fbbe736b649a85cddf773548b895ccaa9ead8c67 | docker/nvidia/setup_nvidia_docker_compose.py | docker/nvidia/setup_nvidia_docker_compose.py | #!/usr/bin/env python
import requests
import yaml
# query nvidia docker plugin for the command-line parameters to use with the
# `docker run` command
response = requests.get('http://localhost:3476/docker/cli/json')
docker_cli_params = response.json()
devices = docker_cli_params['Devices']
volumes = docker_cli_params[... | #!/usr/bin/env python
import requests
import yaml
# query nvidia docker plugin for the command-line parameters to use with the
# `docker run` command
try:
response = requests.get('http://localhost:3476/docker/cli/json')
except requests.exceptions.ConnectionError, e:
print('Cannot connect to the nvidia docker ... | Add error handling in case nvidia plugin daemon is not running | Add error handling in case nvidia plugin daemon is not running
| Python | bsd-3-clause | ORNL-CEES/DataTransferKit,dalg24/DataTransferKit,amccaskey/DataTransferKit,dalg24/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,dalg24/DataTransferKit,Rombur/DataTransferKit,dalg24/DataTransferKit,amccaskey/DataTransferKit,ORNL-CEES/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,amc... | ---
+++
@@ -5,7 +5,12 @@
# query nvidia docker plugin for the command-line parameters to use with the
# `docker run` command
-response = requests.get('http://localhost:3476/docker/cli/json')
+try:
+ response = requests.get('http://localhost:3476/docker/cli/json')
+except requests.exceptions.ConnectionError, e:... |
4503294985c45e02e284dc3ab7dac4631856c126 | rainforest_makers/urls.py | rainforest_makers/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rainforest_makers.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', ... | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rainforest_makers.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', ... | Add Media url/root to settings | Add Media url/root to settings
| Python | mit | bjorncooley/rainforest_makers,bjorncooley/rainforest_makers | ---
+++
@@ -10,4 +10,4 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('spirit.urls', namespace="spirit", app_name="spirit")),
-)
+)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
7092293a569c382dac4f2f9ac69b879ea4b500d1 | django_prometheus/db/backends/mysql/base.py | django_prometheus/db/backends/mysql/base.py | from django_prometheus.db.common import DatabaseWrapperMixin
from django.db.backends.mysql import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
CURSOR_CLASS = bas... | from django_prometheus.db.common import (
DatabaseWrapperMixin, ExportingCursorWrapper)
from django.db.backends.mysql import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseW... | Use the proper API to Python-MySQL. | Use the proper API to Python-MySQL.
The common mixin used for other databases uses an API established
across databases, but Python-MySQL differs. This was broken during the
refactoring in 432f1874ffde0ad120aa79e568086a1731d22aeb.
Fixes #24
| Python | apache-2.0 | korfuri/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,obytes/django-prometheus | ---
+++
@@ -1,4 +1,5 @@
-from django_prometheus.db.common import DatabaseWrapperMixin
+from django_prometheus.db.common import (
+ DatabaseWrapperMixin, ExportingCursorWrapper)
from django.db.backends.mysql import base
@@ -9,3 +10,9 @@
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
... |
3c982cd4d7742600d5785f8620d0b982d0fd741e | sensors/dylos.py | sensors/dylos.py | import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STO... | import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STO... | Print better logs for Dylos | Print better logs for Dylos
| Python | apache-2.0 | VDL-PRISM/dylos | ---
+++
@@ -19,8 +19,9 @@
def read():
line = ser.readline()
- small, large = [int(x) for x in line.split(b',')]
- LOGGER.debug("Read from serial port: %s %s", small, large)
+ LOGGER.debug("Read from serial port: %s", line)
+ small, large = [int(x.strip()) for x in line.spli... |
ed68f3f8961fd9cc212c2bc7700ba758af51d335 | mailchimp_manager/tests/test_list_manager.py | mailchimp_manager/tests/test_list_manager.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_list_manager.py - Integration test for list management of mailchimp_manager
"""
from mailchimp_manager import MailChimpManager
import unittest
TEST_EMAIL = u'john.doe@gmail.com'
class TestMailChimpListManager(unittest.TestCase):
def test_Subscribe_TestEma... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_list_manager.py - Integration test for list management of mailchimp_manager
"""
try:
from mailchimp_manager import MailChimpManager
except:
# Local module testing - assuming mailchimp_manager folder put in grandparent folder
import sys, os.path
... | Update test script for local testing | Update test script for local testing
| Python | bsd-3-clause | Kudo/mailchimp_manager | ---
+++
@@ -3,7 +3,14 @@
"""
test_list_manager.py - Integration test for list management of mailchimp_manager
"""
-from mailchimp_manager import MailChimpManager
+try:
+ from mailchimp_manager import MailChimpManager
+except:
+ # Local module testing - assuming mailchimp_manager folder put in grandparent... |
959b5fd80a2eeb4ddb56dea07edd16c1aeabc4ff | userprofile/admin.py | userprofile/admin.py | from django.contrib import admin
from .models import Profile, Skill, DutyTime, Group
admin.site.register(Profile)
admin.site.register(Skill)
admin.site.register(DutyTime)
admin.site.register(Group)
| from django.contrib import admin
from .models import Profile, Skill, DutyTime, Group
class ProfileAdmin(admin.ModelAdmin):
list_filter = (
('tos_accepted', admin.BooleanFieldListFilter),
)
admin.site.register(Profile, ProfileAdmin)
admin.site.register(Skill)
admin.site.register(DutyTime)
admin.site.... | Add filtering option to see profiles that have not accepted new tos | Add filtering option to see profiles that have not accepted new tos
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website | ---
+++
@@ -1,7 +1,14 @@
from django.contrib import admin
from .models import Profile, Skill, DutyTime, Group
-admin.site.register(Profile)
+
+class ProfileAdmin(admin.ModelAdmin):
+ list_filter = (
+ ('tos_accepted', admin.BooleanFieldListFilter),
+ )
+
+
+admin.site.register(Profile, ProfileAdmin)
... |
a795274811b3df67a04593b1889d9c93fed40737 | examples/webhooks.py | examples/webhooks.py | from __future__ import print_function
import os
import stripe
from flask import Flask, request
stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
webhook_secret = os.environ.get('WEBHOOK_SECRET')
app = Flask(__name__)
@app.route('/webhooks', methods=['POST'])
def webhooks():
payload = request.data
recei... | from __future__ import print_function
import os
import stripe
from flask import Flask, request
stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
webhook_secret = os.environ.get('WEBHOOK_SECRET')
app = Flask(__name__)
@app.route('/webhooks', methods=['POST'])
def webhooks():
payload = request.data.decode('u... | Fix example for Python 3 compatibility | Fix example for Python 3 compatibility
| Python | mit | stripe/stripe-python | ---
+++
@@ -13,7 +13,7 @@
@app.route('/webhooks', methods=['POST'])
def webhooks():
- payload = request.data
+ payload = request.data.decode('utf-8')
received_sig = request.headers.get('Stripe-Signature', None)
try: |
8664741930e5a21bfbdcffe2fc0ca612b4b3e4ea | clburlison_scripts/dropbox_folder_location/dropbox_folder_location.py | clburlison_scripts/dropbox_folder_location/dropbox_folder_location.py | #!/usr/bin/python
"""H/t to eholtam for posting in slack"""
import json
import os
print("Personal: ")
f = open(os.path.expanduser('~/.dropbox/info.json'), 'r').read()
data = json.loads(f)
print(data.get('personal', {}).get('path', '').replace('', 'None'))
print("Business: ")
f = open(os.path.expanduser('~/.dropbox/i... | #!/usr/bin/python
import json, os, pprint
f = open(os.path.expanduser('~/.dropbox/info.json'), 'r').read()
data = json.loads(f)
# To list all dropbox data
pprint.pprint(data)
print('')
# Or to find just the paths
for i in ['personal', 'business']:
print('{}:'.format(i.capitalize()))
print(data.get(i, {}).ge... | Update dropbox folder location script | Update dropbox folder location script
| Python | mit | clburlison/scripts,clburlison/scripts,clburlison/scripts | ---
+++
@@ -1,15 +1,15 @@
#!/usr/bin/python
-"""H/t to eholtam for posting in slack"""
-import json
-import os
+import json, os, pprint
-print("Personal: ")
f = open(os.path.expanduser('~/.dropbox/info.json'), 'r').read()
data = json.loads(f)
-print(data.get('personal', {}).get('path', '').replace('', 'None'))... |
7a5fdf50f4a986336c577ce57ed73da1c445b6cd | db_mutex/models.py | db_mutex/models.py | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | Declare app_label in model Meta class to work with Django 1.9 | Declare app_label in model Meta class to work with Django 1.9
Fixes RemovedInDjango19Warning:
Model class db_mutex.models.DBMutex doesn't declare an explicit
app_label and either isn't in an application in INSTALLED_APPS or else
was imported before its application was loaded. This will no longer be
supported in Djan... | Python | mit | ambitioninc/django-db-mutex,minervaproject/django-db-mutex | ---
+++
@@ -13,3 +13,6 @@
"""
lock_id = models.CharField(max_length=256, unique=True)
creation_time = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ app_label = 'db_mutex' |
a89f2f52170ffbb238d01f58650bcb4e55f3253a | structure.py | structure.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... | Structure keyword get accepted now | Bugfix: Structure keyword get accepted now
| Python | mit | hastern/jelly | ---
+++
@@ -26,8 +26,9 @@
if len(self.__slots__) > i:
self.__setattr__(self.__slots__[i], a)
# Keyword definition of members
- map(lambda k: self.__setattr__(k, None), filter(lambda k: k in self.__slots__, kwargs))
+ map(lambda k: self.__setattr__(k, kwargs[k]), filter(lambda k: k in self.__slots__, kwa... |
91c3f218bdd5a660568238daa16c217501d39d05 | create_database.py | create_database.py | import author
import commit
import config
import os
import pygit2
import sqlalchemy
repo = pygit2.Repository(config.REPO_PATH)
# Probably want to completly reset the DB
if config.RESET_DB and os.path.exists(config.DB_PATH):
os.remove(config.DB_PATH)
engine = sqlalchemy.create_engine(config.DB_URL, echo=True)
conf... | from author import Author
from commit import Commit
import config
import os
import pygit2
import sqlalchemy
# If it exists and we want to reset the DB, remove the file
if config.RESET_DB and os.path.exists(config.DB_PATH):
os.remove(config.DB_PATH)
engine = sqlalchemy.create_engine(config.DB_URL, echo=False)
confi... | Create database now properly loads all authors and commits into the repository | Create database now properly loads all authors and commits into the repository
| Python | mit | mglidden/git-analysis,mglidden/git-analysis | ---
+++
@@ -1,18 +1,33 @@
-import author
-import commit
+from author import Author
+from commit import Commit
import config
import os
import pygit2
import sqlalchemy
-repo = pygit2.Repository(config.REPO_PATH)
-
-# Probably want to completly reset the DB
+# If it exists and we want to reset the DB, remove the... |
28681f8b2f88f818c2b5a0197a00df90d3065aaf | models/official/detection/configs/factory.py | models/official/detection/configs/factory.py | # Copyright 2019 The TensorFlow Authors. 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 applica... | # Copyright 2019 The TensorFlow Authors. 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 applica... | Fix shapemask_config import to handle copy.bara masking that allows cloud detection test to pass. | Fix shapemask_config import to handle copy.bara masking that allows cloud detection test to pass.
PiperOrigin-RevId: 267404830
| Python | apache-2.0 | tensorflow/tpu,tensorflow/tpu,tensorflow/tpu,tensorflow/tpu | ---
+++
@@ -15,7 +15,6 @@
"""Factory to provide model configs."""
from configs import retinanet_config
-from configs import shapemask_config
from hyperparameters import params_dict
|
a51c8238ba61d213d089767ba38f18f29dacb08f | dakis/api/views.py | dakis/api/views.py | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Experiment
exclude = ('author',)
... | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(label='ID', read_only=True)
class ... | Add exp and task ids to API | Add exp and task ids to API
| Python | agpl-3.0 | niekas/dakis,niekas/dakis,niekas/dakis | ---
+++
@@ -7,6 +7,8 @@
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
+ id = serializers.IntegerField(label='ID', read_only=True)
+
class Meta:
model = Experiment
exclude = ('author',)
@@ -19,8 +21,11 @@
class TaskSerializer(serializers.HyperlinkedModelSeriali... |
fedd90e80a6c56ab406e52b9b0ece14b324fa5d5 | aldryn_apphooks_config/fields.py | aldryn_apphooks_config/fields.py | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs.update({'help_text': _(u'When selecting ... | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigFormField(forms.ModelChoiceField):
def __init__(self, queryset, empty_label="---------", required=True,
wi... | Improve the ability for developers to extend or modify | Improve the ability for developers to extend or modify
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config | ---
+++
@@ -4,6 +4,14 @@
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
+
+
+class AppHookConfigFormField(forms.ModelChoiceField):
+
+ def __init__(self, queryset, empty_label="---------", required=True,
+ widget=AppHookConfigWidget, *args, **kwargs)... |
16002b001a120410e4f993ad6fb93b123de183cb | astrodynamics/tests/test_util.py | astrodynamics/tests/test_util.py | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... | Test string form of verify_unit | Test string form of verify_unit
| Python | mit | python-astrodynamics/astrodynamics,python-astrodynamics/astrodynamics | ---
+++
@@ -10,10 +10,14 @@
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
+ assert verify_unit(0, '') == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.me... |
631bfc08a31477a81103cb83329ce4b29d977658 | 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 | JioEducation/edx-platform,Lektorium-LLC/edx-platform,cecep-edu/edx-platform,jzoldak/edx-platform,eduNEXT/edunext-platform,chrisndodge/edx-platform,gsehub/edx-platform,shabab12/edx-platform,arbrandes/edx-platform,CredoReference/edx-platform,fintech-circle/edx-platform,miptliot/edx-platform,amir-qayyum-khan/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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.