Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :) |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
... |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
... |
Fix the python-windows installer generator by making it include the .dll files in the installer. That list originally consisted only of "*.dll". When the build system was modified to generate .pyd files for the binary modules, it was changed to "*.pyd". The Subversion libraries and the dependencies are still .dll files... | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://sub... | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://sub... |
Allow blank entries for title and description for flatpages | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = mod... | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('con... |
Add pandas as requirement for the project | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language... | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language... |
Comment out python3 classifier for now. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_descriptio... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_descriptio... |
Fix paths to json files | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open... | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open... |
Add missing import statement for igor translator | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . imp... | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . ... |
Test DatadogMetricsBackend against datadog's get_hostname | from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('... | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(pr... |
Remove logic for iterating directories to search for config file | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topd... | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
... |
Add fits file to package build | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import
import os
# setup paths to the test data
# can specify a single file or a list of files
def get_package_data():
paths = [os.path.join('data', '*.vot'),
os.path.join('data', '*.xml'),
o... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import
import os
# setup paths to the test data
# can specify a single file or a list of files
def get_package_data():
paths = [os.path.join('data', '*.vot'),
os.path.join('data', '*.xml'),
o... |
Add docstring to program drive provider | import os
from functools import lru_cache
from .. import logger
# use absolute path because of re-occuraing imports '.' could not work
from .program_path_provider import get_cached_program_path
@lru_cache(maxsize=None)
def get_cached_program_drive():
"""Get the value of the #PROGRAMDRIVE# variable"""
rainme... | """
This module provides methods for determine the program drive.
Rainmeter has an built-in variable called #PROGRAMDRIVE#.
With this you can directly route to the drive in which Rainmeter is contained.
If by some chance people use @Include on #PROGRAMDRIVE# it is still able to resolve
the path and open the include fo... |
Fix the misspell in docstring | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... |
Add support for multiple datasets | import sys
import click
import json
import csv
from rdflib import Graph, Namespace, URIRef
def observe_dataset(dataset, query, prefixes):
g = Graph()
if prefixes:
prefixes = json.load(prefixes)
for name, url in prefixes.items():
g.bind(name, Namespace(url.strip('<>')))
g.parse(... | import sys
import click
import json
import csv
from rdflib import Graph, Namespace, URIRef
def observe_dataset(datasets, query, prefixes):
g = Graph()
if prefixes:
prefixes = json.load(prefixes)
for name, url in prefixes.items():
g.bind(name, Namespace(url.strip('<>')))
for dat... |
Fix exception handling in HTTPNotifier | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If ... | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If ... |
Add Element admin view in admin url | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import AdminHandler, CubeHandler, ConnectionHandler
INCLUDE_URLS = [
(r"/admin", AdminHandler),
(r"/admin/connection", ConnectionHandler),
(r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler),
]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import AdminHandler, CubeHandler, ConnectionHandler
from .views import ElementHandler
INCLUDE_URLS = [
(r"/admin", AdminHandler),
(r"/admin/connection", ConnectionHandler),
(r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler),
(r"/admin/element/?(?... |
Add documentation and touch up formatting of attr_string util method | """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
| """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
"""Build a string consisting of 'key=value' substrings for each keyword
argument in :kwargs:
@param filterKeys: list of key names to ignore
@param filterValues: list of values t... |
Add datetime field to Event model in sensor.core | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... |
Make discrete functions for each force field | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... |
Fix an incorrect postcode for Reading | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... |
Add catch for undefined opcodes | import MOS6502
import instructions
def disasm(memory, maxLines=0, address=-1):
index = 0
lines = []
while index < len(memory):
currInst = instructions.instructions[memory[index]]
if address > 0:
line = format(address+index, '04x') + ": "
else:
line ... | import MOS6502
import instructions
import code
def disasm(memory, maxLines=0, address=-1):
index = 0
lines = []
while index < len(memory):
opcode = memory[index]
if opcode not in instructions.instructions.keys():
print "Undefined opcode: " + hex(opcode)
code.interac... |
Add some documentation for weird init | from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['guid'].required = True
| from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
def __init__(self, *args, **kwargs):
'''
Add required marker, so OpenAPI schema generator can remove it again
... |
Add method to get initialize url. | from kolibri.plugins.app.kolibri_plugin import App
from kolibri.plugins.registry import registered_plugins
SHARE_FILE = "share_file"
CAPABILITES = (SHARE_FILE,)
class AppInterface(object):
__slot__ = "_capabilities"
def __init__(self):
self._capabilities = {}
def __contains__(self, capability... | from django.core.urlresolvers import reverse
from kolibri.plugins.app.kolibri_plugin import App
from kolibri.plugins.registry import registered_plugins
SHARE_FILE = "share_file"
CAPABILITES = (SHARE_FILE,)
class AppInterface(object):
__slot__ = "_capabilities"
def __init__(self):
self._capabiliti... |
Remove redundant empty line at end of file | """Power Digit Sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
assert sum(int(x) for x in str(2 ** 1000)) == 1366
| """Power Digit Sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
assert sum(int(x) for x in str(2 ** 1000)) == 1366
|
Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "mib"
__date__ = "$2011-01-22 12:02:41$"
from abstract import Abstract
from local import Local
__all__ = ['Abstract', 'Local']
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "mib"
__date__ = "$2011-01-22 12:02:41$"
from pygrapes.util import not_implemented
from pygrapes.adapter.abstract import Abstract
from pygrapes.adapter.local import Local
try:
from pygrapes.adapter.zeromq import Zmq
except ImportError:
Zmq = not_imple... |
Add custom JSON serialize for Python datetime | from functools import partial
from pyws.errors import BadRequest
from pyws.functions.args.types.complex import List
from pyws.response import Response
from pyws.utils import json
from pyws.protocols.base import Protocol
__all__ = ('RestProtocol', 'JsonProtocol', )
create_response = partial(Response, content_type='a... | from functools import partial
from pyws.errors import BadRequest
from pyws.functions.args.types.complex import List
from pyws.response import Response
from pyws.utils import json
class encoder( json.JSONEncoder ):
# JSON Serializer with datetime support
def default(self,obj):
if isinstance(obj, dateti... |
Remove test db setup from postgres processor | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
# Need to force cassandra to ignore set keyspace
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresPr... | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
engine = create_engine('postgresql://lo... |
Update dsub version to 0.4.4.dev0 | # Copyright 2017 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 a... | # Copyright 2017 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 a... |
Change database url for create_engine() | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://avvcurseaphtxf:X0466JySVtLq6nyq_5pb7BQ... | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://fbcmeskynsvati:aURfAdENt6-kumO0j224GuX... |
Add outlines of functions and code for soundspeeds. | ''' pyflation.analysis.deltaprel - Module to calculate relative pressure
perturbations.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
| ''' pyflation.analysis.deltaprel - Module to calculate relative pressure
perturbations.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
def soundspeeds(Vphi, phidot, H):
"""Sound speeds of the background fields
Arguments
---------
... |
Return a list of lists | def generate_ngrams(text, n):
''' Generates all possible n-grams of a
piece of text
>>> text = 'this is a random piece'
>>> n = 2
>>> generate_ngrams(text, n)
this is
is a
a random
random piece
'''
text_array = text.split(' ')
for i in range(0, len(text_array) - n + 1):
... | def generate_ngrams(text, n):
''' Generates all possible n-grams of a
piece of text
>>> text = 'this is a random piece'
>>> n = 2
>>> generate_ngrams(text, n)
this is
is a
a random
random piece
'''
text_array = text.split(' ')
ngram_list = []
for i in range(0, len(te... |
Use new property format for WorldcatData | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from ..common import ReadOnlyDataStructure
class WorldcatData (ReadOnlyDataStructure):
@property
def title (self):
return s... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from ..common import ReadOnlyDataStructure
class WorldcatData (ReadOnlyDataStructure):
auto_properties = ("title",)
def __iter__ (... |
Add drf_yasg module for dev env | #
# Django Development
# ..........................
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#
# Developper additions
# ..........................
INSTALLED_APPS = (
'django_extensions',
'debug_toolbar',
) + INSTALLED_APPS
INTERNAL_IPS = type(str('c'), (), {'__contains_... | #
# Django Development
# ..........................
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#
# Developper additions
# ..........................
INSTALLED_APPS = (
'django_extensions',
'debug_toolbar',
'drf_yasg',
) + INSTALLED_APPS
INTERNAL_IPS = type(str('c'), (... |
Fix event source for S3 put events | import logging
import urllib
import sentry_sdk
from cloudpathlib import AnyPath
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
from .config import Config
from .main import get_all_unsubmitted_roots, process_file, setup_logging
config = Config()
setup_logging(config)
sentry_sdk.init(
dsn=con... | import logging
import urllib
import sentry_sdk
from cloudpathlib import AnyPath
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
from .config import Config
from .main import get_all_unsubmitted_roots, process_file, setup_logging
config = Config()
setup_logging(config)
sentry_sdk.init(
dsn=con... |
Add encoding to open file | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r") as file:
return json... | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r", encoding="utf8") as file:
... |
Exit if imported on Python 2 | from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
compatible_py2 = (2, 7) <= sys.version_info < (3,)
compatible_py3 = (3, 7) <= sys.version_info
if not (compatible_py2 or compatible_py3):
sys.exit(
'ERROR: Mopidy requires Python 2.7 or >=... | from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
if not sys.version_info >= (3, 7):
sys.exit(
'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open d... |
Add access token from auth not report | """ Connection class establishes HTTP connection with server.
Utilized to send Proto Report Requests.
"""
import threading
import requests
from lightstep.collector_pb2 import ReportResponse
class _HTTPConnection(object):
"""Instances of _Connection are used to establish a connection to the
server via HTT... | """ Connection class establishes HTTP connection with server.
Utilized to send Proto Report Requests.
"""
import threading
import requests
from lightstep.collector_pb2 import ReportResponse
class _HTTPConnection(object):
"""Instances of _Connection are used to establish a connection to the
server via HTT... |
Improve LQR example for integrator_chains domain | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self... | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
from control import lqr
import numpy as np
class StateFeedback(rospy.Subscriber):
def __init__(self, intopic, outtopic, K=None):
rospy.Sub... |
Fix Django 1.10 url patterns warning | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls), name='admin'),
)
| from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls), name='admin'),
]
|
Clear command registry BEFORE each test. | import unittest
from nymms import registry
from nymms.resources import Command, MonitoringGroup
from weakref import WeakValueDictionary
class TestRegistry(unittest.TestCase):
def tearDown(self):
# Ensure we have a fresh registry after every test
Command.registry.clear()
def test_empty_regist... | import unittest
from nymms import registry
from nymms.resources import Command, MonitoringGroup
from weakref import WeakValueDictionary
class TestRegistry(unittest.TestCase):
def setUp(self):
# Ensure we have a fresh registry before every test
Command.registry.clear()
def test_empty_registry... |
Throw a ValueError if we get a non-JID for the JID | import os
import json
import datetime
from pupa.core import db
from pupa.models import Organization
from pupa.models.utils import DatetimeValidator
from pupa.models.schemas.jurisdiction import schema as jurisdiction_schema
def import_jurisdiction(org_importer, jurisdiction):
obj = jurisdiction.get_db_object()
... | import os
import json
import datetime
from pupa.core import db
from pupa.models import Organization
from pupa.models.utils import DatetimeValidator
from pupa.models.schemas.jurisdiction import schema as jurisdiction_schema
def import_jurisdiction(org_importer, jurisdiction):
obj = jurisdiction.get_db_object()
... |
Fix the gc_content bug to get a clean Travis report. | #!/usr/bin/env python2
def reverse(seq):
return seq[::-1]
def complement(seq):
from string import maketrans
complements = maketrans('ACTGactg', 'TGACtgac')
return seq.translate(complements)
def reverse_complement(seq):
return reverse(complement(seq))
def gc_content(seq):
# This function cont... | #!/usr/bin/env python2
from __future__ import division
def reverse(seq):
"""Return the reverse of the given sequence (i.e. 3' to
5')."""
return seq[::-1]
def complement(seq):
"""Return the complement of the given sequence (i.e. G=>C,
A=>T, etc.)"""
from string import maketrans
complemen... |
Fix mapping for codon keys for Serine | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCC, UCC | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... |
Make context output behavior overridable | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.la... | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.lan... |
Make test dependencies more explicit | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license... |
Use the official notation of the Django package | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description =... | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description =... |
Change package version to 0.5.0 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is... | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is... |
Add splitlines method to substitute_keywords | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_te... | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_te... |
Update mini_installer test wrapper script. | #!/usr/bin/env python
# Copyright 2013 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.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import bu... | #!/usr/bin/env python
# Copyright 2013 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.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import bu... |
Implement an Optional Element function | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules impo... | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', N... |
Return None on missing object | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
b... | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
b... |
Migrate old passwords without "set_unusable_password" | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database does... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
... |
Fix http->https for the API | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debu... | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.deb... |
Fix for non-DRMAA cluster run |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globa... |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globa... |
Fix migration to work with flows with no base_language | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = ap... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = ap... |
Increase version number to 0.4.0 - fix | from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
| from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
|
Make compatible with Django 1.9 | from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
| from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
|
Set sleep times to zero for tests | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_nam... | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_nam... |
Update for api change with linter_configs. | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list... | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(la... |
Update to use new RSF `append-entry` format | import sys
from datetime import datetime
import json
import hashlib
def print_rsf(item, key_field):
key = item[key_field]
timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
item_str = json.dumps(item, separators=(',', ':'), sort_keys=True)
item_hash = hashlib.sha256(item_str.encode("utf-8"))... | import sys
from datetime import datetime
import json
import hashlib
def print_rsf(item, key_field):
key = item[key_field]
timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
item_str = json.dumps(item, separators=(',', ':'), sort_keys=True)
item_hash = hashlib.sha256(item_str.encode("utf-8"))... |
Check for the isatty property on sys.stdout. | # /psqtraviscontainer/printer.py
#
# Utility functions for printing unicode text.
#
# See /LICENCE.md for Copyright information
"""Utility functions for printing unicode text."""
import sys
def unicode_safe(text):
"""Print text to standard output, handle unicode."""
# Don't trust non-file like replacements o... | # /psqtraviscontainer/printer.py
#
# Utility functions for printing unicode text.
#
# See /LICENCE.md for Copyright information
"""Utility functions for printing unicode text."""
import sys
def unicode_safe(text):
"""Print text to standard output, handle unicode."""
# If a replacement of sys.stdout doesn't h... |
Remove extraneous logging and bad param | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... |
Allow setting email when creating a staff account. | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... |
Check if Google Maps is enabled when trying to get the client | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
import googlemaps
import datetime
class GoogleMapsSettings(Document... | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import googlemaps
import frappe
from frappe import _
from frappe.model.document import Document
class GoogleMapsSettings(Document):
def valid... |
Use PExpect to change the logging buffer size (logging buffered <size>) on pynet-rtr2. Verify this change by examining the output of 'show run'. | from getpass import getpass
import time
from netmiko import ConnectHandler
password = getpass()
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022}
ssh_connection = ConnectHandler(**pynet_rtr2)
time.sleep(2)
ssh_connection.config_mode()
output = ... | # Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode).
from getpass import getpass
import time
from netmiko import ConnectHandler
password = getpass()
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'usern... |
Fix detecting css output folder in different jasy versions | # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profil... | # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profil... |
Test json file with api key is in API service class | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... |
Fix import, use fileinput.iput as context, and fix its argument | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
from dstruct import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file_... | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
import sys
from dstruct.Sentence import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.p... |
Add a fab command to run jstests | """Fabric commands useful for working on developing Bookie are loaded here"""
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def ge... | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.p... |
Check for RMG_workingDirectory environment variable in qmtp_package | import os
if not os.environ.get("RMG_workingDirectory"):
import os.path
message = "Please set your RMG_workingDirectory environment variable.\n" +\
"(eg. export RMG_workingDirectory=%s )" % \
os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
raise Exception(message)
| |
Add 'notebook' as a dependency | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
... | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
... |
Allow to fake the currency rates. | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3... |
Return response instead of print on client side | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_so... | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_so... |
Fix st2actions tests so they pass under Python 3. | # 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... | # 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 new caps variable, fix line length | from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['b... | from zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # I... |
Make tests pass in Django 1.4. | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... |
Add support for per Argument help data | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at leas... | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must h... |
Fix templates path error (template -> templates) | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLA... | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLA... |
Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well. | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
fo... | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
fo... |
Increase request buffer as workaround for stackoverflow in asyncio | from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
#AsyncIO buffer problem
req.trans... | from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
#AsyncIO buffer problem
req.trans... |
Fix one more place where STAGING_HOSTNAME uses settings | import os
from django import template
from wagtail.wagtailcore.models import Page
from django.conf import settings
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
ret... | import os
from django import template
from wagtail.wagtailcore.models import Page
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
return False
@register.assignment_... |
Clear unnecessary code, add comments on sorting | #!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = '... | #!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = '... |
Update test to use standard scenario | from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from login.tests.model_maker import make_user
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
... | from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from crm.tests.scenario import (
contact_contractor,
)
from login.tests.scenario import (
get_fred,
get_sara,
user_contractor,
)
class TestContactUser(T... |
Fix unicode in citation (again) | """
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@ar... | """
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@ar... |
Add utility function for executable checking | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener = gzip.op... | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener... |
Check proper error when accessing source without instance | from djangosanetesting.cases import DatabaseTestCase
from djangomarkup.fields import RichTextField
from djangomarkup.models import SourceText
from exampleapp.models import Article
class TestRichTextField(DatabaseTestCase):
def setUp(self):
super(TestRichTextField, self).setUp()
self.field = Rich... | from djangosanetesting.cases import UnitTestCase
from djangomarkup.fields import RichTextField
from exampleapp.models import Article
class TestRichTextField(UnitTestCase):
def setUp(self):
super(TestRichTextField, self).setUp()
self.field = RichTextField(
instance = Article(),
... |
Remove SQLite database before running tests | # -*- Mode: Python -*-
import os
import glob
import sys
import shutil
import unittest
testLoader = unittest.TestLoader()
names = []
for filename in glob.iglob("test_*.py"):
names.append(filename[:-3])
names.sort()
testSuite = testLoader.loadTestsFromNames(names)
runner = unittest.TextTestRunner(verbosity=2)
resu... | # -*- Mode: Python -*-
import os
import glob
import sys
import shutil
import unittest
if os.path.isfile("./test_data/test_gir.db"):
os.remove("./test_data/test_gir.db")
testLoader = unittest.TestLoader()
names = []
for filename in glob.iglob("test_*.py"):
names.append(filename[:-3])
names.sort()
testSuite = t... |
Move from celery task to regular-old function | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from api.base import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: t... | import urlparse
import requests
from celery.utils.log import get_task_logger
from api.base import settings
logger = get_task_logger(__name__)
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
def ban_url(url):
timeout = 0.5... |
Update settings for tinymce to allow show_blog_latest tag | # if you want support for tinymce in the admin pages
# add tinymce to the installed apps (after installing if needed)
# and then import these settings, or copy and adjust as needed
TINYMCE_DEFAULT_CONFIG = {
'relative_urls': False,
'plugins': "table code image link colorpicker textcolor wordcount",
'tools'... | # if you want support for tinymce in the admin pages
# add tinymce to the installed apps (after installing if needed)
# and then import these settings, or copy and adjust as needed
TINYMCE_DEFAULT_CONFIG = {
'relative_urls': False,
'plugins': "table code image link colorpicker textcolor wordcount",
'tools'... |
Remove commented code . | """From http://stackoverflow.com/a/12260597/400691"""
import sys
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbarray',
'HOST': 'localhost'
}
},
INSTALLED_APPS... | """From http://stackoverflow.com/a/12260597/400691"""
import sys
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbarray',
'HOST': 'localhost'
}
},
INSTALLED_APPS... |
Make chapter validator loop over all chapter files in the knowledge model | # Testing jsonschema error printing capabilities
import jsonschema
import json
# Custom printing of errors (skip no-information messages)
# TODO: solve repetition of same error (with different paths)
def print_errors(errors, indent=0):
next_indent = indent + 2
for error in errors:
msg = error.message
... | # Testing jsonschema error printing capabilities
import jsonschema
import json
# Custom printing of errors (skip no-information messages)
# TODO: solve repetition of same error (with different paths)
def print_errors(errors, indent=0):
next_indent = indent + 2
for error in errors:
msg = error.message
... |
PUT services rather than POSTing them | #!/usr/bin/env python
import sys
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir in subdirs:... | #!/usr/bin/env python
import sys
import json
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir... |
Add `can_delete=True` to the example formset | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = fo... | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = fo... |
Clean up configuration check utility | import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
geoipdb = None
def main():
config = Co... | import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
print ("GeoIP is missing, please install de... |
Add trove classifiers specifying Python 3 support. | #!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | #!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... |
Change HTTP method for validate endpoint | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400)... | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400)... |
Add cards for Ideasbox in Burundi | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... |
Add a test for queue_search_JSON. | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
... | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
... |
Set path to find _xxdata.so files | from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
el... |
Add is_uuid unit-tests, including garbage types. | # -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(... | # -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert str... |
Return code from script must reflect that of the test. | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.