code stringlengths 1 199k |
|---|
from django import template
from wagtail.wagtailcore.models import Page
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_site_root(context):
return context['request'].site.root_page
def has_menu_children(page):
if page.get_children().filter(live=True, show_in_menus=True):
... |
l=[20,10,15,75]
ret = sum(l)/len(l)
print ret |
from os.path import exists
from distutils.core import setup
from liveserver import __version__
setup(
name='django-live-server',
version=__version__,
# Your name & email here
maintainer='Adam Charnock',
maintainer_email='adam@playnice.ly',
# If you had liveserver.tests, you would also include th... |
'''Mercurial interface to codereview.appspot.com.
To configure, set the following options in
your repository's .hg/hgrc file.
[extensions]
codereview = /path/to/codereview.py
[codereview]
server = codereview.appspot.com
The server should be running Rietveld; see http://code.google.com/p/rietveld/.
In addition to th... |
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from revcanonical.baseconv import base62
def encode(obj):
ctype = ContentType.objects.get_for_model(obj)
return '%s.%s' % tuple(map(base62.from_decimal, [ctype.pk, obj.pk]))
def decode(addr):
ctype_pk, ... |
from __future__ import unicode_literals
import os
import mdsynthesis as mds
from fireworks import FireTaskBase, FWAction, Workflow
class GromacsContinueTask(FireTaskBase):
"""
A FireTask to check the step listed in the CPT file against the total
number of steps desired in the TPR file. If there are steps le... |
"""
sentry.services.http
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2016 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import os
import sys
from sentry.services.base import Service
def convert_options_to_env(optio... |
import json
from django import template
from django.utils.html import escape
from ..serializers.user import FullUserSerializer
register = template.Library()
@register.filter
def serialize(user):
return escape(json.dumps(FullUserSerializer(user).data)) |
import re
import mock
import pytest
from django.contrib.auth import SESSION_KEY
from django.core import mail
from social.apps.django_app.default.models import Code, UserSocialAuth
from social.exceptions import SocialAuthBaseException
from mailme.models.user import User
from mailme.testutils import get_messages_from_coo... |
import time
import re
import random
from lib.htmlentity import unescape
from html.parser import HTMLParser
def date(timestamp, formatter):
return time.strftime(formatter, time.gmtime(float(timestamp)))
def build_uri(uri, param, value):
regx = re.compile("[\?&](%s=[^\?&]*)" % param)
find = regx.search(uri)
... |
"""
A Printer which converts an expression into its LaTeX equivalent.
"""
from __future__ import print_function, division
from sympy.core import S, C, Add, Symbol
from sympy.core.function import _coeff_isneg
from sympy.core.sympify import SympifyError
from sympy.core.alphabets import greeks
from sympy.logic.boolalg imp... |
from wtforms.fields import HiddenField
from wtforms.validators import ValidationError
__all__ = ("CSRFTokenField", "CSRF")
class CSRFTokenField(HiddenField):
"""
A subclass of HiddenField designed for sending the CSRF token that is used
for most CSRF protection schemes.
Notably different from a normal f... |
import logging
from django.core.management import BaseCommand
from django_prbac.models import Role
from corehq.apps.accounting.models import SoftwarePlanVersion
logger = logging.getLogger(__name__)
class OldRoleDoesNotExist(Exception):
pass
class NewRoleDoesNotExist(Exception):
pass
def change_role_for_software... |
"""
repair-amounts.py -- Replace invalid alues with valid values. Write
a repair function to transforma before value to an after value.
For the examples here, remove dollars signs, commas and HTML elements
from values intended to contain numbers.
Version 1.0 MC 2014-05-24
-- Works as expected. ... |
import re
import datetime
from django.conf import settings
from django.core import mail
from django.core.exceptions import SuspiciousOperation
from django.core.files import temp as tempfile
from django.core.urlresolvers import reverse
from django.contrib.auth import REDIRECT_FIELD_NAME, admin
from django.contrib.auth.m... |
from mrcrowbar import models as mrc
from mrcrowbar import utils, bits
class AECompressor( mrc.Transform ):
def import_data( self, buffer ):
unk1 = buffer[0]
flags = buffer[1]
rle_c = RLECompressor()
dict_c = DictCompressor()
pointer = 2
if (flags & 2 != 0) and (flags ... |
"""
Django settings for rescuests_example project.
Generated by 'django-admin startproject' using Django 1.8.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import... |
from __future__ import print_function, absolute_import, division
__author__ = 'Andrew Perry <Andrew.Perry@monash.edu.au>'
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object)
import six
from six.moves.urllib.parse import urlparse, urljoin
import sys
import shu... |
from django.contrib.gis import admin
from anthill.people.models import Profile
admin.site.register(Profile, admin.OSMGeoAdmin) |
from django.test import TestCase
from dojo.tools.ccvs.parser import CCVSParser
from dojo.models import Test
class TestCCVSParser(TestCase):
def test_ccvs_parser_has_no_finding(self):
testfile = open("dojo/unittests/scans/ccvs/no_vuln.json")
parser = CCVSParser()
findings = parser.get_finding... |
class OR(object):
"""Specify that a value should be one of several types."""
def __init__(self, *args):
self.valid_types = tuple(sorted(args))
def evaluate(self, value):
"""Determine if `value` meets this operator's criteria."""
return isinstance(value, self.valid_types)
def __eq... |
"""Entry point for both build and try bots.
This script is invoked from XXX, usually without arguments
to package an SDK. It automatically determines whether
this SDK is for mac, win, linux.
The script inspects the following environment variables:
BUILDBOT_BUILDERNAME to determine whether the script is run locally
and ... |
"""
Django settings for lot project.
Generated by 'django-admin startproject' using Django 1.11.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
BASE_D... |
from ..errors import ButtshockChecksumError, ButtshockError, ButtshockIOError
import binascii
import struct
class ET232Base(object):
"""Base class for ET-232 communication. Should be inherited by other classes
that implement specific communication types, such as RS-232."""
def __init__(self, key=None, debug... |
import datetime
import itertools
from abc import ABCMeta, abstractmethod, abstractproperty
import six
from whylog.constraints.const import ConstraintType
from whylog.converters import ConverterType, get_converter
from whylog.converters.exceptions import ConverterError
from whylog.teacher.user_intent import UserConstrai... |
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
class TestModel(models.Model):
text = models.CharField(max_length=10, default=_('Anything'))
class Company(models.Model):
name = models.CharField(max_length=50)
date_added = models.DateTimeFiel... |
'''
Example exposing the plot_labelled_group_connectivity_circle function.
Author: Praveen Sripad <pravsripad@gmail.com>
'''
import numpy as np
from jumeg.connectivity import plot_labelled_group_connectivity_circle
from jumeg import get_jumeg_path
import yaml
yaml_fname = get_jumeg_path() + '/data/rsn_desikan_aparc_cor... |
import copy
from elasticsearch import Elasticsearch, helpers
import time
import uuid
import yaml
CONFIG_DICT = {}
PGS = []
VPORTS = []
ACL_ACTION = ["ALLOW", "DENY", "OTHER"]
PROTOCOL = ["TCP", "UDP", "ICMP"]
def populatePGs():
global PGS
for i in range(CONFIG_DICT["no_of_pgs"]):
PGS.append("PG" + str(i+1))
def pop... |
from django.dispatch import receiver
from metaci.build.signals import build_complete
from metaci.plan.models import PlanRepositoryTrigger
@receiver(build_complete)
def trigger_dependent_builds(sender, **kwargs):
build = kwargs.get("build")
status = kwargs.get("status")
if status != "success":
return... |
__version__ = '0.2'
__version_info__ = tuple([ int(num) for num in __version__.split('.')]) |
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration... |
"""A Python debugger."""
import sys
import linecache
import cmd
import bdb
from repr import Repr
import os
import re
import pprint
import traceback
class Restart(Exception):
"""Causes a debugger to be restarted for the debugged python program."""
pass
_repr = Repr()
_repr.maxstring = 200
_saferepr = _repr.repr
... |
"""
NP Release Script
======================
Generates a CSV file for all subjects included in NP analysis for Dolf
"""
import os
import sys
import datetime
import pandas as pd
directory = "/fs/ncanda-share/releases/NCANDA_DATA_00010/summaries"
csv_dir = "/fs/u00/alfonso/Desktop/"
today = datetime.date.today()
nps_fil... |
"""
Layered Plot with Dual-Axis
---------------------------
This example shows how to combine two plots and keep their axes.
"""
import altair as alt
from vega_datasets import data
source = data.seattle_weather()
base = alt.Chart(source).encode(
alt.X('date:O',
axis=alt.Axis(format='%b'),
timeUnit='... |
import cgi
print('Content-type: text/html')
print()
print('script cgi with post<p>')
fs = cgi.FieldStorage()
for key in fs.keys():
print('%s:%s' %(key,fs[key].value)+'<br>')
print('ok') |
def test_compile():
try:
import tiddlywebplugins.hashmaker
assert True
except ImportError, exc:
assert False, exc |
from djangoautoconf.auth.req_auth_base_backend import ReqAuthBaeBackend
class SessionBackend(ReqAuthBaeBackend):
def authenticate(self, request):
if request.user.is_authenticated():
return request.user
return None |
from future.utils import python_2_unicode_compatible
from django.db import models
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
@python_2_unicode_compatible
class SnippetItem(ContentItem):
html = models.TextField(_('HT... |
import httplib, urllib, base64, json
def get_emotion(url, key, image_path):
ret = ""
subscription_key = key
headers = {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': subscription_key,
}
params = urllib.urlencode({
'returnFaceAttributes': 'emotion',
... |
import pytest
from enma.public.forms import LoginForm
from enma.user.forms import RegisterForm
from .factories import UserFactory
class TestRegisterForm:
def test_validate_user_already_registered(self, user):
# Enters username that is already registered
form = RegisterForm(username=user.username, em... |
from zeit.cms.i18n import MessageFactory as _
import grokcore.component as grok
import zeit.content.article.edit.block
import zeit.content.article.edit.interfaces
import itertools
class Topicbox(zeit.content.article.edit.block.Block):
grok.implements(zeit.content.article.edit.interfaces.ITopicbox)
type = 'topic... |
import re
import gdb
from libport.tools import *
@gdb_pretty_printer
class BoostOptional(object):
"Pretty Printer for boost::optional"
regex = re.compile('^boost::optional<(.*)>$')
@staticmethod
def supports(type):
return BoostOptional.regex.search(type.tag)
def __init__(self, value):
... |
from .fields import DigField, Field, MapperField, field # NOQA
from .mappers import DataMapper # NOQA
from .models import ModelDataMapper # NOQA
from .utils import DictObject # NOQA |
from dask.distributed import Worker, Scheduler, Client
from dask.utils import raises
from contextlib import contextmanager
from operator import add
from time import sleep
from multiprocessing.pool import ThreadPool
from toolz import partial
def inc(x):
return x + 1
@contextmanager
def scheduler_and_workers(n=2):
... |
'''
Copyright (c) 2010, Alexandru Dancu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the follo... |
from django.utils.translation import ugettext_lazy as _
JP_PREFECTURES = (
('hokkaido', _('Hokkaido'),),
('aomori', _('Aomori'),),
('iwate', _('Iwate'),),
('miyagi', _('Miyagi'),),
('akita', _('Akita'),),
('yamagata', _('Yamagata'),),
('fukushima', _('Fukushima'),),
('ibaraki', _('Ibarak... |
from django.contrib import admin
from django_subs.models import Subscription
admin.site.register(Subscription) |
"""Fichier décrivant la classe Commentaire, détaillée plus bas."""
import datetime
from abstraits.obase import BaseObj
from primaires.format.date import get_date
class Commentaire(BaseObj):
"""Classe décrivant un commentaire
Un commentaire est défini par son contenu, son auteur,
sa date de publication et l'... |
from __future__ import annotations # isort:skip
import pytest ; pytest
import datetime
import warnings
from copy import copy
import numpy as np
from bokeh._testing.util.api import verify_all
from bokeh.core.has_props import HasProps, Local
from bokeh.core.property.vectorization import (
Field,
Value,
field,... |
"""Helper utilty function for customization."""
import sys
import os
import docutils
import subprocess
READTHEDOCS_BUILD = (os.environ.get('READTHEDOCS', None) is not None)
if not os.path.exists('../recommonmark'):
subprocess.call('cd ..; rm -rf recommonmark;' +
'git clone https://github.com/tqc... |
import json
from django import http
from django.db.transaction import non_atomic_requests
from django.forms.models import modelformset_factory
from django.shortcuts import get_object_or_404, redirect
import olympia.core.logger
from olympia import amo
from olympia.addons.decorators import addon_view_factory
from olympia... |
__version__ = "0.0.dev1" |
import io
import json
import os
import unittest
from . import conceptmap
from .fhirdate import FHIRDate
class ConceptMapTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding=... |
import argparse
import datetime
import logging
import time
import zmq
import queue
from orwell_common.broadcast_pinger import BroadcastPinger
from orwell_common.broadcast_listener import BroadcastListener
from orwell_common.sockets_lister import SocketsLister
import orwell_common.broadcast
import orwell_common.broadcas... |
from kitchensink.data.routing import route, inspect
from kitchensink.data import RemoteData
def inspect_test():
a = RemoteData(data_url="foo/1")
b = RemoteData(data_url="foo/3")
c = RemoteData(data_url="foo/2")
args = [a,b]
kwargs = {'extra' : c}
result = inspect(args, kwargs)
assert set(res... |
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from forocacao.app.views import HomeView
urlpatterns = [
# django smart selects... |
try:
from dev_appserver_version import DEV_APPSERVER_VERSION
except ImportError:
DEV_APPSERVER_VERSION = 2
try:
from google.appengine.api import apiproxy_stub_map
except ImportError:
from djangoappengine.boot import setup_env
setup_env(DEV_APPSERVER_VERSION)
from djangoappengine.utils import on_prod... |
from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from eve_api import views
urlpatterns = patterns('',
url(r'^eveapi/add/$', views.EVEAPICreateView.as_view(), name="eveapi-add"),
url(r'^eveapi/update/(?P<pk>\d+)/$', vie... |
"""
A management command which deletes expired accounts (e.g.,
accounts which signed up but never activated) from the database.
Calls ``RegistrationProfile.objects.delete_expired_subscribers()``, which
contains the actual logic for determining which accounts are deleted.
"""
from django.core.management.base import NoAr... |
import os
import sys
import subprocess
import shlex
import re
def abort(message):
print('ABORTING: ' + message)
sys.exit(1)
def getstatusoutput(command):
try:
args = shlex.split(command)
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
return 0, output.rstrip('\n')
except subprocess.... |
"""
V8 correctness fuzzer launcher script.
"""
import argparse
import hashlib
import itertools
import json
import os
import re
import sys
import traceback
import v8_commands
import v8_suppressions
CONFIGS = dict(
default=[],
fullcode=[
'--nocrankshaft',
'--turbo-filter=~',
],
ignition=[
'--ignition'... |
import datetime
import logging
import time
import traceback
from .filters import FilterBase
from .reporters import ReporterBase
logger = logging.getLogger(__name__)
class JobState(object):
def __init__(self, cache_storage, job):
self.cache_storage = cache_storage
self.job = job
self.verb = N... |
from __future__ import absolute_import
import os
import os.path
import sys
import gzip
import shutil
import tarfile
import hashlib
import subprocess
import tempfile
from io import BytesIO
from contextlib import closing
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
URL = ... |
import os
import fcntl
class LockError(RuntimeError):
pass
class Lockfile(object):
def __init__(self, path, blocking=True, content=None):
self._path = path
self._fd = None
self._locked = False
self._blocking = blocking
self._content = content
def __repr__(self):
... |
__author__ = "Sunil Kumar (kumar.sunil.p@gmail.com)"
__copyright__ = "Copyright 2014, Washington University in St. Louis"
__credits__ = ["Sunil Kumar", "Steve Pieper", "Dan Marcus"]
__license__ = "XNAT Software License Agreement " + \
"(see: http://xnat.org/about/license.php)"
__version__ = "2.1.1"
__main... |
from webViews.view import normalView
from webViews.authenticate.auth import is_authenticated
from webViews.dockletrequest import dockletRequest
from flask import redirect, request, render_template, session, make_response, abort
from webViews import cookie_tool
import hashlib
import os, sys, inspect
this_folder = os.pat... |
"""
MongoEngine models for Social Auth
Requires MongoEngine 0.6.10
"""
try:
from django.contrib.auth.hashers import UNUSABLE_PASSWORD
_ = UNUSABLE_PASSWORD # to quiet flake
except (ImportError, AttributeError):
UNUSABLE_PASSWORD = '!'
from django.utils.importlib import import_module
from mongoengine import... |
import re
import time
from django.conf import settings
from rest_framework.permissions import SAFE_METHODS
from rest_framework.throttling import UserRateThrottle
import olympia
from olympia import amo
from olympia.activity.models import ActivityLog
log = olympia.core.logger.getLogger('z.api.throttling')
class GranularU... |
"""
Created on Sun Jul 3 11:26:33 2016
@module: nested_logit.py
@name: Nested Logit Model
@author: Timothy Brathwaite
@summary: Contains functions necessary for estimating nested logit models
(with the help of the "base_multinomial_cm.py" file).
"""
from __future__ import absolute_import
impor... |
"""Converts a typing model file to C++ code.
Usage:
$ gen_typing_model.py model.tsv > output.h
"""
__author__ = "noriyukit"
import bisect
import codecs
import collections
import optparse
import struct
UNDEFINED_COST = -1
MAX_UINT16 = struct.unpack('H', '\xFF\xFF')[0]
MAX_UINT8 = struct.unpack('B', '\xFF')[0]
def Pars... |
from datetime import datetime
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.auth.models import Group
from django.utils.translation import ugettext_lazy as _
from authority.compat import user_mo... |
import calendar
import time
from django.conf import settings
from django.core.urlresolvers import reverse
import mock
from nose.tools import eq_
import amo
import amo.tests
from addons.models import AddonUser
from amo.helpers import absolutify
from amo.tests import addon_factory
from mkt.receipts.utils import create_re... |
from setuptools import setup
entry_points = """
[console_scripts]
lettherebe = lettherebe.main:main
"""
setup(
version='0.0.2',
url="https://github.com/LetThereBe/lettherebe",
name="lettherebe",
description='LetThereBe Python library and command-line scripts',
packages=['lettherebe'],
install_re... |
import os
PWD = os.path.abspath(os.path.dirname(__file__))
ADMINS = (
('Jeremy Carbaugh', 'jcarbaugh@sunlightfoundation.com'),
)
MANAGERS = ADMINS
TIME_ZONE = 'America/New_York'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = os.path.abs... |
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_escape, escape
from django... |
"""
In other backends, we expect the UI toolkit to have a main loop running
external to Enable.
As of Pyglet 1.1, a new Pyglet App object was introduced which handles
running a main loop and efficiently dispatching to windows and event
handlers, so the former Enable PygletApp object is no longer needed,
and this file i... |
import sys
import rospy
import unittest
from actionlib import SimpleActionClient
import moveit_commander
from moveit_msgs.msg import (
MoveItErrorCodes,
MoveGroupGoal,
Constraints,
JointConstraint,
MoveGroupAction,
)
class TestMoveActionCancelDrop(unittest.TestCase):
def setUp(self):
# c... |
import os
import sys
import pwd
import itertools
from re import sub
from datetime import datetime
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from django.db import models, connection
from multidb.feature.manag... |
import os, sys
import os.path as op
from optparse import OptionParser
try:
import pylab
except:
pylab = None
from sfepy.base.base import *
from sfepy.homogenization.coefficients import Coefficients
def show_array( arr, name ):
pylab.ion()
fig = pylab.figure()
ax = fig.add_subplot( 111 )
ax.set_t... |
"""
testing import maud
"""
def test_answer():
import maud
#import cmaud
from maud import window_func |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 7, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 0); |
from ....testing import assert_equal
from ..utils import MakeSurfaces
def test_MakeSurfaces_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
fix_mtl=dict(argstr='-fix_mtl',
mandatory=False,
),
hemisphere=dict(argstr='%s',
mandator... |
from django.contrib import admin, messages
from django.conf import settings
from django import http
from amazoncloud import models, forms
from amazoncloud.core import utils
from amazoncloud import actions
class EC2Admin(admin.ModelAdmin):
'''
Base class for amazon admin
'''
#def has_change_permission(se... |
import sys, os
source_dir = os.path.split(os.path.abspath(__file__))[0]
docs_dir = os.path.split(source_dir)[0]
base_dir = os.path.split(docs_dir)[0]
sys.path.append(os.path.join(source_dir, "_ext"))
sys.path.append(base_dir)
import stdnet
version = stdnet.__version__
release = version
extensions = ['sphinx.ext.aut... |
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import import_string
from rest_framework import serializers
from shop.conf import app_settings
class SerializeFormAsTextField(serializers.SerializerMethodField):
def __init__(self, form_c... |
from django.template.defaultfilters import stringfilter
from django import template
import textwrap
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def columnize(textblock, width):
"""
Simple helper to take in a plain-text definition list delimited by colons
and add formats it nic... |
class Android(): # class Android(android.Android):
#******** ActivityResultFacade Functions : min SDK 3 ********
def setResultBoolean(self,resultCode,resultValue):
'''
setResultBoolean(
Integer resultCode: The result code to propagate back to the originating activity, often RESULT_CAN... |
import datetime
import commonware.log
import django_tables as tables
import jinja2
from django.conf import settings
from django.template import Context, loader
from django.utils.datastructures import SortedDict
from jingo import register
from tower import ugettext as _, ugettext_lazy as _lazy, ungettext as ngettext
imp... |
__version__ = '1.0.1' |
from . import qt_api
if qt_api == 'pyqt5':
from PyQt5.uic import *
elif qt_api == 'pyqt4':
from PyQt4.uic import *
elif qt_api == 'pyside':
from pysideuic import *
# Credit:
# http://stackoverflow.com/questions/7144313/loading-qtdesigners-ui-files-in-pyside
def loadUi(uifilename, parent=None):
... |
import sys
import pytest
import textwrap
import subprocess
import numpy as np
import numpy.core._multiarray_tests as _multiarray_tests
from numpy import array, arange, nditer, all
from numpy.testing import (
assert_, assert_equal, assert_array_equal, assert_raises,
HAS_REFCOUNT, suppress_warnings
)
def iter... |
import os
from django.test import TestCase
from ..analyzers.formtools import FormToolsAnalyzer
from ..parsers import Parser
from .base import TESTS_ROOT
class FormToolsAnalyzerTests(TestCase):
def setUp(self):
self.example_project = os.path.join(TESTS_ROOT, 'example_project')
self.code = Parser(self... |
from setuptools import setup
setup(
name='dynamodb_utils',
version='1.0.0',
packages=['dynamodb_utils'],
author='Adam Johnson',
author_email='me@adamj.eu',
url='https://github.com/adamchainz/dynamodb_utils',
description='A toolchain for AWS DynamoDB to make common operations (backup, restore... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that parallel builds work correctly when a Node is duplicated
in the children (once in the sources and once in the depends list).
"""
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.write('cat.py', """\
import sys
... |
import getpass
import sys
import requests
from django.core.exceptions import ValidationError
from django.core.management import call_command
from django.core.validators import URLValidator
from django.urls import reverse
from django.utils.six.moves import input
from morango.certificates import Certificate
from morango.... |
from rlib.unroll import unrolling_iterable
class AbstractNode(object):
pass
def _get_all_child_fields(clazz):
cls = clazz
field_names = []
while cls is not AbstractNode:
if hasattr(cls, "_child_nodes_"):
field_names += cls._child_nodes_ # pylint: disable=protected-access
cls... |
from .util import TimeoutManager
def iterate_with_timeout(iterator, timeout):
timeout_mgr = TimeoutManager(timeout)
for item in iterator:
yield item
if timeout_mgr.is_finished():
return
def generate(domain):
while True:
yield domain.generate_one()
def iterate_steps(domain... |
from tkinter import *
class QuitButton(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.__init_window_ui()
def __init_window_ui(self):
self.pack(fill = BOTH, expand = 1)
self.parent.title('Quit Button')
self.__init_window_... |
from .file import File
from .image import Image
from .helpers import IMAGES, DOCUMENTS, DATA, ARCHIVES |
"""Module for partially stirred reactor simulations.
"""
from __future__ import division
from __future__ import print_function
import sys
import itertools
from argparse import ArgumentParser
if sys.version_info.major == 2:
from itertools import izip as zip
try:
import numpy as np
except ImportError:
print('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.