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 |
|---|---|---|---|---|---|---|---|---|---|---|
31d9644f1f5790e63affd89fd0f2145777e8f0f6 | pymodels/__init__.py | pymodels/__init__.py | """PyModels package."""
import os as _os
from . import LI_V01_01
from . import TB_V02_01
from . import BO_V03_02
from . import TS_V03_03
from . import SI_V22_02
from . import coordinate_system
with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f:
__version__ = _f.read().strip()
__all__ = ('LI_V01_01', 'T... | """PyModels package."""
import os as _os
from . import LI_V01_01
from . import TB_V02_01
from . import BO_V03_02
from . import TS_V03_03
from . import SI_V24_04
from . import coordinate_system
with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f:
__version__ = _f.read().strip()
__all__ = ('LI_V01_01', 'T... | Update SI version in init | Update SI version in init
| Python | mit | lnls-fac/sirius | ---
+++
@@ -5,18 +5,18 @@
from . import TB_V02_01
from . import BO_V03_02
from . import TS_V03_03
-from . import SI_V22_02
+from . import SI_V24_04
from . import coordinate_system
with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f:
__version__ = _f.read().strip()
-__all__ = ('LI_V01_01', 'TB_... |
a1c8326b9e520a9f262360ef97e2d5651c2e973e | inventory.py | inventory.py | from flask import Flask, render_template, url_for, redirect
from peewee import *
app = Flask(__name__)
database = SqliteDatabase('developmentData.db')
#class Device(Model):
@app.route('/')
def index():
# http://flask.pocoo.org/snippets/15/
return render_template('inventory.html', inventoryData="", deviceLogData="... | from flask import Flask, render_template, url_for, redirect
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
@app.route('/')
def index():
# http://flask.pocoo.org/... | Add comments for references later | Add comments for references later
| Python | mit | lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory | ---
+++
@@ -1,7 +1,9 @@
from flask import Flask, render_template, url_for, redirect
from peewee import *
+#from datetime import date
app = Flask(__name__)
+# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model): |
6a246c46f5adadc12fe4034c2b25e79196c3c831 | bake/load.py | bake/load.py | # load.py
# loads and formats bp files
import re
import os
import os.path
def load(iterator):
"""
Loads lines from an iterator and does line parsing
1 Handles line continuation
2 Handles include statements
3 Handle comments at start of line
"""
lines = []
for l in iterator:
# Handle... | # load.py
# loads and formats bp files
import re
import os
import os.path
def load(iterator):
"""
Loads lines from an iterator and does line parsing
1 Handles line continuation
2 Handles include statements
3 Handle comments at start of line
"""
lines = []
for l in iterator:
# Handle... | Allow for user-specified newline breaks in values | Allow for user-specified newline breaks in values
| Python | mit | AlexSzatmary/bake | ---
+++
@@ -31,7 +31,7 @@
elif re.match(r'^\s*#', l):
l = ''
if l:
- lines.append(l.replace('\n', ''))
+ lines.append(l.replace('\n', '').replace('\\n','\n'))
return lines
|
1abe172a31805d26a02b4c57d940c9afcc60ce78 | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client']
import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self):
self... | from __future__ import absolute_import
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client']
import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localho... | Add host and port parameters | Add host and port parameters
| Python | apache-2.0 | kragniz/python-etcd3 | ---
+++
@@ -13,8 +13,10 @@
class Etcd3Client(object):
- def __init__(self):
- self.channel = grpc.insecure_channel('localhost:2379')
+ def __init__(self, host='localhost', port=2379):
+ self.channel = grpc.insecure_channel('{host}:{port}'.format(
+ host=host, port=port)
+ )
... |
83d4c5b9b1f7ed9b75ae04464423b7ca4b5d627d | nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py | nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack 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
#
... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack 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
#
... | Fix config_drive migration, per Matt Dietz. | Fix config_drive migration, per Matt Dietz. | Python | apache-2.0 | plumgrid/plumgrid-nova,adelina-t/nova,houshengbo/nova_vmware_compute_driver,cyx1231st/nova,redhat-openstack/nova,noironetworks/nova,jeffrey4l/nova,Stavitsky/nova,zaina/nova,CloudServer/nova,openstack/nova,sridevikoushik31/nova,eonpatapon/nova,usc-isi/extra-specs,shail2810/nova,sridevikoushik31/nova,russellb/nova,bclau/... | ---
+++
@@ -23,20 +23,15 @@
instances = Table("instances", meta,
Column("id", Integer(), primary_key=True, nullable=False))
-config_drive_column = Column("config_drive", String(255)) # matches image_ref
+
+# matches the size of an image_ref
+config_drive_column = Column("config_drive", String(255), nullab... |
4c69afe07533c37c3780b653d343e795cc515c5c | tests/test_examples.py | tests/test_examples.py | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import examples.basic_usage
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
e... | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import examples.basic_usage
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
e... | Add stdout tests for basic usage example | Add stdout tests for basic usage example
| Python | mit | cihai/cihai,cihai/cihai-python,cihai/cihai | ---
+++
@@ -19,5 +19,10 @@
examples.variant_ts_difficulties.run(unihan_options=unihan_options)
-def test_basic_usage(unihan_options):
+def test_basic_usage(unihan_options, capsys):
examples.basic_usage.run(unihan_options=unihan_options)
+
+ captured = capsys.readouterr()
+
+ assert 'lookup for 好: ... |
a64221bbf3ebc2c1be24c82870f1f233bac10cd4 | app_v2/client.py | app_v2/client.py | #!/usr/bin/env python3
import socket
import atexit
import pygame
from message import Message
PRECISION = 3
host = "localhost"
port = 9999
# create a socket object and connect to specified host/port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def close_socket():
s.close()
d... | #!/usr/bin/env python3
import socket
import atexit
import pygame
from message import Message
PRECISION = 3
host = "192.168.0.1"
port = 9999
# create a socket object and connect to specified host/port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def close_socket():
s.close()
... | Update host to use Pi’s static address | Update host to use Pi’s static address
| Python | mit | thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x | ---
+++
@@ -8,7 +8,7 @@
PRECISION = 3
-host = "localhost"
+host = "192.168.0.1"
port = 9999
# create a socket object and connect to specified host/port |
f6313e28bbf00d65d6a4635b5377f9ad06548de6 | appengine_config.py | appengine_config.py | # Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Configures appstats.
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
# Enable appstats and optionally cost calculation... | # Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Configures appstats.
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
# The app engine headers are located locally, so ... | Enable app stats on '-dev' instance. | Enable app stats on '-dev' instance.
This will also enable them on local dev server as well since default app name
in app.yaml is 'isolateserver-dev'.
R=maruel@chromium.org
Review URL: https://codereview.appspot.com/13457054
| Python | apache-2.0 | luci/luci-py,luci/luci-py,madecoste/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming,madecoste/swarming,pombreda/swarming,pombreda/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming | ---
+++
@@ -7,9 +7,15 @@
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
-# Enable appstats and optionally cost calculation.
-# Change these values and upload again if you want to enable appstats.
-enable_appstats = False
+# The app engine headers are located locally, so don't worry ... |
215e02ea7a5aecd73fcef39f7aac3e6622dcf906 | api/wikia.py | api/wikia.py | import urllib.request
import json
class Wikia:
wiki_name = ""
def __init__(self, wiki):
self.wiki_name = wiki
def search(self, term, limit=1):
# Search for a page on Wikia
# TODO: make limits over 1 return an array
searchTerm = term.replace(" ", "+")
url = "http://... | import urllib.request
import json
class Wikia:
wiki_name = ""
def __init__(self, wiki):
self.wiki_name = wiki
def search(self, term, limit=1):
# Search for a page on Wikia
# TODO: make limits over 1 return an array
searchTerm = term.replace(" ", "+")
url = "http://... | Fix Wikia API to not be limited to SVTFOE Wikia | Fix Wikia API to not be limited to SVTFOE Wikia
| Python | apache-2.0 | StarbotDiscord/Starbot,dhinakg/BitSTAR,StarbotDiscord/Starbot,dhinakg/BitSTAR | ---
+++
@@ -11,7 +11,7 @@
# Search for a page on Wikia
# TODO: make limits over 1 return an array
searchTerm = term.replace(" ", "+")
- url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm)... |
1316e3ab69fe3e08de6d6f08a04ce0f4bd94dc04 | examples/completion.py | examples/completion.py | import gtk
from kiwi.ui.widgets.entry import Entry
entry = Entry()
entry.set_completion_strings(['apa', 'apapa', 'apbla',
'apppa', 'aaspa'])
win = gtk.Window()
win.connect('delete-event', gtk.main_quit)
win.add(entry)
win.show_all()
gtk.main()
| # encoding: iso-8859-1
import gtk
from kiwi.ui.widgets.entry import Entry
def on_entry_activate(entry):
print 'You selected:', entry.get_text().encode('latin1')
gtk.main_quit()
entry = Entry()
entry.connect('activate', on_entry_activate)
entry.set_completion_strings(['Belo Horizonte',
... | Extend example to include non-ASCII characters | Extend example to include non-ASCII characters | Python | lgpl-2.1 | stoq/kiwi | ---
+++
@@ -1,10 +1,21 @@
+# encoding: iso-8859-1
import gtk
from kiwi.ui.widgets.entry import Entry
+def on_entry_activate(entry):
+ print 'You selected:', entry.get_text().encode('latin1')
+ gtk.main_quit()
+
entry = Entry()
-entry.set_completion_strings(['apa', 'apapa', 'apbla',
- ... |
c55b587667887732f7b64b6dcf3a8c806c1c85c0 | esp32/modules/tasks/badgeeventreminder.py | esp32/modules/tasks/badgeeventreminder.py | # File: badgeeventreminder.py
# Version: 1
# Description: Easter egg
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
import virtualtimers, time, appglue, badge
# Tue Aug 8 13:30:00 2017 (CEST)
whenToTrigger = 1502191800 - 600
def ber_task():
global whenToTrigger
now = time.time()
if now>=whenT... | # File: badgeeventreminder.py
# Version: 1
# Description: Easter egg
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
import virtualtimers, time, appglue, badge
# Tue Aug 8 13:30:00 2017 (CEST)
whenToTrigger = 1502191800 - 600
def ber_task():
global whenToTrigger
now = time.time()
if now>=whenT... | Return the number of ms, not seconds. | Return the number of ms, not seconds.
| Python | mit | SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32 | ---
+++
@@ -19,7 +19,7 @@
idleFor = whenToTrigger - now
if idleFor<0:
idleFor = 0
- return idleFor
+ return idleFor * 1000
def enable():
if badge.nvs_get_u8('badge','evrt',0)==0: |
5b892de6093de62615e327a805948b76ce806cb4 | protoplot-test/test_options_resolving.py | protoplot-test/test_options_resolving.py | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
class Series(Item):
pass
Series.options.register("color", True)
Series.options.register("lineWidth", False)
Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):... | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
class TestOptionsResolving(unittes... | Disable code made for old engine model | Disable code made for old engine model
| Python | agpl-3.0 | deffi/protoplot | ---
+++
@@ -3,12 +3,12 @@
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
-class Series(Item):
- pass
-
-Series.options.register("color", True)
-Series.options.register("lineWidth", False)
-Series.options.register("lineStyle", False)
+# class Series(Item):
+# ... |
3a80d6670b32912e091c6f5ca102e33899de117e | terms/managers.py | terms/managers.py | # coding: utf-8
from django.db.models import Manager
from django.template.loader import render_to_string
import re
class TermManager(Manager):
def replace_dict(self):
t = 'terms/term_replace.html'
d = {}
for term in self.get_query_set().iterator():
d[term.name] = render_to_str... | # coding: utf-8
from django.db.models import Manager
from django.template.loader import render_to_string
import re
class TermManager(Manager):
def replace_dict(self):
t = 'terms/term_replace.html'
d = {}
for term in self.get_query_set().iterator():
d[term.name] = render_to_str... | Allow replacements in terms at the start and/or end of a text. | Allow replacements in terms at the start and/or end of a text.
| Python | bsd-3-clause | philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms | ---
+++
@@ -15,5 +15,5 @@
def replace_regexp(self):
replace_dict = self.replace_dict()
- return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)'
+ return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)'
% '|'.join(map(re.escape, replace_dict))) |
5d7a70d2d5e5934d1804d7aac69fd6c79d2ac9a7 | src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py | src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py | from django.db import migrations
def drop_events(apps, schema_editor):
Event = apps.get_model('logging', 'Event')
Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete()
class Migration(migrations.Migration):
dependencies = [
('logging', '0007_drop_alerts'),
]
... | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('logging', '0007_drop_alerts'),
]
# Run SQL instead of Run Python is used to avoid OOM error
# See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delet... | Fix migration script to avoid OOM error. | Fix migration script to avoid OOM error.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -1,9 +1,4 @@
from django.db import migrations
-
-
-def drop_events(apps, schema_editor):
- Event = apps.get_model('logging', 'Event')
- Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete()
class Migration(migrations.Migration):
@@ -12,4 +7,13 @@
('logging', ... |
49e89bee4a7c5e241402766072ae60697c136ca6 | guild/__init__.py | guild/__init__.py | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... | Fix to git status info | Fix to git status info
| Python | apache-2.0 | guildai/guild,guildai/guild,guildai/guild,guildai/guild | ---
+++
@@ -20,7 +20,7 @@
def _init_git_status():
raw = _git_cmd("git -C \"%(repo)s\" status -s")
- globals()["__git_status__"] = raw.split("\n")
+ globals()["__git_status__"] = raw.split("\n") if raw else []
def _git_cmd(cmd, **kw):
repo = os.path.dirname(__file__) |
f90467edaf02ae66cdfd01a34f7e03f20073c12d | tests/__init__.py | tests/__init__.py | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
os.mkdir(yvs.ALFRED_DATA_DIR)
def mock_open(path, mode):
... | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
def mock_open(path, mode):
if path.endswith('preference... | Create Alfred data dir on test setup | Create Alfred data dir on test setup
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -10,7 +10,6 @@
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
-os.mkdir(yvs.ALFRED_DATA_DIR)
def mock_open(path, mode):
@@ -23,6 +22,7 @@
def setup():
+ os.mkdir(yvs.ALFRED_DATA_DIR)
patch_open.st... |
587cfa978eb2d2d6708061016836710ca7e3057b | scrapple/utils/exceptions.py | scrapple/utils/exceptions.py | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
... | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
... | Add custom error class 'InvalidOutputType' | Add custom error class 'InvalidOutputType'
| Python | mit | AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,scrappleapp/scrapple,AlexMathew/scrapple | ---
+++
@@ -14,6 +14,11 @@
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
+ pass
+
+
+class InvalidOutputType(ValueError):
+ """Exception class for invalid output_type in arguments."""
pass
@@ -34,7 +39,7 @@
raise InvalidSelector("--selector has to be 'xpath' or 'css... |
98e5aa7e5964c827bc58fffde8008bb9795b2238 | socorro/cron/jobs/truncate_partitions.py | socorro/cron/jobs/truncate_partitions.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgres_transactions,
with_single_... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgre... | Add config option for weeks to truncate and default to 2 weeks | Add config option for weeks to truncate and default to 2 weeks
| Python | mpl-2.0 | cliqz/socorro,pcabido/socorro,Tchanders/socorro,Serg09/socorro,AdrianGaudebert/socorro,spthaolt/socorro,cliqz/socorro,linearregression/socorro,Serg09/socorro,Tayamarn/socorro,mozilla/socorro,Tayamarn/socorro,lonnen/socorro,twobraids/socorro,m8ttyB/socorro,adngdb/socorro,luser/socorro,adngdb/socorro,AdrianGaudebert/soco... | ---
+++
@@ -2,6 +2,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+from configman import Namespace
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgres_transactions,
@@ -19,13 +20,15 @@
... |
cefbcda91d6f9d5a0fce97c7b72844f8dcb8d8cf | tests/conftest.py | tests/conftest.py | import pytest
from .fixtures import *
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
def pytest_runtest_setup(item):
if "slow" in item.keywords and not item.config.getoption("--runslow"):
pytest.skip("need --runslow option to run")
| import pytest
import os.path
from functools import lru_cache
from django.conf import settings
from .fixtures import *
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
def pytest_runtest_setup(item):
if "slow" in item.keywords and not item.config.getop... | Load tags sql on connection is created on tests. | Load tags sql on connection is created on tests.
| Python | agpl-3.0 | seanchen/taiga-back,obimod/taiga-back,frt-arch/taiga-back,CoolCloud/taiga-back,EvgeneOskin/taiga-back,rajiteh/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,astronaut1712/taiga-back,gauravjns/taiga-back,dayatz/taiga-back,forging2012/taiga-back,bdang2012/taiga-back-casting,dycodedev/taiga-back,taigaio/taiga-b... | ---
+++
@@ -1,4 +1,8 @@
import pytest
+import os.path
+from functools import lru_cache
+
+from django.conf import settings
from .fixtures import *
@@ -10,3 +14,18 @@
def pytest_runtest_setup(item):
if "slow" in item.keywords and not item.config.getoption("--runslow"):
pytest.skip("need --runslow ... |
9cbc1b41506b54b7cc60278907c8d9346bfc0b25 | app/main/views/feedback.py | app/main/views/feedback.py | import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_confi... | import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_confi... | Fix broken submission on Python 3. | Fix broken submission on Python 3.
- this breaks Python 2, but we don't care any more.
https://trello.com/c/Uak7y047/8-feedback-forms
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | ---
+++
@@ -16,7 +16,7 @@
for field, google_form_field in feedback_config['fields'].items():
form_data.setlist(google_form_field, request.form.getlist(field))
- result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True)))
+ result = requests.post(feedback_config['uri'], ... |
5fd879dbd5278d54a6659eb060f959af36556e1e | tests/test_usb.py | tests/test_usb.py | import unittest
from openxc.sources import UsbDataSource, DataSourceError
class UsbDataSourceTests(unittest.TestCase):
def setUp(self):
super(UsbDataSourceTests, self).setUp()
def test_create(self):
def callback(message):
pass
try:
UsbDataSource(callback)
... | import unittest
from openxc.sources import UsbDataSource, DataSourceError
class UsbDataSourceTests(unittest.TestCase):
def setUp(self):
super(UsbDataSourceTests, self).setUp()
def test_create(self):
def callback(message):
pass
| Disable trivial USB test case to get suite running on CI. | Disable trivial USB test case to get suite running on CI.
| Python | bsd-3-clause | openxc/openxc-python,openxc/openxc-python,openxc/openxc-python | ---
+++
@@ -9,8 +9,3 @@
def test_create(self):
def callback(message):
pass
-
- try:
- UsbDataSource(callback)
- except DataSourceError as e:
- pass |
555d557b71792c94a605b64c2da45eb4902e406d | lib/rpnpy/__init__.py | lib/rpnpy/__init__.py | import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.deco... | import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode(... | Add missing rpnpy.range reference for Python 3. | Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca>
(cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c)
(cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)
| Python | lgpl-2.1 | meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn | ---
+++
@@ -7,7 +7,7 @@
else:
integer_types = (int,)
long = int
- # xrange = range
+ range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' |
c191101ff26a9931c8aeb92bc6ff68f7a0baf95a | wordbridge/mappings.py | wordbridge/mappings.py | from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
def top_level_element(tag_name):
return TopLevelElement(tag_name)
class TopLevelElement(object):
def __init__(self, tag_name):
self._tag_name = tag_name
def start(self, html_stack):
html_stack.open_element(self._tag_name)
... | from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
def top_level_element(tag_name):
return Style(
on_start=_sequence(_clear_stack, _open_element(tag_name)),
on_end=_clear_stack
)
def _clear_stack(html_stack):
while html_stack.current_element() is not None:
html_stack.clo... | Build up style from composable functions | Build up style from composable functions
| Python | bsd-2-clause | mwilliamson/wordbridge | ---
+++
@@ -3,18 +3,27 @@
html = HtmlBuilder()
def top_level_element(tag_name):
- return TopLevelElement(tag_name)
+ return Style(
+ on_start=_sequence(_clear_stack, _open_element(tag_name)),
+ on_end=_clear_stack
+ )
-class TopLevelElement(object):
- def __init__(self, tag_name):
- ... |
6c9fa6a8d82a57b51e963c453fece5f445b3a3ba | spicedham/split_tokenizer.py | spicedham/split_tokenizer.py | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
is_not_blan... | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
text = [tok... | Make mapping & filtering into a list comprehension | Make mapping & filtering into a list comprehension
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | ---
+++
@@ -10,8 +10,5 @@
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
- is_not_blank = lambda x: x != ''
- text = filter(is_not_blank, text)
- lower_case = lambda x: x.lower()
- text = map(lower_case, text)
+ text = [token.lower() for token in text... |
66f467c64a0dbfcbb81d9edc74e506c076aac439 | onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py | onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# This custom migration must be run on Postgres 9.5+.
# Because some servers already have ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# Because some servers already have these modifications applied by Django South migration,
... | Remove incorrect remark about Postgres 9.5 | Remove incorrect remark about Postgres 9.5
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat | ---
+++
@@ -10,7 +10,6 @@
('logger', '0005_instance_xml_hash'),
]
- # This custom migration must be run on Postgres 9.5+.
# Because some servers already have these modifications applied by Django South migration,
# we need to delete old indexes to let django recreate them according to Dja... |
b75751d1c4ec58027173c66a869eac1319a36d7a | src/anypytools/utils/py3k.py | src/anypytools/utils/py3k.py | try:
from future_builtins import *
except ImportError:
pass
try:
input = raw_input
range = xrange
except NameError:
pass
try:
string_types = basestring
except NameError:
string_types = str
# This handles pprint always returns string witout ' prefix
# important when running docte... | # try:
# from future.builtins import *
# except ImportError:
# pass
try:
input = raw_input
range = xrange
except NameError:
pass
try:
string_types = basestring
except NameError:
string_types = str
# This handles pprint always returns string witout ' prefix
# important when runni... | Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program | Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program
| Python | mit | AnyBody-Research-Group/AnyPyTools | ---
+++
@@ -1,7 +1,7 @@
-try:
- from future_builtins import *
-except ImportError:
- pass
+# try:
+ # from future.builtins import *
+# except ImportError:
+ # pass
try:
input = raw_input |
ee3b11a7a15535ffe52a6bdd493819fbd76b2300 | vroom/graphics.py | vroom/graphics.py | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | Make color easier to read | Make color easier to read
| Python | mit | thibault/vroom | ---
+++
@@ -29,11 +29,9 @@
# Change car color depending on acceleration
if acceleration_rate > 0:
- rate = min(1, acceleration_rate)
- color = (0, 0, int(rate * 255))
+ color = (0, 0, 255)
else:
- rate = max(-1, acceleration_rate)
- c... |
44ff13234dcc8452d525eb0c648b350243b81ddb | calendarBotModule/setup.py | calendarBotModule/setup.py | #!/usr/bin/env python3
from setuptools import setup, find_packages
install_requires = (
'html2text',
'matterhook',
'exchangelib',
)
setup(name='calendarBot',
version='0.1',
description='Mattermost calendar Bot',
long_description=open('README.md').read(),
url='https://github.com/mh... | #!/usr/bin/env python3
from setuptools import setup, find_packages
install_requires = (
'html2text',
'matterhook',
'exchangelib',
)
setup(name='calendarBot',
version='0.1.1',
description='Mattermost calendar Bot',
long_description=open('README.md').read(),
url='https://github.com/... | Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed | Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed
| Python | mit | mharrend/matterbot-calendarBot,mharrend/matterbot-calendarBot | ---
+++
@@ -9,7 +9,7 @@
)
setup(name='calendarBot',
- version='0.1',
+ version='0.1.1',
description='Mattermost calendar Bot',
long_description=open('README.md').read(),
url='https://github.com/mharrend',
@@ -18,6 +18,7 @@
license='MIT',
keywords='chat bot calendar mat... |
27e14d057aad81f4686ed3def25cfffc8156fd4c | scp-slots.py | scp-slots.py | #!/usr/bin/python
import re
import sys
from bs4 import BeautifulSoup
from urllib.request import urlopen
SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}')
def count_slots(url):
with urlopen(url) as response:
data = response.read()
empty_slots = 0
total_slots = 0
scps = set()
soup = Beau... | #!/usr/bin/python
import re
import sys
from bs4 import BeautifulSoup
from urllib.request import urlopen
SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}')
def count_slots(url):
with urlopen(url) as response:
data = response.read()
empty_slots = 0
total_slots = 0
scps = set()
soup = Beau... | Add support for Series I. | Add support for Series I.
| Python | mit | ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts | ---
+++
@@ -32,13 +32,19 @@
return empty_slots, total_slots
+def get_series_url(number):
+ if number == 1:
+ return 'http://www.scp-wiki.net/scp-series'
+
+ return f'http://www.scp-wiki.net/scp-series-{series}'
+
if __name__ == '__main__':
if len(sys.argv) > 1:
series = int(sys.ar... |
f53f8b7cb7c45bc9bb7db65ebeb8791fd2e62873 | send_boto.py | send_boto.py | import sys
import boto
import boto.s3
# AWS ACCESS DETAILS
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
# a bucket per author maybe
bucket_name = 'boto-demo-1421108796'
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.D... | import sys
import boto
import boto.s3
# for debugging
boto.set_stream_logger('boto')
# AWS ACCESS DETAILS
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
# a bucket per author maybe
bucket_name = 'boto-demo-1421108796'
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(buc... | Debug sending data w/ boto. | Debug sending data w/ boto.
| Python | bsd-2-clause | LeMeteore/ballin-octo-ninja | ---
+++
@@ -1,6 +1,9 @@
import sys
import boto
import boto.s3
+
+# for debugging
+boto.set_stream_logger('boto')
# AWS ACCESS DETAILS
AWS_ACCESS_KEY_ID = '' |
76784dc06bc1d7fedb7e2e85f87fc4a2c2a489fc | chainer/functions/reshape.py | chainer/functions/reshape.py | from chainer import function
class Reshape(function.Function):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def forward(self, x):
return x[0].reshape(self.shape),
def backward(self, x, gy):
return gy[0].reshape(x[0].shape),
def... | import numpy
from chainer import function
from chainer.utils import type_check
class Reshape(function.Function):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def check_type_forward(self, in_type):
type_check.expect(in_type.size() == 1)
... | Add typecheck for Reshape function | Add typecheck for Reshape function
| Python | mit | muupan/chainer,niboshi/chainer,AlpacaDB/chainer,ktnyt/chainer,keisuke-umezawa/chainer,ytoyama/yans_chainer_hackathon,elviswf/chainer,wkentaro/chainer,jfsantos/chainer,chainer/chainer,ikasumi/chainer,hvy/chainer,okuta/chainer,bayerj/chainer,tigerneil/chainer,okuta/chainer,cupy/cupy,muupan/chainer,sinhrks/chainer,anaruse... | ---
+++
@@ -1,4 +1,7 @@
+import numpy
+
from chainer import function
+from chainer.utils import type_check
class Reshape(function.Function):
@@ -7,6 +10,27 @@
def __init__(self, shape):
self.shape = shape
+
+ def check_type_forward(self, in_type):
+ type_check.expect(in_type.size() == ... |
df8c19fe4679aa0d4fff90a15efcf4183a8ec8c1 | api/v2/serializers/details/image_version.py | api/v2/serializers/details/image_version.py | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import LicenseSerializer
from api.v2.serializers.summaries import ImageVersionSummarySerializer
from api.v2.serializers.fields import ProviderMachineRelatedField
class ImageVersionSerial... | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import (
LicenseSerializer,
UserSummarySerializer,
IdentitySummarySerializer,
ImageVersionSummarySerializer)
from api.v2.serializers.fields import ProviderM... | Add 'user' and 'identity' attributes to the ImageVersion Details Serializer | Add 'user' and 'identity' attributes to the ImageVersion Details Serializer
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -1,7 +1,10 @@
from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
-from api.v2.serializers.summaries import LicenseSerializer
-from api.v2.serializers.summaries import ImageVersionSummarySerializer
+from api.v2.serializers.summaries import (
+ LicenseS... |
06dd856ce57193f34395f8ee6e7c7d3030356609 | tests/test_single.py | tests/test_single.py | import json
from fixtures import PostSerializer
def test_single(post):
data = PostSerializer().to_json(post)
assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]}
def test_meta(post):
data = PostSerializer().to_json(post, meta={'key': 'value'})
assert json.loads(data)['meta']['ke... | import json
from fixtures import PostSerializer
def test_single(post):
data = PostSerializer().to_json(post)
assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]}
def test_multiple(post_factory):
post = post_factory(id=1, title='A title')
another_post = post_factory(id=2, title='A... | Add test for multiple resources | Add test for multiple resources
| Python | mit | kalasjocke/hyp | ---
+++
@@ -9,6 +9,20 @@
assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]}
+def test_multiple(post_factory):
+ post = post_factory(id=1, title='A title')
+ another_post = post_factory(id=2, title='Another title')
+
+ data = PostSerializer().to_json([post, another_post])
+
+ a... |
0a628ed81ca11fc4175b480aad9a136b8a4fe1c2 | constantsgen/pythonwriter.py | constantsgen/pythonwriter.py | class PythonWriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write("# This file was generated by generate_constants.\n\n")
out.write("from enum import Enum, unique\n\n")
for name, enum in self.constants.enum_values.items():
... | class PythonWriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write("# This file was generated by generate_constants.\n\n")
out.write("from enum import Enum, unique\n\n")
for name, enum in self.constants.enum_values.items():
... | Add PEP8 whitespace around Enums | Add PEP8 whitespace around Enums
| Python | bsd-3-clause | barracudanetworks/constantsgen,barracudanetworks/constantsgen,barracudanetworks/constantsgen | ---
+++
@@ -8,7 +8,6 @@
for name, enum in self.constants.enum_values.items():
out.write("""
-
@unique
class {}(Enum):\n""".format(name))
for base_name, value in enum.items():
@@ -21,5 +20,7 @@
out.write(" {} = {}\n".format(name, value))
+ out.w... |
640e0d0c9ec58c534f4d08962dd558e87401abb2 | problem_4/solution.py | problem_4/solution.py | def is_palindrome_number(n): return n == n[::-1]
largest_number = 0
for x in xrange(100, 999):
for y in xrange(100, 999):
v = x * y
if v > largest_number:
if is_palindrome_number(str(v)):
largest_number = v
print largest_number
| import time
def is_palindrome_number(n): return n == n[::-1]
def largest_palindrome_from_the_product_of_three_digit_numbers():
largest_number = 0
for x in xrange(100, 999):
for y in xrange(100, 999):
v = x * y
if v > largest_number:
if is_palindrome_number(str(v)... | Add timing for python implementation of problem 4 | Add timing for python implementation of problem 4
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler | ---
+++
@@ -1,9 +1,18 @@
+import time
def is_palindrome_number(n): return n == n[::-1]
-largest_number = 0
-for x in xrange(100, 999):
- for y in xrange(100, 999):
- v = x * y
- if v > largest_number:
- if is_palindrome_number(str(v)):
- largest_number = v
-print largest_nu... |
619033bc8daf3b8f5faafa95b04c06d98c39969f | stack/vpc.py | stack/vpc.py | from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
Route,
RouteTable,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = Inte... | from troposphere import (
GetAtt,
Ref,
)
from troposphere.ec2 import (
EIP,
InternetGateway,
NatGateway,
Route,
RouteTable,
Subnet,
SubnetRouteTableAssociation,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
Ci... | Add a public subnet that holds a `NAT` gateway | Add a public subnet that holds a `NAT` gateway
| Python | mit | caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics | ---
+++
@@ -1,11 +1,16 @@
from troposphere import (
+ GetAtt,
Ref,
)
from troposphere.ec2 import (
+ EIP,
InternetGateway,
+ NatGateway,
Route,
RouteTable,
+ Subnet,
+ SubnetRouteTableAssociation,
VPC,
VPCGatewayAttachment,
)
@@ -51,3 +56,38 @@
DestinationCidrBl... |
26e16c6229f12ca75c4bbf224eb9d1cf3b250b9c | rock/utils.py | rock/utils.py | import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):... | import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
def isexecutable(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
de... | Split isexecutable into its own function | Split isexecutable into its own function
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock | ---
+++
@@ -4,6 +4,10 @@
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
+
+
+def isexecutable(path):
+ return os.path.isfile(path) and os.access(path, os.X_OK)
class Shell(object):
@@ -18,7 +22,7 @@
self.run()
def run(self):
- if not os.path.isfile(ROCK_SHELL[... |
6c564ebe538d2723cc5f9397e09e5945796a257e | pyelevator/message.py | pyelevator/message.py | import msgpack
import logging
from .constants import FAILURE_STATUS
class MessageFormatError(Exception):
pass
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, *args, **kwargs):
content = {
'DB_UID': kwargs.pop('db_uid'),
... | import msgpack
import logging
from .constants import FAILURE_STATUS
class MessageFormatError(Exception):
pass
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, *args, **kwargs):
content = {
'DB_UID': kwargs.pop('db_uid'),
... | Fix : Range of len(1) have to be a tuple of tuples | Fix : Range of len(1) have to be a tuple of tuples
| Python | mit | oleiade/py-elevator | ---
+++
@@ -39,7 +39,7 @@
@property
def datas(self):
if hasattr(self, '_datas') and self._datas is not None:
- if (len(self._datas) == 1):
+ if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)):
return self._datas[0]
return... |
3c30166378d37c812cecb505a3d9023b079d24be | app/__init__.py | app/__init__.py | # Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
try:
nl... | # Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
nltk.downlo... | Fix stupid nltk data download thing | Fix stupid nltk data download thing
| Python | mit | PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews | ---
+++
@@ -14,10 +14,7 @@
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
-try:
- nltk.data.find('tokenizers/punkt')
-except LookupError:
- nltk.download("punkt")
+nltk.download("punkt")
# DB
db = boto3.resource("dynamodb", |
1599bc03b0a1cd202836479fba2406457a17f118 | user_map/tests/urls.py | user_map/tests/urls.py | from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^user-map/', include('user_map.urls', namespace='user_map'))
)
| from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^user-map/', include('user_map.urls', namespace='user_map')),
url(r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'admin/login.html'},
name='my_login',
),
)
| Add login url for testing. | Add login url for testing.
| Python | lgpl-2.1 | akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map | ---
+++
@@ -2,5 +2,10 @@
urlpatterns = patterns(
'',
- url(r'^user-map/', include('user_map.urls', namespace='user_map'))
+ url(r'^user-map/', include('user_map.urls', namespace='user_map')),
+ url(r'^login/$',
+ 'django.contrib.auth.views.login',
+ {'template_name': 'admin/login.html'}... |
2a9c213c02abbabeddbf2a699fd6caf5e18bf6dd | utils/word_checking.py | utils/word_checking.py | from __future__ import unicode_literals
import re
from collections import Counter
def check_for_flag_words(message, words_array):
cnt = Counter()
delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r '
pattern = r"[{}]".format(delims)
message_array = re.split(pattern, message.lower())
for word... | from __future__ import unicode_literals
import re
from collections import Counter
def check_for_flag_words(message, words_array):
cnt = Counter()
delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r '
pattern = r"[{}]".format(delims)
message_array = re.split(pattern, message.lower())
for word... | Remove numbers from the word to check for. | Remove numbers from the word to check for.
| Python | apache-2.0 | jkvoorhis/cheeseburger_backpack_bot | ---
+++
@@ -11,7 +11,10 @@
pattern = r"[{}]".format(delims)
message_array = re.split(pattern, message.lower())
for word in message_array:
- formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s")
+ # remove numbers from the word
+ ... |
186cd6148bba29baebad0dfcdbe57cd393bf1777 | report/report_util.py | report/report_util.py | def compare_ledger_types(account, data, orm):
# TODO alternate_ledger
return True
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledger = int(data['form']['ledger_type'])
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
data['ledger_typ... | def compare_ledger_types(account, data, orm):
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledgers = data['form']['ledger_types']
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
ledger_A = orm.pool.get('alternate_ledger.ledger_type').search(
... | Make the ledger type selector work | Make the ledger type selector work
| Python | agpl-3.0 | xcgd/account_report_webkit,xcgd/account_report_webkit,lithint/account_report_webkit,lithint/account_report_webkit | ---
+++
@@ -1,19 +1,26 @@
def compare_ledger_types(account, data, orm):
- # TODO alternate_ledger
- return True
-
account_ledgers = [ledger.id for ledger in account.ledger_types]
- selected_ledger = int(data['form']['ledger_type'])
+ selected_ledgers = data['form']['ledger_types']
# Store in ... |
a7b1bc006c23f534820fe06dea2da3b6553b64df | shcol/config.py | shcol/config.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | Use environment variable to detect Windows systems. | Use environment variable to detect Windows systems.
| Python | bsd-2-clause | seblin/shcol | ---
+++
@@ -20,7 +20,7 @@
LINESEP = '\n'
MAKE_UNIQUE = False
NEEDS_DECODING = (sys.version_info < (3, 0))
-ON_WINDOWS = sys.platform.startswith('win')
+ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2 |
19c46fd57e04a026c6e52e1be9ba265a82d651f1 | walletname/__init__.py | walletname/__init__.py | __author__ = 'mdavid'
import json
import re
import requests
from blockexplorer.settings import WNS_URL_BASE
WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$')
TIMEOUT_IN_SECONDS = 20
def is_valid_wallet_name(string):
return WALLET_NAME_RE.match(string)
def lookup_wallet_name(wallet_name, curre... | __author__ = 'mdavid'
import json
import re
import requests
from blockexplorer.settings import WNS_URL_BASE
WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$')
TIMEOUT_IN_SECONDS = 20
def is_valid_wallet_name(string):
return WALLET_NAME_RE.match(string)
def lookup_wallet_name(wallet_name, curre... | Add try/except block around lookup in lookup_wallet_name function | Add try/except block around lookup in lookup_wallet_name function
| Python | apache-2.0 | ychaim/explorer,blockcypher/explorer,blockcypher/explorer,ychaim/explorer,ychaim/explorer,blockcypher/explorer | ---
+++
@@ -17,9 +17,12 @@
assert is_valid_wallet_name(wallet_name)
- r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS)
- rdict = json.loads(r.text)
- if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('... |
74faea73440c4ff8b94493d5864e23e3fae7a53f | core/observables/file.py | core/observables/file.py | from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes"... | from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringFie... | Clean up File edit view | Clean up File edit view
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti | ---
+++
@@ -1,21 +1,30 @@
from __future__ import unicode_literals
+from flask import url_for
+from flask_mongoengine.wtf import model_form
from mongoengine import *
+
from core.observables import Observable
-from core.observables import Hash
+from core.database import StringListField
class File(Observable... |
b0362233c278ed37c8d10ccdd60388e0fa749b4a | etools/apps/pcs/constants.py | etools/apps/pcs/constants.py | # допустимое отклонение от начала часа для фиксации замера
PERMISSIBLE_PREC = 3
| # допустимое отклонение от начала часа для фиксации замера
PERMISSIBLE_PREC = 5
| Increase permessable interval to +- 5 min | Increase permessable interval to +- 5 min
| Python | bsd-3-clause | Igelinmist/etools,Igelinmist/etools | ---
+++
@@ -1,2 +1,2 @@
# допустимое отклонение от начала часа для фиксации замера
-PERMISSIBLE_PREC = 3
+PERMISSIBLE_PREC = 5 |
724d7235e546fb79009800700fd74328f8171b8c | src/etc/tidy.py | src/etc/tidy.py | #!/usr/bin/python
import sys, fileinput, subprocess
err=0
cols=78
try:
result=subprocess.check_output([ "git", "config", "core.autocrlf" ])
autocrlf=result.strip() == b"true"
except CalledProcessError:
autocrlf=False
def report_err(s):
global err
print("%s:%d: %s" % (fileinput.filename(), filein... | #!/usr/bin/python
import sys, fileinput
err=0
cols=78
def report_err(s):
global err
print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s))
err=1
for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")):
if line.find('\t') != -1 and fileinput.filename().find("Makefile") =... | Revert "Don't complain about \r when core.autocrlf is on in Git" | Revert "Don't complain about \r when core.autocrlf is on in Git"
This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
| Python | apache-2.0 | SiegeLord/rust,gifnksm/rust,kwantam/rust,defuz/rust,aidancully/rust,avdi/rust,sae-bom/rust,erickt/rust,pelmers/rust,avdi/rust,pythonesque/rust,Ryman/rust,carols10cents/rust,robertg/rust,aepsil0n/rust,kwantam/rust,jbclements/rust,aepsil0n/rust,kmcallister/rust,mihneadb/rust,andars/rust,pczarn/rust,pczarn/rust,krzysz00/r... | ---
+++
@@ -1,15 +1,9 @@
#!/usr/bin/python
-import sys, fileinput, subprocess
+import sys, fileinput
err=0
cols=78
-
-try:
- result=subprocess.check_output([ "git", "config", "core.autocrlf" ])
- autocrlf=result.strip() == b"true"
-except CalledProcessError:
- autocrlf=False
def report_err(s):
... |
2805eb26865d7a12cbc0e6f7a71dbd99ba49224e | gem/templatetags/gem_tags.py | gem/templatetags/gem_tags.py | from django.template import Library
from django.conf import settings
register = Library()
@register.simple_tag()
def get_site_static_prefix():
return settings.SITE_STATIC_PREFIX
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
@register.filter(name='smarttr... | from django.template import Library
from django.conf import settings
from gem.models import GemSettings
register = Library()
@register.simple_tag()
def get_site_static_prefix():
return settings.SITE_STATIC_PREFIX
@register.filter()
def get_bbm_app_id(request):
return GemSettings.for_site(request.site).bbm... | Create GEM filter to get BBM App ID | Create GEM filter to get BBM App ID
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | ---
+++
@@ -1,5 +1,7 @@
from django.template import Library
from django.conf import settings
+
+from gem.models import GemSettings
register = Library()
@@ -7,6 +9,11 @@
@register.simple_tag()
def get_site_static_prefix():
return settings.SITE_STATIC_PREFIX
+
+
+@register.filter()
+def get_bbm_app_id(req... |
062a2e41e6e605dad4d8a8dc23abaa50f8348595 | start_server.py | start_server.py | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | Use ModuleNotFoundError instead of ImportError | Use ModuleNotFoundError instead of ImportError
| Python | agpl-3.0 | Attorney-Online-Engineering-Task-Force/tsuserver3,Mariomagistr/tsuserver3 | ---
+++
@@ -23,7 +23,7 @@
def check_pyyaml():
try:
import yaml
- except ImportError:
+ except ModuleNotFoundError:
print("Couldn't import PyYAML. Installing it for you...")
import pip
pip.main(["install", "--user", "pyyaml"]) |
eb98db3ceedca1a7dd043eb3579c35dd2257c2ee | test_seasurf.py | test_seasurf.py | import unittest
from flask import Flask
from flaskext.seasurf import SeaSurf
class SeaSurfTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
app.debug = True
app.secret_key = 'hunter2'
self.app = app
csrf = SeaSurf(app)
csrf._csrf_dis... | import unittest
from flask import Flask
from flaskext.seasurf import SeaSurf
class SeaSurfTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
app.debug = True
app.secret_key = 'hunter2'
self.app = app
csrf = SeaSurf(app)
csrf._csrf_dis... | Make tests compatible with python 2.5 and 2.6. | Make tests compatible with python 2.5 and 2.6.
| Python | bsd-3-clause | heamon7/flask-seasurf,killpanda/flask-seasurf | ---
+++
@@ -46,6 +46,13 @@
rv = self.app.test_client().post('/bar')
self.assertIn('403 Forbidden', rv.data)
+ # Methods for backwards compatibility with python 2.5 & 2.6
+ def assertIn(self, value, container):
+ self.assertTrue(value in container)
+
+ def assertIsNotNone(self, valu... |
5cf839df99a03299215db7c2f6d9a78ac724c155 | src/rinoh/language/__init__.py | src/rinoh/language/__init__.py | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
from .cls import Language
from .en import EN
from .fr i... | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
from .cls import Language
from .en import EN
from .fr i... | Fix the rendering of language instance docstrings | Fix the rendering of language instance docstrings
| Python | agpl-3.0 | brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype | ---
+++
@@ -21,11 +21,11 @@
for code, language_ref in Language.languages.items():
language = language_ref()
- lines = []
+ lines = ['Localized strings for {}'.format(language.name)]
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
... |
502ef2c155aeaed7a2b9a2e4ad0471f34ef3790f | app/utils/utilities.py | app/utils/utilities.py | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth() | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0... | Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity | Add validate_email and verify_token methods
Methods to be used to:
- check that a valid email is provided
- check the token authenticity
| Python | mit | Elbertbiggs360/buckelist-api | ---
+++
@@ -6,3 +6,19 @@
from instance.config import Config
auth = HTTPBasicAuth()
+
+
+def validate_email(email):
+ ''' Method to check that a valid email is provided '''
+ email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
+ return True if search(email_re, email) else False
+
+@auth.verify_t... |
099545e7a68ef82af8e8db15dc21746553143310 | statictemplate/management/commands/statictemplate.py | statictemplate/management/commands/statictemplate.py | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... | Add verbose error for a meddling middleware | Add verbose error for a meddling middleware
| Python | bsd-3-clause | ojii/django-statictemplate,bdon/django-statictemplate,yakky/django-statictemplate | ---
+++
@@ -9,6 +9,10 @@
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client
+
+
+class InvalidResponseError(Exception):
+ pass
@contextmanager
@@ -27,6 +31,10 @@
with override_urlconf():
client = Client()
... |
b528b2cf4379369da8277a0a1c904267b5c7cf6f | Lib/test/test_atexit.py | Lib/test/test_atexit.py | # Test the atexit module.
from test_support import TESTFN, vereq
import atexit
import os
input = """\
import atexit
def handler1():
print "handler1"
def handler2(*args, **kargs):
print "handler2", args, kargs
atexit.register(handler1)
atexit.register(handler2)
atexit.register(handler2, 7, kw="abc")
"""
fna... | # Test the atexit module.
from test_support import TESTFN, vereq
import atexit
import os
import sys
input = """\
import atexit
def handler1():
print "handler1"
def handler2(*args, **kargs):
print "handler2", args, kargs
atexit.register(handler1)
atexit.register(handler2)
atexit.register(handler2, 7, kw="abc... | Use sys.executable to run Python, as suggested by Neal Norwitz. | Use sys.executable to run Python, as suggested by Neal Norwitz.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -2,6 +2,7 @@
from test_support import TESTFN, vereq
import atexit
import os
+import sys
input = """\
import atexit
@@ -22,7 +23,7 @@
f.write(input)
f.close()
-p = os.popen("python " + fname)
+p = os.popen("%s %s" % (sys.executable, fname))
output = p.read()
p.close()
vereq(output, """\
@@ -50... |
4381c4cabbeb870f3fe18da4e7bbdee9a39c55fd | dotbot/config.py | dotbot/config.py | import yaml
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
with open(config_file_path) as fin:
data = yaml.load(fin)
return da... | import yaml
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
with open(config_file_path) as fin:
data = yaml.safe_load(fin)
retu... | Use `safe_load` function to load YAML | Use `safe_load` function to load YAML
In our use case, we are *not* reading arbitrary input that could be
malicious. Still, because we know that what we're reading is made up of
only dictionaries and lists and not arbitrary Python objects, we might
as well use the more restrictive `safe_load` function rather than the
... | Python | mit | anishathalye/dotbot,pulgalipe/dotbot,pulgalipe/dotbot,imattman/dotbot,imattman/dotbot,pulgalipe/dotbot,bchretien/dotbot,imattman/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot | ---
+++
@@ -8,7 +8,7 @@
def _read(self, config_file_path):
try:
with open(config_file_path) as fin:
- data = yaml.load(fin)
+ data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e)) |
4409823a5611d0f426ca09541d7e9dc982bc8c9f | asyncqlio/utils.py | asyncqlio/utils.py | """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it ... | """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it ... | Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper. | Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.
| Python | mit | SunDwarf/asyncqlio | ---
+++
@@ -23,7 +23,10 @@
return self
async def __anext__(self):
- return self.__next__()
+ try:
+ return self.__next__()
+ except StopIteration:
+ raise StopAsyncIteration
def iter_to_aiter(type_): |
f1cf2d2e9cbdd4182a5a755b5958e499fc9d9585 | gcloud_expenses/views.py | gcloud_expenses/views.py | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... | Improve status display for reports. | Improve status display for reports.
| Python | apache-2.0 | GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo | ---
+++
@@ -20,11 +20,19 @@
return {'employees': list_employees()}
+def fixup_report(report):
+ if report['status'] == 'paid':
+ report['status'] = 'paid, check #%s' % report.pop('memo')
+ elif report['status'] == 'rejected':
+ report['status'] = 'rejected, #%s' % report.pop('memo')
+ ... |
737e2877cfad9ea801641b72094633a7c0178a44 | UM/Settings/__init__.py | UM/Settings/__init__.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from .SettingDefinition import SettingDefinition
from .SettingInstance import SettingInstance
from .DefinitionContainer import DefinitionContainer
from .InstanceContainer import InstanceContainer
from .ContainerStack i... | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from .ContainerRegistry import ContainerRegistry
from .SettingDefinition import SettingDefinition
from .SettingInstance import SettingInstance
from .DefinitionContainer import DefinitionContainer
from .InstanceContaine... | Add ContainerRegistry to the exposed classes of UM.Settings | Add ContainerRegistry to the exposed classes of UM.Settings
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -1,8 +1,9 @@
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
+from .ContainerRegistry import ContainerRegistry
+
from .SettingDefinition import SettingDefinition
-
from .SettingInstance import SettingInstance
from .DefinitionContainer import Defin... |
d8965e937a0f5b649c80c9ac14a3d5652d5a1859 | getContentFromURL.py | getContentFromURL.py | # Team nameSpace@HINT2017
#
# This script contains a function which takes a URL as input
# and returns the content of the content in the webpage
# 'newspaper' library is used here to extract only the main
# content in a webpage
from flask import Flask,render_template
import urllib
from newspaper import Article
app =... | # Team nameSpace@HINT2017
#
# This script contains a function which takes a URL as input
# and returns the content of the content in the webpage
# 'newspaper' library is used here to extract only the main
# content in a webpage
from flask import Flask,render_template
import urllib
from newspaper import Article
app =... | Return keywords instead of summary | Return keywords instead of summary
| Python | mit | urdarinda/LISTS,urdarinda/LISTS,urdarinda/LISTS | ---
+++
@@ -17,14 +17,17 @@
return "Please enter a valid url"
@app.route('/', defaults={'path': ''})
-@app.route('/<path:path>')
-def getContentFromURL(path):
- article = Article(path)
+@app.route('/<path:url>')
+def getContentFromURL(url):
+ article = Article(url)
article.download()
article.parse()
artic... |
243bb615c579c0598a2f2be5791d3d5092dcd556 | invoice/tasks.py | invoice/tasks.py | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... | Remove HTML table (our mail cannot send HTML) | Remove HTML table (our mail cannot send HTML)
| Python | apache-2.0 | pkimber/invoice,pkimber/invoice,pkimber/invoice | ---
+++
@@ -22,29 +22,19 @@
for user in users:
logger.info('mail_time_summary: {}'.format(user.username))
report = time_summary(user, days=1)
- message = '<table border="0">'
+ message = ''
for d, summary in report.items():
- message = message + '<tr colspan="3... |
5e5f5c8bfb5b61bd87ff4e55004e80c0e7edf408 | ikea-ota-download.py | ikea-ota-download.py | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... | Update json.loads line for python 3.5 | Update json.loads line for python 3.5
Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'".
Fixed it by decoding downloaded json to utf-8 | Python | bsd-3-clause | dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin | ---
+++
@@ -16,7 +16,7 @@
f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json")
data = f.read()
-arr = json.loads(data)
+arr = json.loads(data.decode('utf-8'))
otapath = '%s/otau' % os.path.expanduser('~')
|
208081800ab7e6217ec0f88e76c2dffd32187db1 | whyp/shell.py | whyp/shell.py | import os
from pysyte.types.paths import path
def value(key):
"""A value from the shell environment, defaults to empty string
>>> value('SHELL') is not None
True
"""
try:
return os.environ[key]
except KeyError:
return ''
def paths(name=None):
"""A list of paths in the ... | import os
from pysyte.types.paths import path
def value(key):
"""A value from the shell environment, defaults to empty string
>>> value('SHELL') is not None
True
"""
try:
return os.environ[key]
except KeyError:
return ''
def paths(name=None):
"""A list of paths in the ... | Allow for missing directories in $PATH | Allow for missing directories in $PATH
| Python | mit | jalanb/what,jalanb/what | ---
+++
@@ -36,6 +36,8 @@
"""
commands = {}
for path_dir in paths():
+ if not path_dir.isdir():
+ continue
for file_path in path_dir.list_files():
if not file_path.isexec():
continue |
c727f8382237c177d508d5113a7e3b8ca8ea7066 | fasta/graphs.py | fasta/graphs.py | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... | Return graph object after ploting | Return graph object after ploting
| Python | mit | xapple/fasta | ---
+++
@@ -35,3 +35,5 @@
if y_log: axes.set_yscale('symlog')
# Save it #
self.save_plot(fig, axes, sep=('x'))
+ # For convenience #
+ return self |
1851190543d24d6f4c26a5d7a3a04f56aeba511d | sheldon/exceptions.py | sheldon/exceptions.py | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
""" | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.utils import logger
def catch_plugin_errors(plugin_call_function):
"""
Catch all plugin exceptions and log it
:param plugin_call_function: function with calling... | Create decorator for catching plugin errors | Create decorator for catching plugin errors
| Python | mit | lises/sheldon | ---
+++
@@ -7,3 +7,22 @@
Copyright (C) 2015
"""
+
+from sheldon.utils import logger
+
+
+def catch_plugin_errors(plugin_call_function):
+ """
+ Catch all plugin exceptions and log it
+
+ :param plugin_call_function: function with calling user plugin
+ :return:
+ """
+ def wrapper(*args, **kwargs... |
301fd00ea31346126d78696c50ac9daf1b76a428 | classifier.py | classifier.py | import training_data
import re
import math
class Classifier:
def classify(self,text,prior=0.5,c=10e-6):
""" Remove a pontuacao do texto """
words = re.findall(r"[\w']+",text)
"""words = text.split()"""
data = training_data.TrainingData()
spamLikehood = math.log(1)
hamLikehood = math.log(1)
for word in ... | import re
import math
class Classifier:
def classify(self,text,trainingData,prior=0.5,c=10e-6):
""" Remove a pontuacao do texto """
words = re.findall(r"[\w']+",text)
"""words = text.split()"""
likehood = math.log(1)
for word in words:
""" Calculo do likehood """
if word in trainingData:
likehood... | Change so that we can use with any data | Change so that we can use with any data
| Python | mit | anishihara/SpamFilter | ---
+++
@@ -1,26 +1,16 @@
-import training_data
import re
import math
class Classifier:
- def classify(self,text,prior=0.5,c=10e-6):
+ def classify(self,text,trainingData,prior=0.5,c=10e-6):
""" Remove a pontuacao do texto """
words = re.findall(r"[\w']+",text)
"""words = text.split()"""
- data = trai... |
bc083087cd7aadbf11fba9a8d1312bde3b7a2a27 | osgtest/library/mysql.py | osgtest/library/mysql.py | import os
from osgtest.library import core
from osgtest.library import service
def name():
if core.el_release() < 7:
return 'mysql'
else:
return 'mariadb'
def daemon_name():
if core.el_release() < 7:
return 'mysqld'
else:
return 'mariadb'
def init_script():
return... | import os
import re
from osgtest.library import core
from osgtest.library import service
def name():
if core.el_release() < 7:
return 'mysql'
else:
return 'mariadb'
def daemon_name():
if core.el_release() < 7:
return 'mysqld'
else:
return 'mariadb'
def init_script():
... | Add several useful MySQL functions | Add several useful MySQL functions
Functions useful for examining and manipulating MySQL databases:
- execute() -- execute one or more MySQL statements (as a single string),
optionally on a specific database. Returns the same thing as core.system()
- check_execute() -- same as execute(), but checks return code and
... | Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | ---
+++
@@ -1,4 +1,5 @@
import os
+import re
from osgtest.library import core
from osgtest.library import service
@@ -35,3 +36,24 @@
def is_running():
service.is_running('mysql', init_script=init_script())
+
+def _get_command(user='root', database=None):
+ command = ['mysql', '-N', '-B', '--user=' + s... |
4cd0d2a947bbfa9ba830c4dc543b1688ecf2e54f | produceEports.py | produceEports.py | #!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
f = open("app/static/exports/AllMeasurements_inprogress.csv", "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/Al... | #!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename("app/static/exports/... | Add application directory to export directory | Add application directory to export directory
| Python | mit | rabramley/telomere,rabramley/telomere,rabramley/telomere | ---
+++
@@ -3,7 +3,7 @@
import tempfile
import os
-f = open("app/static/exports/AllMeasurements_inprogress.csv", "w")
+f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w")
try:
write_all_measurements_csv(f) |
4072f8ec6e1908d6e84859c8a0bd6c96562ea5cc | parts/plugins/x-shell.py | parts/plugins/x-shell.py | import snapcraft
class ShellPlugin(snapcraft.BasePlugin):
@classmethod
def schema(cls):
schema = super().schema()
schema['required'] = []
schema['properties']['shell'] = {
'type': 'string',
'default': '/bin/sh',
}
schema['required'].append('shell')
schema['properties']['shell-flags'] = {
'typ... | import snapcraft
class ShellPlugin(snapcraft.BasePlugin):
@classmethod
def schema(cls):
schema = super().schema()
schema['required'] = []
schema['properties']['shell'] = {
'type': 'string',
'default': '/bin/sh',
}
schema['required'].append('shell')
schema['properties']['shell-flags'] = {
'typ... | Add "SNAPDIR" and simple vim modeline | Add "SNAPDIR" and simple vim modeline
| Python | mit | infosiftr/snap-docker,docker-snap/docker,docker-snap/docker | ---
+++
@@ -31,6 +31,7 @@
def env(self, root):
return super().env(root) + [
'DESTDIR=' + self.installdir,
+ 'SNAPDIR=' + self.builddir,
]
def build(self):
@@ -41,3 +42,5 @@
] + self.options.shell_flags + [
'-c', self.options.shell_command,
])
+
+# vim:set ts=4 noet: |
338672c4f79fe01b4801346594bcd0d95a925e75 | python-prefix.py | python-prefix.py | #!/usr/bin/env python
import sys
import os.path
import site
def main():
'''\
Check if the given prefix is included in sys.path for the given
python version; if not find an alternate valid prefix. Print the
result to standard out.
'''
if len(sys.argv) != 3:
msg = 'usage: %s <prefix> <p... | #!/usr/bin/env python
import sys
import os.path
import site
def main():
'''\
Check if the given prefix is included in sys.path for the given
python version; if not find an alternate valid prefix. Print the
result to standard out.
'''
if len(sys.argv) != 3:
msg = 'usage: %s <prefix> <p... | Fix typo in previous commit. | Fix typo in previous commit. | Python | bsd-2-clause | D3f0/coreemu,abn/coreemu,cudadog/coreemu,cudadog/coreemu,abn/coreemu,D3f0/coreemu,abn/coreemu,D3f0/coreemu,eiginn/coreemu,eiginn/coreemu,cudadog/coreemu,eiginn/coreemu | ---
+++
@@ -24,7 +24,7 @@
prefix = None
for p in sys.path:
if p.startswith(path):
- prefix = path
+ prefix = python_prefix
break
if not prefix:
prefix = site.PREFIXES[-1] |
f035ca424504a37e350fd009e973b89ba7e00670 | desertbot/datastore.py | desertbot/datastore.py | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
with open(os.path.join("desertbot", "datastore_d... | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
with open(os.path.join("desertbot", "datastore_d... | Load data from defaults if defaults has keys that data doesn't. | Load data from defaults if defaults has keys that data doesn't.
| Python | mit | DesertBot/DesertBot | ---
+++
@@ -16,6 +16,17 @@
return
with open(self.storagePath) as storageFile:
self.data = json.load(storageFile)
+ self.checkDefaults()
+
+ def checkDefaults(self):
+ """
+ If data exists, we still wanna make sure we load in things from defaults if there's th... |
bbb12dd60222ae617e5ed70d37c0ea3d350b9f3a | satsound/views.py | satsound/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... | Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite | Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
| Python | mit | saanobhaai/apman,saanobhaai/apman | ---
+++
@@ -14,16 +14,32 @@
@login_required
def satellite(request, norad_id):
- sat = {'pk': norad_id, 'name': 'not found'}
+ sat = {'pk': norad_id, 'name': 'TBD'}
+ newsat = False
try:
sat = Satellite.objects.get(pk=norad_id)
except Satellite.DoesNotExist:
- pass
+ newsa... |
a967b62c5f11b35ac3b31d64975ea62471be8295 | script_helpers.py | script_helpers.py | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | Add destination directory to default arguments for scripts | Add destination directory to default arguments for scripts
| Python | bsd-3-clause | mwcraig/msumastro | ---
+++
@@ -54,6 +54,22 @@
help="Directory to process")
+def add_destination_directory(parser):
+ """
+ Add a destination directory option
+
+ Parameters
+ ----------
+
+ parser : `ArgumentParser`
+
+ """
+ arg_help = 'Directory in which output from this script will b... |
1d828dfdb77cf69ce88386c3bb98036d851a891a | data_structures/linked_list.py | data_structures/linked_list.py | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
... | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
... | Add methods to linked list. | Add methods to linked list.
| Python | mit | sjschmidt44/python_data_structures | ---
+++
@@ -38,20 +38,41 @@
self._current = self._current.next
return node
- def insert(self):
- pass
+ def insert(self, val):
+ '''Insert new Node at head of Linked List.'''
+ self.head = Node(val, self.head)
+ self.length += 1
+ return None
+
+ def pop... |
788f9f3d917491355e819263c754ec637caaf261 | evesrp/util/request.py | evesrp/util/request.py | from __future__ import unicode_literals
from flask import Request
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['application/rss+xml', 'application/rd... | from __future__ import unicode_literals
from flask import Request
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['application/rss+xml', 'application/rd... | Reorder preferred mimetypes to prefer HTML over JSON | Reorder preferred mimetypes to prefer HTML over JSON | Python | bsd-2-clause | paxswill/evesrp,paxswill/evesrp,paxswill/evesrp | ---
+++
@@ -14,8 +14,8 @@
@property
def _known_mimetypes(self):
- return self._json_mimetypes + \
- self._html_mimetypes + \
+ return self._html_mimetypes + \
+ self._json_mimetypes + \
self._xml_mimetypes + \
self._rss_mimetypes
|
9ba1a13de76881c9951e8ca330d6f99b8a279446 | devtools/ci/set_doc_version.py | devtools/ci/set_doc_version.py | import os
import shutil
import msmbuilder.version
if msmbuilder.version.release:
docversion = msmbuilder.version.short_version
else:
docversion = 'latest'
os.mkdir("doc/_deploy")
shutil.copytree("doc/_build", "doc/_deploy/{docversion}"
.format(docversion=docversion))
| import os
import shutil
import msmbuilder.version
if msmbuilder.version.release:
docversion = msmbuilder.version.short_version
else:
docversion = 'development'
os.mkdir("doc/_deploy")
shutil.copytree("doc/_build", "doc/_deploy/{docversion}"
.format(docversion=docversion))
| Send docs to development/ not latest/ | Send docs to development/ not latest/
| Python | lgpl-2.1 | Eigenstate/msmbuilder,brookehus/msmbuilder,rmcgibbo/msmbuilder,rmcgibbo/msmbuilder,mpharrigan/mixtape,rmcgibbo/msmbuilder,dr-nate/msmbuilder,msultan/msmbuilder,peastman/msmbuilder,dr-nate/msmbuilder,brookehus/msmbuilder,msmbuilder/msmbuilder,rmcgibbo/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,dr-nate/msmbuild... | ---
+++
@@ -6,7 +6,7 @@
if msmbuilder.version.release:
docversion = msmbuilder.version.short_version
else:
- docversion = 'latest'
+ docversion = 'development'
os.mkdir("doc/_deploy")
shutil.copytree("doc/_build", "doc/_deploy/{docversion}" |
46ab82bf387b6f7d13abc94bacb16b76bc292080 | util/cron/verify_config_names.py | util/cron/verify_config_names.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
config_name = content.split('"')[1]
expe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import os.path
import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
filename_parts = os... | Update config name verify script to work with the .bat files. | Update config name verify script to work with the .bat files.
| Python | apache-2.0 | chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel... | ---
+++
@@ -7,14 +7,27 @@
from __future__ import print_function
+import os.path
+import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
- config_name = content.split('"')[1]
- expected_script_name = 'test-{0}.bash'.format(config_name)
+ filename_parts =... |
637953efa1f71b123bb28c8404b79219a6bd6b3e | fablab-businessplan.py | fablab-businessplan.py | # -*- encoding: utf-8 -*-
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: MIT
#
import xlsxwriter
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet... | # -*- encoding: utf-8 -*-
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: MIT
#
import xlsxwriter
# Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
... | Add structure and first styles | Add structure and first styles
| Python | mit | openp2pdesign/FabLab-BusinessPlan | ---
+++
@@ -6,6 +6,8 @@
#
import xlsxwriter
+
+# Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
@@ -16,8 +18,38 @@
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Tot... |
54691f9be052e5564ca0e5c6a503e641ea3142e1 | keras/layers/normalization.py | keras/layers/normalization.py | from ..layers.core import Layer
from ..utils.theano_utils import shared_zeros
from .. import initializations
class BatchNormalization(Layer):
'''
Reference:
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
http://arxiv.org/pdf/1502.03... | from ..layers.core import Layer
from ..utils.theano_utils import shared_zeros
from .. import initializations
import theano.tensor as T
class BatchNormalization(Layer):
'''
Reference:
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
h... | Add modes to BatchNormalization, fix BN issues | Add modes to BatchNormalization, fix BN issues | Python | mit | yingzha/keras,imcomking/Convolutional-GRU-keras-extension-,jayhetee/keras,why11002526/keras,marchick209/keras,relh/keras,mikekestemont/keras,florentchandelier/keras,jbolinge/keras,tencrance/keras,meanmee/keras,kuza55/keras,nehz/keras,keras-team/keras,EderSantana/keras,kemaswill/keras,abayowbo/keras,dhruvparamhans/keras... | ---
+++
@@ -1,17 +1,23 @@
from ..layers.core import Layer
from ..utils.theano_utils import shared_zeros
from .. import initializations
+
+import theano.tensor as T
class BatchNormalization(Layer):
'''
Reference:
Batch Normalization: Accelerating Deep Network Training by Reducing Inte... |
3b30a036f9f9fb861c0ed1711b5bd967756a072d | flask_cors/__init__.py | flask_cors/__init__.py | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | Disable logging for flask_cors by default | Disable logging for flask_cors by default
| Python | mit | corydolphin/flask-cors,ashleysommer/sanic-cors | ---
+++
@@ -23,4 +23,10 @@
def emit(self, record):
pass
-logging.getLogger(__name__).addHandler(NullHandler())
+# Set initial level to WARN. Users must manually enable logging for
+# flask_cors to see our logging.
+rootlogger = logging.getLogger(__name__)
+rootlogger.addHandler(NullHandler())
... |
3699cc594d9a4f02d24308cb41b8757124616f78 | boltiot/requesting.py | boltiot/requesting.py | from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except req... | from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except req... | Add ERROR: keyword in error message return | Add ERROR: keyword in error message return
| Python | mit | Inventrom/bolt-api-python | ---
+++
@@ -14,7 +14,7 @@
except requests.exceptions.RequestException as err:
return str({"success":"0", "message":"Not able to handle error"})
except Exception as err:
- return str({"success":"0", "message":str(err)})
+ return str({"success":"0", "message": "ERROR: " + str(err)})
... |
7feb7eeba7e591f7a0c1cbf3b72efb099bd9f644 | hijack/urls.py | hijack/urls.py | from compat import patterns, url
from django.conf import settings
urlpatterns = patterns('hijack.views',
url(r'^release-hijack/$', 'release_hijack', name='release_hijack'),
)
if getattr(settings, "HIJACK_NOTIFY_ADMIN", False):
urlpatterns += patterns('hijack.views',
url(r'^disable-hijack-warning/$', '... | from compat import patterns, url
from django.conf import settings
urlpatterns = patterns('hijack.views',
url(r'^release-hijack/$', 'release_hijack', name='release_hijack'),
)
if getattr(settings, "HIJACK_NOTIFY_ADMIN", False):
urlpatterns += patterns('hijack.views',
url(r'^disable-hijack-warning/$', '... | Use a more liberal/naive approach to regex checking for an email | Use a more liberal/naive approach to regex checking for an email
The problem with the old method is that it does not support
- Internationalized TLDs, domains or users, such as .xn--4gbrim domains
- Geographic TLDs, such as .europe
- ICANN-era TLDs, such as .audio and .clothing
The new regex still matches <anything>@... | Python | mit | arteria/django-hijack,arteria/django-hijack,arteria/django-hijack | ---
+++
@@ -14,7 +14,7 @@
if not hijacking_user_attributes or 'email' in hijacking_user_attributes:
urlpatterns += patterns('hijack.views',
- url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email')
+ url(r'^email/(?P<email>[^@]+@[^@]+\.[^@... |
5f6ba1b3a1f2798df1e17d2c29785f04939bd847 | src/test/testlexer.py | src/test/testlexer.py |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, ( text, tp ) ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
def test_hello_world():
... |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
if... | Test line numbers in lexer tests. | Test line numbers in lexer tests.
| Python | mit | andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper | ---
+++
@@ -7,17 +7,21 @@
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
-def _assert_token( token, ( text, tp ) ):
+def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
+ if line is no... |
a8811b5a746533467281437575b1fbaf776e5df9 | nhlstats/__init__.py | nhlstats/__init__.py |
import logging
from version import __version__
logger = logging.getLogger(__name__)
logger.debug('Loading %s ver %s' % (__name__, __version__))
# Actions represents the available textual items that can be passed to main
# to drive dispatch. These should be all lower case, no spaces or underscores.
actions = [
... |
import logging
from version import __version__
logger = logging.getLogger(__name__)
logger.debug('Loading %s ver %s' % (__name__, __version__))
# Actions represents the available textual items that can be passed to main
# to drive dispatch. These should be all lower case, no spaces or underscores.
actions = [
... | Fix case in function names to be PEP8 compatible | Fix case in function names to be PEP8 compatible
| Python | mit | fancystats/nhlstats | ---
+++
@@ -16,16 +16,16 @@
]
-def GetDataForGame(game):
+def get_data_for_game(game):
pass
-def GetDataForGames(games=[]):
+def get_data_for_games(games=[]):
for game in games:
- GetDataForGame(game)
+ get_data_for_game(game)
-def GetGames(active=True, beginning=None, end=None):
... |
ebe7e1012ddc1286d61de5c5a565aff9cd4faedf | stdnum/jp/__init__.py | stdnum/jp/__init__.py | # __init__.py - collection of Japanese numbers
# coding: utf-8
#
# Copyright (C) 2019 Alan Hettinger
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License,... | # __init__.py - collection of Japanese numbers
# coding: utf-8
#
# Copyright (C) 2019 Alan Hettinger
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License,... | Add missing vat alias for Japan | Add missing vat alias for Japan
| Python | lgpl-2.1 | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum | ---
+++
@@ -19,3 +19,4 @@
# 02110-1301 USA
"""Collection of Japanese numbers."""
+from stdnum.jp import cn as vat # noqa: F401 |
e0308672543d0bbe8309351c9d63732d0d0e3e30 | steel/fields/mixin.py | steel/fields/mixin.py | from gettext import gettext as _
class Fixed:
_("A mixin that ensures the presence of a predetermined value")
def __init__(self, value, *args, **kwargs):
self.value = value
super(Fixed, self).__init__(*args, **kwargs)
def encode(self, value):
# Always encode the fixed value
... | from gettext import gettext as _
class Fixed:
_("A mixin that ensures the presence of a predetermined value")
def __init__(self, value, *args, **kwargs):
self.value = value
# Pass the value in as a default as well, to make
# sure it goes through when no value was supplied
sup... | Include fixed values as defaults | Include fixed values as defaults
I'm not a big fan of this approach, but it avoids a good bit of code duplication
| Python | bsd-3-clause | gulopine/steel-experiment | ---
+++
@@ -6,7 +6,10 @@
def __init__(self, value, *args, **kwargs):
self.value = value
- super(Fixed, self).__init__(*args, **kwargs)
+
+ # Pass the value in as a default as well, to make
+ # sure it goes through when no value was supplied
+ super(Fixed, self).__init__(*ar... |
ad477313b38ff97c69c5bd281a540138c04354e2 | githistorydata/main.py | githistorydata/main.py |
import subprocess
import sys
from githistorydata.csv import Csv
from githistorydata.expand_commits import expand_authors, expand_lines
from githistorydata.git import Git
from githistorydata.rawgit import RawGit
def main( argv, out, err ):
try:
git = Git( RawGit() )
csv = Csv(
out,
... |
import subprocess
import sys
from githistorydata.csv import Csv
from githistorydata.expand_commits import expand_authors, expand_lines
from githistorydata.git import Git
from githistorydata.rawgit import RawGit
def main( argv, out, err ):
try:
git = Git( RawGit() )
csv = Csv(
out,
... | Rename column "Hash" to "Commit". | Rename column "Hash" to "Commit".
| Python | bsd-2-clause | andybalaam/git-history-data,andybalaam/git-history-data | ---
+++
@@ -13,7 +13,7 @@
git = Git( RawGit() )
csv = Csv(
out,
- ( "Hash", "Date", "Author", "Added", "Removed", "File" )
+ ( "Commit", "Date", "Author", "Added", "Removed", "File" )
)
for cod in expand_lines( git, expand_authors( git.log() ) ):
... |
a287c1e7a6e96a2a2143e9270a5f9b2ec295022e | fireplace/cards/removed/all.py | fireplace/cards/removed/all.py | """
Cards removed from the game
"""
from ..utils import *
# Adrenaline Rush
class NEW1_006:
action = drawCard
combo = drawCards(2)
# Bolstered (Bloodsail Corsair)
class NEW1_025e:
Health = 1
| """
Cards removed from the game
"""
from ..utils import *
# Dagger Mastery
class CS2_083:
def action(self):
if self.hero.weapon:
self.hero.weapon.buff("CS2_083e")
else:
self.hero.summon("CS2_082")
class CS2_083e:
Atk = 1
# Adrenaline Rush
class NEW1_006:
action = drawCard
combo = drawCards(2)
# Bo... | Implement the old Dagger Mastery | Implement the old Dagger Mastery
| Python | agpl-3.0 | Ragowit/fireplace,beheh/fireplace,NightKev/fireplace,liujimj/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,liujimj/fireplace,butozerca/fireplace,oftc-ftw/fireplace,smallnamespace/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,Ragowit/fireplace,Meerkov/fi... | ---
+++
@@ -3,6 +3,18 @@
"""
from ..utils import *
+
+
+# Dagger Mastery
+class CS2_083:
+ def action(self):
+ if self.hero.weapon:
+ self.hero.weapon.buff("CS2_083e")
+ else:
+ self.hero.summon("CS2_082")
+
+class CS2_083e:
+ Atk = 1
# Adrenaline Rush |
a6a405cbcb3ba2696d63473f0f7892b18ac0e6dc | application.py | application.py | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging
application = create_app(
os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manage... | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
import watchtower
import logging
application = create_app(
os.getenv('EQ_ENVIRONMENT') or 'development'
)
application.debug = True
manager = Manager(application)
port = int(os.environ.get('PORT', 5000))
manage... | Allow logging level to be selected through environment variable | Allow logging level to be selected through environment variable
| Python | mit | ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner | ---
+++
@@ -17,7 +17,14 @@
cloud_watch_handler = watchtower.CloudWatchLogHandler()
-logging.basicConfig(level=logging.INFO)
+levels = {
+ 'CRITICAL': logging.CRITICAL,
+ 'ERROR': logging.ERROR,
+ 'WARNING': logging.WARNING,
+ 'INFO': logging.INFO,
+ 'DEBUG': logging.DEBUG
+}
+logging.basicConfig(l... |
6184fb10b7a48df4e7c75485ed12b4a389dd3c3c | avatar/conf.py | avatar/conf.py | from django.conf import settings
from PIL import Image
from appconf import AppConf
class AvatarConf(AppConf):
DEFAULT_SIZE = 80
RESIZE_METHOD = Image.ANTIALIAS
STORAGE_DIR = 'avatars'
GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/'
GRAVATAR_BACKUP = True
GRAVATAR_DEFAULT = None
DEFA... | from django.conf import settings
from PIL import Image
from appconf import AppConf
class AvatarConf(AppConf):
DEFAULT_SIZE = 80
RESIZE_METHOD = Image.ANTIALIAS
STORAGE_DIR = 'avatars'
GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/'
GRAVATAR_BACKUP = True
GRAVATAR_DEFAULT = None
DEF... | Use https to gravatar url | Use https to gravatar url
| Python | bsd-3-clause | therocode/django-avatar,dannybrowne86/django-avatar,brajeshvit/avatarmodule,barbuza/django-avatar,imgmix/django-avatar,grantmcconnaughey/django-avatar,jezdez/django-avatar,ad-m/django-avatar,MachineandMagic/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,brajeshvit/avatarmodule,therocode/django-avata... | ---
+++
@@ -8,7 +8,7 @@
DEFAULT_SIZE = 80
RESIZE_METHOD = Image.ANTIALIAS
STORAGE_DIR = 'avatars'
- GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/'
+ GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/'
GRAVATAR_BACKUP = True
GRAVATAR_DEFAULT = None
DEFAULT_URL = 'avatar/im... |
01fce49f6ecb0a5c6ff5db858efd0ea1e88608b3 | sensors/dylos.py | sensors/dylos.py | import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1... | import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1... | Fix bug with fan turning itself off | Fix bug with fan turning itself off
This would happen when the service was restarted. In the stopping code,
I added a call to clean up.
| Python | apache-2.0 | VDL-PRISM/dylos | ---
+++
@@ -46,4 +46,5 @@
def stop(self):
self.running = False
+ GPIO.cleanup(DYLOS_POWER_PIN)
self.ser.close() |
2d94532e316e9ad563b3b7506d47cfd78ca7f689 | tests/test_cattery.py | tests/test_cattery.py | import pytest
from catinabox import cattery
###########################################################################
# add_cats
###########################################################################
def test__add_cats__succeeds():
c = cattery.Cattery()
c.add_cats(["Fluffy", "Snookums"])
assert c... | import pytest
from catinabox import cattery
###########################################################################
# fixtures
###########################################################################
@pytest.fixture
def c():
return cattery.Cattery()
#####################################################... | Add fixtures to cattery tests | Step_5: Add fixtures to cattery tests
Add a fixture to remove initialisation of the cattery in every test.
Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>
| Python | mit | indexOutOfBound5/catinabox | ---
+++
@@ -4,11 +4,19 @@
###########################################################################
+# fixtures
+###########################################################################
+
+@pytest.fixture
+def c():
+ return cattery.Cattery()
+
+
+##########################################################... |
6d859d72ac2091b1f5bc50c5a5c8d13cd13ff697 | photobox/photobox.py | photobox/photobox.py | from os.path import expanduser
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from switch import KeyboardSwitch
# from rcswitch import RCSwitch
##########
# config #
##########
photodirectory = '/var/www/html/'
windowwidth = 1024
windowheigh... | from os.path import expanduser
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from switch import KeyboardSwitch
# from rcswitch import RCSwitch
##########
# config #
##########
photodirectory = '/var/www/html/'
windowwidth = 1024
windowheigh... | Change comments to represents correct type | Change comments to represents correct type
| Python | mit | MarkusAmshove/Photobox | ---
+++
@@ -14,7 +14,7 @@
windowwidth = 1024
windowheight = 768
camera = Gphoto()
-# switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT")
+# switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT)
switch = KeyboardSwitch()
##########
filesystemFolder = RealFolder(photodirectory) |
2ecdd2feb18ef23610e55242b70b64ce0d6f6fe9 | src/sentry/app.py | src/sentry/app.py | """
sentry.app
~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from sentry.conf import settings
from sentry.utils.imports import import_string
from threading import local
class State(local):
request = None
def get_buffer(p... | """
sentry.app
~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from sentry.conf import settings
from sentry.utils.imports import import_string
from threading import local
class State(local):
request = None
def get_buffer(p... | Raise an import error when import_string fails on get_buffer | Raise an import error when import_string fails on get_buffer
| Python | bsd-3-clause | mvaled/sentry,llonchj/sentry,argonemyth/sentry,songyi199111/sentry,1tush/sentry,fotinakis/sentry,BayanGroup/sentry,alexm92/sentry,NickPresta/sentry,fotinakis/sentry,jokey2k/sentry,looker/sentry,fuziontech/sentry,imankulov/sentry,felixbuenemann/sentry,boneyao/sentry,Kryz/sentry,drcapulet/sentry,rdio/sentry,SilentCircle/... | ---
+++
@@ -17,6 +17,8 @@
def get_buffer(path, options):
cls = import_string(path)
+ if cls is None:
+ raise ImportError('Unable to find module %s' % path)
return cls(**options)
buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) |
80de36ddbe4e2eb2e0d00d5910ab8c199d1a6edb | gom_server/char_attr/router.py | gom_server/char_attr/router.py | from rest_framework import routers, serializers, viewsets
import models
# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
attributes = AttributeSerializer(many... | from rest_framework import routers, serializers, viewsets
import models
# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
attributes = AttributeSerializer(many... | Add api end point /api-detail/ | Add api end point /api-detail/
| Python | bsd-2-clause | jhogg41/gm-o-matic,jhogg41/gm-o-matic,jhogg41/gm-o-matic | ---
+++
@@ -17,7 +17,11 @@
def get_queryset(self):
gameid = self.kwargs['gameid']
return models.AttributeType.objects.filter(game=gameid)
+class AttributeDetailViewSet(viewsets.ModelViewSet):
+ serializer_class = AttributeSerializer
+ queryset = models.Attribute.objects.all()
# Register actua... |
6611641fec2342fa8dcfdbf12d74558df65ed2eb | isserviceup/services/heroku.py | isserviceup/services/heroku.py | import requests
from isserviceup.services.models.service import Service, Status
class Heroku(Service):
name = 'Heroku'
status_url = 'https://status.heroku.com/'
icon_url = '/images/icons/heroku.png'
def get_status(self):
r = requests.get('https://status.heroku.com/api/v3/current-status')
... | import requests
from isserviceup.services.models.service import Service, Status
class Heroku(Service):
name = 'Heroku'
status_url = 'https://status.heroku.com/'
icon_url = '/images/icons/heroku.png'
def get_status(self):
r = requests.get('https://status.heroku.com/api/v3/current-status')
... | Raise exception for unexpected status | Raise exception for unexpected status
| Python | apache-2.0 | marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up | ---
+++
@@ -21,3 +21,6 @@
return Status.major
elif status == 'red':
return Status.critical
+ else:
+ raise Exception('unexpected status')
+ |
fcddaececf4d30fa8588f72812338e551efea056 | oscar/apps/wishlists/forms.py | oscar/apps/wishlists/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | Use bootstrap input styles to shrink quantity field width | Use bootstrap input styles to shrink quantity field width
| Python | bsd-3-clause | faratro/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,kapt/django-oscar,eddiep1101/django-oscar,itbabu/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,solarissmoke/django-oscar,jinnykoo/wuyisj.com,MatthewWilkes/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,michaelkuty/django-os... | ---
+++
@@ -22,7 +22,7 @@
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
- self.fields['quantity'].widget.attrs['size'] = 2
+ self.fields['quantity'].widget.attrs['class'] = 'input-mini'
LineFormset = inlineformset_factory( |
903030fc0a0d545e652337d543c6167e2bb192b1 | pyaggr3g470r/duplicate.py | pyaggr3g470r/duplicate.py | #! /usr/bin/env python
#-*- coding: utf-8 -*-
import itertools
import utils
def compare_documents(feed):
"""
Compare a list of documents by pair.
"""
duplicates = []
for pair in itertools.combinations(feed.articles, 2):
if pair[0].content != "" and pair[0].content == pair[1].content:
... | #! /usr/bin/env python
#-*- coding: utf-8 -*-
import itertools
import utils
def compare_documents(feed):
"""
Compare a list of documents by pair.
"""
duplicates = []
for pair in itertools.combinations(feed.articles, 2):
if pair[0].content != "" and \
(utils.clear_string(pair[0... | Test the equality of the contents and of the titles. | Test the equality of the contents and of the titles.
| Python | agpl-3.0 | JARR-aggregator/JARR,jaesivsm/JARR,JARR-aggregator/JARR,cedricbonhomme/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR-aggregator/JARR,jaesivsm/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,JARR/JARR,cedricbonhomme/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,jaesivsm/pyAggr3g470r,jaesivsm/JARR... | ---
+++
@@ -11,6 +11,8 @@
"""
duplicates = []
for pair in itertools.combinations(feed.articles, 2):
- if pair[0].content != "" and pair[0].content == pair[1].content:
+ if pair[0].content != "" and \
+ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \... |
177418e6331f8fb02f8176ea37dc7aef2f586586 | settings/__init__.py | settings/__init__.py | # this is a hack to work around https://code.djangoproject.com/ticket/15064
# normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day
# this way if you run ./manage.py without specifying a --settings you'll get the dev settings
from .development import * | Work around Django bug in manage.py | Work around Django bug in manage.py
manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development
| Python | mit | QLGu/djangopackages,nanuxbe/djangopackages,miketheman/opencomparison,miketheman/opencomparison,benracine/opencomparison,pydanny/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,benracine/opencomparison,QLGu/djangopackages,audreyr/opencomparison,pydanny/djangopackages,nanuxbe/djangopackages,audreyr/opencomparis... | ---
+++
@@ -0,0 +1,4 @@
+# this is a hack to work around https://code.djangoproject.com/ticket/15064
+# normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day
+# this way if you run ./manage.py without specifying a --settings you'll get the dev settings
+from .developme... | |
a5dd30e38e58c08d67a2f831e2ae3cbc4a288337 | diary/admin.py | diary/admin.py | from django.contrib import admin
from diary.models import DiaryItem, EventLocation, ImageItem
class DiaryAdmin(admin.ModelAdmin):
list_display = ('title', 'start_date', 'start_time', 'author', 'location')
# Register your models here.
admin.site.register(DiaryItem, DiaryAdmin)
admin.site.register(EventLocation)
admi... | from django.contrib import admin
from diary.models import DiaryItem, EventLocation, ImageItem
class DiaryAdmin(admin.ModelAdmin):
list_display = ('title', 'start_date', 'start_time', 'author', 'location')
exclude = ('author',)
def save_model(self, request, obj, form, change):
if obj.pk is None:
... | Set author automatically for diary items | Set author automatically for diary items
| Python | mit | DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at | ---
+++
@@ -2,7 +2,12 @@
from diary.models import DiaryItem, EventLocation, ImageItem
class DiaryAdmin(admin.ModelAdmin):
- list_display = ('title', 'start_date', 'start_time', 'author', 'location')
+ list_display = ('title', 'start_date', 'start_time', 'author', 'location')
+ exclude = ('author',)
+ de... |
27a7e589ec3f5b29d99cede4af66780509ab6973 | foursquare/tests/test_photos.py | foursquare/tests/test_photos.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... | Make test compatible with Python 2.6. | Make test compatible with Python 2.6.
| Python | mit | mLewisLogic/foursquare,mLewisLogic/foursquare | ---
+++
@@ -22,14 +22,14 @@
"""Creates a checkin and attaches a photo to it."""
response = self.api.checkins.add(params={'venueId': self.default_venueid})
checkin = response.get('checkin')
- self.assertIsNotNone(checkin)
+ self.assertNotEqual(checkin, None)
photo_da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.