Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use correct url pattern format | from django.conf.urls import patterns, include
urlpatterns = patterns(
(r'^jmbo/', include('jmbo.urls')),
(r'^comments/', include('django.contrib.comments.urls')),
(r'^post/', include('post.urls')),
)
| from django.conf.urls import patterns, include
urlpatterns = patterns(
'',
(r'^jmbo/', include('jmbo.urls')),
(r'^comments/', include('django.contrib.comments.urls')),
(r'^post/', include('post.urls')),
)
|
Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed. | import os
import os.path
import subprocess
from module import Module
class git(Module):
def __init__(self, scrap):
super(git, self).__init__(scrap)
scrap.register_event("git", "msg", self.distribute)
self.register_cmd("version", self.git_version)
self.register_cmd("update", self.up... | import os
import os.path
import subprocess
from module import Module
class git(Module):
def __init__(self, scrap):
super(git, self).__init__(scrap)
scrap.register_event("git", "msg", self.distribute)
self.register_cmd("version", self.git_version)
self.register_cmd("update", self.up... |
Upgrade Fitbit to OAuth 2.0 | import foauth.providers
class Fitbit(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.fitbit.com/'
docs_url = 'https://dev.fitbit.com/'
category = 'Fitness'
# URLs to interact with the API
request_token_url = 'https://api.fitbit.com/oauth/request_token'
... | import requests
import foauth.providers
class Fitbit(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://www.fitbit.com/'
docs_url = 'https://dev.fitbit.com/'
category = 'Fitness'
# URLs to interact with the API
authorize_url = 'https://www.fitbit.com/oauth2/a... |
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" | import ssl
import logging
from logging.handlers import SysLogHandler
from threading import Timer
logger = logging.getLogger('pixelated.startup')
def init_logging(name, level=logging.INFO, config_file=None):
global logger
logger_name = 'pixelated.%s' % name
logging.basicConfig(level=level)
if config_... | import ssl
import logging
from logging.handlers import SysLogHandler
from threading import Timer
logger = logging.getLogger('pixelated.startup')
def init_logging(name, level=logging.INFO, config_file=None):
global logger
logger_name = 'pixelated.%s' % name
logging.basicConfig(level=level)
if config_... |
Reduce textarea height in Story form | from django import forms
from .models import Story
from cms.forms import ContentManageableModelForm
class StoryForm(ContentManageableModelForm):
class Meta:
model = Story
fields = (
'name',
'company_name',
'company_url',
'category',
'aut... | from django import forms
from .models import Story
from cms.forms import ContentManageableModelForm
class StoryForm(ContentManageableModelForm):
pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5}))
class Meta:
model = Story
fields = (
'name',
'compan... |
Bump app version to 2018.12.2 | __version__ = "2018.12.1"
__versionfull__ = __version__
| __version__ = "2018.12.2"
__versionfull__ = __version__
|
Fix DebugToolbar requirement in non-debug envs | import functools
import os
from flask.ext.debugtoolbar import DebugToolbarExtension
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask_app.app import app
from flask_app.models import db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', Mi... | import functools
import os
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask_app.app import app
from flask_app.models import db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
_FROM_HERE = functools.partial(os.path.joi... |
Truncate spotify current song if it is too long | #!/usr/bin/python
# -*- coding: utf-8 -*-
import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2')
spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties')
metadata = spotify_properties.Get('org.mpris.Media... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2')
spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties')
metadata = spotify_properties.Get('org.mpris.Media... |
Add basic script to get most common committers | #!/usr/bin/env python3
try:
import configparser
except ImportError:
raise ImportError("Must be using Python 3")
import argparse
import os
import subprocess
UBER=True
def extract_username(shortlog):
shortlog = shortlog.strip()
email = shortlog[shortlog.rfind("<")+1:]
email = email[:email.find("... | |
Add test route for heroku | from flask import Flask
from SPARQLWrapper import SPARQLWrapper, JSON
from flask import request, jsonify
from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello_world():
auth = request.authorization
query = request.args.get('query')
if not auth is None and not query is N... | from flask import Flask
from SPARQLWrapper import SPARQLWrapper, JSON
from flask import request, jsonify
from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/sparql')
def do_sparql():
auth = request.authorization
query = requ... |
Add Tornado settings and log location command line options. | import logging
import os
import tornado.ioloop
import tornado.log
import tornado.web
def configure_tornado_logging():
fh = logging.handlers.RotatingFileHandler(
'/var/log/ipborg/tornado.log', maxBytes=2**29, backupCount=10)
fmt = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
... | import logging
import os
import tornado.ioloop
import tornado.log
import tornado.options
import tornado.web
tornado.options.define('tornado_log_file',
default='/var/log/ipborg/torando.log',
type=str)
tornado.options.define('app_log_file',
default='... |
Raise supported Python version for currently pinned pylint | '''py.test standard config file.'''
import sys
# pylint: disable=invalid-name
collect_ignore = ('setup.py',)
# pylint: enable=invalid-name
def pytest_cmdline_preparse(args):
is_pylint_compatible = (2, 7) <= sys.version_info < (3, 5)
if not is_pylint_compatible:
args.remove('--pylint')
| '''py.test standard config file.'''
import sys
# pylint: disable=invalid-name
collect_ignore = ('setup.py',)
# pylint: enable=invalid-name
def pytest_cmdline_preparse(args):
is_pylint_compatible = (2, 7) <= sys.version_info < (3, 6)
if not is_pylint_compatible:
args.remove('--pylint')
|
Add fucntion to create bot commands | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
def botcmd(*args, **kwargs):
"""
Decorator to declare a function as a... | |
Remove os.scandir usage (not in python 3.4) | import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the gi... | import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the gi... |
Use 3-point version number as per semver.org | from setuptools import setup, find_packages
setup(
name = "idea-collection",
version = "0.1",
#url = "TBD",
license = "public domain",
description = "An idea collection tool for django",
author = "Jui Dai, Jennifer Ehlers, David Kennedy, Shashank Khandelwal, CM Lubinski",
packages = find_packages('s... | from setuptools import setup, find_packages
setup(
name = "idea-collection",
version = "0.1.0",
#url = "TBD",
license = "public domain",
description = "An idea collection tool for django",
author = "Jui Dai, Jennifer Ehlers, David Kennedy, Shashank Khandelwal, CM Lubinski",
packages = find_packages(... |
Put dependency to "account_analytic_analysis" module. | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributor... | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributor... |
Add Bisnode Rating Report model | from django.db import models
from .constants import COMPANY_RATING_REPORT
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10, null=True,
blank=True)
rating_code = models.Char... | |
Move REPLWrapper and u() function to pkg level | from ._metakernel import MetaKernel
from . import pexpect
from . import replwrap
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, _metakernel, parser, process_metakernel
| from ._metakernel import MetaKernel
from . import pexpect
from .replwrap import REPLWrapper, u
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, _metakernel, parser, process_metakern... |
Remove import of n/a benchmark module. | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
from sheared.python import benchmark
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handl... | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handle(self, request, reply, subpath):
... |
Make this code actually do something! | from __future__ import print_function
from fontTools import ttLib
from multiprocessing import Pool
from .fontcrunch import optimize_glyph, plot_glyph
def _optimize(args):
font, name, pdf, penalty, quiet = args
if not quiet:
print('optimizing', name)
glyph = font['glyf'][name]
plot_glyph(font,... | from __future__ import print_function
from fontTools import ttLib
from multiprocessing import Pool
from .fontcrunch import optimize_glyph, plot_glyph
def _optimize(args):
font, name, pdf, penalty, quiet = args
if not quiet:
print('optimizing', name)
glyph = font['glyf'][name]
plot_glyph(font,... |
Fix task path for cleanup | import os
from datetime import timedelta
BROKER_URL = os.environ['CELERY_BROKER_URL']
CELERY_IMPORTS = ('cabot.cabotapp.tasks', )
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml']
CELERYD_TASK_SOFT_TIME_LIMIT = 120
CELERYD... | import os
from datetime import timedelta
BROKER_URL = os.environ['CELERY_BROKER_URL']
CELERY_IMPORTS = ('cabot.cabotapp.tasks', )
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml']
CELERYD_TASK_SOFT_TIME_LIMIT = 120
CELERYD... |
Create SiteMeta for default site | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... |
Update print_gcide example to work with latest api changes. | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("... | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("... |
Fix typo in function call | """
Handles ambiguities of RFCs.
"""
def normalize_namreply_params(params):
# So… RFC 2812 says:
# "( "=" / "*" / "@" ) <channel>
# :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
# but spaces seem to be missing (eg. before the colon), so we
# don't know if there should be one befo... | """
Handles ambiguities of RFCs.
"""
def normalize_namreply_params(params):
# So… RFC 2812 says:
# "( "=" / "*" / "@" ) <channel>
# :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
# but spaces seem to be missing (eg. before the colon), so we
# don't know if there should be one befo... |
Add completed field to review | from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.... | from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.... |
Fix running unit tests through the old test runner. | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main(sys.argv[1:]))
| #!/usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import pytest
if __name__ == '__main__':
if len(sys.argv) >= 2 and sys.argv[1] != '--':
args = ['--db', sys.argv[1]] + sys.argv[2:]
else:
args = sys.argv[1:]
sys.exit(pytest.main(args))
|
Enable with statement tests for Python 2.5 | import sys
if sys.version_info[:2] > (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '_... | import sys
if sys.version_info[:2] >= (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '... |
Update pubtator test given new pubtator output |
import kindred
def test_pubtator():
data = kindred.pubtator.load([19894120,19894121])
assert isinstance(data,list)
for d in data:
assert isinstance(d,kindred.RelationData)
fileCount = len(data)
entityCount = sum([ len(d.getEntities()) for d in data ])
relationCount = sum([ len(d.getRelations()) for d in dat... |
import kindred
def test_pubtator():
data = kindred.pubtator.load([19894120,19894121])
assert isinstance(data,list)
for d in data:
assert isinstance(d,kindred.RelationData)
fileCount = len(data)
entityCount = sum([ len(d.getEntities()) for d in data ])
relationCount = sum([ len(d.getRelations()) for d in dat... |
Fix typo in exception docstring | class FlowRuntimeError(Exception):
"""Unrecovable flow runtime error."""
class FlowLockFailed(Exception):
"""Flow lock failed."""
| class FlowRuntimeError(Exception):
"""Unrecoverable flow runtime error."""
class FlowLockFailed(Exception):
"""Flow lock failed."""
|
Remove delay from loop for testing | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
wait = delay.next_capture() # Delay time in seconds from delay.py
waithours = wait / 60 / 60 # Co... | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
# wait = delay.next_capture() # Delay time in seconds from delay.py
wait = 60
waithours = wait... |
Allow VendDateTimeField to accept null dates (if required is set to False) | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... |
Remove unicode string markers which are removed in python3 | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... |
Add hash function to RelationKey | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... |
Use same tagname but different scope | """
state_tests.py
"""
import os
from os.path import splitext
from minicps.state import SQLiteState
def test_SQLiteState():
# TODO: change to /tmp when install SQLitesutdio in ubuntu
PATH = "temp/state_test_db.sqlite"
# sqlite use text instead of VARCHAR
SCHEMA = """
CREATE TABLE state_test (
... | """
state_tests.py
"""
import os
from os.path import splitext
from minicps.state import SQLiteState
def test_SQLiteState():
# TODO: change to /tmp when install SQLitesutdio in ubuntu
PATH = "temp/state_test_db.sqlite"
# sqlite use text instead of VARCHAR
SCHEMA = """
CREATE TABLE state_test (
... |
Add a __repr__ method for LoginToken | import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
... | import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
... |
Fix making threads daemonic on Python 3.2 | #
# Copyright 2014 Infoxchange Australia
#
# 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 2014 Infoxchange Australia
#
# 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... |
Make the bot reload its secondary modules when you reload the plugin. | ###
# Copyright (c) 2007, Max Kanat-Alexander
# All rights reserved.
#
#
###
"""
Interact with Bugzilla installations.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
_... | ###
# Copyright (c) 2007, Max Kanat-Alexander
# All rights reserved.
#
#
###
"""
Interact with Bugzilla installations.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
_... |
Remove unused imports and sort | import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner, storage
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
| import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
|
Fix Auth API key check causing error 500s | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
... | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
... |
Add parent so we can track versions. | from dataitem import DataItem
class DataFile(DataItem):
def __init__(self, name, access, owner):
super(DataFile, self).__init__(name, access, owner, "datafile")
self.checksum = ""
self.size = 0
self.location = ""
self.mediatype = ""
self.conditions = []
self.... | from dataitem import DataItem
class DataFile(DataItem):
def __init__(self, name, access, owner):
super(DataFile, self).__init__(name, access, owner, "datafile")
self.checksum = ""
self.size = 0
self.location = ""
self.mediatype = ""
self.conditions = []
self.... |
Handle orgs that you don’t own personally. | import logging
from .models import GithubProject, GithubOrganization
log = logging.getLogger(__name__)
def make_github_project(user, org, privacy, repo_json):
if (repo_json['private'] is True and privacy == 'private' or
repo_json['private'] is False and privacy == 'public'):
project, created ... | import logging
from .models import GithubProject, GithubOrganization
log = logging.getLogger(__name__)
def make_github_project(user, org, privacy, repo_json):
if (repo_json['private'] is True and privacy == 'private' or
repo_json['private'] is False and privacy == 'public'):
project, created ... |
Fix filename creation in csv export action |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... |
Revert file to moneymanager master branch. | #!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/... | #!/usr/bin/env python3
# vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab
import os, sys
import sqlite3
import urllib.request
err = False
for version in range (7, 14):
fname = 'tables_v1.sql' if version < 12 else 'tables.sql'
url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/... |
Add a test of the linearity of scalar multiplication | import pytest # type: ignore
from hypothesis import given
from hypothesis.strategies import floats
from utils import vectors
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0))... | import pytest # type: ignore
from hypothesis import given
from hypothesis.strategies import floats
from utils import vectors
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0))... |
Fix new line stripping in admin site | import hashlib
import urllib.parse as urllib
from django.contrib.auth.models import User
from django.db import models
# extension to django's User class which has authentication details
# as well as some basic info such as name
class Member(models.Model):
def gravatar(self, size=128):
default = "https://... | import hashlib
import urllib.parse as urllib
from django.contrib.auth.models import User
from django.db import models
# extension to django's User class which has authentication details
# as well as some basic info such as name
class Member(models.Model):
def gravatar(self, size=128):
default = "https://... |
Add error message for not implemented error | c = get_config()
c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")]
c.CourseDirectory.db_students = [
dict(id="foo", first_name="foo", last_name="foo")
]
c.ClearSolutions.code_stub = {'python': '##### Implement this part of the code #####\nraise NotImplementedError()'}
| c = get_config()
c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")]
c.CourseDirectory.db_students = [
dict(id="foo", first_name="foo", last_name="foo")
]
c.ClearSolutions.code_stub = {'python': '''##### Implement this part of the code #####
raise NotImplementedError("Code not imp... |
Add default images for podcasts if necessary | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
for key, line in enumerate(contents):
src = re.sear... | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
if re.search('podcast', filename):
if re.s... |
Update dependencies to actual version numbers | from distutils.core import setup
setup(
name='HotCIDR',
version='0.1.0',
author='ViaSat',
author_email='stephan.kemper@viasat.com',
packages=['hotcidr', 'hotcidr.test'],
scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'],
#u... | from distutils.core import setup
setup(
name='HotCIDR',
version='0.1.0',
author='ViaSat',
author_email='stephan.kemper@viasat.com',
packages=['hotcidr', 'hotcidr.test'],
scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'],
#u... |
Use simple TestCase in spam filter tests. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Unit tests for spam filters.
"""
import unittest
from django.conf import settings
from django.test import TestCase
try:
import honeypot
except ImportError:
honeypot = None
from envelope.spam_filters import check_honeypot
# mocking form ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Unit tests for spam filters.
"""
import unittest
from django.conf import settings
try:
import honeypot
except ImportError:
honeypot = None
from envelope.spam_filters import check_honeypot
# mocking form and request, no need to use the r... |
Update migration sequence after rebase | """ Add columns to supplier_frameworks to indicate
Pass/Fail and whether a Framework Agreement has
been returned.
Revision ID: 360_add_pass_fail_returned
Revises: 340
Create Date: 2015-10-23 16:25:02.068155
"""
# revision identifiers, used by Alembic.
revision = '360_add_pass_fail_returned'
down_revision = '... | """ Add columns to supplier_frameworks to indicate
Pass/Fail and whether a Framework Agreement has
been returned.
Revision ID: 360_add_pass_fail_returned
Revises: 350_migrate_interested_suppliers
Create Date: 2015-10-23 16:25:02.068155
"""
# revision identifiers, used by Alembic.
revision = '360_add_pass_fai... |
Use float so test passes on Python 2.6 | # from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
... | # from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
... |
Delete emails before deleting users | #!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI... | #!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI... |
Remove check for existance of VPNs. Not having them may be correct | import json
import os
import sys
sys.path.append('..')
from skytap.Vpns import Vpns # noqa
vpns = Vpns()
def test_vpn_count():
"""Test VPN count."""
assert len(vpns) > 0, 'Vpn list is empty.'
def test_vpn_id():
"""Ensure each VPN has an ID."""
for v in vpns:
assert len(v.id) > 0
def tes... | import json
import os
import sys
sys.path.append('..')
from skytap.Vpns import Vpns # noqa
vpns = Vpns()
def test_vpn_id():
"""Ensure each VPN has an ID."""
for v in vpns:
assert len(v.id) > 0
def test_vpn_json():
"""Ensure vpn json conversion seems to be working."""
for l in list(vpns.dat... |
Add charge to Paystack class | """Entry point defined here."""
from paystackapi.cpanel import ControlPanel
from paystackapi.customer import Customer
from paystackapi.invoice import Invoice
from paystackapi.misc import Misc
from paystackapi.page import Page
from paystackapi.plan import Plan
from paystackapi.product import Product
from paystackapi.ref... | """Entry point defined here."""
from paystackapi.charge import Charge
from paystackapi.cpanel import ControlPanel
from paystackapi.customer import Customer
from paystackapi.invoice import Invoice
from paystackapi.misc import Misc
from paystackapi.page import Page
from paystackapi.plan import Plan
from paystackapi.produ... |
Fix issue which cases lit installed with setup.py to not resolve main | """'lit' Testing Tool"""
__author__ = 'Daniel Dunbar'
__email__ = 'daniel@minormatter.com'
__versioninfo__ = (0, 6, 0)
__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'
__all__ = []
| """'lit' Testing Tool"""
__author__ = 'Daniel Dunbar'
__email__ = 'daniel@minormatter.com'
__versioninfo__ = (0, 6, 0)
__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'
__all__ = []
from .main import main
|
Append slash to API root if needed. | from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
... | from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
... |
Store the player keys in the preserved games | from persistent_dict import *
class PreservedGame():
def game_name(self):
return "Freddo" # TODO
class AllPreservedGames():
def __init__(self, filename):
self.games = PersistentDict(filename, 'c', format='pickle')
def add_game(self, pg):
self.games[pg.game_name()] = pg
sel... | from persistent_dict import *
class PreservedGame():
def __init__(self, game):
self.rules = game.rules # .clone?
self.player = [None, game.player[1].key(), game.player[2].key()]
self.move_history = game.move_history[:]
def game_name(self):
return "Freddo" # TODO
class AllPr... |
Enable mutable config in blazar | # Copyright (c) 2013 Mirantis 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 writ... | # Copyright (c) 2013 Mirantis 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 writ... |
Use a separate set of urlpatterns for each file in views. | from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'... | from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'... |
Remove reference to non-existant file. | import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="disposa... | import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
... |
Add missing lower() in create_container() | import logging
import os
from plumbum.commands.base import BaseCommand
from benchbuild.settings import CFG
from benchbuild.utils.cmd import podman
LOG = logging.getLogger(__name__)
PODMAN_DEFAULT_OPTS = [
'--root',
os.path.abspath(str(CFG['container']['root'])), '--runroot',
os.path.abspath(str(CFG['cont... | import logging
import os
from plumbum.commands.base import BaseCommand
from benchbuild.settings import CFG
from benchbuild.utils.cmd import podman
LOG = logging.getLogger(__name__)
PODMAN_DEFAULT_OPTS = [
'--root',
os.path.abspath(str(CFG['container']['root'])), '--runroot',
os.path.abspath(str(CFG['cont... |
Update code for PEP8 compliance | import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (t... | import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(
os.path.dirname(__file__),
'../LICENSE.txt')
... |
Make buck wrapper logs human-readable. | #!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
logger = logging.getLogger()
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
... | #!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
... |
Order judge list by load | from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.models import Judge
__all__ = ['status', 'status_table']
def status(request):
return render_to_response('judge_status.jade', {
'judges': Judge.objects.all(),
'title': 'Status',
}, context_in... | from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.models import Judge
__all__ = ['status', 'status_table']
def status(request):
return render_to_response('judge_status.jade', {
'judges': Judge.objects.all(),
'title': 'Status',
}, context_in... |
Add __str__ to Preprocessor class | import json
class Preprocessor:
def __init__(self):
self.reset()
def reset(self):
self.number_elements = 0
self.length_elements = []
self.E_elements = []
self.I_elements = []
self.loads = []
self.supports = []
def load_json(self, infile):
s... | import json
class Preprocessor:
def __init__(self):
self.reset()
def __str__(self):
return json.dumps(self.__dict__, indent=2, separators=(',', ': '))
def reset(self):
self.number_elements = 0
self.length_elements = []
self.E_elements = []
self.I_elements ... |
Make JumboFieldsWorkflow fail if no env var | from __future__ import print_function
import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def repeat50k(s):
return s * 50000
@activity.with_attributes(task_list='quickstart', version='example')
def length(x):
... | from __future__ import print_function
import os
from simpleflow import Workflow, activity
@activity.with_attributes(task_list='quickstart', version='example')
def repeat50k(s):
return s * 50000
@activity.with_attributes(task_list='quickstart', version='example')
def length(x):
return len(x)
class JumboF... |
Revert r67, which was not the changeset intended for commit. | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... |
Delete Report models before reloading them | # -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the ... | # -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the ... |
Add some basic geometric functions. | import numpy as np
| import numpy as np
def normalize(v):
'''Normalize a vector based on its 2 norm.'''
if 0 == np.linalg.norm(v):
return v
return v / np.linalg.norm(v)
def create_frame_from_three_points(p1, p2, p3):
'''Create a left-handed coordinate frame from 3 points.
The p2 is the origin; the y-axis is ... |
Use relative imports in compiler package now that it is required. (Should this go into 2.5 or should we do compiler.XXX?) | """Package for parsing and compiling Python source code
There are several functions defined at the top level that are imported
from modules contained in the package.
parse(buf, mode="exec") -> AST
Converts a string containing Python source code to an abstract
syntax tree (AST). The AST is defined in compiler... | """Package for parsing and compiling Python source code
There are several functions defined at the top level that are imported
from modules contained in the package.
parse(buf, mode="exec") -> AST
Converts a string containing Python source code to an abstract
syntax tree (AST). The AST is defined in compiler... |
Fix demo URLs for Dajngo 1.10 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtailadmin import urls as wagtailadmin_... | from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from ... |
Cut a new release to incorporate the HashableDict fix. | # -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)... | # -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)... |
Clear up an unused import. | from django import forms
from tower import ugettext_lazy as _
from challenges.models import Submission
class EntryForm(forms.ModelForm):
class Meta:
model = Submission
fields = (
'title',
'brief_description',
'description',
'created_by'
... | from django import forms
from challenges.models import Submission
class EntryForm(forms.ModelForm):
class Meta:
model = Submission
fields = (
'title',
'brief_description',
'description',
'created_by'
)
|
Align foreign key field length with maximum party ID length | """
byceps.services.party.models.setting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....typing import PartyID
from ....util.instances import ReprBuilder
class Setting(db.Model):
"""A party-... | """
byceps.services.party.models.setting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....typing import PartyID
from ....util.instances import ReprBuilder
class Setting(db.Model):
"""A party-... |
Use self> for selfbot prefix, and >/b> for normal bot prefix | #!/usr/bin/env python
import asyncio
import logging
import sys
import discord
from discord.ext.commands import when_mentioned_or
import yaml
from bot import BeattieBot
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
with open('config/config.yaml'... | #!/usr/bin/env python
import asyncio
import logging
import sys
import discord
from discord.ext.commands import when_mentioned_or
import yaml
from bot import BeattieBot
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
with open('config/config.yaml'... |
Use pathlib in the filter | #!/usr/bin/env python
import json
import sys
from os import scandir, remove
from datetime import datetime
START_DT = datetime(2016, 7, 1, 0, 0, 0)
END_DT = datetime(2016, 12, 1, 0, 0, 0)
DRY_RUN = True
for dir_entry in scandir('preprocessed'):
path = dir_entry.path
with open(path) as f:
# read t... | #!/usr/bin/env python
import json
import sys
from pathlib import Path
from os import remove
from datetime import datetime
START_DT = datetime(2016, 7, 1, 0, 0, 0)
END_DT = datetime(2016, 12, 1, 0, 0, 0)
DRY_RUN = True
for path in Path('preprocessed/').iterdir():
with path.open() as f:
# read the jso... |
Insert the path to the source tree at the front of the python path rather than at the end. Something broken got put into some one of the python include directories somehow. | #!/usr/bin/python
import sys, os
from paste.deploy import loadapp, loadserver
import logging
if __name__ == '__main__':
logging.basicConfig(filename = '/var/log/reporting-api.log', level = logging.INFO)
realfile = os.path.realpath(__file__)
realdir = os.path.dirname(realfile)
pardir = os.path.realpath(os.path.joi... | #!/usr/bin/python
import sys, os
from paste.deploy import loadapp, loadserver
import logging
if __name__ == '__main__':
logging.basicConfig(filename = '/var/log/reporting-api.log', level = logging.INFO)
realfile = os.path.realpath(__file__)
realdir = os.path.dirname(realfile)
pardir = os.path.realpath(os.path.joi... |
Fix SessionKeyValueStore.has to use the correct indexing value when looking up data | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return se... | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return se... |
Update Detective per 2021-04-29 changes | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {}
class MemberInvitation(AWSObject):
resource_type = "AWS::Dete... | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
"Tags": (Tags, False),
}
class MemberInvitation(... |
Fix name of index created for tests. | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... |
Improve the code, return most collisions. Work on hex strings. | from matasano.util.converters import hex_to_bytestr
from Crypto.Cipher import AES
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
for line in chal_file:
ct = hex_to_bytestr(line[:-1])
for i in range(0, len(ct), 16):
for j in range(i+16, len(ct), 16):
... | from matasano.util.converters import hex_to_bytestr
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
coll_count = {}
for idx, line in enumerate(chal_file):
count = 0
ct = line[:-1]
for i in range(0, len(ct), 32):
for j in range(i+32, len(ct), 3... |
Return profile from get_profile view instead of user | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from linked_accounts import LINKED_ACCOUNTS_HANDLERS
HANDLERS = getattr(
settings,
'LINKED_ACCOUNTS_HANDLERS',
LINKED_ACCOUNTS_HANDLERS
)
def get_profile(service=Non... | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from linked_accounts import LINKED_ACCOUNTS_HANDLERS
HANDLERS = getattr(
settings,
'LINKED_ACCOUNTS_HANDLERS',
LINKED_ACCOUNTS_HANDLERS
)
def get_profile(service=Non... |
Use sort,pop,remove and so on. | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
c=list("Perl")
c[1:1]=list('yth... | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
#c=list("Perl")
#c[1:1]=list('y... |
Replace parsing with Python's ast | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos =... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP... |
Increase the number of workers | import multiprocessing
from os import getenv
bind = '127.0.0.1:8001'
workers = multiprocessing.cpu_count() * 2
timeout = 60
threads = multiprocessing.cpu_count() * 2
max_requests = 1000
max_requests_jitter = 5
# Read the DEBUG setting from env var
try:
if getenv('DOCKER_SAL_DEBUG').lower() == 'true':
errorl... | import multiprocessing
from os import getenv
bind = '127.0.0.1:8001'
workers = multiprocessing.cpu_count() * 3
timeout = 60
threads = multiprocessing.cpu_count() * 3
max_requests = 500
max_requests_jitter = 5
# Read the DEBUG setting from env var
try:
if getenv('DOCKER_SAL_DEBUG').lower() == 'true':
errorlo... |
Fix variable and return value | from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scrape... | from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scrape... |
Add list and define functions. | import json
class Noah(object):
pass | import json
class Noah(object):
def __init__(self, dictionary_file):
self.dictionary = json.load(dictionary_file)
def list(self):
return '\n'.join([entry['word'] for entry in self.dictionary])
def define(self, word):
entry = next((x for x in self.dictionary if x['word'] == word), ... |
Bump version to prepare for next release. | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.9.0.11'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredispy',
version=__version__ + __build__,
description='Mock for redis-py',
url='htt... | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.9.0.12'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredispy',
version=__version__ + __build__,
description='Mock for redis-py',
url='htt... |
Add a configuration key for the URL of the Fedora OpenID server | SECRET_KEY = 'changeme please'
# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False
#ADMIN_GROUPS = ['sysadmin-web']
| SECRET_KEY = 'changeme please'
# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False
#ADMIN_GROUPS = ['sysadmin-web']
FMN_FEDORA_OPENID = 'https://id.fedoraproject.org'
|
Increment version number now that 0.1.5 release out. | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... |
Fix bin scripts having python2 or python3 specific path. | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 MUJIN Inc
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=... | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 MUJIN Inc
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=... |
Send the gecos input from USER through the sanitization as well | from twisted.words.protocols import irc
from txircd.modbase import Command
import string
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.setUsername(data["ident"])
user.realname = data["gecos"]
if user.registered =... | from twisted.words.protocols import irc
from txircd.modbase import Command
import string
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.setUsername(data["ident"])
user.setRealname(data["gecos"])
if user.registered... |
Upgrade status to Production/Stable and add specific python version to classifiers | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="valideer",
version="0.4.1",
description="Lightweight data validation and adaptation library for Python",
long_description=open("README.rst").read(),
url="https://github.com/podio/valideer",
author="George Sakkis",
... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="valideer",
version="0.4.1",
description="Lightweight data validation and adaptation library for Python",
long_description=open("README.rst").read(),
url="https://github.com/podio/valideer",
author="George Sakkis",
... |
Change to semantic version number | from setuptools import setup, find_packages
setup(
name = "django-ajax-utilities",
url = 'https://github.com/citylive/django-ajax-utilities',
license = 'BSD',
description = "Pagination, xhr and tabbing utilities for the Django framework.",
long_description = open('README','r').read(),
author = ... | from setuptools import setup, find_packages
setup(
name = "django-ajax-utilities",
version = '1.2.0',
url = 'https://github.com/citylive/django-ajax-utilities',
license = 'BSD',
description = "Pagination, xhr and tabbing utilities for the Django framework.",
long_description = open('README','r'... |
Add boto as requirement for funsize deployment. | from setuptools import setup
PACKAGE_NAME = 'funsize'
PACKAGE_VERSION = '0.1'
setup(name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description='partial mar webservice prototype',
long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
classifiers=[],
author='Anhad Jai Sing... | from setuptools import setup
PACKAGE_NAME = 'funsize'
PACKAGE_VERSION = '0.1'
setup(name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description='partial mar webservice prototype',
long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
classifiers=[],
author='Anhad Jai Sing... |
Remove unused code and get rid of flake8 errors | import json
import os
import time
import uuid
from google.appengine.api import urlfetch
from models import Profile
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.ge... | import json
import os
import time
from google.appengine.api import urlfetch
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.getenv('HTTP_AUTHORIZATION')
bea... |
Add fkey constraints at the same time | from __future__ import print_function
from getpass import getpass
import readline
import sys
from sqlalchemy import *
from migrate import *
from migrate.changeset.constraint import ForeignKeyConstraint
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer... | from sqlalchemy import *
from migrate import *
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer = Table('consumer', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('key', String),
Column('secret', String),
Column(... |
Define a default interpreter rather than using shutil.copyfile. | '''
These are some utilites used when writing and handling interpreters.
'''
import shutil
from cytoplasm import configuration
from cytoplasm.errors import InterpreterError
def SaveReturned(fn):
'''Some potential interpreters, like Mako, don't give you an easy way to save to a destination.
In these cases, sim... | '''
These are some utilites used when writing and handling interpreters.
'''
import shutil
from cytoplasm import configuration
from cytoplasm.errors import InterpreterError
def SaveReturned(fn):
'''Some potential interpreters, like Mako, don't give you an easy way to save to a destination.
In these cases, sim... |
Change gravatar url to use https | import hashlib
def get_gravatar_url(email):
email_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()
return "http://www.gravatar.com/avatar/{}".format(email_hash)
| import hashlib
def get_gravatar_url(email):
email_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()
return "https://www.gravatar.com/avatar/{}".format(email_hash)
|
Fix problem on no-longer existing bands that are still as logged in session available | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.