input
stringlengths
0
2.17k
instruction
stringlengths
18
2.94k
output
stringlengths
47
3.36k
from setuptools import setup, find_packages setup( name = "django-waitinglist", version = "1.0b8", author = "Brian Rosner", author_email = "brosner@gmail.com", description = "a Django waiting list app for running a private beta with cohorts support", long_description = open("README.rst").read(...
Fix packaging (again) - 1.0b9
from setuptools import setup, find_packages setup( name = "django-waitinglist", version = "1.0b9", author = "Brian Rosner", author_email = "brosner@gmail.com", description = "a Django waiting list app for running a private beta with cohorts support", long_description = open("README.rst").read(...
# -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages with open('README.rst', 'rb') as readme: readme_text = readme.read().decode('utf-8') setup( name='django-bootstrap-pagination', version='1.5.2', keywords="django bootstrap pagination templatetag", author...
Prepare for 1.6.0 on pypi
# -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages with open('README.rst', 'rb') as readme: readme_text = readme.read().decode('utf-8') setup( name='django-bootstrap-pagination', version='1.6.0', keywords="django bootstrap pagination templatetag", author...
import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore
Add testcase for database initialization
import os import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore def test_creates_required_dirs(self): for d in groundstation.store.git_store.GitStore.required_dirs: path = os.path.join(self.pat...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
Switch to pycryptodome rather than pycrypto
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pi...
Change "Development Status" classifier to "5 - Production/Stable"
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pi...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'cityhall', packages = ['cityhall'], # this must be the same as the name above version = '0.0.10', description = 'A library for accessing City Hall...
Update package to have the tag/release match
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'cityhall', packages = ['cityhall'], # this must be the same as the name above version = '0.0.10', description = 'A library for accessing City Hall...
from distutils.core import setup setup(name='nikeplus', version='0.1', description='Export nikeplus data to CSV format', author='Luke Lee', author_email='durdenmisc@gmail.com', url='http://www.lukelee.me', packages=['nikeplus'], entry_points={ "console_scripts": [ ...
Change package name for pypi, nikeplus was taken :(
from distutils.core import setup setup(name='nikeplusapi', version='0.1', description='Export nikeplus data to CSV format', author='Luke Lee', author_email='durdenmisc@gmail.com', url='http://www.lukelee.me', packages=['nikeplus'], entry_points={ "console_scripts": [ ...
from setuptools import setup setup( name='chainpoint', version='1.0', description='Federated server for building blockchain notarized Merkle trees.', author='Shawn Wilkinson', author_email='shawn+chainpoint@storj.io', url='http://storj.io', # Uncomment one or more lines below in the install_requi...
Remove Storj and Trigger Travis
from setuptools import setup setup( name='chainpoint', version='1.0', description='Federated server for building blockchain notarized Merkle trees.', author='Shawn Wilkinson', author_email='shawn+chainpoint@storj.io', # Uncomment one or more lines below in the install_requires section # for the ...
from os import path from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(path.join(pa...
Add Python 3.11 support as of version 1.10.0
from os import path from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(path.join(pa...
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-socialregistration', version='0.4.3', author='Alen Mujezinovic', author_email='alen@caffeinehit.com', description='Django application enabling registration through a variety of APIs', long_description...
Remove django requirement to prevent version conflicts when using pip
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-socialregistration', version='0.4.3', author='Alen Mujezinovic', author_email='alen@caffeinehit.com', description='Django application enabling registration through a variety of APIs', long_description...
from setuptools import setup setup( name='tangled.website', version='0.1.dev0', description='tangledframework.org', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.website/tags', author='Wyatt Baldwin', ...
Use the pg8000 pure-Python Postgres DBAPI module
from setuptools import setup setup( name='tangled.website', version='0.1.dev0', description='tangledframework.org', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.website/tags', author='Wyatt Baldwin', ...
from django.core.management import BaseCommand from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm from corehq.apps.domain.models import Domain from corehq.util.decorators import require_debug_true class Command(BaseCommand): help = ('Create a billing account and an enterprise level subscription ' ...
Use parser to add command line arg
from django.core.management import BaseCommand from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm from corehq.apps.domain.models import Domain from corehq.util.decorators import require_debug_true class Command(BaseCommand): help = ('Create a billing account and an enterprise level subscription ' ...
import numpy as np import rasterio def test_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: im_data = rasterio.plot.reshape_as_image(src) assert im_data.shape == (718, 791, 3) def test_toundtrip_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: data = sr...
Update reshape_image test for new decoupled io function
import numpy as np import rasterio def test_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: im_data = rasterio.plot.reshape_as_image(src.read()) assert im_data.shape == (718, 791, 3) def test_toundtrip_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: da...
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
Fix local interface addr parsing On Fedora 21 the format of ifconfig is a little different. Fixes #17
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Support deprecated use of the interface property of Bond.
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from loggers import Logger from core import Controller from sessions import Sessions from...
circuits.web: Add url and expose to this namesapce
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from utils import url from loggers import Logger from sessions import Sessions from core ...
from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), ...
Use unittest and make sure a few other cases don't crash
from test import test_support import symtable import unittest ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error ...
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABAS...
Allow overriding the DATABASE_URL with an environment varible if in development mode
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///app.db') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True c...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file c...
Include player data migration in setup
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating...
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, '...
Add MCMemoryNetwork as a usable solver
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers =...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Fix broken link to ragged tensor guide PiperOrigin-RevId: 368443422 Change-Id: I69818413b7ed8cf2f372580878860a469b9735a8
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('title', 'html', 'markdown')
Add new model fields to form
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('category', 'title', 'markdown', 'level')
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_...
Add a reset task to drop and recreate the db tables with one command.
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_...
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet f...
Fix typo in BackdropUser admin model
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet f...
from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event ...
Add test for button URLs including a 'next' parameter
from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): ...
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_...
Make IRC message delay configurable
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_...
#!/usr/bin/env python """ Autocompletion example. Press [Tab] to complete the current word. - The first Tab press fills in the common part of all completions and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ from __future__ import unicode_litera...
Fix typo: `dolphine` -> `dolphin`
#!/usr/bin/env python """ Autocompletion example. Press [Tab] to complete the current word. - The first Tab press fills in the common part of all completions and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ from __future__ import unicode_litera...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Add _all__ to the module.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
import json import os import sys import dateparser __DATA_DIR = '../data/' def harmonize_data( data ): ## make dates as date objects data2 = [] for d in data: if 'created_time' in d: d['date'] = dateparser.parse( d['created_time'] ) ## should take care of the various formats ...
Change dateparser to datetime to use with Jupyter
import json import os import sys #import dateparser from datetime import datetime __DATA_DIR = '../data/' def harmonize_data( data ): ## make dates as date objects data2 = [] for d in data: if 'created_time' in d: #d['date'] = dateparser.parse( d['created_time'] ) ## should take care o...
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' class PostDetailView(DetailView): model = Post context_object_name = 'post'
posts: Order posts from newest to oldest
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' def get_queryset(self): """ Order posts by the day they were added, from newest, to oldest....
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE`
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = port...
Fix 1010 upgrade step (setBatchID -> setBatch)
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = port...
from fabric.api import cd, run, task try: import fabfile_local _pyflakes = fabfile_local except ImportError: pass @task def update(): with cd("~/vagrant-installers"): run("git pull")
Allow the targetting of specific roles with fabric
from fabric.api import cd, env, run, task try: import fabfile_local _pyflakes = fabfile_local except ImportError: pass @task def update(): with cd("~/vagrant-installers"): run("git pull") @task def all(): "Run the task against all hosts." for _, value in env.roledefs.iteritems(): ...
import os import logging from optparse import OptionParser from pegasus.service import app, em from pegasus.service.command import Command class ServerCommand(Command): usage = "%prog [options]" description = "Start Pegasus Service" def __init__(self): Command.__init__(self) self.parser.a...
Allow service to start without EM if Condor and Pegasus are missing
import os import logging from optparse import OptionParser from pegasus.service import app, em from pegasus.service.command import Command log = logging.getLogger("server") class ServerCommand(Command): usage = "%prog [options]" description = "Start Pegasus Service" def __init__(self): Command._...
###### # 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...
: Create documentation of DataSource Settings Task-Url:
###### # 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...
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import json from odoo.http import request, route from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None...
Fix json.loads when context is None Co-authored-by: Pierre Verkest <94ea506e1738fc492d3f7a19e812079abcde2af1@gmail.com>
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import json from odoo.http import request, route from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None...
import datetime import mongoengine from mongoengine.django import auth from piplmesh.account import fields class User(auth.User): birthdate = fields.LimitedDateTimeField(upper_limit=datetime.datetime.today(), lower_limit=datetime.datetime.today() - datetime.timedelta(366 * 120)) gender = fields.GenderField()...
Change date's limits format to datetime.date.
import datetime import mongoengine from mongoengine.django import auth from piplmesh.account import fields class User(auth.User): birthdate = fields.LimitedDateTimeField(upper_limit=datetime.date.today(), lower_limit=datetime.date.today() - datetime.timedelta(366 * 120)) gender = fields.GenderField() lan...
from paver.easy import task, needs, path, sh, cmdopts from paver.setuputils import setup, install_distutils_tasks, find_package_data from distutils.extension import Extension from optparse import make_option from Cython.Build import cythonize import version pyx_files = ['si_prefix/si_prefix.pyx'] ext_modules = [Ex...
Rename package "si_prefix" to "si-prefix"
from paver.easy import task, needs, path, sh, cmdopts from paver.setuputils import setup, install_distutils_tasks, find_package_data from distutils.extension import Extension from optparse import make_option from Cython.Build import cythonize import version pyx_files = ['si_prefix/si_prefix.pyx'] ext_modules = [Ex...
#!/usr/bin/env python3 from passwd_change import passwd_change, shadow_change, mails_delete from unittest import TestCase, TestLoader, TextTestRunner import subprocess class PasswdChange_Test(TestCase): def setUp(self): """ Preconditions """ subprocess.call(['mkdir', 'test']) ...
Add tearDown() - remove test dir, test files existing and not existing.
#!/usr/bin/env python3 from passwd_change import passwd_change, shadow_change, mails_delete from unittest import TestCase, TestLoader, TextTestRunner import os import subprocess class PasswdChange_Test(TestCase): def setUp(self): """ Preconditions """ subprocess.call(['mkdir', 't...
from django import template from django.conf import settings from socialregistration.utils import _https register = template.Library() @register.inclusion_tag('socialregistration/facebook_js.html') def facebook_js(): return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())} @register.i...
Use syntax compatible with Python 2.4
from django import template from django.conf import settings from socialregistration.utils import _https register = template.Library() @register.inclusion_tag('socialregistration/facebook_js.html') def facebook_js(): return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())} @register.i...
# coding: utf-8 from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.parsers.events.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringO...
Update import of Event class
# coding: utf-8 from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.commons.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone =...
"""Aligner for texts and their segmentations. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals __all__ = ['AlignmentFailed', 'Aligner'] class AlignmentFailed(Exception): pass class Aligner(object): """Align a text with its tokenization. ...
BUG: Fix typo in variable name.
"""Aligner for texts and their segmentations. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals __all__ = ['AlignmentFailed', 'Aligner'] class AlignmentFailed(Exception): pass class Aligner(object): """Align a text with its tokenization. ...
from django import template from .. import perms from ..settings import get_user_attr register = template.Library() @register.filter def is_masquerading(user): info = getattr(user, get_user_attr()) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(u...
Make is_masquerading template tag more robust When masquerading is not enabled, immediately return False to avoid checking for a request attribute that won't be present.
from django import template from .. import perms from ..settings import get_user_attr, is_enabled register = template.Library() @register.filter def is_masquerading(user): if not is_enabled(): return False info = getattr(user, get_user_attr(), None) return info['is_masquerading'] @register.fi...
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^ap...
Fix to use react-router for all unmatched routes.
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^api/auth/', include('rest_auth....
from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) ...
Make this hack compatible with Django 1.9
from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) ...
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just above @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Alw...
Update fabric examples to reflect changes.
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Alw...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-22 23:41 from __future__ import unicode_literals from django.db import migrations def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_model('billj...
Add billing_address and migrate data
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-22 23:41 from __future__ import unicode_literals from django.db import migrations, models def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_mode...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATAB...
:lipstick: Add more verbosity on test running
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATAB...
# expose the most frequently used functions in the top level. from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: ...
Add in the init the newly introduced function
# expose the most frequently used functions in the top level. from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: ...
import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java globdict = globals() def loadFilesService(): global globdict execfile("filesAdmin.py", globdict)
Customize scripts to work with menu
import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java globdict = globals() def loadFilesService(): global globdict exec open("filesAdmin.py").read()
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_should_contain_num_m...
Make Clear Inbox keyword more robust.
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) if not os.path.isdir(maildir): return for fname in os.listdir(maildir): os.remove(os.path.join...
from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', upload_handler_name =...
Allow args and kwargs to upload_handler_name Now can use args and kwargs for reverse url. Example in template: {% jfu 'core/core_fileuploader.html' 'core_upload' object_id=1 content_type_str='app.model' %}
from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', upload_handler_name =...
import os import logging from decouple import config FOLDER = 'public' FOLDER = FOLDER.strip('/') log = logging.getLogger('deploy') def deploy(): import boto from boto.s3.connection import S3Connection AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCES...
Change to use logging and set log level to INFO
import os import logging from decouple import config FOLDER = 'public' FOLDER = FOLDER.strip('/') logging.basicConfig(level=logging.INFO) def deploy(): import boto from boto.s3.connection import S3Connection AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET...
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() def te...
Disable testing for index.html, needs ember build Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() # def t...
from urllib import urlencode from urllib2 import urlopen from rapidsms.backends.base import BackendBase class TropoBackend(BackendBase): """A RapidSMS threadless backend for Tropo""" def configure(self, config=None, **kwargs): self.config = config super(TropoBackend, self).configure(**kwargs) ...
Fix indentation; override old-style start() from BackendBase
from urllib import urlencode from urllib2 import urlopen from rapidsms.backends.base import BackendBase class TropoBackend(BackendBase): """A RapidSMS threadless backend for Tropo""" def configure(self, config=None, **kwargs): self.config = config def start(self): """Override Bac...
from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): class Meta: model = Budget fields = ('name', 'start_date') def save(self): if not self.instance.slug: self.in...
Split the start_date for better data entry (and Javascript date pickers).
import datetime from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget) class Meta: ...
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ # Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * # Utils folder contains scripts for mor...
Add adapter module to init file
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ # Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * # Adapter module contains classes and t...
from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_at = models.TimeFie...
Order stories by descending creation time
from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_at = models.TimeFie...
from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, 'error': 'Bad Request', 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e): return json_error_handler(e) @app.errorhandler(401...
Fix json error handler name
from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, 'error': e.name, 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e): return json_error_handler(e) @app.errorhandler(401) def u...
import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samples_per_element * len(...
Use 16 bit samples instead of float
import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samples_per_element * len(...
from django.utils.simplejson import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} content_object = None def __getattr__(self, name): ...
Use the simplejson bundled with django
from django.utils import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} content_object = None def __getattr__(self, name): return...
import json from flask import request, current_app, redirect from flaskext.bcrypt import generate_password_hash def get_ip(): ip = request.remote_addr if ip == '127.0.0.1' or ip == '127.0.0.2' and "X-Real-IP" in request.headers: ip = request.headers.get("X-Real-IP") return ip def makeMask(n): ...
Update IP address Tor traffic comes from
import json from flask import request, current_app, redirect from flaskext.bcrypt import generate_password_hash def get_ip(): ip = request.remote_addr if ip == '127.0.0.1' or ip == '127.0.0.2' and "X-Real-IP" in request.headers: ip = request.headers.get("X-Real-IP") return ip def makeMask(n): ...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopar...
Add a failure expectation to Linux memory.css3d test. BUG=373098 NOTRY=true R=kbr@chromium.org Review URL: https://codereview.chromium.org/303503009 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@273109 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopar...
# -*- coding: utf-8 -*- import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid...
Add length validator unit tests
# -*- coding: utf-8 -*- import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid...
import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock from van.contactology import Contactology class TestProxy(TestCase): @defer.inlineCallbacks def test_list_return(self): patcher = patch('van.contact...
Test for exception raising on API error.
import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock from van.contactology import Contactology, APIError class TestProxy(TestCase): @defer.inlineCallbacks def test_list_return(self): patcher = patch('v...
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .punctuation import TOKENIZER_SUFFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from...
Add writing_system to ArabicDefaults (experimental)
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .punctuation import TOKENIZER_SUFFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from...
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore class SimpleFileLog(tracelog.FileLog): def pr...
Update conary migration script to deal with extended config
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary import dbstore from .config import UpsrvConfig class SimpleFileLog(tracelog.FileLog): def printLog(self, level, msg): self.fd.wri...
#!/usr/local/bin/python # Code Fights Add Border Problem def arrayReplace(inputArray, elemToReplace, substitutionElem): pass def main(): pass if __name__ == '__main__': main()
Solve Code Fights array replace problem
#!/usr/local/bin/python # Code Fights Add Border Problem def arrayReplace(inputArray, elemToReplace, substitutionElem): return [x if x != elemToReplace else substitutionElem for x in inputArray] def main(): tests = [ [[1, 2, 1], 1, 3, [3, 2, 3]], [[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]], ...
# stdlib from typing import Any from typing import Dict # third party from pandas import DataFrame # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messag...
Update Worker API - ADD type hints - Remove unused imports
# stdlib from typing import Callable # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messages import GetWorkersMessage from ...messages.infra_messages imp...
from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from notification import backends from notification.message import message_to_text # favour djan...
pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling. git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9
from django.conf import settings from django.db.models.loading import get_app from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigur...
#!/usr/bin/env python import sys print("argv: %d" % len(sys.argv)) # Object related test print(type(sys.argv)) print(id(sys.argv)) print(type(sys.argv) is list) if len(sys.argv) != 2: print("%s filename" % sys.argv[0]) raise SystemExit(1) file = open(sys.argv[1], "w") line = [] while True: line = sys.s...
Add comment for object types
#!/usr/bin/env python import sys print("argv: %d" % len(sys.argv)) # Object related test # type and id are unique # ref: https://docs.python.org/2/reference/datamodel.html # mutable object: value can be changed # immutable object: value can NOT be changed after created # This means readonly # ex: ...
import warnings from haystack import indexes from avocado.conf import settings from avocado.models import DataConcept, DataField # Warn if either of the settings are set to false if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \ not getattr(settings, 'FIELD_SEARCH_ENABLED', True): warnings.warn...
Change DataIndex to restrict on published and archived flags only In addition, the warnings of the deprecated settings have been removed. Fix #290 Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
from haystack import indexes from avocado.models import DataConcept, DataField class DataIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) text_auto = indexes.EdgeNgramField(use_template=True) def index_queryset(self, using=None): return self.get_model().objec...
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), ...
Remove debug toolbar in test settings
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), ...
from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): sort_by = request.args....
Add proto of average page. Without sorting.
from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): sort_by = request.args....
import json from rest_framework.authtoken.models import Token from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant class C...
Use client_name instead of schema_name
import json from rest_framework.authtoken.models import Token from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant class C...
from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/', include('djan...
Change url in favor of the re_path
from django.conf import settings from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ re_path(r'^$', index, name='index'), re_path(r'^admin/', admin.site.urls), re_path(r'^summernote/', in...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule class InvalidSyntaxTest(TestCase): pass if __name__ == '__main__': main()
Add base set of rule's invalid syntax tests
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleSyntaxException from .grammar import * class InvalidSyntaxTest(TestCase): def test_rulesMissingEncloseLis...
from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version from reversion.revisions import default_revision_manager global_save_signal_receiver = [] class PreSaveHandler(object): def __init__(s...
Fix broken initial version creation.
from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version def create_initial_version(obj): try: from reversion.revisions import default_revision_manager default_revision_manager...
#!/usr/bin/env python import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) def main(args=sys.argv[1:]): lo...
Allow sub-commands to use same main function
#!/usr/bin/env python import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) def main(args=None): if args is...
# coding: utf-8 import os import traceback from .handlers import find_handler _activate_debugger = os.environ.get('DEBUG') == 'yes' if _activate_debugger: try: from trepan.api import debug set_trace = debug except ImportError: import pdb set_trace = pdb.set_trace def signal...
Fix use of Python 2 print
# coding: utf-8 from __future__ import print_function import os import traceback from .handlers import find_handler _activate_debugger = os.environ.get('DEBUG') == 'yes' if _activate_debugger: try: from trepan.api import debug set_trace = debug except ImportError: import pdb ...
''' Null tester (when nose not importable) Merely returns error reporting lack of nose package See pkgtester, nosetester modules ''' nose_url = 'http://somethingaboutorange.com/mrl/projects/nose' class NullTester(object): def __init__(self, *args, **kwargs): pass def test(self, labels=None, *args, ...
Fix bench error on scipy import when nose is not installed
''' Null tester (when nose not importable) Merely returns error reporting lack of nose package See pkgtester, nosetester modules ''' nose_url = 'http://somethingaboutorange.com/mrl/projects/nose' class NullTester(object): def __init__(self, *args, **kwargs): pass def test(self, labels=None, *args, ...
from scrapy.item import Item, Field class DatasetItem(Item): name = Field() frequency = Field()
Add url field to Dataset web item
from scrapy.item import Item, Field class DatasetItem(Item): url = Field() name = Field() frequency = Field()
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "IncludeManagementE...
Update Cloudtrail per 2021-09-10 changes
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "ExcludeManagementE...
# Copyright (c) 2017, Frappe and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") frappe...
Move reload doc before get query
# Copyright (c) 2017, Frappe and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("stock", "doctype", "item_barcode") items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })...
from django.db import models from django.utils.translation import ugettext_lazy as _ class Farmer(models.Model): first_name = models.CharField(_('first name'), max_length=50) surname = models.CharField(_('surname'), max_length=50) town = models.CharField(_('town'), max_length=50, db_index=True) class...
Repair bug in the Farmer model
from django.db import models from django.utils.translation import ugettext_lazy as _ class Farmer(models.Model): first_name = models.CharField(_('first name'), max_length=50) surname = models.CharField(_('surname'), max_length=50) town = models.CharField(_('town'), max_length=50, db_index=True) class...
# Standard imports import math import logging import numpy as np import emission.core.common as ec import emission.analysis.section_features as sf def calDistance(point1, point2): return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude]) def calHeading(point1, point2): re...
Change the feature calculation to match the new unified format - the timestamps are now in seconds, so no need to divide them - the field is called ts, not mTime
# Standard imports import math import logging import numpy as np import emission.core.common as ec import emission.analysis.section_features as sf def calDistance(point1, point2): return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude]) def calHeading(point1, point2): re...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch from salt import minion from salt.exceptions import ...
Add test for sock path length
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import python libs import os # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch # Import salt libs f...
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_P...
Make sure this value is always an integer
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_P...
from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer
Add search functionality to permissions endpoint
from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer search_fields = ('name',)
"""Tests for the Caeser module""" import pycipher from lantern.modules import atbash def _test_atbash(plaintext, *fitness_functions, top_n=1): ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True) decryption = atbash.decrypt(ciphertext) assert decryption == plaintext.upper() def test_de...
Remove unnecessary testing code from atbash
"""Tests for the Caeser module""" from lantern.modules import atbash def test_decrypt(): """Test decryption""" assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}" def test_encrypt(): """Test encryption""" assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake da...
Fix string using py3 only feature.
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake da...
import helper from rock import utils class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s.write('ok') s.__exit__(None, None, None) self.a...
Test isexecutable check in utils.Shell
import helper from rock import utils from rock.exceptions import ConfigError class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s.write('ok') s._...
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
Update the default settings file to include the database threaded option
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=Tru...
Fix migration file for Python 3.2 (and PEP8)
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, ...
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'consol...
Add missing config that caused test to fail
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'consol...
from parglare import Grammar grammar = Grammar.from_string(""" start: ab EOF; ab: "a" ab "b" | EMPTY; """) start_symbol = 'start'
Remove `EOF` -- update examples refs #64
from parglare import Grammar grammar = Grammar.from_string(""" start: ab; ab: "a" ab "b" | EMPTY; """) start_symbol = 'start'
from cellulario import iocell import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) iocell.DEBUG = True
Remove uvloop from test run.
from cellulario import iocell iocell.DEBUG = True
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.CreditedUserId = None #...
Add possibilty to get ResultMessage
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.CreditedUserId = None #...
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
Fix ConnectedSWFObject: pass default value to pop()
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid_position(self, icon, x, y): i...
Use get/set_property rather than direct accessors
import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid_position(self, icon, x, y): i...