input stringlengths 0 2.17k | instruction stringlengths 18 2.94k | output stringlengths 47 3.36k |
|---|---|---|
# pylint: disable=unused-import, unused-variable, missing-docstring
def _readline():
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], '.... | Move python rl history file
just to help clean up ~/
| # pylint: disable=unused-import, unused-variable, missing-docstring
def _readline():
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], 'p... |
import os
import string
import importlib
import traceback
from .. import irc
def execute(**kwargs):
module_string = string.join([__name__, kwargs['command']], '.')
module = None
try:
module = importlib.import_module(module_string)
except ImportError as e:
traceback.print_exc()
... | Add support for hyphens, and list of commands
Adds a function to retrieve all commands, and converts incoming commands
from hyphenated to underscored form.
| import os
import fnmatch
import string
import importlib
import traceback
from .. import irc
def get_all():
files = os.listdir('./nickenbot/command')
files.remove('__init__.py')
commands = [os.path.splitext(f)[0] for f in files if fnmatch.fnmatch(f, '*.py')]
commands = [string.replace(c, '_', '-') for c... |
import javabridge as jv
import bioformats as bf
def start(max_heap_size='8G'):
"""Start the Java Virtual Machine, enabling bioformats IO.
Parameters
----------
max_heap_size : string, optional
The maximum memory usage by the virtual machine. Valid strings
include '256M', '64k', and '2G... | Add function to determine metadata length
| import numpy as np
import javabridge as jv
import bioformats as bf
def start(max_heap_size='8G'):
"""Start the Java Virtual Machine, enabling bioformats IO.
Parameters
----------
max_heap_size : string, optional
The maximum memory usage by the virtual machine. Valid strings
include '25... |
# -#- coding: utf-8 -#-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import Widget
LOGIN_TYPE_CHOICES = (
(1, _("Admin")),
(2, _("Public")),
)
class UserLoginWidget(Widget):
type = models.PositiveIntegerField(verbose_name=_(
... | Fix missing next in context.
| # -#- coding: utf-8 -#-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import Widget
LOGIN_TYPE_CHOICES = (
(1, _("Admin")),
(2, _("Public")),
)
class UserLoginWidget(Widget):
type = models.PositiveIntegerField(verbose_name=_(
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Logging
class LoggingAdmin(admin.ModelAdmin):
model = Logging
raw_id_fields = ('user',)
exclude = ('site_iid', 'site_domain')
admin.site.register(Logging, LoggingAdmin)
| Add field mirror_site at exclude on LoggingAdmin
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Logging
class LoggingAdmin(admin.ModelAdmin):
model = Logging
raw_id_fields = ('user',)
exclude = ('site_iid', 'site_domain', 'mirror_site')
admin.site.register(Logging, LoggingAdmin)
|
#! /usr/bin/env python
import sys
import json
for filepath in sys.argv[1:]:
with open(filepath) as f:
try:
oyster = json.load(f)
except ValueError:
sys.stderr.write("In file: {}\n".format(filepath))
raise
with open(filepath, 'w') as f:
json.dump(oyst... | Make this work for non-ASCII chars as well.
| #! /usr/bin/env python3
import sys
import json
for filepath in sys.argv[1:]:
with open(filepath) as f:
try:
oyster = json.load(f)
except ValueError:
sys.stderr.write("In file: {}\n".format(filepath))
raise
with open(filepath, 'w') as f:
json.dump(oys... |
"""set suppliers active flag NOT NULLABLE
Ensure that all suppliers are either active or inactive.
Revision ID: 1340
Revises: 1330
Create Date: 2019-06-26 11:53:56.085586
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1340'
down_revision = '1330'
def upgr... | Fix comparison with NULL bug
| """set suppliers active flag NOT NULLABLE
Ensure that all suppliers are either active or inactive.
Revision ID: 1340
Revises: 1330
Create Date: 2019-06-26 11:53:56.085586
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1340'
down_revision = '1330'
def upgr... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | Test public body showing, json view and csv export | from django.test import TestCase
from django.core.urlresolvers import reverse
from publicbody.models import PublicBody
class PublicBodyTest(TestCase):
fixtures = ['auth.json', 'publicbodies.json', 'foirequest.json']
def test_web_page(self):
response = self.client.get(reverse('publicbody-list'))
... |
import argparse
import json
import sys
import gcl
from gcl import query
from gcl import util
def main(argv=None, stdin=None):
parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.')
parser.add_argument('file', metavar='FILE', type=str, nargs='?',
help='F... | Add proper root selector to gcl2json
| import argparse
import json
import sys
import gcl
from gcl import query
from gcl import util
def select(dct, path):
for part in path:
if not hasattr(dct, 'keys'):
raise RuntimeError('Value %r cannot be indexed with %r' % (dct, part))
if part not in dct:
raise RuntimeError('Value %r has no key %... |
import os
import shutil
import pytest
from LiSE.engine import Engine
from LiSE.examples.kobold import inittest
def test_keyframe_load_init(tempdir):
"""Can load a keyframe at start of branch, including locations"""
eng = Engine(tempdir)
inittest(eng)
eng.branch = 'new'
eng.snap_keyframe()
e... | Make test_multi_keyframe demonstrate what it's supposed to
I was testing a cache that wasn't behaving correctly for
unrelated reasons.
| import os
import shutil
import pytest
from LiSE.engine import Engine
from LiSE.examples.kobold import inittest
def test_keyframe_load_init(tempdir):
"""Can load a keyframe at start of branch, including locations"""
eng = Engine(tempdir)
inittest(eng)
eng.branch = 'new'
eng.snap_keyframe()
e... |
from troposphere import Join, iam, logs
from .common import arn_prefix
from .template import template
container_log_group = logs.LogGroup(
"ContainerLogs",
template=template,
RetentionInDays=365,
DeletionPolicy="Retain",
)
logging_policy = iam.Policy(
PolicyName="LoggingPolicy",
PolicyDocume... | Add logging permissions needed by aws-for-fluent-bit | from troposphere import Join, iam, logs
from .common import arn_prefix
from .template import template
container_log_group = logs.LogGroup(
"ContainerLogs",
template=template,
RetentionInDays=365,
DeletionPolicy="Retain",
)
logging_policy = iam.Policy(
PolicyName="LoggingPolicy",
PolicyDocume... |
from pluginbase import PluginBase
class PluginManager:
def __init__(self, paths, provider):
self.paths = [paths]
self.provider = provider
plugin_base = PluginBase(package='foremast.plugins')
self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths)
def plugin... | chore: Add docstring to plugin manager
| """Manager to handle plugins"""
from pluginbase import PluginBase
class PluginManager:
"""Class to manage and create Spinnaker applications
Args:
paths (str): Path of plugin directory.
provider (str): The name of the cloud provider.
"""
def __init__(self, paths, provider):
se... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 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.
import factory
from factory.faker import Faker
from pycroft.model.user import User, Roo... | Allow adjusting of RoomHistoryEntry attributes in UserFactory
| # -*- coding: utf-8 -*-
# Copyright (c) 2016 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.
import factory
from factory.faker import Faker
from pycroft.model.user import User, Roo... |
from sentinels import NOTHING
class ErrorContainer(object):
def add_error(self, exception, exception_type, traceback, timestamp=NOTHING):
return self.client.api.call_function('add_error', {self._get_id_key(): self.id,
'exception': exception,
... | Unify errors and failures in API
| from sentinels import NOTHING
class ErrorContainer(object):
def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING):
return self.client.api.call_function('add_error', {self._get_id_key(): self.id,
'message': mes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abstract import Abstract
from json import Json
from msgpack import MsgPack
__all__ = ['Abstract', 'Json', 'MsgPack']
| Load resources by absolute path not relative
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygrapes.serializer.abstract import Abstract
from pygrapes.serializer.json import Json
from pygrapes.serializer.msgpack import MsgPack
__all__ = ['Abstract', 'Json', 'MsgPack']
|
from channels.generic.websockets import WebsocketConsumer, JsonWebsocketConsumer
from .jsonrpcwebsocketconsumer import JsonRpcWebsocketConsumer
class MyJsonRpcWebsocketConsumer(JsonRpcWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
de... | Print statements updated to be compatible with Python 3.
| from channels.generic.websockets import WebsocketConsumer, JsonWebsocketConsumer
from .jsonrpcwebsocketconsumer import JsonRpcWebsocketConsumer
class MyJsonRpcWebsocketConsumer(JsonRpcWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
de... |
import TPunitA
import TPunitB
def __lldb_init_module(debugger,*args):
debugger.HandleCommand("command script add -f thepackage.TPunitA.command TPcommandA")
debugger.HandleCommand("command script add -f thepackage.TPunitB.command TPcommandB")
| Fix TestImport.py to work with Python 3.5.
Differential Revision: http://reviews.llvm.org/D16431
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@258448 91177308-0d34-0410-b5e6-96231b3b80d8
| from __future__ import absolute_import
from . import TPunitA
from . import TPunitB
def __lldb_init_module(debugger,*args):
debugger.HandleCommand("command script add -f thepackage.TPunitA.command TPcommandA")
debugger.HandleCommand("command script add -f thepackage.TPunitB.command TPcommandB")
|
from fabric.api import env, run, sudo, settings, hide
# Default system user
env.user = 'ubuntu'
# Default puppet environment
env.environment = 'prod'
# Default puppet module directory
env.puppet_module_dir = 'modules/'
# Default puppet version
# If loom_puppet_version is None, loom installs the latest version
env.l... | Revert "sudo is required to run which <gem-exec> on arch."
This reverts commit 15162c58c27bc84f1c7fc0326f782bd693ca4d7e.
| from fabric.api import env, run, settings, hide
# Default system user
env.user = 'ubuntu'
# Default puppet environment
env.environment = 'prod'
# Default puppet module directory
env.puppet_module_dir = 'modules/'
# Default puppet version
# If loom_puppet_version is None, loom installs the latest version
env.loom_pu... |
import uuid
class BaseTransport(object):
"""Base transport class."""
REQUEST_ID_KEY = 'requestId'
REQUEST_ACTION_KEY = 'action'
def __init__(self, data_format_class, data_format_options, handler_class,
handler_options, name):
self._data_format = data_format_class(**data_form... | Rename is_connected method to connected
| import uuid
class BaseTransport(object):
"""Base transport class."""
REQUEST_ID_KEY = 'requestId'
REQUEST_ACTION_KEY = 'action'
def __init__(self, data_format_class, data_format_options, handler_class,
handler_options, name):
self._data_format = data_format_class(**data_form... |
import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_delete=models.CASCADE
)
raw_da... | Use None rather than -1 for Pandas
| import json
from django.db import models
from model_utils.models import TimeStampedModel
class ParsedSOPN(TimeStampedModel):
"""
A model for storing the parsed data out of a PDF
"""
sopn = models.OneToOneField(
"official_documents.OfficialDocument", on_delete=models.CASCADE
)
raw_da... |
"""Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... | Refactor main as a separate function
| """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... |
#!/usr/bin/env python
import search
import tmap
if __name__ == "__main__":
from pprint import pprint as pp
import sys
to_dict = lambda r: r.to_dict()
h = search.HuluSearch()
a = search.AmazonSearch()
n = search.NetflixSearch()
# get the query from the first argument or from user input
... | Change CL to require a non-blank query
| #!/usr/bin/env python
import search
import tmap
if __name__ == "__main__":
from pprint import pprint as pp
import sys
to_dict = lambda r: r.to_dict()
h = search.HuluSearch()
a = search.AmazonSearch()
n = search.NetflixSearch()
# get the query from the first argument or from user input
... |
from eth_utils import (
is_address,
is_checksum_address,
is_checksum_formatted_address,
is_dict,
is_list_like,
)
def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
for e in abi:
... | Raise error specific to address checksum failure
Because is_address() also checks for a valid checksum, the old code showed a generic "not an address" error if the checksum failed. | from eth_utils import (
is_address,
is_checksum_address,
is_checksum_formatted_address,
is_dict,
is_list_like,
)
def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
for e in abi:
... |
from firecares.settings.base import * # noqa
INSTALLED_APPS += ('debug_toolbar', 'fixture_magic', 'django_extensions') # noqa
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) # noqa
# The Django Debug Toolbar will only be shown to these client IPs.
INTERNAL_IPS = (
'127.0.0.1',
)
D... | Set registration open by default
| from firecares.settings.base import * # noqa
INSTALLED_APPS += ('debug_toolbar', 'fixture_magic', 'django_extensions') # noqa
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) # noqa
# The Django Debug Toolbar will only be shown to these client IPs.
INTERNAL_IPS = (
'127.0.0.1',
)
D... |
def execute():
import webnotes
gd = webnotes.model.code.get_obj('Global Defaults')
gd.doc.maintain_same_rate = 1
gd.doc.save()
gd.on_update()
| Maintain same rate throughout pur cycle: in global defaults, by default set true
| def execute():
import webnotes
from webnotes.model.code import get_obj
gd = get_obj('Global Defaults')
gd.doc.maintain_same_rate = 1
gd.doc.save()
gd.on_update()
|
# This app doesn't contain any models, but as its template tags need to
# be added to built-ins at start-up time, this is a good place to do it.
from django.template.loader import add_to_builtins
add_to_builtins("overextends.templatetags.overextends_tags")
| Fix import path of add_to_builtins |
# This app doesn't contain any models, but as its template tags need to
# be added to built-ins at start-up time, this is a good place to do it.
from django.template.base import add_to_builtins
add_to_builtins("overextends.templatetags.overextends_tags")
|
# -*- coding: utf-8 -*-
import logging
from flask import g
from celery import group
from website import settings
logger = logging.getLogger(__name__)
def celery_before_request():
g._celery_tasks = []
def celery_teardown_request(error=None):
if error is not None:
return
try:
tasks = ... | Handle queued tasks when working outside request context.
| # -*- coding: utf-8 -*-
import logging
from flask import g
from celery import group
from website import settings
logger = logging.getLogger(__name__)
def celery_before_request():
g._celery_tasks = []
def celery_teardown_request(error=None):
if error is not None:
return
try:
tasks = ... |
# Copyright (c) 2015 "Hugo Herter http://hugoherter.com"
#
# This file is part of Billabong.
#
# Intercom 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
# License, or (at your o... | Add test for cli 'add' command
| # Copyright (c) 2015 "Hugo Herter http://hugoherter.com"
#
# This file is part of Billabong.
#
# Intercom 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
# License, or (at your o... |
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.Docum... | Allow any logged-in user to perform image searches.
| from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.Docum... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import re
from django import template
from django.conf import settings
register = template.Library()
_remove_slash_re = re.compile(r'/+')
def _urljoin(*args):
"""Joins relative... | Add warning message to tricky template tag
| # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import re
from django import template
from django.conf import settings
register = template.Library()
_remove_slash_re = re.compile(r'/+')
def _urljoin(*args):
"""Joins relative... |
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
fai... | Tests: Make it possible to run individual tests.
| #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
tests = "tests" if len(sys.argv) == 1 else sys.argv[1]
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = ... |
"""
Command function to schema-validate a HXL dataset.
David Megginson
November 2014
Can use a whitelist of HXL tags, a blacklist, or both.
Usage:
import sys
from hxl.scripts.hxlvalidate import hxlvalidate
hxlvalidate(sys.stdin, sys.stdout, open('MySchema.csv', 'r'))
License: Public Domain
Documentation: htt... | Return result of validation from the command script.
| """
Command function to schema-validate a HXL dataset.
David Megginson
November 2014
Can use a whitelist of HXL tags, a blacklist, or both.
Usage:
import sys
from hxl.scripts.hxlvalidate import hxlvalidate
hxlvalidate(sys.stdin, sys.stdout, open('MySchema.csv', 'r'))
License: Public Domain
Documentation: htt... |
# -*- coding: utf-8 -*-
# © 2015 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Set Snippet's Anchor",
"summary": "Allow to reach a concrete section in the page",
"version": "8.0.1.0.0",
"category": "Website",
"website": "http://... | Remove unused keys from manifest.
| # -*- coding: utf-8 -*-
# © 2015 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Set Snippet's Anchor",
"summary": "Allow to reach a concrete section in the page",
"version": "8.0.1.0.0",
"category": "Website",
"website": "http://... |
#!/usr/bin/env python
import os
from apiclient.discovery import build
from apiclient import errors
PROJECT_NAME = os.getenv('PROJECT_NAME')
TASK_QUEUE_NAME = os.getenv('QUEUE_NAME')
TASK_LEASE_SECONDS = os.getenv('TASK_LEASE_SECONDS', 300)
TASK_BATCH_SIZE = os.getenv('TASK_BATCH_SIZE', 10)
assert PROJECT_NAME
assert ... | Fix up logging and env vars.
| #!/usr/bin/env python
import os
import logging
from apiclient.discovery import build
from apiclient import errors
PROJECT_NAME = os.getenv('PROJECT_NAME')
TASKQUEUE_NAME = os.getenv('TASKQUEUE_NAME', 'builds')
TASKQUEUE_LEASE_SECONDS = os.getenv('TASKQUEUE_LEASE_SECONDS', 300)
TASKQUEUE_BATCH_SIZE = os.getenv('TASKQU... |
import json
import base64
import urllib
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
class OXSessionDecryptor(object):
def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000):
self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations)
... | Add unpad function for unpacking cookie
| import json
import base64
import urllib
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
class OXSessionDecryptor(object):
def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000):
self.secret = PBKDF2(secret_ke... |
#!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
def pprint_expr_trees(trees):
from parser import ExprParser
print('[')
for t in trees:
print(' ', ExprParser(t))
print(']')
| Update pprint_expr_trees to adopt Expr
| #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
def pprint_expr_trees(trees):
print('[')
for t in trees:
print(' ', t)
print(']')
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for PSpec
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import PowerSpectrum, PSpec_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
cla... | Add test to ensure power spectrum slope is same w/ transposed array
| # Licensed under an MIT open source license - see LICENSE
'''
Test functions for PSpec
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import PowerSpectrum, PSpec_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
cla... |
"""
Map puzzle URLs to views. Also maps the root URL to the latest puzzle.
"""
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from puzzle import views
from puzzle.feeds import PuzzleFeed
urlpatterns = [ #pylint: disable=invalid-name
url(r'^$', views.latest, name='lat... | Replace deprecated login/logout function-based views
| """
Map puzzle URLs to views. Also maps the root URL to the latest puzzle.
"""
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from puzzle import views
from puzzle.feeds import PuzzleFeed
urlpatterns = [ #pylint: disable=invalid-name
url(r'^$', views.latest, name='lat... |
"""
Module that provides a connection to the ModuleStore specified in the django settings.
Passes settings.MODULESTORE as kwargs to MongoModuleStore
"""
from __future__ import absolute_import
from importlib import import_module
from django.conf import settings
_MODULESTORES = {}
FUNCTION_KEYS = ['render_template'... | Put quick check so we don't load course modules on init unless we're actually running in Django
| """
Module that provides a connection to the ModuleStore specified in the django settings.
Passes settings.MODULESTORE as kwargs to MongoModuleStore
"""
from __future__ import absolute_import
from importlib import import_module
from os import environ
from django.conf import settings
_MODULESTORES = {}
FUNCTION_KEY... |
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()
| 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
import lotusConnectionsCommonAdmin
globdict = globals()
def loadFilesService():
global globdict
exec open("filesAdmin.py").read()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://softwarejourneyman.com'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/{slug}.atom.xml'
DELETE_... | Add samroeca.com to url pointing
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://samroeca.com'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/{slug}.atom.xml'
DELETE_OUTPUT_DIR... |
'''
Salt module to manage monit
'''
def version():
'''
List monit version
Cli Example::
salt '*' monit.version
'''
cmd = 'monit -V'
res = __salt__['cmd.run'](cmd)
return res.split("\n")[0]
def status():
'''
Monit status
CLI Example::
salt '*' monit.status
... | Check to see if we are going donw the right path
| '''
Monit service module. This module will create a monit type
service watcher.
'''
import os
def start(name):
'''
CLI Example::
salt '*' monit.start <service name>
'''
cmd = "monit start {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
def stop(name):
'''
Stops servic... |
from django.db import models
class Playbook(models.Model):
class Meta:
verbose_name_plural = "playbooks"
name = models.CharField(max_length=200)
path = models.CharField(max_length=200, default="~/")
ansible_config = models.CharField(max_length=200, default="~/")
inventory = models.CharFie... | Fix string output of Playbook
| from django.db import models
class Playbook(models.Model):
class Meta:
verbose_name_plural = "playbooks"
name = models.CharField(max_length=200)
path = models.CharField(max_length=200, default="~/")
ansible_config = models.CharField(max_length=200, default="~/")
inventory = models.CharFie... |
# The version number must follow these rules:
# - When the server is released, a client with exactly the same version number
# should be released.
# - Bugfixes should be released as consecutive post-releases,
# that is versions of the form X.Y.Z.postN, where X.Y.Z is
# the AG version number and N increa... | Set __version__ to 6.1.4 in preparation for the v6.1.4 release
That is all.
Change-Id: I79edd9574995e50c17c346075bf158e6f1d64a0c
Reviewed-on: https://gerrit.franz.com:9080/6845
Reviewed-by: Tadeusz Sznuk <4402abb98f9559cbfb6d73029f928227b498069b@franz.com>
Reviewed-by: Ahmon Dancy <8f7d8ce2c6797410ae95fecd4c30801ee9f... | # The version number must follow these rules:
# - When the server is released, a client with exactly the same version number
# should be released.
# - Bugfixes should be released as consecutive post-releases,
# that is versions of the form X.Y.Z.postN, where X.Y.Z is
# the AG version number and N increa... |
import eventlet
eventlet.monkey_patch() # NOLINT
import importlib
import sys
from weaveserver.main import create_app
from weaveserver.core.logger import configure_logging
def handle_launch():
import signal
from weaveserver.core.config_loader import get_config
configure_logging()
token = sys.stdin.... | Support 2nd parameter for weave-launch so that a plugin from any directory can be loaded.
| import eventlet
eventlet.monkey_patch() # NOLINT
import importlib
import os
import sys
from weaveserver.main import create_app
from weaveserver.core.logger import configure_logging
def handle_launch():
import signal
from weaveserver.core.config_loader import get_config
configure_logging()
token = ... |
"""
The following exceptions may be raised during the course of using
:py:class:`tornado_aws.client.AWSClient` and
:py:class:`tornado_aws.client.AsyncAWSClient`:
"""
class AWSClientException(Exception):
"""Base exception class for AWSClient
:ivar msg: The error message
"""
fmt = 'An error occurred'... | Add a new generic AWS Error exception
| """
The following exceptions may be raised during the course of using
:py:class:`tornado_aws.client.AWSClient` and
:py:class:`tornado_aws.client.AsyncAWSClient`:
"""
class AWSClientException(Exception):
"""Base exception class for AWSClient
:ivar msg: The error message
"""
fmt = 'An error occurred'... |
import pytest
from kafka import KafkaConsumer, KafkaProducer
from test.conftest import version
from test.testutil import random_string
@pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
def test_end_to_end(kafka_broker):
connect_str = 'localhost:' + str(kafka_broker.port)
producer = KafkaProdu... | Disable auto-commit / group assignment in producer test
| import pytest
from kafka import KafkaConsumer, KafkaProducer
from test.conftest import version
from test.testutil import random_string
@pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
def test_end_to_end(kafka_broker):
connect_str = 'localhost:' + str(kafka_broker.port)
producer = KafkaProdu... |
import os
import sys
# Modify the sys.path to allow tests to be run without
# installing the module.
test_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, test_path + '/../')
import pypm
import pytest
def test_patch_replaces_and_restores():
i = __import__
pypm.patch_import()
asser... | Change import path in tests to reflect new name
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
| import os
import sys
# Modify the sys.path to allow tests to be run without
# installing the module.
test_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, test_path + '/../')
import require
import pytest
def test_patch_replaces_and_restores():
i = __import__
require.patch_import()
... |
#!/usr/bin/env python
# Copyright 2012 Citrix Systems, Inc. Licensed under the
# Apache License, Version 2.0 (the "License"); you may not use this
# file except in compliance with the License. Citrix Systems, Inc.
from distutils.core import setup
from sys import version
if version < "2.7":
print "Marvin needs at ... | Install paramiko as a dependency, don't complain about the requirement
| #!/usr/bin/env python
# Copyright 2012 Citrix Systems, Inc. Licensed under the
# Apache License, Version 2.0 (the "License"); you may not use this
# file except in compliance with the License. Citrix Systems, Inc.
from distutils.core import setup
from sys import version
if version < "2.7":
print "Marvin needs at ... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2019 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
# @author: Théo Nikles <theo.nikles@gmail.com>
#
# The licence is in the file __manifest__.py
#... | FIX language of privacy statement
| # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2019 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
# @author: Théo Nikles <theo.nikles@gmail.com>
#
# The licence is in the file __manifest__.py
#... |
#!/usr/bin/env python2
from setuptools import setup
setup(
name='bouncer-plumbing',
description='Glue scripts to integrate oonib with mlab-ns (simulator).',
version='0.1.dev0',
author='LeastAuthority',
author_email='consultancy@leastauthority.com',
license='FIXME',
url='https://github.co... | Add ``update_bouncer.sh`` as a data file to the python package for bouncer_plumbing.
| #!/usr/bin/env python2
from setuptools import setup
setup(
name='bouncer-plumbing',
description='Glue scripts to integrate oonib with mlab-ns (simulator).',
version='0.1.dev0',
author='LeastAuthority',
author_email='consultancy@leastauthority.com',
license='FIXME',
url='https://github.co... |
# -*- coding: UTF-8 -*-
from boilerpipe.extract import Extractor
URL='http://sportv.globo.com/site/eventos/mundial-de-motovelocidade/noticia/2016/06/em-duelo-eletrizante-rossi-vence-marquez-salom-e-homenageado.html'
extractor = Extractor(extractor='ArticleExtractor', url=URL)
print extractor.getText().encode('utf-8... | Add one more url to example 1
| # -*- coding: UTF-8 -*-
from boilerpipe.extract import Extractor
URL='http://sportv.globo.com/site/eventos/mundial-de-motovelocidade/noticia/2016/06/em-duelo-eletrizante-rossi-vence-marquez-salom-e-homenageado.html'
# URL='http://grandepremio.uol.com.br/motogp/noticias/rossi-supera-largada-ruim-vence-duelo-com-marque... |
from __future__ import unicode_literals
from mopidy import models
import spotify
def to_track(sp_track):
if not sp_track.is_loaded:
return
if sp_track.error != spotify.ErrorType.OK:
return
if sp_track.availability != spotify.TrackAvailability.AVAILABLE:
return
# TODO artis... | Add TODOs on how to expose non-playable tracks
| from __future__ import unicode_literals
from mopidy import models
import spotify
def to_track(sp_track):
if not sp_track.is_loaded:
return # TODO Return placeholder "[loading]" track?
if sp_track.error != spotify.ErrorType.OK:
return # TODO Return placeholder "[error]" track?
if sp_t... |
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
| Make no-api-key test more reliable
| import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
original_api_key = delighted.api_key
try:
delighted.api_key = None
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.C... |
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except... | Fix the expected argument check in scoring tests
| #!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except... |
import importlib
import pkgutil
import sys
from collections import OrderedDict
from inselect.lib.metadata import MetadataTemplate
from inselect.lib.utils import debug_print
_library = None
def library():
"""Returns a list of MetadataTemplate instances
"""
global _library
if not _library:
_l... | Fix metadata template import on OS X
| import importlib
import pkgutil
import sys
from collections import OrderedDict
from inselect.lib.metadata import MetadataTemplate
from inselect.lib.utils import debug_print
from inselect.lib.templates import dwc, price
if True:
_library = {}
for template in [p.template for p in (dwc, price)]:
_libr... |
from setuptools import setup, find_packages
setup(
name='lightstep',
version='2.2.0',
description='LightStep Python OpenTracing Implementation',
long_description='',
author='LightStep',
license='',
install_requires=['thrift==0.9.2',
'jsonpickle',
... | Remove explicit OT dep; we get it via basictracer
| from setuptools import setup, find_packages
setup(
name='lightstep',
version='2.2.0',
description='LightStep Python OpenTracing Implementation',
long_description='',
author='LightStep',
license='',
install_requires=['thrift==0.9.2',
'jsonpickle',
... |
from codecs import open as codecs_open
from setuptools import setup, find_packages
# Get the long description from the relevant file
with codecs_open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(name='borica',
version='0.0.1',
description=u"Python integration for Borica",
... | Fix issue - load README.md, not .rst
| from codecs import open as codecs_open
from setuptools import setup, find_packages
# Get the long description from the relevant file
with codecs_open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(name='borica',
version='0.0.1',
description=u"Python integration for Borica",
... |
#!/usr/bin/env python
from setuptools import setup
setup(
name="htmlgen",
version="1.1.0",
description="HTML 5 Generator",
long_description=open("README.rst").read(),
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/python-htmlgen",
package... | Mark as supporting Python 3.7
| #!/usr/bin/env python
from setuptools import setup
setup(
name="htmlgen",
version="1.1.0",
description="HTML 5 Generator",
long_description=open("README.rst").read(),
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/python-htmlgen",
package... |
'''setup script for this module'''
from setuptools import setup
def readme():
'''pull iin the readme file for the long description'''
with open('README.md') as rfile:
return rfile.read()
setup(
name='chamberconnectlibrary',
version='2.1.2',
description='A library for interfacing with Espe... | Correct pypi package; file naming was wrong.
| '''setup script for this module'''
from setuptools import setup
def readme():
'''pull iin the readme file for the long description'''
with open('README.md') as rfile:
return rfile.read()
setup(
name='chamberconnectlibrary',
version='2.1.3',
description='A library for interfacing with Espe... |
from threading import Thread, Lock
import logging
import webview
from time import sleep
from server import run_server
server_lock = Lock()
logger = logging.getLogger(__name__)
def url_ok(url, port):
# Use httplib on Python 2
try:
from http.client import HTTPConnection
except ImportError:
... | Fix Flask example to allow freezing
| import logging
import webview
from contextlib import redirect_stdout
from io import StringIO
from threading import Thread, Lock
from time import sleep
from server import run_server
server_lock = Lock()
logger = logging.getLogger(__name__)
def url_ok(url, port):
# Use httplib on Python 2
try:
from h... |
"""Implements the Runner interface fo LDA
"""
from microscopes.common import validator
from microscopes.common.rng import rng
from microscopes.lda.kernels import lda_crp_gibbs
from microscopes.lda.kernels import lda_sample_dispersion
class runner(object):
"""The LDA runner
Parameters
----------
defn... | Use C++ implementations of hp sampling
| """Implements the Runner interface fo LDA
"""
from microscopes.common import validator
from microscopes.common.rng import rng
from microscopes.lda.kernels import lda_crp_gibbs
from microscopes.lda.kernels import sample_gamma, sample_alpha
class runner(object):
"""The LDA runner
Parameters
----------
... |
#!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentia... | Use key fixture in boto tests.
| #!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentia... |
from kivy.animation import Animation
class RelativeAnimation(Animation):
"""Class that extends the Kivy Animation base class to add relative animation
property target values that are calculated when the animation starts."""
def _initialize(self, widget):
"""Initializes the animation and calculat... | Fix relative animation of list values
| from kivy.animation import Animation
class RelativeAnimation(Animation):
"""Class that extends the Kivy Animation base class to add relative animation
property target values that are calculated when the animation starts."""
def _initialize(self, widget):
"""Initializes the animation and calculat... |
# coding: utf-8
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
unset_app(db)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_UR... | Fix bug that used dev db instead of test db
| # coding: utf-8
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
# set test vars
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
# set test db
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = co... |
#!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, ... | Update validation check for paper bundles.
| #!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.