Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Create basic user model for auth | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | |
Fix JSONResponse to work without complaints on django 1.6 | # -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.utils import simplejson
def JSONResponse(data):
return HttpResponse(simplejson.dumps(data), mimetype='application/json')
| # -*- coding: utf-8 -*-
from django.http import HttpResponse
import json
def JSONResponse(data):
return HttpResponse(json.dumps(data), content_type='application/json')
|
Convert script to Python 3 | import sys
from datetime import datetime
TEMPLATE = """
Title: {title}
Date: {year}-{month}-{day} {hour}:{minute:02d}
Modified:
Author:
Category:
Tags:
"""
def make_entry(title):
today = datetime.today()
title_no_whitespaces = title.lower().strip().replace(' ', '-')
f_create = "content/{}_{:0>2}_{... | import sys
from datetime import datetime
TEMPLATE = """
Title: {title}
Date: {year}-{month}-{day} {hour}:{minute:02d}
Modified:
Author:
Category:
Tags:
"""
def make_entry(title):
today = datetime.today()
title_no_whitespaces = title.lower().strip().replace(' ', '-')
f_create = "content/{}_{:0>2}_{... |
Fix quick union functions issue | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class WeightedQuickUnion(object):
def __init__(self):
self.id = []
self.weight = []
def find(self, val):
p = val
while self.id[p] != p:
p = self.id[p]
return self.id[p]
def union(self, p, q):
p_ro... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class WeightedQuickUnion(object):
def __init__(self, data=None):
self.id = data
self.weight = [1] * len(data)
self.count = len(data)
def count(self):
return self.count
def find(self, val):
p = val
while self.i... |
Adjust entry_points to fix autoscan | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
name = 'morepath_cerebral_todomvc'
description = (
'Morepath example of using React & Cerebral'
)
version = '0.1.0'
setup(
name=name,
version=version,
description=description,
author='Henri Hulski',
author_email='henri.hulsk... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
name = 'morepath_cerebral_todomvc'
description = (
'Morepath example of using React & Cerebral'
)
version = '0.1.0'
setup(
name=name,
version=version,
description=description,
author='Henri Hulski',
author_email='henri.hulski... |
Use absolute path on find packages | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
tests_require = []
setup(
name='Mule',
version='1.0',
author='DISQUS',
author_email='opensource@d... | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import os.path
tests_require = []
setup(
name='Mule',
version='1.0',
author='DISQUS',
author_emai... |
Add media server to dev server | # Django
from django.conf.urls import (
include,
url,
)
from django.contrib import admin
from django.http import HttpResponse
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('apps.api.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^robots.txt$', lambd... | # Django
from django.conf.urls import (
include,
url,
)
from django.contrib import admin
from django.http import HttpResponse
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('apps.api.urls')),
url(r'... |
Add route for preview request | import os
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession, Base
def main(global_config, **settings):
'''This function returns a Pyramid WSGI application.'''
settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL')
engine = engine_from_con... | import os
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession, Base
def main(global_config, **settings):
'''This function returns a Pyramid WSGI application.'''
settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL')
engine = engine_from_con... |
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561) | # -*- coding: utf-8 -*-
# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
pycroft
~~~~~~~~~~~~~~
This package contains everything.
:copyrigh... | # -*- coding: utf-8 -*-
# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
pycroft
~~~~~~~~~~~~~~
This package contains everything.
:copyrigh... |
Add pytest markers for cassandra tests | import mock
import pytest
from scrapi import settings
settings.DEBUG = True
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
@pytest.fixture(autouse=True)
def harvester(monkeypatch):
import_mock = mock.MagicMock()
harvester_mock = mock.MagicMock()
import_mock.return... | import mock
import pytest
from scrapi import settings
from scrapi import database
database._manager = database.DatabaseManager(keyspace='test')
settings.DEBUG = True
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
@pytest.fixture(autouse=True)
def harvester(monkeypatch):
... |
Fix the HDF5 type of mesh_uuid for imported meshes. | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import uuid
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add ... | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import uuid
import numpy as np
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyf... |
Fix args to list. Args is a tuple, list takes a tuple | from genes.process.commands import get_env_run
from .traits import only_posix
run = get_env_run()
@only_posix()
def chmod(*args):
# FIXME: this is ugly, name the args
run(['chmod'] + list(*args))
| from genes.process.commands import get_env_run
from .traits import only_posix
run = get_env_run()
@only_posix()
def chmod(*args):
# FIXME: this is ugly, name the args
run(['chmod'] + list(args))
|
Mark test as xfail so that releases can be cut | import pytest
import pika
from mettle.settings import get_settings
from mettle.publisher import publish_event
def test_long_routing_key():
settings = get_settings()
conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url))
chan = conn.channel()
exchange = settings['state_exchange']
... | import pytest
import pika
from mettle.settings import get_settings
from mettle.publisher import publish_event
@pytest.mark.xfail(reason="Need RabbitMQ fixture")
def test_long_routing_key():
settings = get_settings()
conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url))
chan = conn.chann... |
Clean up an import in simple backend URLs. | """
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... | """
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... |
Make compatible with py-redis 3.x | from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(ResultStore, self).__init__(config)
if not ResultStore.redis_instance:
R... | from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(ResultStore, self).__init__(config)
if not ResultStore.redis_instance:
R... |
Increment version number to 0.4.1dev | __version__ = '0.4.0'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... | __version__ = '0.4.1dev'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiat... |
Update number of fonts in Docker image | """
tests.test_fonts
~~~~~~~~~~~~~~~~~~~~~
Test fonts API.
:copyright: (c) 2018 Yoan Tournade.
:license: AGPL, see LICENSE for more details.
"""
import requests
def test_api_fonts_list(latex_on_http_api_url):
"""
The API list available fonts.
"""
r = requests.get("{}/fonts".format... | """
tests.test_fonts
~~~~~~~~~~~~~~~~~~~~~
Test fonts API.
:copyright: (c) 2018 Yoan Tournade.
:license: AGPL, see LICENSE for more details.
"""
import requests
def test_api_fonts_list(latex_on_http_api_url):
"""
The API list available fonts.
"""
r = requests.get("{}/fonts".format... |
Fix bug in sms router. |
class SMSRouter(object):
app_label = 'sms'
db_name = 'sms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self.app_label:
... |
class TurboSMSRouter(object):
app_label = 'turbosms'
db_name = 'turbosms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self... |
Use the notice ID as priary key | #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import sys
import pymongo
from pathlib import Path
import argh
from xml2json import etree_to_dict
from hilma_conversion import get_handler
hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler)
def load_hilma_xml(inputfile, collection):
root = E... | #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import sys
import pymongo
from pathlib import Path
import argh
from xml2json import etree_to_dict
from hilma_conversion import get_handler
hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler)
def load_hilma_xml(inputfile, collection):
root = E... |
Use relative imports for consistency; pep8 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from photutils.psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01,... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from ..psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01, 0.1, 1]
@... |
Remove Url model from admin | 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
|
Change /contacts/groups to display only static groups (instead of all groups) | 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... |
Revert "emails now sent through mailgun, small warning css change" | 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... |
Make lines jumps only jump to blocks over changes | 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
... |
Fix displaying None in statistics when there's no book sold | 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_... |
Move log file to constant | #!/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... |
Fix the wikipedia link and include a warning | # -*- 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... |
Comment out temporally scoresheet editing page | 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... |
Update tools script for file renaming | #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import... | #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import... |
Fix bug to avoid duplicating topics | from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
def extract_topic_items(topic):
db = MongoClient(MONGO_URI).get_default_database()
resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))
da... | from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
from redis import StrictRedis
import rq
def extract_topic_items(topic):
r = StrictRedis()
def topic_in_queue(topic):
q = rq.Queue('topics', connec... |
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_objec... | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_objec... |
Insert the current directory to the front of sys.path -- and remove it at the end. This fixes a problem where | from test_support import TESTFN
import os
import random
source = TESTFN + ".py"
pyc = TESTFN + ".pyc"
pyo = TESTFN + ".pyo"
f = open(source, "w")
print >> f, "# This will test Python's ability to import a .py file"
a = random.randrange(1000)
b = random.randrange(1000)
print >> f, "a =", a
print >> f, "b =", b
f.clos... | from test_support import TESTFN
import os
import random
import sys
sys.path.insert(0, os.curdir)
source = TESTFN + ".py"
pyc = TESTFN + ".pyc"
pyo = TESTFN + ".pyo"
f = open(source, "w")
print >> f, "# This will test Python's ability to import a .py file"
a = random.randrange(1000)
b = random.randrange(1000)
print ... |
Use whatever is default open mode. | import logging
import json
import py
from fields import Namespace
from pytest_benchmark.plugin import BenchmarkSession
class MockSession(BenchmarkSession):
def __init__(self):
self.histogram = True
me = py.path.local(__file__)
self.storage = me.dirpath(me.purebasename)
self.benc... | import logging
import json
import py
from fields import Namespace
from pytest_benchmark.plugin import BenchmarkSession
class MockSession(BenchmarkSession):
def __init__(self):
self.histogram = True
me = py.path.local(__file__)
self.storage = me.dirpath(me.purebasename)
self.benc... |
Update deprecated excel kwarg in pandas | import pandas as pd
def _params_dict_to_dataframe(d):
s = pd.Series(d)
s.index.name = 'parameters'
f = pd.DataFrame({'values': s})
return f
def write_excel(filename, **kwargs):
"""Write data tables to an Excel file, using kwarg names as sheet names.
Parameters
----------
filenam... | import pandas as pd
def _params_dict_to_dataframe(d):
s = pd.Series(d)
s.index.name = 'parameters'
f = pd.DataFrame({'values': s})
return f
def write_excel(filename, **kwargs):
"""Write data tables to an Excel file, using kwarg names as sheet names.
Parameters
----------
filenam... |
Replace hashbang with /usr/bin/env python3 for better portability | #!/usr/bin/python3
import argparse
if __name__ == '__main__':
# Boilerplate to allow running as script directly. Avoids error below:
# SystemError: Parent module '' not loaded, cannot perform relative import
# See http://stackoverflow.com/questions/2943847/
if __package__ is None:
import sys
... | #!/usr/bin/env python3
import argparse
if __name__ == '__main__':
# Boilerplate to allow running as script directly. Avoids error below:
# SystemError: Parent module '' not loaded, cannot perform relative import
# See http://stackoverflow.com/questions/2943847/
if __package__ is None:
import ... |
Simplify plot test for now | """Tests K2fov.plot"""
from .. import plot
def test_basics():
"""Make sure this runs without exception."""
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
except ImportError:
pass
| """Tests K2fov.plot"""
from .. import plot
"""
def test_basics():
# Make sure this runs without exception.
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
except ImportError:
pass
"""
|
Remove retries limit in read ftm. | import json
import logging
class IOHandler(object):
@classmethod
def is_host_compatible(cls, host):
return False
def __init__(self, host):
raise NotImplementedError
def is_ready(self):
raise NotImplementedError
def read(self, trials=5):
try:
data = se... | import json
import logging
class IOHandler(object):
@classmethod
def is_host_compatible(cls, host):
return False
def __init__(self, host):
raise NotImplementedError
def is_ready(self):
raise NotImplementedError
def read(self, trials=5):
try:
data = se... |
Fix broken utils test with seed | import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
self.assertEqual(sorted(list(set(rargmax(... | import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
np.random.seed(1)
self.assertEqua... |
Use better string concatenation in mkthumb() | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... |
Add file source and subjectID to processing exceptions | import pandas
import traceback
import typing
def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame:
def get_frames():
for file in file_iterator:
df = processor(file)
yield (df
.assign(Source=getattr(file, 'n... | import pandas
import typing
def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame:
def get_frames():
for file in file_iterator:
source = getattr(file, 'name', None)
subject_id = getattr(file, 'cpgintegrate_subject_id', None)
... |
Add shapefile library, used for shapefile-based fixtures. | import os.path
from setuptools import find_packages
from setuptools import setup
version_path = os.path.join(os.path.dirname(__file__), 'VERSION')
with open(version_path) as fh:
version = fh.read().strip()
setup(name='vector-datasource',
version=version,
description="",
long_description="""\
"""... | import os.path
from setuptools import find_packages
from setuptools import setup
version_path = os.path.join(os.path.dirname(__file__), 'VERSION')
with open(version_path) as fh:
version = fh.read().strip()
setup(name='vector-datasource',
version=version,
description="",
long_description="""\
"""... |
Add 'treq' as a requirement for GitHubStatusPush. | from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.2',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.up... | from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.3',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.up... |
Fix error when setting JSON value to be `None` | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
... | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
... |
Add more tests against live API | # -*- coding: utf-8 -*-
import os
import pytest
import holviapi
@pytest.fixture
def connection():
pool = os.environ.get('HOLVI_POOL', None)
key = os.environ.get('HOLVI_KEY', None)
if not pool or not key:
raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests")
cnc = holviap... | # -*- coding: utf-8 -*-
import os
import pytest
import holviapi
@pytest.fixture
def connection():
pool = os.environ.get('HOLVI_POOL', None)
key = os.environ.get('HOLVI_KEY', None)
if not pool or not key:
raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests")
cnc = holviap... |
Adjust hashtag to be consistently one word | from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey... | from django.conf import settings
from django.db import models
class Hashtag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey... |
Add a list conversion test | import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import vector_likes, vectors
class V(Vector2): pass
@pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore
@pytest.mark.parametrize('cls', [Vector2, V]) # type: ignore
... | import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import vector_likes, vectors
class V(Vector2): pass
@pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore
@pytest.mark.parametrize('cls', [Vector2, V]) # type: ignore
... |
Remove deprecated kwarg and undefined variable. | #!/usr/bin/env python
from setuptools import setup
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version='0.1.6',
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
... | #!/usr/bin/env python
from setuptools import setup
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version='0.1.6',
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
... |
Add package transip.service or else this is not installed | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... |
Install scripts properly rather than as datafiles | #!/usr/bin/env python
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
author = "Mike Svoboda",
author_email = "msvoboda@linkedin.com",
py_modules=['CacheExtractor', 'RedisFinder'],
data_files=[('/usr/local/bin', [... | #!/usr/bin/env python
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
author="Mike Svoboda",
author_email="msvoboda@linkedin.com",
py_modules=['CacheExtractor', 'RedisFinder'],
scripts=['scripts/extract_sysops_cac... |
Update Django requirement to latest LTS | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-yadt',
url='https://chris-lamb.co.uk/projects/django-yadt',
version='2.0.5',
description="Yet Another Django Thumbnailer",
author="Chris Lamb",
author_email='chris@chris-lamb.co.uk',
license='BSD',
... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-yadt',
url='https://chris-lamb.co.uk/projects/django-yadt',
version='2.0.5',
description="Yet Another Django Thumbnailer",
author="Chris Lamb",
author_email='chris@chris-lamb.co.uk',
license='BSD',
... |
Add --nowait option to resubmit-tasks cmd | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%prog %s tas... | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%prog %s tas... |
Fix call to renamed function | from datetime import datetime
from typing import Union, Callable
from rx import empty, timer, operators as ops
from rx.core import Observable
def _delay_subscription(duetime: Union[datetime, int]) -> Callable[[Observable], Observable]:
"""Time shifts the observable sequence by delaying the subscription.
1 -... | from datetime import datetime
from typing import Union, Callable
from rx import empty, timer, operators as ops
from rx.core import Observable
def _delay_subscription(duetime: Union[datetime, int]) -> Callable[[Observable], Observable]:
"""Time shifts the observable sequence by delaying the subscription.
1 -... |
Split get_input from set_input in FormTestMixin. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(... |
Make the lib imports work on other computers than Simon's | #!/usr/bin/env python
import sys
paths = (
'/home/simon/sites/djangopeople.net',
'/home/simon/sites/djangopeople.net/djangopeoplenet',
'/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib',
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.m... | #!/usr/bin/env python
import sys, os
root = os.path.dirname(__file__)
paths = (
os.path.join(root),
os.path.join(root, "djangopeople", "lib"),
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.management import execute_manager
try:
import settings # Assume... |
Add keyword to echo worker. | # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(sel... | # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(sel... |
Make pledge foreignkey to userprofile | from django.utils import timezone
from django.db import models
from users.models import Course, BaseModel, User
class Pledge(BaseModel):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
money = models.DecimalField(max_digits=8, decimal_places=2)
pledge_date = models.DateTimeField('da... | from django.utils import timezone
from django.db import models
from users.models import Course, BaseModel, UserProfile
class Pledge(BaseModel):
user = models.ForeignKey(UserProfile)
course = models.ForeignKey(Course)
money = models.DecimalField(max_digits=8, decimal_places=2)
pledge_date = models.Dat... |
Modify exception handler to cover multiple data types i.e. dict and list and handle when more than one error returned | from rest_framework.exceptions import APIException
from rest_framework import status
def jsonapi_exception_handler(exc, context):
"""
Custom exception handler that returns errors object as an array with a 'detail' member
"""
from rest_framework.views import exception_handler
response = exception_ha... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
"""
Custom exception handler that returns errors object as an array
"""
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
... |
Fix Python 2/3 exception base class compatibility | from __future__ import absolute_import
from functools import wraps
from exceptions import StandardError
from turbodbc_intern import Error as InternError
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
def translate_exceptions(f):
@wraps(f)
... | from __future__ import absolute_import
from functools import wraps
from turbodbc_intern import Error as InternError
# Python 2/3 compatibility
try:
from exceptions import StandardError as _BaseError
except ImportError:
_BaseError = Exception
class Error(_BaseError):
pass
class InterfaceError(Error):... |
Update to the run tests script to force database deletion if the test database exists. | #!/usr/bin/env python
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
apps = []
if len(sys.argv) > 1:
... | #!/usr/bin/env python
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver --noinput"
apps = []
if len(sys.argv)... |
Remove unused import and redundant comment | """
NOTE: this API is WIP and has not yet been approved. Do not use this API
without talking to Christina or Andy.
For more information, see:
https://openedx.atlassian.net/wiki/display/TNL/User+API
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import stat... | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from openedx.core.lib.api.authentication import (
SessionAuthenticationAllowInactiveUser,
OAuth2AuthenticationAllowInactiveUser,
)
from openedx.core.lib.api.parsers import MergePatchParser
fr... |
Fix typo from bad conflict resolution during merge | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
kwargs['_jo... | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task,... |
Add missing parser argument to BeautifulSoup instance | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, valu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, valu... |
Add special character name test case | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... |
Add benchmark tests for numpy.random.randint. | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(... | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = nam... |
Update serializer to deal with new model | from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
| from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
fields = ('count_total',)
|
Update goodreads API to `show original_publication_year` | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... |
Create documentation of DataSource Settings | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... |
Add standard header, use spack helpers | from spack import *
from glob import glob
import os
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/download/v0.20.1/nextflow',
... | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
Write out concatenated frame on decode test failure | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... |
Change call method for Python2.7 | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.run(
"notif... | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.check_call(
... |
Allow proxy minions to load static grains | # -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this syste... |
Test cases for push with export flag | # -*- coding: utf-8 -*-
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=Tru... | # -*- coding: utf-8 -*-
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=Tru... |
Refactor GSI, LSI to use base Index class | missing = object()
class GlobalSecondaryIndex(object):
def __init__(self, hash_key=None, range_key=None,
write_units=1, read_units=1, name=missing):
self._model_name = None
self._backing_name = name
self.write_units = write_units
self.read_units = read_units
... | class Index(object):
def __init__(self, write_units=1, read_units=1, name=None, range_key=None):
self._model_name = None
self._dynamo_name = name
self.write_units = write_units
self.read_units = read_units
self.range_key = range_key
@property
def model_name(self):
... |
Add task for pushing code with rsync | #!/usr/bin/env python
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def update_dependencies():
with prefix('workon jarvis2'):
run('... | #!/usr/bin/env python
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def push_code():
rsync... |
Add support for QTest with PySide | # -*- coding: utf-8 -*-
#
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Developmet Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtTest and functions
.. warning:: PySide is not supported here, that's why there is not unit tests
running wi... | # -*- coding: utf-8 -*-
#
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Developmet Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtTest and functions
"""
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest ... |
Update project downloader to do diffs before overwriting | #!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
repo_names = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
... | #!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
import simplediff
from pprint import pprint
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
with open("projects.txt", mode = "r", encoding = "utf-8") as projects_file:
cur_rep... |
Validate sub and jti claims |
__version__ = "0.3.0"
__author__ = 'Michael Davis'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Michael Davis'
from .exceptions import JOSEError
from .exceptions import JWSError
from .exceptions import ExpiredSignatureError
from .exceptions import JWTError
|
__version__ = "0.4.0"
__author__ = 'Michael Davis'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Michael Davis'
from .exceptions import JOSEError
from .exceptions import JWSError
from .exceptions import ExpiredSignatureError
from .exceptions import JWTError
|
Fix bug in module selection. | import lib.collect.config as config
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
| import lib.collect.config as config
try:
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
except AttributeError:
import lib.collect.backends.localfs as api
|
Disable REST Upload by default | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healt... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healt... |
Fix specification of Python 3.6 and 3.7 | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.3',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
... | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.3',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
... |
Add more Python version classifiers | #!/usr/bin/env python
from setuptools import find_packages, setup
# Use quickphotos.VERSION for version numbers
version_tuple = __import__('quickphotos').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-quick-photos',
version=version,
description='Latest Photos from Instagra... | #!/usr/bin/env python
from setuptools import find_packages, setup
# Use quickphotos.VERSION for version numbers
version_tuple = __import__('quickphotos').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-quick-photos',
version=version,
description='Latest Photos from Instagra... |
Allow new version of requires | from setuptools import setup, find_packages
long_description = open('./README.rst').read()
setup(
name='ebi',
version='0.6.2',
install_requires=[
'awsebcli==3.7.3',
'boto3==1.2.6',
],
description='Simple CLI tool for ElasticBeanstalk with Docker',
long_description=long_descript... | from setuptools import setup, find_packages
long_description = open('./README.rst').read()
setup(
name='ebi',
version='0.6.2',
install_requires=[
'awsebcli>=3.7.3,<4',
'boto3>==1.2.6,<2',
],
description='Simple CLI tool for ElasticBeanstalk with Docker',
long_description=long_d... |
Make it DESC order by id. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action',... |
Add a manager to make getting preferences prettier. | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 agre... | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 agre... |
Correct typing issues in string interp. | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program 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 Free Software Foundation, either version 3 of the... | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program 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 Free Software Foundation, either version 3 of the... |
Test framework fix - url replacing handles jenkins url with 'prefix' | # Copyright (c) 2012 - 2014 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://[^/]*/')
def replace_host_port(contains_url):
return _htt... | # Copyright (c) 2012 - 2014 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://.*?/job/')
def replace_host_port(contains_url):
return _h... |
Remove closed_at field from Task model | from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
... | from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
... |
Add utility function for retrieving the active registration backend. | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.cor... | |
Allow searching restricted courses by key | """
Django admin page for embargo models
"""
import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
... | """
Django admin page for embargo models
"""
import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
... |
Test assumption, composition for RPC Java proofs | import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int,... | import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int,... |
Add helper function to create a DualPlot | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r',... | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r',... |
Add VERSION and __version__ directly to pystorm namespace | from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
| '''
pystorm is a production-tested Storm multi-lang implementation for Python
It is mostly intended to be used by other libraries (e.g., streamparse).
'''
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
from .version import __version__, VERSI... |
Update test to reflect new default version for node | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... |
Simplify get_joke test, add raise checks |
def test_get_joke():
from pyjokes import get_joke
for i in range(10):
assert get_joke()
languages = ['eng', 'de', 'spa']
categories = ['neutral', 'explicit', 'all']
for lang in languages:
for cat in categories:
for i in range(10):
assert get_joke(cat,... |
import pytest
from pyjokes import get_joke
from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError
def test_get_joke():
assert get_joke()
languages = ['en', 'de', 'es']
categories = ['neutral', 'explicit', 'all']
for lang in languages:
assert get_joke(language=lang)
... |
Update with real train users | #!/usr/bin/env python
import pandas as pd
from datetime import date
import holidays
def sanitize_holiday_name(name):
new_name = [c for c in name if c.isalpha() or c.isdigit() or c == ' ']
new_name = "".join(new_name).lower().replace(" ", "_")
return new_name
def process_holidays(df):
# Create a dat... | #!/usr/bin/env python
import pandas as pd
from datetime import date
import holidays
def sanitize_holiday_name(name):
new_name = [c for c in name if c.isalpha() or c.isdigit() or c == ' ']
new_name = "".join(new_name).lower().replace(" ", "_")
return new_name
def process_holidays(df):
# Create a dat... |
Delete the unused LOG code | # Copyright 2017 Objectif Libre
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2017 Objectif Libre
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
Add an exception to tell a controller does not implement something. | import unittest
import operator
import itertools
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism:... | import unittest
import operator
import itertools
class NotImplementedByController(unittest.SkipTest):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'... |
Remove volume consistency group tab from horizon in mitaka | # Disable Floating IPs
from openstack_dashboard.dashboards.project.access_and_security import tabs
from openstack_dashboard.dashboards.project.instances import tables
import horizon
NO = lambda *x: False
tabs.FloatingIPsTab.allowed = NO
tabs.APIAccessTab.allowed = NO
tables.AssociateIP.allowed = NO
tables.SimpleAssoc... | # Disable Floating IPs
from openstack_dashboard.dashboards.project.access_and_security import tabs
from openstack_dashboard.dashboards.project.instances import tables
import horizon
NO = lambda *x: False
tabs.FloatingIPsTab.allowed = NO
tabs.APIAccessTab.allowed = NO
tables.AssociateIP.allowed = NO
tables.SimpleAssoc... |
Change string representation for django model | from django.db import models
from django.utils.translation import ugettext_lazy as _
{%% for model_name, props in all_models.iteritems() %%}
{%% set model_name = model_name|capitalize %%}
class {{{ model_name }}}(models.Model):
{%% for prop, value in props.iteritems() %%}
{{{ prop }}} = {{{ value|model_field }}... | from django.db import models
from django.utils.translation import ugettext_lazy as _
{%% for model_name, props in all_models.iteritems() %%}
{%% set model_name = model_name|capitalize %%}
class {{{ model_name }}}(models.Model):
{%% for prop, value in props.iteritems() %%}
{{{ prop }}} = {{{ value|model_field }}... |
Change package name in loadmodule call | # -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file):
"""
Load problem file a... | # -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file_path):
"""
Load p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.