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 |
|---|---|---|---|---|---|---|---|---|---|---|
9ab1530a010e974a376c75da806016185199c545 | evelink/__init__.py | evelink/__init__.py | """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.6.2"
# Implement NullHandler... | """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.7.0"
# Implement NullHandler... | Update version to 0.7.0 for release | Update version to 0.7.0 for release
| Python | mit | FashtimeDotCom/evelink,ayust/evelink,bastianh/evelink,zigdon/evelink | ---
+++
@@ -11,7 +11,7 @@
from evelink import map
from evelink import server
-__version__ = "0.6.2"
+__version__ = "0.7.0"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler): |
f16994fd3722acba8a60157eed0630a5e2a3d387 | macdict/cli.py | macdict/cli.py | from __future__ import absolute_import
import sys
import argparse
from macdict.dictionary import lookup_word, ensure_unicode
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('word')
return parser.parse_args()
def abort(text):
sys.stderr.write(u'%s\n' % text)
sys.exit(1)... | from __future__ import absolute_import
import sys
import argparse
from macdict.dictionary import lookup_word, ensure_unicode
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('word')
return parser.parse_args()
def abort(text):
sys.stderr.write(u'%s\n' % text)
sys.exit(1)... | Fix unicode decoding on error messages | Fix unicode decoding on error messages
| Python | mit | tonyseek/macdict | ---
+++
@@ -24,8 +24,9 @@
def main():
args = parse_args()
- definition = lookup_word(ensure_unicode(args.word, 'utf-8'))
+ word = ensure_unicode(args.word, 'utf-8')
+ definition = lookup_word(word)
if definition is None:
- abort(u'Definition not found for "%s"' % args.word)
+ abort... |
554bf6551d0be9d11e046610e4b5772b5beeb9b8 | mwdb/schema.py | mwdb/schema.py | from contextlib import contextmanager
from sqlalchemy import MetaData, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
class Schema():
def __init__(self, engine_or_url, *args, **kwargs):
if isinstance(engine_or_url, Engine):
self.engine = engine_or... | from contextlib import contextmanager
from sqlalchemy import MetaData, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
class Schema():
def __init__(self, engine_or_url, *args, **kwargs):
if isinstance(engine_or_url, Engine):
self.engine = engine_or... | Return the result of an Execute! | Return the result of an Execute!
| Python | mit | mediawiki-utilities/python-mwdb | ---
+++
@@ -25,7 +25,7 @@
def execute(self, *args, **kwargs):
with self.session() as session:
- session.execute(*args, **kwargs)
+ return session.execute(*args, **kwargs)
@contextmanager
def session(self): |
75171ed80079630d22463685768072ad7323e653 | boundary/action_installed.py | boundary/action_installed.py | ###
### Copyright 2014-2015 Boundary, Inc.
###
### Licensed under the Apache License, Version 2.0 (the "License");
### you may not use this file except in compliance with the License.
### You may obtain a copy of the License at
###
### http://www.apache.org/licenses/LICENSE-2.0
###
### Unless required by applicable... | #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | Change code to be PEP-8 compliant | Change code to be PEP-8 compliant
| Python | apache-2.0 | boundary/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/boundary-api-cli,jdgwartney/pulse-api-cli,wcainboundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/pulse-api-cli | ---
+++
@@ -1,18 +1,18 @@
-###
-### Copyright 2014-2015 Boundary, Inc.
-###
-### 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
-... |
57bc8b3c40bbafda6f69b23c230ad73750e881ab | hashable/helpers.py | hashable/helpers.py | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equality_comparable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equality_comparabl... | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equalable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equalable(cls, attributes, m... | Rename decorator equality_comparable to equalable | Rename decorator equality_comparable to equalable
| Python | mit | minmax/hashable | ---
+++
@@ -4,7 +4,7 @@
__all__ = [
'hashable',
- 'equality_comparable',
+ 'equalable',
]
@@ -12,13 +12,13 @@
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
- cls = equality_comparable(cls, attributes, methods)
+ cls = equalable(cls, attributes, ... |
4f6e27a6bbc2bbdb19c165f21d47d1491bffd70e | scripts/mc_check_lib_file.py | scripts/mc_check_lib_file.py | #!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assume... | #!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assume... | Move sessionmaker outside of loop | Move sessionmaker outside of loop
| Python | bsd-2-clause | HERA-Team/hera_mc,HERA-Team/hera_mc | ---
+++
@@ -25,9 +25,9 @@
db = mc.connect_to_mc_db(args)
found_files = []
-for pathname in args.files:
- filename = os.path.basename(pathname)
- with db.sessionmaker() as session:
+with db.sessionmaker() as session:
+ for pathname in args.files:
+ filename = os.path.basename(pathname)
out... |
5436068e2a0974a932d59d51dd529af221832735 | test/vim_autopep8.py | test/vim_autopep8.py | """Run autopep8 on the selected buffer in Vim.
map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>
"""
import vim
if vim.eval('&syntax') == 'python':
encoding = vim.eval('&fileencoding')
source = '\n'.join(line.decode(encoding)
for line in vim.current.buffer) + '\n'
import autopep8
... | """Run autopep8 on the selected buffer in Vim.
map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>
Replace ":pyfile" with ":py3file" if Vim is built with Python 3 support.
"""
from __future__ import unicode_literals
import sys
import vim
ENCODING = vim.eval('&fileencoding')
def encode(text):
if sys.version_in... | Support Python 3 in Vim usage example | Support Python 3 in Vim usage example
| Python | mit | vauxoo-dev/autopep8,Vauxoo/autopep8,vauxoo-dev/autopep8,hhatto/autopep8,SG345/autopep8,SG345/autopep8,MeteorAdminz/autopep8,Vauxoo/autopep8,hhatto/autopep8,MeteorAdminz/autopep8 | ---
+++
@@ -2,12 +2,36 @@
map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>
+Replace ":pyfile" with ":py3file" if Vim is built with Python 3 support.
+
"""
+from __future__ import unicode_literals
+
+import sys
+
import vim
+
+
+ENCODING = vim.eval('&fileencoding')
+
+
+def encode(text):
+ if sys.version_in... |
b1402c6ad51af7e76302605e6892684dcb6cd52c | addons/resource/models/res_company.py | addons/resource/models/res_company.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resourc... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resourc... | Allow 'Access Rights' users to create companies | [FIX] resource: Allow 'Access Rights' users to create companies
Purpose
=======
A 'Access Rights' (group_erp_manager) user can create a company
A 'Settings' (group_system) user can create a resource.calendar
With the resource module, if a resource.calendar is not set on the new company values, a default one is creat... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -20,7 +20,7 @@
@api.model
def create(self, values):
if not values.get('resource_calendar_id'):
- values['resource_calendar_id'] = self.env['resource.calendar'].create({'name': _('Standard 40 hours/week')}).id
+ values['resource_calendar_id'] = self.env['resource.cal... |
c105d6f18a5a17b0a47fda5a2df2f8f47352b037 | setuptools/command/upload.py | setuptools/command/upload.py | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | Simplify logic by eliminating retries in password prompt and returning results directly. | Simplify logic by eliminating retries in password prompt and returning results directly.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -24,21 +24,15 @@
"""
try:
keyring = __import__('keyring')
- password = keyring.get_password(self.repository, self.username)
+ return keyring.get_password(self.repository, self.username)
except Exception:
- password = None
- fin... |
7ce46ada7322f2618fd92adf3eb0e8813b118031 | changes/api/build_restart.py | changes/api/build_restart.py | from sqlalchemy.orm import joinedload
from datetime import datetime
from changes.api.base import APIView
from changes.api.build_index import execute_build
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, ItemStat
class BuildRestartAPIView(APIView):
... | from sqlalchemy.orm import joinedload
from datetime import datetime
from changes.api.base import APIView
from changes.api.build_index import execute_build
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, ItemStat
class BuildRestartAPIView(APIView):
... | Clean up job stats when jobs are removed in build restart | Clean up job stats when jobs are removed in build restart
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes | ---
+++
@@ -22,14 +22,21 @@
if build.status != Status.finished:
return '', 400
+ # ItemStat doesnt cascade
+ ItemStat.query.filter(
+ ItemStat.item_id == build.id
+ ).delete()
+
+ ItemStat.query.filter(
+ ItemStat.item_id.in_(Job.query.filter(
... |
8faf4cd2fa6e155bbe85510ce3ee388bb0e19d3c | src/data/clean_scripts/SG_dengue_malaria_clean.py | src/data/clean_scripts/SG_dengue_malaria_clean.py | import os.path
import sys
import pandas as pd
import logging
INPUT_DIRECTORY = '../../../data/raw/disease_SG'
INPUT_FILE = "weekly-dengue-malaria.csv"
OUTPUT_DIRECTORY = '../../Data/interim/disease_SG'
OUTPUT_FILE = "weekly-dengue-malaria.csv"
logger = logging.getLogger(__name__)
def clean():
input_path = os.pat... | import os.path
import sys
import pandas as pd
import logging
INPUT_DIRECTORY = '../../../data/raw/disease_SG'
INPUT_FILE = "weekly-dengue-malaria.csv"
OUTPUT_DIRECTORY = '../../../data/interim/disease_SG'
OUTPUT_FILE = "weekly-dengue-malaria-cleaned.csv"
logger = logging.getLogger(__name__)
def clean():
input_p... | Transform data to the target format | Transform data to the target format
| Python | mit | DataKind-SG/healthcare_ASEAN | ---
+++
@@ -5,19 +5,31 @@
INPUT_DIRECTORY = '../../../data/raw/disease_SG'
INPUT_FILE = "weekly-dengue-malaria.csv"
-OUTPUT_DIRECTORY = '../../Data/interim/disease_SG'
-OUTPUT_FILE = "weekly-dengue-malaria.csv"
+OUTPUT_DIRECTORY = '../../../data/interim/disease_SG'
+OUTPUT_FILE = "weekly-dengue-malaria-cleaned.cs... |
a3213788d0d8591b235359d4b17886ce3f50ab37 | tests/test_plugin.py | tests/test_plugin.py | import datajoint.errors as djerr
import datajoint.plugin as p
import pkg_resources
def test_check_pubkey():
base_name = 'datajoint'
base_meta = pkg_resources.get_distribution(base_name)
pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name))
with open('./datajoint.pub', "r") as f:
as... | import datajoint.errors as djerr
import datajoint.plugin as p
import pkg_resources
from os import path
def test_check_pubkey():
base_name = 'datajoint'
base_meta = pkg_resources.get_distribution(base_name)
pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name))
with open(path.join(path.abspa... | Make pubkey test more portable. | Make pubkey test more portable.
| Python | lgpl-2.1 | datajoint/datajoint-python,dimitri-yatsenko/datajoint-python | ---
+++
@@ -1,6 +1,7 @@
import datajoint.errors as djerr
import datajoint.plugin as p
import pkg_resources
+from os import path
def test_check_pubkey():
@@ -8,7 +9,8 @@
base_meta = pkg_resources.get_distribution(base_name)
pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name))
- with ... |
bc5475bcc3608de75c42d24c5c74e416b41b873f | pages/base.py | pages/base.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 selenium.webdriver.common.by import By
from page import Page
class Base(Page):
_login_locator = (By.ID, 'lo... | # 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 selenium.webdriver.common.by import By
from page import Page
class Base(Page):
_login_locator = (By.ID, 'lo... | Make username and password required arguments | Make username and password required arguments
| Python | mpl-2.0 | mozilla/mozwebqa-examples,davehunt/mozwebqa-examples,mozilla/mozwebqa-examples,davehunt/mozwebqa-examples | ---
+++
@@ -21,7 +21,7 @@
def click_logout(self):
self.selenium.find_element(*self._logout_locator).click()
- def login(self, username=None, password=None):
+ def login(self, username, password):
login_page = self.click_login()
return login_page.login(username, password)
|
54bce2a224843ec9c1c8b7eb35cdc6bf19d5726b | expensonator/api.py | expensonator/api.py | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... | Fix key error when no tags are specified | Fix key error when no tags are specified
| Python | mit | matt-haigh/expensonator | ---
+++
@@ -13,7 +13,8 @@
def save(self, bundle, skip_errors=False):
bundle = super(ExpenseResource, self).save(bundle, skip_errors)
- bundle.obj.reset_tags_from_string(bundle.data["tags"])
+ if "tags" in bundle.data:
+ bundle.obj.reset_tags_from_string(bundle.data["tags"])
... |
f02b6505f190011f06b37619ec4fdf9bda1e804e | cea/interfaces/dashboard/api/utils.py | cea/interfaces/dashboard/api/utils.py | from flask import current_app
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
try:
params['choices'] = p._choices
except AttributeError:
pass
if p.typename == 'WeatherPathParameter':
... | from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'Weath... | Add parameter deconstruction fro DatabasePathParameter | Add parameter deconstruction fro DatabasePathParameter
| Python | mit | architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS | ---
+++
@@ -1,18 +1,19 @@
from flask import current_app
+import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
- try:
+ if isinstance(p, cea.config.ChoiceParameter):
params['c... |
dfdeaf536466cfa8003af4cd5341d1d7127ea6b7 | py/_test_py2go.py | py/_test_py2go.py | #!/usr/bin/env python
import datetime
def return_true():
return True
def return_false():
return False
def return_int():
return 123
def return_float():
return 1.0
def return_string():
return "ABC"
def return_bytearray():
return bytearray('abcdefg')
def return_array():
return [1, 2, {"k... | #!/usr/bin/env python
import datetime
def return_true():
return True
def return_false():
return False
def return_int():
return 123
def return_float():
return 1.0
def return_string():
return "ABC"
def return_bytearray():
return bytearray('abcdefg')
def return_array():
return [1,... | Update python script for pep8 style | Update python script for pep8 style
| Python | mit | sensorbee/py,sensorbee/py | ---
+++
@@ -1,35 +1,46 @@
#!/usr/bin/env python
import datetime
+
def return_true():
return True
+
def return_false():
return False
+
def return_int():
return 123
+
def return_float():
return 1.0
+
def return_string():
return "ABC"
+
def return_bytearray():
return byt... |
fee11dbff232216726516eea6c8bf7645fdef1a7 | pyxif/__init__.py | pyxif/__init__.py | from ._remove import remove
from ._load_and_dump import load, dump, ZerothIFD, ExifIFD, GPSIFD
from ._transplant import transplant
from ._insert import insert
try:
from ._thumbnail import thumbnail
except ImportError:
print("'thumbnail' function depends on PIL or Pillow.")
VERSION = '0.4.7' | from ._remove import remove
from ._load_and_dump import load, dump, ZerothIFD, ExifIFD, GPSIFD
from ._transplant import transplant
from ._insert import insert
try:
from ._thumbnail import thumbnail
except ImportError:
print("'thumbnail' function depends on PIL or Pillow.")
VERSION = '0.4.6' | Revert "up version to 0.4.7." | Revert "up version to 0.4.7."
This reverts commit 9b1177d4a56070092faa89778911d11c70efdc54.
| Python | mit | hMatoba/Piexif | ---
+++
@@ -8,4 +8,4 @@
print("'thumbnail' function depends on PIL or Pillow.")
-VERSION = '0.4.7'
+VERSION = '0.4.6' |
5d2dfa9f40f29ce7ddd23f8aff574c131539ed6c | util/versioncheck.py | util/versioncheck.py | #!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.\+]+... | #!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version 2>&1', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\... | Handle version string sent to stderr | Handle version string sent to stderr
An unfortunate side effect of switching from print to output() is
that all output() goes to stderr. We should probably carefully
consider whether this is the right thing to do.
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | ---
+++
@@ -4,7 +4,7 @@
from sys import exit
# Actually run bin/mn rather than importing via python path
-version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
+version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version 2>&1', shell=True )
version = version.strip()
# Find all Mininet path re... |
caf9795cf0f775442bd0c3e06cd550a6e8d0206b | virtool/labels/db.py | virtool/labels/db.py | async def count_samples(db, label_id):
return await db.samples.count_documents({"labels": {"$in": [label_id]}})
| async def attach_sample_count(db, document, label_id):
document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
| Rewrite function for sample count | Rewrite function for sample count
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -1,2 +1,2 @@
-async def count_samples(db, label_id):
- return await db.samples.count_documents({"labels": {"$in": [label_id]}})
+async def attach_sample_count(db, document, label_id):
+ document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})}) |
6dc90420dcd7dbfa787bd1e132cf5b304f72bfe7 | likes/middleware.py | likes/middleware.py | try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
... | try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
... | Fix hashing for Python 3 | Fix hashing for Python 3
| Python | bsd-3-clause | Afnarel/django-likes,Afnarel/django-likes,Afnarel/django-likes | ---
+++
@@ -15,7 +15,7 @@
return request.user.username
else:
try:
- s = ''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
+ s = u''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s)... |
453730335b1e8d5d159350e0752faf282378f5e6 | newsletter/models.py | newsletter/models.py | from django.db import models
from django.utils import timezone
from django.utils.datetime_safe import strftime
from hashlib import sha256
from markdownx.models import MarkdownxField
def generate_unsub_token(email, date):
return sha256('{date}:{email}'.format(date=date, email=email).encode()).hexdigest()
clas... | from django.db import models
from django.utils import timezone
from django.utils.datetime_safe import strftime
from hashlib import sha256
from markdownx.models import MarkdownxField
def generate_unsub_token(email, date):
return sha256('{date}:{email}'.format(date=date, email=email).encode()).hexdigest()
clas... | Change default email to newsletter@uwcs instead of noreply | Change default email to newsletter@uwcs instead of noreply
| Python | mit | davidjrichardson/uwcs-zarya,davidjrichardson/uwcs-zarya | ---
+++
@@ -30,7 +30,7 @@
class Mail(models.Model):
subject = models.CharField(max_length=120)
sender_name = models.CharField(max_length=50, default='UWCS Newsletter')
- sender_email = models.EmailField(default='noreply@uwcs.co.uk')
+ sender_email = models.EmailField(default='newsletter@uwcs.co.uk')
... |
51e7cd3bc5a9a56fb53a5b0a8328d0b9d58848dd | modder/utils/desktop_notification.py | modder/utils/desktop_notification.py | # coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, titl... | # coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, titl... | Fix title for desktop notification | Fix title for desktop notification
| Python | mit | JokerQyou/Modder2 | ---
+++
@@ -8,7 +8,9 @@
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
- def desktop_notify(text, title='Modder', sound=False):
+ def desktop_notify(text, title=None, sound=False):
+ title = title or 'Modder'... |
925aa2ef91f15511ce7a3c97564f106d57d13623 | djangopypi/templatetags/safemarkup.py | djangopypi/templatetags/safemarkup.py | from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
def saferst(value):
try:
from docutils.core import publish_parts
except ImportError:
return force... | from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
def saferst(value):
try:
from docutils.core import publish_parts
except ImportError:
return force... | Fix typo foce_unicode -> force_unicode | Fix typo foce_unicode -> force_unicode
| Python | bsd-3-clause | pitrho/djangopypi2,mattcaldwell/djangopypi,EightMedia/djangopypi,benliles/djangopypi,popen2/djangopypi2,disqus/djangopypi,ask/chishop,pitrho/djangopypi2,hsmade/djangopypi2,popen2/djangopypi2,hsmade/djangopypi2,disqus/djangopypi,EightMedia/djangopypi | ---
+++
@@ -20,7 +20,7 @@
writer_name="html4css1",
settings_overrides=docutils_settings)
except:
- return foce_unicode(value)
+ return force_unicode(value)
else:
return mark_safe(force_unicode(parts["fragment"]))
saferst.i... |
02b67810263ac5a39882a1e12a78ba28249dbc0a | webapp/config/settings/development.py | webapp/config/settings/development.py | from .base import *
DEBUG = True
# TEMPLATES[1]['DEBUG'] = True
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, '..', 'tmp', 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'compass_webapp_dev',
... | from .base import *
DEBUG = True
# TEMPLATES[1]['DEBUG'] = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'compass_webapp_dev',
'USER': 'compass_webapp',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}... | Remove sql comments from settings file | Remove sql comments from settings file
| Python | apache-2.0 | patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass | ---
+++
@@ -6,8 +6,6 @@
DATABASES = {
'default': {
- # 'ENGINE': 'django.db.backends.sqlite3',
- # 'NAME': os.path.join(BASE_DIR, '..', 'tmp', 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'compass_webapp_dev',
'USER': 'compass_webapp', |
8a7837a8ce7b35c3141374c6a5c99361261fa70a | Cura/avr_isp/chipDB.py | Cura/avr_isp/chipDB.py |
avrChipDB = {
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
return chip
return False
|
avrChipDB = {
'ATMega1280': {
'signature': [0x1E, 0x97, 0x03],
'pageSize': 128,
'pageCount': 512,
},
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
ret... | Add ATMega1280 chip to programmer chips. | Add ATMega1280 chip to programmer chips.
| Python | agpl-3.0 | MolarAmbiguity/OctoPrint,EZ3-India/EZ-Remote,JackGavin13/octoprint-test-not-finished,spapadim/OctoPrint,dragondgold/OctoPrint,hudbrog/OctoPrint,CapnBry/OctoPrint,Javierma/OctoPrint-TFG,chriskoz/OctoPrint,javivi001/OctoPrint,shohei/Octoprint,eddieparker/OctoPrint,MolarAmbiguity/OctoPrint,mayoff/OctoPrint,uuv/OctoPrint,C... | ---
+++
@@ -1,5 +1,10 @@
avrChipDB = {
+ 'ATMega1280': {
+ 'signature': [0x1E, 0x97, 0x03],
+ 'pageSize': 128,
+ 'pageCount': 512,
+ },
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128, |
ef96000b01c50a77b3500fc4071f83f96d7b2458 | mrbelvedereci/api/views/cumulusci.py | mrbelvedereci/api/views/cumulusci.py | from django.shortcuts import render
from mrbelvedereci.api.serializers.cumulusci import OrgSerializer
from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer
from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer
from mrbelvedereci.cumulusci.filters import OrgFilter
from mrbelved... | from django.shortcuts import render
from mrbelvedereci.api.serializers.cumulusci import OrgSerializer
from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer
from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer
from mrbelvedereci.cumulusci.filters import OrgFilter
from mrbelved... | Remove ServiceFilter from view since it's not needed. Service only has name and json | Remove ServiceFilter from view since it's not needed. Service only has
name and json
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | ---
+++
@@ -4,7 +4,6 @@
from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer
from mrbelvedereci.cumulusci.filters import OrgFilter
from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter
-from mrbelvedereci.cumulusci.filters import ServiceFilter
from mrbelvedereci.cumulusci.models im... |
4f0dbf920a6867d8f3e16eb420391c8bcca43c44 | onirim/card/_door.py | onirim/card/_door.py | from onirim.card._base import ColorCard
class _Door(ColorCard):
def drawn(self, agent, content):
do_open = agent.ask("if open") if content.can_open(self) else False
if do_open:
content.discard(self)
else:
content.limbo(self)
def door(color):
return _Door(color)... | from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door may ... | Implement openable check for door card. | Implement openable check for door card.
| Python | mit | cwahbong/onirim-py | ---
+++
@@ -1,13 +1,26 @@
from onirim.card._base import ColorCard
+from onirim.card._location import LocationKind
+
+
+def _openable(door_card, card):
+ """Check if the door can be opened by another card."""
+ return card.kind == LocationKind.key and door_card.color == card.color
+
+def _may_open(door_card, co... |
24f0402e27ce7e51f370e82aa74c783438875d02 | oslo_db/tests/sqlalchemy/__init__.py | oslo_db/tests/sqlalchemy/__init__.py | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Remove deprecation warning when loading tests/sqlalchemy | Remove deprecation warning when loading tests/sqlalchemy
/home/sam/Work/ironic/.tox/py27/local/lib/python2.7/site-packages/oslo_db/tests/sqlalchemy/__init__.py:20:
DeprecationWarning: Function
'oslo_db.sqlalchemy.test_base.optimize_db_test_loader()' has moved to
'oslo_db.sqlalchemy.test_fixtures.optimize_package_test_... | Python | apache-2.0 | openstack/oslo.db,openstack/oslo.db | ---
+++
@@ -13,6 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-from oslo_db.sqlalchemy import test_base
+from oslo_db.sqlalchemy import test_fixtures
-load_tests = test_base.optimize_db_test_loader(__file__)
+load_tests = test_fixtures.optimize_package_... |
db6cb95d5d4261780482b4051f556fcbb2d9f237 | rest_api/forms.py | rest_api/forms.py | from django.forms import ModelForm
from rest_api.models import Url
class UrlForm(ModelForm):
class Meta:
model = Url
| from django.forms import ModelForm
from gateway_backend.models import Url
class UrlForm(ModelForm):
class Meta:
model = Url
| Remove Url model from admin | Remove Url model from admin
| Python | bsd-2-clause | victorpoluceno/shortener_frontend,victorpoluceno/shortener_frontend | ---
+++
@@ -1,5 +1,6 @@
from django.forms import ModelForm
-from rest_api.models import Url
+
+from gateway_backend.models import Url
class UrlForm(ModelForm):
class Meta: |
3410fba1c8a39156def029eac9c7ff9f779832e6 | dev/ci.py | dev/ci.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... | Fix CI to ignore system install of asn1crypto | Fix CI to ignore system install of asn1crypto
| Python | mit | wbond/oscrypto | ---
+++
@@ -12,6 +12,8 @@
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(deps_dir)
+ # In case any of the deps are installed system-wide
+ sys.path.insert(0, deps_dir)
if sys.version_info[0:2] not in [(2, 6), (3, 2)]:
from .lint import run a... |
502d99042428175b478e796c067e41995a0ae5bf | picoCTF-web/api/apps/v1/__init__.py | picoCTF-web/api/apps/v1/__init__.py | """picoCTF API v1 app."""
from flask import Blueprint, jsonify
from flask_restplus import Api
from api.common import PicoException
from .achievements import ns as achievements_ns
from .problems import ns as problems_ns
from .shell_servers import ns as shell_servers_ns
from .exceptions import ns as exceptions_ns
from... | """picoCTF API v1 app."""
from flask import Blueprint, jsonify
from flask_restplus import Api
from api.common import PicoException
from .achievements import ns as achievements_ns
from .problems import ns as problems_ns
from .shell_servers import ns as shell_servers_ns
from .exceptions import ns as exceptions_ns
from... | Fix PicoException response code bug | Fix PicoException response code bug
| Python | mit | royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF | ---
+++
@@ -35,5 +35,5 @@
def handle_pico_exception(e):
"""Handle exceptions."""
response = jsonify(e.to_dict())
- response.status_code = 203
+ response.status_code = e.status_code
return response |
5d71215645683a059a51407a3768054c9ea77406 | pisite/logs/forms.py | pisite/logs/forms.py | from django import forms
from logs.models import Log
class LineCountForm(forms.Form):
linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) | from django import forms
from logs.models import Log
class LineCountForm(forms.Form):
linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow) | Add to the label that 0 lines will result in the entire file being downloaded | Add to the label that 0 lines will result in the entire file being downloaded
| Python | mit | sizlo/RPiFun,sizlo/RPiFun | ---
+++
@@ -2,4 +2,4 @@
from logs.models import Log
class LineCountForm(forms.Form):
- linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow)
+ linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.default... |
94dad4c56a4b6a1968fa15c20b8482fd56774f32 | optimize/py/main.py | optimize/py/main.py | from scipy import optimize as o
import clean as c
def minimize(func, guess):
return o.minimize(func, guess)
def minimize_scalar(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
retu... | from scipy import optimize as o
import numpy as np
import clean as c
def minimize_scalar(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
try:
return o.minimize_scalar(func, bracke... | Add non negative least squares scipy functionality | Add non negative least squares scipy functionality
| Python | mit | acjones617/scipy-node,acjones617/scipy-node | ---
+++
@@ -1,10 +1,6 @@
from scipy import optimize as o
+import numpy as np
import clean as c
-
-def minimize(func, guess):
- return o.minimize(func, guess)
-
-
def minimize_scalar(func, options):
bracket = options['bracket']
@@ -13,4 +9,17 @@
tol = options['tol']
options = options['option... |
a389f20c7f2c8811a5c2f50c43a9ce5c7f3c8387 | jobs_backend/vacancies/serializers.py | jobs_backend/vacancies/serializers.py | from rest_framework import serializers
from .models import Vacancy
class VacancySerializer(serializers.HyperlinkedModelSerializer):
"""
Common vacancy model serializer
"""
class Meta:
model = Vacancy
fields = (
'id', 'url', 'title', 'description', 'created_on', 'modified_o... | from rest_framework import serializers
from .models import Vacancy
class VacancySerializer(serializers.ModelSerializer):
"""
Common vacancy model serializer
"""
class Meta:
model = Vacancy
fields = (
'id', 'url', 'title', 'description', 'created_on', 'modified_on'
... | Fix for correct resolve URL | jobs-010: Fix for correct resolve URL
| Python | mit | pyshopml/jobs-backend,pyshopml/jobs-backend | ---
+++
@@ -3,7 +3,7 @@
from .models import Vacancy
-class VacancySerializer(serializers.HyperlinkedModelSerializer):
+class VacancySerializer(serializers.ModelSerializer):
"""
Common vacancy model serializer
"""
@@ -13,5 +13,5 @@
'id', 'url', 'title', 'description', 'created_on', 'mo... |
cdd6bc5258a21a1447c6313fad87056163b58a45 | product_details/settings_defaults.py | product_details/settings_defaults.py | import logging
import os
# URL to clone product_details JSON files from.
# Include trailing slash.
PROD_DETAILS_URL = 'http://svn.mozilla.org/libs/product-details/json/'
# Target dir to drop JSON files into (must be writable)
PROD_DETAILS_DIR = os.path.join(os.path.dirname(__file__), 'json')
# log level.
LOG_LEVEL ... | import logging
import os
# URL to clone product_details JSON files from.
# Include trailing slash.
PROD_DETAILS_URL = 'https://svn.mozilla.org/libs/product-details/json/'
# Target dir to drop JSON files into (must be writable)
PROD_DETAILS_DIR = os.path.join(os.path.dirname(__file__), 'json')
# log level.
LOG_LEVEL... | Use HTTPS when fetching JSON files | Use HTTPS when fetching JSON files | Python | bsd-3-clause | mozilla/django-product-details | ---
+++
@@ -4,7 +4,7 @@
# URL to clone product_details JSON files from.
# Include trailing slash.
-PROD_DETAILS_URL = 'http://svn.mozilla.org/libs/product-details/json/'
+PROD_DETAILS_URL = 'https://svn.mozilla.org/libs/product-details/json/'
# Target dir to drop JSON files into (must be writable)
PROD_DETAIL... |
441a1b85f6ab954ab89f32977e4f00293270aac6 | sphinxcontrib/multilatex/__init__.py | sphinxcontrib/multilatex/__init__.py |
import directive
import builder
#===========================================================================
# Node visitor functions
def visit_passthrough(self, node):
pass
def depart_passthrough(self, node):
pass
passthrough = (visit_passthrough, depart_passthrough)
#=================... |
import directive
import builder
#===========================================================================
# Node visitor functions
def visit_passthrough(self, node):
pass
def depart_passthrough(self, node):
pass
passthrough = (visit_passthrough, depart_passthrough)
#=================... | Set LaTeX builder to skip latex_document nodes | Set LaTeX builder to skip latex_document nodes
This stops Sphinx' built-in LaTeX builder from complaining about unknown
latex_document node type.
| Python | apache-2.0 | t4ngo/sphinxcontrib-multilatex,t4ngo/sphinxcontrib-multilatex | ---
+++
@@ -20,6 +20,7 @@
def setup(app):
app.add_node(directive.latex_document,
+ latex=passthrough,
html=passthrough)
app.add_directive("latex-document", directive.LatexDocumentDirective)
app.add_builder(builder.MultiLatexBuilder) |
84f7fe2d17a82d095ff6cf4f2bbd13a2a8426c2d | go/contacts/urls.py | go/contacts/urls.py | from django.conf.urls.defaults import patterns, url
from go.contacts import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^groups/$', views.groups, name='groups'),
url(r'^groups/(?P<type>[\w ]+)/$', views.groups, name='groups_type'),
# TODO: Is the group_name regex sane?... | from django.conf.urls.defaults import patterns, url
from go.contacts import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^groups/$', views.groups, name='groups', kwargs={'type': 'static'}),
url(r'^groups/(?P<type>[\w ]+)/$', views.groups, name='groups_type'),
# TODO: Is... | Change /contacts/groups to display only static groups (instead of all groups) | Change /contacts/groups to display only static groups (instead of all groups)
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -3,7 +3,7 @@
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
- url(r'^groups/$', views.groups, name='groups'),
+ url(r'^groups/$', views.groups, name='groups', kwargs={'type': 'static'}),
url(r'^groups/(?P<type>[\w ]+)/$', views.groups, name='groups_type'),
# TODO:... |
5c11a65af1d51794133895ebe2de92861b0894cf | flask_limiter/errors.py | flask_limiter/errors.py | """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
werkzeug_exception = None
werkzeug_version = get_distribution("werkzeug").version
if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pra... | """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
class RateLimitExceeded(exceptions.TooManyRequests):
"""exception raised when a rate limit is hit.
The exception results in ``abort(429... | Remove backward compatibility hack for exception subclass | Remove backward compatibility hack for exception subclass
| Python | mit | alisaifee/flask-limiter,alisaifee/flask-limiter | ---
+++
@@ -5,20 +5,8 @@
from six import text_type
from werkzeug import exceptions
-werkzeug_exception = None
-werkzeug_version = get_distribution("werkzeug").version
-if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pragma: no cover
- # sorry, for touching your internals :).
- import werkzeug._i... |
b3979a46a7bcd71aa9b40892167910fdeed5ad97 | frigg/projects/admin.py | frigg/projects/admin.py | from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
... | from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
... | Return empty tuple in get_readonly_fields | fix: Return empty tuple in get_readonly_fields
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq | ---
+++
@@ -12,6 +12,7 @@
def get_readonly_fields(request, obj=None):
if obj:
return 'key', 'value', 'is_secret'
+ return tuple()
class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): |
0d7c0b045c4a2e930fe0d7aa68b96d5a99916a34 | scripts/document_path_handlers.py | scripts/document_path_handlers.py | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
from nikola import nikola
n = nikola.Nikola()
n.init_plugins()
print(""".. title: Path Handlers for Nikola
.. slug: path-handlers
.. author: The Nikola Team
Nikola supports special links with the syntax ``link://kind/name``. Here is
the de... | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
from nikola import nikola
n = nikola.Nikola()
n.init_plugins()
print(""".. title: Path Handlers for Nikola
.. slug: path-handlers
.. author: The Nikola Team
Nikola supports special links with the syntax ``link://kind/name``. Here is
the de... | Make path handlers list horizontal | Make path handlers list horizontal
Signed-off-by: Chris Warrick <de6f931166e131a07f31c96c765aee08f061d1a5@gmail.com>
| Python | mit | s2hc-johan/nikola,wcmckee/nikola,gwax/nikola,x1101/nikola,okin/nikola,masayuko/nikola,xuhdev/nikola,wcmckee/nikola,gwax/nikola,knowsuchagency/nikola,atiro/nikola,andredias/nikola,gwax/nikola,xuhdev/nikola,atiro/nikola,x1101/nikola,okin/nikola,knowsuchagency/nikola,wcmckee/nikola,okin/nikola,getnikola/nikola,masayuko/ni... | ---
+++
@@ -12,6 +12,7 @@
Nikola supports special links with the syntax ``link://kind/name``. Here is
the description for all the supported kinds.
+.. class:: dl-horizontal
""")
for k in sorted(n.path_handlers.keys()): |
c6d50c3feed444f8f450c5c140e8470c6897f2bf | societies/models.py | societies/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | Make the Guitar Society __str__ Method a bit more Logical | Make the Guitar Society __str__ Method a bit more Logical
| Python | bsd-3-clause | chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org | ---
+++
@@ -29,4 +29,7 @@
region = models.CharField(max_length=512, null=True, default=None, blank=True)
def __str__(self):
- return 'GuitarSociety(name="{}", link="{}")'.format(self.name, self.link)
+ return self.name
+
+ def __repr__(self):
+ return 'GuitarSociety("{}")'.format(s... |
c7a209d2c4455325f1d215ca1c12074b394ae00e | gitdir/host/__init__.py | gitdir/host/__init__.py | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not s... | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not s... | Add status messages to `gitdir update` | Add status messages to `gitdir update`
| Python | mit | fenhl/gitdir | ---
+++
@@ -21,6 +21,7 @@
def update(self):
for repo_dir in self:
+ print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all(): |
051a0ae16f7c387fcab55abff7debb4e0985654e | senlin/db/sqlalchemy/migration.py | senlin/db/sqlalchemy/migration.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | Make 0 the default version | Make 0 the default version
| Python | apache-2.0 | tengqm/senlin-container,stackforge/senlin,openstack/senlin,stackforge/senlin,Alzon/senlin,openstack/senlin,tengqm/senlin,Alzon/senlin,openstack/senlin,tengqm/senlin-container,tengqm/senlin | ---
+++
@@ -15,7 +15,7 @@
from oslo.db.sqlalchemy import migration as oslo_migration
-INIT_VERSION = 1
+INIT_VERSION = 0
def db_sync(engine, version=None): |
11278ec546cf1c84a6aefff7ed4e5a677203d008 | index_addresses.py | index_addresses.py | import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Elasticsearch(... | import sys
import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Ela... | Change index to OpenAddresses schema | Change index to OpenAddresses schema
| Python | mit | codeforamerica/streetscope,codeforamerica/streetscope | ---
+++
@@ -1,3 +1,4 @@
+import sys
import csv
import re
import os
@@ -13,18 +14,25 @@
else:
es = Elasticsearch()
-with open('data/ParcelCentroids.csv', 'r') as csvfile:
- print "open file"
- csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
+files_given = s... |
461ad75cdb5b8d1a514ff781fd021b33cfd5aa3d | constants.py | constants.py | from __future__ import (
absolute_import,
print_function,
)
POSTGRES_MAX_INT = 2147483647
# class statuses
STATUS_OPEN = 0
STATUS_FULL = 1
STATUS_CLOSED = 2
STATUS_TENTATIVE = 3
STATUS_CANCELLED = 4
STATUS_STOPPED = 5
# semesters
SUMMER_SEM = 0
SEMESTER_1 = 1
SEMESTER_2 = 2
CURRENT_SEM = SEMESTER_1
# conta... | from __future__ import (
absolute_import,
print_function,
)
POSTGRES_MAX_INT = 2147483647
# class statuses
STATUS_OPEN = 0
STATUS_FULL = 1
STATUS_CLOSED = 2
STATUS_TENTATIVE = 3
STATUS_CANCELLED = 4
STATUS_STOPPED = 5
# semesters
SUMMER_SEM = 0
SEMESTER_1 = 1
SEMESTER_2 = 2
CURRENT_SEM = SEMESTER_2
# conta... | Revert "emails now sent through mailgun, small warning css change" | Revert "emails now sent through mailgun, small warning css change"
This reverts commit 12ffeb9562bb9e865fe3ce76266ba3f5c45b815d.
| Python | mit | Chybby/Tutorifull,Chybby/Tutorifull,Chybby/Tutorifull | ---
+++
@@ -18,7 +18,7 @@
SEMESTER_1 = 1
SEMESTER_2 = 2
-CURRENT_SEM = SEMESTER_1
+CURRENT_SEM = SEMESTER_2
# contact types
CONTACT_TYPE_EMAIL = 0 |
9a3c134de0c1c7d194f3d7e30bd9cea917154cba | gitver/sanity.py | gitver/sanity.py | #!/usr/bin/env python2
# coding=utf-8
"""
Implements reused sanity checks
"""
import os
import sys
from gitver.termcolors import term, bold
from gitver.defines import PRJ_ROOT, CFGDIR, CFGDIRNAME, GITIGNOREFILE
def check_project_root():
if len(PRJ_ROOT) == 0:
term.err("Couldn't determine your project's ... | #!/usr/bin/env python2
# coding=utf-8
"""
Implements reused sanity checks
"""
import os
import sys
from gitver.termcolors import term, bold
from gitver.defines import PRJ_ROOT, CFGDIR, CFGDIRNAME, GITIGNOREFILE
def check_project_root():
if len(PRJ_ROOT) == 0:
term.err("Couldn't determine your project's ... | Fix wrong output stream usage | Fix wrong output stream usage
| Python | apache-2.0 | manuelbua/gitver,manuelbua/gitver,manuelbua/gitver | ---
+++
@@ -21,7 +21,7 @@
def check_config():
# check config directory exists
if not os.path.exists(CFGDIR):
- term.prn("Please run " + bold("gitver init") + " first.")
+ term.err("Please run " + bold("gitver init") + " first.")
sys.exit(1)
|
b2a7b299e38ca2cb0d1a725fcfbf6d5d73fa1dfc | dame/dame.py | dame/dame.py | __author__ = "Richard Lindsley"
import sys, os
import argparse
import sip
sip.setapi('QDate', 2)
sip.setapi('QDateTime', 2)
sip.setapi('QString', 2)
sip.setapi('QTextStream', 2)
sip.setapi('QTime', 2)
sip.setapi('QUrl', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtCore,QtGui
from . import __version__
from .ui.ma... | __author__ = "Richard Lindsley"
import sys, os
import argparse
import sip
sip.setapi('QDate', 2)
sip.setapi('QDateTime', 2)
sip.setapi('QString', 2)
sip.setapi('QTextStream', 2)
sip.setapi('QTime', 2)
sip.setapi('QUrl', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtCore,QtGui
from . import __version__
from .ui.ma... | Fix bug if no args were on command line | Fix bug if no args were on command line
| Python | mit | richli/dame | ---
+++
@@ -24,8 +24,7 @@
def main():
parser = argparse.ArgumentParser(description="View SIR file(s)")
- #parser.add_argument("sir_files", action="store", nargs='*',
- parser.add_argument("sir_files", action="store", nargs=1,
+ parser.add_argument("sir_files", action="store", nargs='*',
... |
932ee2737b822742996f234c90b715771fb876bf | tests/functional/api/view_pdf_test.py | tests/functional/api/view_pdf_test.py | import pytest
from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-st... | from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-store"]
)... | Fix lint errors after adding missing __init__ files | Fix lint errors after adding missing __init__ files
| Python | bsd-2-clause | hypothesis/via,hypothesis/via,hypothesis/via | ---
+++
@@ -1,5 +1,3 @@
-import pytest
-
from tests.conftest import assert_cache_control
|
50f2cd076aae183376ab14d31594c104ac210738 | shivyc.py | shivyc.py | #!/usr/bin/env python3
"""Main executable for ShivyC compiler
For usage, run "./shivyc.py --help".
"""
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args... | #!/usr/bin/env python3
"""Main executable for ShivyC compiler
For usage, run "./shivyc.py --help".
"""
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args... | Rename file_name argument on command line | Rename file_name argument on command line
| Python | mit | ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC | ---
+++
@@ -19,8 +19,10 @@
parser = argparse.ArgumentParser(description="Compile C files.")
- # The C file to compile
- parser.add_argument("file_name")
+ # The file name of the C file to compile. The file name gets saved to the
+ # file_name attribute of the returned object, but this parameter a... |
d7149d8ea09c897fb954652beeef3bf008448d9e | mopidy/__init__.py | mopidy/__init__.py | import sys
if not (2, 6) <= sys.version_info < (3,):
sys.exit(u'Mopidy requires Python >= 2.6, < 3')
from subprocess import PIPE, Popen
VERSION = (0, 4, 0)
def get_git_version():
process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
if process.wait() != 0:
raise Exception('Execution of "... | import sys
if not (2, 6) <= sys.version_info < (3,):
sys.exit(u'Mopidy requires Python >= 2.6, < 3')
from subprocess import PIPE, Popen
VERSION = (0, 4, 0)
def get_git_version():
process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
if process.wait() != 0:
raise EnvironmentError('Executi... | Raise EnvironmentError instead of Exception to make pylint happy | Raise EnvironmentError instead of Exception to make pylint happy
| Python | apache-2.0 | pacificIT/mopidy,swak/mopidy,jodal/mopidy,vrs01/mopidy,swak/mopidy,woutervanwijk/mopidy,tkem/mopidy,rawdlite/mopidy,jodal/mopidy,mokieyue/mopidy,rawdlite/mopidy,jmarsik/mopidy,bacontext/mopidy,mokieyue/mopidy,quartz55/mopidy,ZenithDK/mopidy,dbrgn/mopidy,priestd09/mopidy,mopidy/mopidy,quartz55/mopidy,glogiotatidis/mopid... | ---
+++
@@ -9,7 +9,7 @@
def get_git_version():
process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
if process.wait() != 0:
- raise Exception('Execution of "git describe" failed')
+ raise EnvironmentError('Execution of "git describe" failed')
version = process.stdout.read().str... |
66a9d140feb3a0bd332031853fb1038622fd5c5b | oidc_apis/utils.py | oidc_apis/utils.py | from collections import OrderedDict
def combine_uniquely(iterable1, iterable2):
"""
Combine unique items of two sequences preserving order.
:type seq1: Iterable[Any]
:type seq2: Iterable[Any]
:rtype: list[Any]
"""
result = OrderedDict.fromkeys(iterable1)
for item in iterable2:
... | from collections import OrderedDict
import django
from oidc_provider import settings
from django.contrib.auth import BACKEND_SESSION_KEY
from django.contrib.auth import logout as django_user_logout
from users.models import LoginMethod, OidcClientOptions
from django.contrib.auth.views import redirect_to_login
def comb... | Implement current session auth method check | Implement current session auth method check
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo | ---
+++
@@ -1,4 +1,10 @@
from collections import OrderedDict
+import django
+from oidc_provider import settings
+from django.contrib.auth import BACKEND_SESSION_KEY
+from django.contrib.auth import logout as django_user_logout
+from users.models import LoginMethod, OidcClientOptions
+from django.contrib.auth.views i... |
23ca8b449a075b4d8ebee19e7756e39f327e9988 | dwitter/user/urls.py | dwitter/user/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<url_username>\w+)$',
views.user_feed, {'page_nr': '1', 'sort': 'new'}, name='user_feed'),
url(r'^(?P<url_username>\w+)/(?P<sort>hot|new|top)$',
views.user_feed, {'page_nr': '1'}, name='user_sort_feed'),
url(r'^(... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$',
views.user_feed, {'page_nr': '1', 'sort': 'new'}, name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/(?P<sort>hot|new|top)$',
views.user_feed, {'page_nr': '1'}, name='user_sort_feed'),
... | Fix url lookup error for usernames certain special characters | Fix url lookup error for usernames certain special characters
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | ---
+++
@@ -2,10 +2,10 @@
from . import views
urlpatterns = [
- url(r'^(?P<url_username>\w+)$',
+ url(r'^(?P<url_username>[\w.@+-]+)$',
views.user_feed, {'page_nr': '1', 'sort': 'new'}, name='user_feed'),
- url(r'^(?P<url_username>\w+)/(?P<sort>hot|new|top)$',
+ url(r'^(?P<url_username>[\w.@+... |
bca736ac15b06263c88d0265339b93b8c2b20d79 | test/settings/gyptest-settings.py | test/settings/gyptest-settings.py | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('settings.gyp')
test.build('test.gyp', test.AL... | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
# 'settings' is only supported for make and scons (and will be removed there as
# we... | Make new settings test not run for xcode generator. | Make new settings test not run for xcode generator.
TBR=evan
Review URL: http://codereview.chromium.org/7472006 | Python | bsd-3-clause | witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp | ---
+++
@@ -10,7 +10,9 @@
import TestGyp
-test = TestGyp.TestGyp()
+# 'settings' is only supported for make and scons (and will be removed there as
+# well eventually).
+test = TestGyp.TestGyp(formats=['make', 'scons'])
test.run_gyp('settings.gyp')
test.build('test.gyp', test.ALL)
test.pass_test() |
9ec80ed117ca393a63bf7eb739b4702bfbc0884e | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | Add function to schedule later | Add function to schedule later | Python | mit | waltermoreira/tartpy | ---
+++
@@ -34,6 +34,9 @@
"""
self.scheduler.enter(0, 1, event)
+ def later(self, delay, event):
+ self.scheduler.enter(delay, 1, event)
+
def stop(self):
"""Stop the loop."""
pass |
b552d550ca7e4468d95da9a3005e07cbd2ab49d6 | tests/test_stock.py | tests/test_stock.py | import cutplanner
import unittest
class TestStock(unittest.TestCase):
def setUp(self):
self.stock = cutplanner.Stock(120)
def test_cut(self):
self.stock.assign_cut(20)
self.assertEqual(self.stock.remaining_length, 100)
if __name__ == '__main__':
unittest.main()
| import cutplanner
import unittest
class TestStock(unittest.TestCase):
def setUp(self):
self.stock = cutplanner.Stock(120)
self.piece = cutplanner.Piece(1, 20)
def test_cut(self):
self.stock.cut(self.piece)
self.assertEqual(self.stock.remaining_length, 100)
def test_used_l... | Add some initial tests for Stock. | Add some initial tests for Stock.
| Python | mit | alanc10n/py-cutplanner | ---
+++
@@ -5,11 +5,23 @@
def setUp(self):
self.stock = cutplanner.Stock(120)
+ self.piece = cutplanner.Piece(1, 20)
def test_cut(self):
- self.stock.assign_cut(20)
+ self.stock.cut(self.piece)
self.assertEqual(self.stock.remaining_length, 100)
+ def test_used... |
54eb7862d6b17f4e86a380004f6e682452fbebce | git_gutter_change.py | git_gutter_change.py | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def run(self):
view = self.window.active_view()
inserted, modified, ... | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
... | Make lines jumps only jump to blocks over changes | Make lines jumps only jump to blocks over changes
Instead of every line in a block of modifications which is tedious
| Python | mit | tushortz/GitGutter,biodamasceno/GitGutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,natecavanaugh/GitGutter,natecavanaugh/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,natecavanaugh/GitGutter,biodamasceno/GitGutter,akpersad/GitGutter,akpersad/GitGutter,robfrawley/sublime-git-gutter,natecavanaugh/... | ---
+++
@@ -6,10 +6,21 @@
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
+ def lines_to_blocks(self, lines):
+ blocks = []
+ last_line = -2
+ for line in lines:
+ if line > last_line+1:
+ blocks.appen... |
21304ed626998ae4fd359d2e8358bf7563b9020d | harness/summarize.py | harness/summarize.py | #!/usr/bin/env python3
import os
import json
import math
import uncertain
TIMINGS_DIR = 'collected'
def _mean(values):
"""The arithmetic mean."""
return sum(values) / len(values)
def _mean_err(vals):
"""The mean and standard error of the mean."""
if len(vals) <= 1:
return 0.0
mean = _me... | #!/usr/bin/env python3
import os
import json
import uncertain
TIMINGS_DIR = 'collected'
def summarize_run(data):
"""Summarize the data from a single run."""
print(data['fn'])
all_latencies = []
for msg in data['messages']:
# As a sanity check, we can get an average frame latency for the
... | Remove old uncertainty quantification stuff | Remove old uncertainty quantification stuff
| Python | mit | cucapra/braid,cucapra/braid,guoyiteng/braid,guoyiteng/braid,guoyiteng/braid,cucapra/braid,guoyiteng/braid,guoyiteng/braid,cucapra/braid,cucapra/braid,guoyiteng/braid,cucapra/braid | ---
+++
@@ -1,24 +1,9 @@
#!/usr/bin/env python3
import os
import json
-import math
import uncertain
TIMINGS_DIR = 'collected'
-
-
-def _mean(values):
- """The arithmetic mean."""
- return sum(values) / len(values)
-
-
-def _mean_err(vals):
- """The mean and standard error of the mean."""
- if len(v... |
a36fe5002bbf5dfcf27a3251cfed85c341e2156d | cbcollections.py | cbcollections.py | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | Save generated value for defaultdict | MB-6867: Save generated value for defaultdict
Instead of just returning value, keep it in dict.
Change-Id: I2a9862503b71f2234a4a450c48998b5f53a951bc
Reviewed-on: http://review.couchbase.org/21602
Tested-by: Bin Cui <ed18693fff32c00e22495f4877a3b901bed09041@gmail.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a... | Python | apache-2.0 | couchbase/couchbase-cli,couchbaselabs/couchbase-cli,membase/membase-cli,membase/membase-cli,couchbase/couchbase-cli,membase/membase-cli,couchbaselabs/couchbase-cli,couchbaselabs/couchbase-cli | ---
+++
@@ -14,4 +14,5 @@
try:
return super(defaultdict, self).__getitem__(key)
except KeyError:
- return self.default_factory()
+ self[key] = self.default_factory()
+ return self[key] |
3a5e2e34374f92f0412d121fb9552278105f230a | salt/acl/__init__.py | salt/acl/__init__.py | # -*- coding: utf-8 -*-
'''
The acl module handles client_acl operations
Additional information on client_acl can be
found by reading the salt documention:
http://docs.saltstack.com/en/latest/ref/clientacl.html
'''
# Import python libraries
from __future__ import absolute_import
import re
class ClientACL(objec... | # -*- coding: utf-8 -*-
'''
The acl module handles client_acl operations
Additional information on client_acl can be
found by reading the salt documentation:
http://docs.saltstack.com/en/latest/ref/clientacl.html
'''
# Import python libraries
from __future__ import absolute_import
import re
class ClientACL(obj... | Fix typo documention -> documentation | Fix typo documention -> documentation
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -3,7 +3,7 @@
The acl module handles client_acl operations
Additional information on client_acl can be
-found by reading the salt documention:
+found by reading the salt documentation:
http://docs.saltstack.com/en/latest/ref/clientacl.html
''' |
7548a1245cc21c92f09302ccaf065bdf6189ef2d | quilt/cli/series.py | quilt/cli/series.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | Remove whitespace at end of line | Remove whitespace at end of line
| Python | mit | bjoernricks/python-quilt,vadmium/python-quilt | ---
+++
@@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
... |
b27a51f19ea3f9d13672a0db51f7d2b05f9539f0 | kitten/validation.py | kitten/validation.py | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS = {
'core': CORE_SCHEMA
}
def validate(request, schema_na... | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
'address': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS ... | Add 'address' field to core schema | Add 'address' field to core schema
| Python | mit | thiderman/network-kitten | ---
+++
@@ -10,6 +10,9 @@
'method': {
'type': 'string',
},
+ 'address': {
+ 'type': 'string',
+ },
},
'additionalProperties': False,
}
@@ -18,5 +21,6 @@
'core': CORE_SCHEMA
}
+
def validate(request, schema_name):
jsonschema.validate(requ... |
fb0b956563efbcd22af8300fd4341e3cb277b80a | app/models/user.py | app/models/user.py | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | Add avatar_url and owner field for User | Add avatar_url and owner field for User
| Python | agpl-3.0 | lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger | ---
+++
@@ -8,6 +8,8 @@
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
+ avatar_url = db.Column(db.String(256))
+ owner = db.Column(db.String(32), nullable=False, default='user')
github_id = db.Column(db.Integer, unique=True)
... |
f42e62005ea4cc3e71cf10dda8c0bace029014c5 | kubespawner/utils.py | kubespawner/utils.py | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurable, ThreadPool... | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurab... | Add random jitter to the exponential backoff function | Add random jitter to the exponential backoff function
| Python | bsd-3-clause | yuvipanda/jupyterhub-kubernetes-spawner,jupyterhub/kubespawner | ---
+++
@@ -2,6 +2,7 @@
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
+import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
@@ -19,12 +20,20 @@
@gen.coroutine
def exponential_backoff(func,... |
9f6d4d9e82ef575164535a8fb9ea80417458dd6b | website/files/models/dataverse.py | website/files/models/dataverse.py | import requests
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, F... | from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, Folder):
pass
... | Move override logic into update rather than touch | Move override logic into update rather than touch
| Python | apache-2.0 | Johnetordoff/osf.io,mluke93/osf.io,SSJohns/osf.io,chrisseto/osf.io,hmoco/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,acshi/osf.io,alexschiller/osf.io,caseyrollins/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,alexschiller/osf.io,adlius/osf.... | ---
+++
@@ -1,5 +1,3 @@
-import requests
-
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
@@ -17,27 +15,21 @@
class DataverseFile(DataverseFileNode, File):
+ version_identifier = 'version'
- def touch(self, version=None, rev... |
06d210cdc811f0051a489f335cc94a604e99a35d | werobot/session/mongodbstorage.py | werobot/session/mongodbstorage.py | # -*- coding: utf-8 -*-
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | # -*- coding: utf-8 -*-
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | Use new pymongo API in MongoDBStorage | Use new pymongo API in MongoDBStorage
| Python | mit | whtsky/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot,whtsky/WeRoBot,weberwang/WeRoBot,weberwang/WeRoBot | ---
+++
@@ -23,9 +23,6 @@
:param collection: 一个 MongoDB Collection。
"""
def __init__(self, collection):
- import pymongo
- assert isinstance(collection,
- pymongo.collection.Collection)
self.collection = collection
collection.create_index("wechat... |
841ca9cfbdb8faac9d8deb47b65717b5fb7c8eb4 | mfh.py | mfh.py | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfh... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
client = create_process("client", mfhclient.main, args, update_event)
serv = c... | Move all the process creation in a new function | Move all the process creation in a new function
This reduces the size of code.
| Python | mit | Zloool/manyfaced-honeypot | ---
+++
@@ -14,35 +14,32 @@
def main():
update_event = Event()
- mfhclient_process = Process(
- args=(args, update_event,),
- name="mfhclient_process",
- target=mfhclient.main,
- )
- server_process = Process(
- args=(args, update_event,),
- name="server_process"... |
3aacfd7147836ef95133aa88d558a1d69bbcd0cd | mopidy/exceptions.py | mopidy/exceptions.py | from __future__ import absolute_import, unicode_literals
class MopidyException(Exception):
def __init__(self, message, *args, **kwargs):
super(MopidyException, self).__init__(message, *args, **kwargs)
self._message = message
@property
def message(self):
"""Reimplement message fie... | from __future__ import absolute_import, unicode_literals
class MopidyException(Exception):
def __init__(self, message, *args, **kwargs):
super(MopidyException, self).__init__(message, *args, **kwargs)
self._message = message
@property
def message(self):
"""Reimplement message fie... | Fix typo in new CoreErrors | exception: Fix typo in new CoreErrors
| Python | apache-2.0 | mopidy/mopidy,hkariti/mopidy,tkem/mopidy,bacontext/mopidy,swak/mopidy,mokieyue/mopidy,ZenithDK/mopidy,ali/mopidy,mokieyue/mopidy,bencevans/mopidy,jcass77/mopidy,bencevans/mopidy,bacontext/mopidy,diandiankan/mopidy,hkariti/mopidy,dbrgn/mopidy,ZenithDK/mopidy,bacontext/mopidy,mopidy/mopidy,pacificIT/mopidy,SuperStarPL/mo... | ---
+++
@@ -23,8 +23,8 @@
class CoreError(MopidyException):
- def __init(self, message, errno=None):
- super(CoreError, self).__init(message, errno)
+ def __init__(self, message, errno=None):
+ super(CoreError, self).__init__(message, errno)
self.errno = errno
@@ -53,8 +53,8 @@
... |
5f128bbfc61169ac6b5f0e9f4dc6bcd05092382c | requests_cache/serializers/pipeline.py | requests_cache/serializers/pipeline.py | """
.. automodsumm:: requests_cache.serializers.pipeline
:classes-only:
:nosignatures:
"""
from typing import Any, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
def __init__(self, obj: An... | """
.. automodsumm:: requests_cache.serializers.pipeline
:classes-only:
:nosignatures:
"""
from typing import Any, Callable, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods
Args:
obj: ... | Allow Stage objects to take functions instead of object + method names | Allow Stage objects to take functions instead of object + method names
| Python | bsd-2-clause | reclosedev/requests-cache | ---
+++
@@ -3,27 +3,41 @@
:classes-only:
:nosignatures:
"""
-from typing import Any, List, Union
+from typing import Any, Callable, List, Union
from ..models import CachedResponse
class Stage:
- """Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
+ ... |
657741f3d4df734afef228e707005dc21d540e34 | post-refunds-back.py | post-refunds-back.py | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wi... | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchange... | Update post-back script for Braintree | Update post-back script for Braintree
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com | ---
+++
@@ -2,21 +2,32 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
+from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billi... |
9be282d3f2f278ca8fe0dd65d78d03005b6e43cd | url_shortener/forms.py | url_shortener/forms.py | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
... | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
... | Replace double quotes with single quotes as string delimiters | Replace double quotes with single quotes as string delimiters
This commit replaces double quotes with single quotes as string delimiters
to improve consistency.
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | ---
+++
@@ -10,14 +10,14 @@
url = StringField(
validators=[
validators.DataRequired(),
- validators.URL(message="A valid URL is required"),
+ validators.URL(message='A valid URL is required'),
not_blacklisted_nor_spam
]
)
recaptcha = Rec... |
022062c409ee06a719b5687ea1feb989c5cad627 | app/grandchallenge/pages/sitemaps.py | app/grandchallenge/pages/sitemaps.py | from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False
)
| from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False, hidden=False,
)
| Remove hidden public pages from sitemap | Remove hidden public pages from sitemap
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | ---
+++
@@ -7,5 +7,5 @@
def items(self):
return Page.objects.filter(
- permission_level=Page.ALL, challenge__hidden=False
+ permission_level=Page.ALL, challenge__hidden=False, hidden=False,
) |
c5239c6bbb40ede4279b33b965c5ded26a78b2ae | app/tests/manual/test_twitter_api.py | app/tests/manual/test_twitter_api.py | # -*- coding: utf-8 -*-
"""
Twitter API test module.
Local test to check that Twitter credentials are valid connect to Twitter
API and that the auth functions can be used to do this.
s"""
from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(T... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Twitter API test module.
Local test to check that Twitter credentials are valid connect to Twitter
API and that the auth functions can be used to do this.
"""
from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# A... | Update Twitter auth test to run directly | test: Update Twitter auth test to run directly
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | ---
+++
@@ -1,12 +1,22 @@
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Twitter API test module.
Local test to check that Twitter credentials are valid connect to Twitter
API and that the auth functions can be used to do this.
-s"""
+"""
from __future__ import absolute_import
+import os
+import sys
+impo... |
c6862c5f864db4e77dd835f074efdd284667e6fd | util/ldjpp.py | util/ldjpp.py | #! /usr/bin/env python
from __future__ import print_function
import argparse
import json
parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
parser.add_argument('--indent', metavar='N', type=int, default=2,
dest='indent', help='indentation for pretty-printing')
parser.add_argument... | #! /usr/bin/env python
from __future__ import print_function
import click
import json
from collections import OrderedDict
def json_loader(sortkeys):
def _loader(line):
if sortkeys:
return json.loads(line)
else:
# if --no-sortkeys, let's preserve file order
retu... | Use click instead of argparse | Use click instead of argparse
| Python | mit | mhyfritz/goontools,mhyfritz/goontools,mhyfritz/goontools | ---
+++
@@ -1,19 +1,34 @@
#! /usr/bin/env python
from __future__ import print_function
-import argparse
+import click
import json
+from collections import OrderedDict
-parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
-parser.add_argument('--indent', metavar='N', type=int, default=2,
- ... |
fdfa3aae605eaadf099c6d80c86a9406f34fb71c | bluebottle/organizations/urls/api.py | bluebottle/organizations/urls/api.py | from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view()... | from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view()... | Fix organization-contact url having an extra slash | Fix organization-contact url having an extra slash
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -9,7 +9,7 @@
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view(),
name='organization_detail'),
- url(r'^/contacts/$', OrganizationContactList.as_view(),
+ url(r'^/contacts$', OrganizationContactList.as_view(),
... |
b7decb588f5b6e4d15fb04fa59aa571e5570cbfe | djangae/contrib/contenttypes/apps.py | djangae/contrib/contenttypes/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | Fix up for Django 1.9 | Fix up for Django 1.9
| Python | bsd-3-clause | grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae | ---
+++
@@ -18,12 +18,17 @@
from django.db import models
from django.contrib.contenttypes import models as django_models
if not isinstance(django_models.ContentType.objects, SimulatedContentTypeManager):
- django_models.ContentType.objects = SimulatedContentTypeMa... |
c02239af435cece9c2664436efbe0b2aeb200a1b | stats/views.py | stats/views.py | from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from django.db.models import Sum, Count
from common.auth import user_is_admin
from django.utils.translation import ugettext_lazy as _
from common.models import Purchase, BookType
from egielda import settings
@user_passes_... | from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from django.db.models import Sum, Count
from common.auth import user_is_admin
from django.utils.translation import ugettext_lazy as _
from common.models import Purchase, BookType
from egielda import settings
@user_passes_... | Fix displaying None in statistics when there's no book sold | Fix displaying None in statistics when there's no book sold
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | ---
+++
@@ -12,7 +12,7 @@
def index(request):
stats = dict()
stats['books_sold_value'] = BookType.objects.filter(book__sold=True).annotate(count=Count('book')).aggregate(
- Sum('price', field='count * price'))['price__sum']
+ ... |
dfd3bff4560d1711624b8508795eb3debbaafa40 | changes/api/snapshotimage_details.py | changes/api/snapshotimage_details.py | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | Mark snapshots as inactive if any are not valid | Mark snapshots as inactive if any are not valid
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes | ---
+++
@@ -40,6 +40,9 @@
if not db.session.query(inactive_image_query).scalar():
snapshot.status = SnapshotStatus.active
db.session.add(snapshot)
+ elif snapshot.status == SnapshotStatus.active:
+ snapshot.status = SnapshotStatus.inactive
+ ... |
f8b4b1a860b5c0a3ff16dbb8bbf83010bd9a1009 | feincms3/plugins/__init__.py | feincms3/plugins/__init__.py | # flake8: noqa
from . import html
from . import snippet
try:
from . import external
except ImportError: # pragma: no cover
pass
try:
from . import image
except ImportError: # pragma: no cover
pass
try:
from . import richtext
except ImportError: # pragma: no cover
pass
try:
from . import... | # flake8: noqa
from . import html
from . import snippet
try:
import requests
except ImportError: # pragma: no cover
pass
else:
from . import external
try:
import imagefield
except ImportError: # pragma: no cover
pass
else:
from . import image
try:
import feincms3.cleanse
except ImportErr... | Stop hiding local import errors | feincms3.plugins: Stop hiding local import errors
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 | ---
+++
@@ -4,18 +4,26 @@
from . import snippet
try:
- from . import external
+ import requests
except ImportError: # pragma: no cover
pass
+else:
+ from . import external
try:
- from . import image
+ import imagefield
except ImportError: # pragma: no cover
pass
+else:
+ from . im... |
b2eebbdcc14dd47d6ad8bb385966f13ed13890c1 | superdesk/coverages.py | superdesk/coverages.py | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | Fix data relation not working for custom Guids | Fix data relation not working for custom Guids
| Python | agpl-3.0 | plamut/superdesk,sivakuna-aap/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk,mugurrus/superdesk,ioanpocol/superdesk,pavlovicnemanja/superdesk,Aca-jov/superdesk,akintolga/superdesk,vied12/superdesk,gbbr/superdesk,fritzSF/superdesk,ancafarcas/superd... | ---
+++
@@ -19,8 +19,8 @@
'type': {'type': 'string'},
'ed_note': {'type': 'string'},
'scheduled': {'type': 'datetime'},
- 'delivery': rel('archive'),
+ 'delivery': {'type': 'string'},
'assigned_user': rel('users', True),
'assigned_desk': rel('desks', True),
-... |
4147e6f560889c75abbfd9c8e85ea38ffe408550 | suelta/mechanisms/facebook_platform.py | suelta/mechanisms/facebook_platform.py | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | Work around Python3's byte semantics. | Work around Python3's byte semantics.
| Python | mit | dwd/Suelta | ---
+++
@@ -17,21 +17,21 @@
def process(self, challenge=None):
if challenge is not None:
values = {}
- for kv in challenge.split('&'):
- key, value = kv.split('=')
+ for kv in challenge.split(b'&'):
+ key, value = kv.split(b'=')
... |
1dbe7acc945a545d3b18ec5025c19b26d1ed110f | test/test_sparql_construct_bindings.py | test/test_sparql_construct_bindings.py | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://github.com/RDFLib/rdflib/issu... | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
from nose.tools import eq_
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://gi... | Fix unit tests for python2 | Fix unit tests for python2
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib | ---
+++
@@ -3,6 +3,7 @@
from rdflib.compare import isomorphic
import unittest
+from nose.tools import eq_
class TestConstructInitBindings(unittest.TestCase):
@@ -36,4 +37,4 @@
'c': Literal('C')
})
- self.assertCountEqual(list(results), expected)
+ eq_(sorted(results, key=l... |
2ebbe2f9f23621d10a70d0817d83da33b002299e | rest_surveys/urls.py | rest_surveys/urls.py | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | Set a default api path | Set a default api path
| Python | mit | danxshap/django-rest-surveys | ---
+++
@@ -18,8 +18,10 @@
slashless_router.registry = router.registry[:]
urlpatterns = [
- url(r'^{api_path}'.format(api_path=settings.REST_SURVEYS['API_PATH']),
+ url(r'^{api_path}'.format(
+ api_path=settings.REST_SURVEYS.get('API_PATH', 'api/')),
include(router.urls)),
- url(r... |
1cbd56988478320268838f77e8cc6237d95346fd | test/dunya/conn_test.py | test/dunya/conn_test.py | import unittest
from compmusic.dunya.conn import _make_url
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
url = _make_url("path", **params)
self.assertEqual(url, 'http://dunya.compmusic.upf.edu/path?first=%25%5Egrt%C3%A0') | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
import unittest
from compmusic.dunya.conn import _make_url
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
url = _make_url("path", **params)
self.assertEqual(url, 'http://dunya.compmusic.upf.edu/path?... | Declare the encoding of conn.py as utf-8 | Declare the encoding of conn.py as utf-8
| Python | agpl-3.0 | MTG/pycompmusic | ---
+++
@@ -1,3 +1,5 @@
+#!/usr/local/bin/python
+# -*- coding: utf-8 -*-
import unittest
from compmusic.dunya.conn import _make_url |
a7437e657f55cd708baba83421941e67d474daf7 | tests/test_utilities.py | tests/test_utilities.py | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name') == 'name'
assert camelize('very_long_variable_name... | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize, deep_copy
from folium import Map, FeatureGroup, Marker
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name'... | Add test for deep_copy function | Add test for deep_copy function
| Python | mit | python-visualization/folium,ocefpaf/folium,ocefpaf/folium,python-visualization/folium | ---
+++
@@ -1,6 +1,7 @@
from __future__ import (absolute_import, division, print_function)
-from folium.utilities import camelize
+from folium.utilities import camelize, deep_copy
+from folium import Map, FeatureGroup, Marker
def test_camelize():
@@ -8,3 +9,24 @@
assert camelize('variableName') == 'varia... |
fe05b5f694671a46dd3391b9cb6561923345c4b7 | rpi_gpio_http/app.py | rpi_gpio_http/app.py | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | Disable warnings in GPIO lib | Disable warnings in GPIO lib
| Python | mit | voidpp/rpi-gpio-http | ---
+++
@@ -15,6 +15,7 @@
channels = {}
+GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
for ch in config['channels']: |
378f55687131324bb5c43e3b50f9db5fe3b39662 | zaqar_ui/__init__.py | zaqar_ui/__init__.py | # Copyright 2015 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | # Copyright 2015 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | Fix Zaqar-ui with wrong reference pbr version | Fix Zaqar-ui with wrong reference pbr version
Change-Id: I84cdb865478a232886ba1059febf56735a0d91ba
| Python | apache-2.0 | openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui | ---
+++
@@ -14,5 +14,4 @@
import pbr.version
-__version__ = pbr.version.VersionInfo(
- 'neutron_lbaas_dashboard').version_string()
+__version__ = pbr.version.VersionInfo('zaqar_ui').version_string() |
38888d34506b743a06aa93f5dc6c187844774d58 | scripts/constants.py | scripts/constants.py | # Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | # Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | Add missing parentheses to print() | Add missing parentheses to print() | Python | apache-2.0 | skuda/client-python,mbohlool/client-python,kubernetes-client/python,djkonro/client-python,sebgoa/client-python,skuda/client-python,mbohlool/client-python,kubernetes-client/python,sebgoa/client-python,djkonro/client-python | ---
+++
@@ -36,7 +36,7 @@
sys.exit(1)
if sys.argv[1] in globals():
- print globals()[sys.argv[1]]
+ print(globals()[sys.argv[1]])
else:
- print "Cannot find constant %s" % sys.argv[1]
+ print("Cannot find constant %s" % sys.argv[1])
sys.exit(1) |
d659c685f40de7eb7b2ccd007888177fb158e139 | tests/integration/players.py | tests/integration/players.py | #!/usr/bin/env python
import urllib.parse
import urllib.request
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
data = urllib.parse.urlencode(values)
data = dat... | #!/usr/bin/env python
import requests
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
r = requests.post(url, params=values, verify=False)
r.raise_for_status()... | Switch to requests library instead of urllib | Switch to requests library instead of urllib
| Python | mit | dropshot/dropshot-server | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-import urllib.parse
-import urllib.request
+
+import requests
def create_player(username, password, email):
url = 'https://localhost:3000/players'
@@ -8,12 +8,15 @@
'password' : password,
'email' : email }
- data = urllib.pa... |
eeeba609afe732b8e95aa535e70d4cdd2ae1aac7 | tests/unit/test_cufflinks.py | tests/unit/test_cufflinks.py | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | Remove some cruft from the cufflinks test. | Remove some cruft from the cufflinks test.
| Python | mit | vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,verdurin/bcbio-nextgen,fw1121/bcbio-nextgen,gifford-lab/bcbio-nextgen,chapmanb/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,verdurin/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantan... | ---
+++
@@ -21,11 +21,8 @@
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
-# fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
-# fixed = cufflinks.fix_cuf... |
ff09f40b763ac9c968919871d649c47ce6aa7489 | main.py | main.py | from BaseHTTPServer import HTTPServer
from HTTPHandler import HTTPHandler
import socket
from threading import currentThread
from Cron import Cron
from Settings import PORT
from Update import check
from Event import addEventHandler
from event_handlers import *
currentThread().name = 'main'
check()
try:
server = HTT... | from BaseHTTPServer import HTTPServer
from HTTPHandler import HTTPHandler
import socket
from threading import currentThread
import signal
from Cron import Cron
from Settings import PORT
from Update import check
from Event import addEventHandler
from event_handlers import *
currentThread().name = 'main'
check()
try:... | Handle SIGINT even if it's ignored by default | Handle SIGINT even if it's ignored by default
| Python | mit | mrozekma/Sprint,mrozekma/Sprint,mrozekma/Sprint | ---
+++
@@ -2,6 +2,7 @@
from HTTPHandler import HTTPHandler
import socket
from threading import currentThread
+import signal
from Cron import Cron
from Settings import PORT
@@ -25,6 +26,9 @@
addEventHandler(DBLogger.DBLogger())
addEventHandler(MessageDispatcher.MessageDispatcher())
+# When python is starte... |
ddfd7a3a2a2806045c6f4114c3f7f5a0ca929b7c | main.py | main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
from datetime import datetime
from update_wrapper import UpdateWrapper
if not os.path.isdir("log"):
os.mkdir("log")
logging.basicConfig(
filename="log/{}.log".format(datetime.now().strftime("%Y%m%d%H%M%S%f")),
level=logging.DEBUG)
l... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
from datetime import datetime
from update_wrapper import UpdateWrapper
if not os.path.isdir("log"):
os.mkdir("log")
LOG_FILE = datetime.now().strftime("%Y%m%d%H%M%S%f")
logging.basicConfig(
filename="log/{}.log".format(LOG_FILE),
le... | Move log file to constant | Move log file to constant
| Python | mit | stormaaja/csvconverter,stormaaja/csvconverter,stormaaja/csvconverter | ---
+++
@@ -10,8 +10,10 @@
if not os.path.isdir("log"):
os.mkdir("log")
+LOG_FILE = datetime.now().strftime("%Y%m%d%H%M%S%f")
+
logging.basicConfig(
- filename="log/{}.log".format(datetime.now().strftime("%Y%m%d%H%M%S%f")),
+ filename="log/{}.log".format(LOG_FILE),
level=logging.DEBUG)
logging.... |
c956fbbbc6e4dbd713728c1feda6bce2956a0894 | runtime/Python3/src/antlr4/__init__.py | runtime/Python3/src/antlr4/__init__.py | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA import DFA
from... | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import... | Allow importing StdinStream from antlr4 package | Allow importing StdinStream from antlr4 package
| Python | bsd-3-clause | parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr... | ---
+++
@@ -1,6 +1,7 @@
from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
+from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer impor... |
14c22be85b9c9b3d13cad1130bb8d8d83d69d68a | selenium_testcase/testcases/content.py | selenium_testcase/testcases/content.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .utils import dom_contains, wait_for
class ContentTestMixin:
def should_see_immediately(self, text):
""" Assert that DOM contains the given text. """
self.assertTrue(dom_contains(self.browser, text))
@wait_for
def shou... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .utils import wait_for
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
class ContentTestMixin:
content_search_list = (
(By.XPATH,
'//*[contains(normalize-space(.), "{}... | Update should_see_immediately to use local find_element method. | Update should_see_immediately to use local find_element method.
This commit adds a content_search_list and replaces dom_contains
with our local version of find_element. It adds an attribute
called content_search_list that can be overridden by the derived
TestCase class as necessary for corner cases.
| Python | bsd-3-clause | nimbis/django-selenium-testcase,nimbis/django-selenium-testcase | ---
+++
@@ -2,14 +2,24 @@
from __future__ import absolute_import
-from .utils import dom_contains, wait_for
+from .utils import wait_for
+
+from selenium.common.exceptions import NoSuchElementException
+from selenium.webdriver.common.by import By
class ContentTestMixin:
- def should_see_immediately(sel... |
7947d474da8bb086493890d81a6788d76e00b108 | numba/cuda/tests/__init__.py | numba/cuda/tests/__init__.py | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
suite.add... | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
if cuda.i... | Fix tests on machine without CUDA | Fix tests on machine without CUDA
| Python | bsd-2-clause | sklam/numba,numba/numba,seibert/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,gmarkall/numba,cpcloud/numba,IntelLabs/numba,gmarkall/numba,jriehl/numba,cpcloud/numba,sklam/numba,cpcloud/numba,numba/numba,stonebig/numba,stefanseefeld/numba,sklam/numba,cpcloud/numba,seibert/numba,sklam/numba,gmarkall/numba,stefanseefe... | ---
+++
@@ -9,8 +9,8 @@
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
- suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim')))
if cuda.is_available():
+ suite.addTests(load_testsuite(loader, join(this_dir, '... |
910d1288adddd0c8dd500c1be5e488502c1ed335 | localflavor/nl/forms.py | localflavor/nl/forms.py | # -*- coding: utf-8 -*-
"""NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch... | # -*- coding: utf-8 -*-
"""NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch... | Fix the wikipedia link and include a warning | Fix the wikipedia link and include a warning
| Python | bsd-3-clause | django/django-localflavor,rsalmaso/django-localflavor | ---
+++
@@ -36,7 +36,9 @@
"""
A Dutch social security number (BSN) field.
- http://nl.wikipedia.org/wiki/Sofinummer
+ https://nl.wikipedia.org/wiki/Burgerservicenummer
+
+ Note that you may only process the BSN if you have a legal basis to do so!
.. versionadded:: 1.6
""" |
2e5ec8483930ad328b0a212ccc4b746f73b18c4c | pinax/ratings/tests/tests.py | pinax/ratings/tests/tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
self.jtauber = User.objects.create(username="jtauber")
... | from decimal import Decimal
from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
self.jtauber = User.objects.c... | Use explicit Decimal in test | Use explicit Decimal in test
| Python | mit | rizumu/pinax-ratings,pinax/pinax-ratings,arthur-wsw/pinax-ratings,arthur-wsw/pinax-ratings,pinax/pinax-ratings,arthur-wsw/pinax-ratings,pinax/pinax-ratings,rizumu/pinax-ratings,rizumu/pinax-ratings | ---
+++
@@ -1,3 +1,5 @@
+from decimal import Decimal
+
from django.test import TestCase
from django.contrib.auth.models import User
@@ -18,6 +20,6 @@
def test_rating(self):
overall = Rating.update(self.bronco, self.paltman, rating=5)
- self.assertEquals(overall, 5)
+ self.assertEqual... |
95fcaffa1dc73ec3c83734587c311b47e79e0d3c | pylamb/bmi_ilamb.py | pylamb/bmi_ilamb.py | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'run_ilamb'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name... | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'run_ilamb'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name... | Update no longer takes an argument | Update no longer takes an argument
See the docs: http://bmi-python.readthedocs.io.
| Python | mit | permamodel/ILAMB,permamodel/ILAMB,permamodel/ILAMB | ---
+++
@@ -21,7 +21,7 @@
def initialize(self, filename):
self._args = [filename or 'ILAMB_PARA_SETUP']
- def update(self, time):
+ def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
|
b07c26c4d00de2b7dd184e0d173ec9e03ce4b456 | qtui/exam_wizard.py | qtui/exam_wizard.py | from PyQt4.QtGui import *
from master_page import MasterPage
from generate_page import GeneratePage
from scan_page import ScanPage
from scores_page import ScoresPage
from results_page import ResultsPage
class ExamWizard(QWizard):
def __init__(self, project):
super(ExamWizard, self).__init__()
sel... | from PyQt4.QtGui import *
from master_page import MasterPage
from generate_page import GeneratePage
from scan_page import ScanPage
from scores_page import ScoresPage
from results_page import ResultsPage
class ExamWizard(QWizard):
def __init__(self, project):
super(ExamWizard, self).__init__()
sel... | Comment out temporally scoresheet editing page | Comment out temporally scoresheet editing page
| Python | mit | matcom/autoexam,matcom/autoexam,matcom/autoexam,matcom/autoexam,matcom/autoexam | ---
+++
@@ -13,8 +13,9 @@
self.project = project
self.order = None # TODO: Implement order loading here?
self.results = None # TODO: Implement result loading here?
+ self.setOption(QWizard.IndependentPages, False)
self.addPage(MasterPage(project, self))
self.addPage... |
41a0fa6412427dadfb33c77da45bc88c576fa67c | rdo/drivers/base.py | rdo/drivers/base.py | from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
def do(self, cmd):
cmd = self.command(cmd)
call(cmd)
def command(self):
raise NotImplementedError()
| from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
def working_dir(self, cmd):
command = ' '.join(cmd)
working_dir = self.config.get('directory')
if working_dir:
command = 'cd %s && %s' % (working_dir, command)
... | Add a common function for deriving the working dir. | Add a common function for deriving the working dir.
| Python | bsd-3-clause | ionrock/rdo | ---
+++
@@ -6,6 +6,13 @@
def __init__(self, config):
self.config = config
+ def working_dir(self, cmd):
+ command = ' '.join(cmd)
+ working_dir = self.config.get('directory')
+ if working_dir:
+ command = 'cd %s && %s' % (working_dir, command)
+ return command... |
3940fd8b58b6a21627ef0ff62f7480593e5108eb | remedy/radremedy.py | remedy/radremedy.py | #!/usr/bin/env python
"""
radremedy.py
Main web application file. Contains initial setup of database, API, and other components.
Also contains the setup of the routes.
"""
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from ra... | #!/usr/bin/env python
"""
radremedy.py
Main web application file. Contains initial setup of database, API, and other components.
Also contains the setup of the routes.
"""
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from fl... | Move around imports and not shadow app | Move around imports and not shadow app
| Python | mpl-2.0 | radremedy/radremedy,radioprotector/radremedy,radioprotector/radremedy,AllieDeford/radremedy,radremedy/radremedy,radremedy/radremedy,radioprotector/radremedy,radremedy/radremedy,AllieDeford/radremedy,AllieDeford/radremedy,radioprotector/radremedy | ---
+++
@@ -8,22 +8,27 @@
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
+from flask.ext.login import current_user
from rad.models import db, Resource
def create_app(config, models=()):
- from remedyblueprint im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.