code stringlengths 1 199k |
|---|
import os
import shutil
import time
import threading
import yaml
from datetime import timedelta
from random import randrange
from celery import shared_task
from celery.utils.log import get_task_logger
from django.utils import timezone
from dashboard.constants import TS_JOB_TYPES, BRANCH_MAPPING_KEYS, WEBLATE_SLUGS
from... |
import fileinput
import operator
import optparse
import os
import pprint
import re
import subprocess
import sys
import json
def format_bytes(bytes):
"""Pretty-print a number of bytes."""
if bytes > 1e6:
bytes = bytes / 1.0e6
return '%.1fm' % bytes
if bytes > 1e3:
bytes = bytes / 1.0e... |
import sys
from oslo.config import cfg
from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api
from neutron.api.v2 import attributes
from neutron.common import constants as q_const
from neutron.commo... |
__author__ = 'ansi' |
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class Operator:
"""
Enumerates the list of operators that can be u... |
from __future__ import unicode_literals
from collections import namedtuple
from django.conf import settings
from django.db.models.base import ModelBase
from django.http.request import HttpRequest
from django.utils.encoding import iri_to_uri
from rest_framework.request import Request
from rest_framework.reverse import r... |
import os
def which(program):
"""
Find a program on the system path
Args:
program (str): the program to be found
Returns:
if found the full path to the program, else None
"""
def is_exe(f):
return os.path.isfile(f) and os.access(f, os.X_OK)
fpath, fname = os.path.spli... |
import sys
import math
import scipy.interpolate
ibp = [
# Mass Flow Rate = 0 kg/s/m^2; T = 298.15, 619 K; p = 15.5 MPa
{
'rho_liquid': 1003.8758764456 ,
'u_liquid': 0 ,
'u_vapor': 0
},
# Mass Flow Rate = 3729.9625 kg/s/m^2; T = 559.1355 (old=565.05) (oldold=... |
"""A collection of native images.
"""
import errno
import glob
import logging
import os
import pwd
import shutil
import stat
import treadmill
from treadmill import appcfg
from treadmill import cgroups
from treadmill import fs
from treadmill import runtime
from treadmill import subproc
from treadmill import supervisor
f... |
import xml.sax
from boto import handler
from boto.emr import emrobject
from boto.resultset import ResultSet
from tests.compat import unittest
JOB_FLOW_EXAMPLE = b"""
<DescribeJobFlowsResponse
xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-01-15">
<DescribeJobFlowsResult>
<JobFlows>
<member>
... |
from skew.resources.aws import AWSResource
class Application(AWSResource):
class Meta(object):
service = 'elasticbeanstalk'
type = 'application'
enum_spec = ('describe_applications', 'Applications', None)
detail_spec = None
id = 'ApplicationName'
filter_name = None
... |
from setuptools import setup
setup(
# Do not use underscores in the plugin name.
name='a4c-overrides-aws',
version='1.4.1',
author='alien4cloud',
author_email='alien4cloud@fastconnect.fr',
description='custom overrides',
# This must correspond to the actual packages in the plugin.
packag... |
import json
from apache_ranger.utils import *
class RangerBase(dict):
def __init__(self, attrs):
pass
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(RangerBase, se... |
"""Manage access to the clients, including authenticating when needed.
"""
from tackerclient import client
from tackerclient.tacker import client as tacker_client
class ClientCache(object):
"""Descriptor class for caching created client handles."""
def __init__(self, factory):
self.factory = factory
... |
__author__ = 'karlo' |
"""Unit test for treadmill.ad.gmsa.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import shutil
import tempfile
import unittest
import ldap3
import mock
import yaml
import treadmill.tests.tread... |
import uuid
from oslo.utils import timeutils
import six
from keystone import assignment
from keystone.common import controller
from keystone.common import dependency
from keystone.common import validation
from keystone import exception
from keystone.i18n import _
from keystone.models import token_model
from keystone.op... |
import time,traceback
import re
import sys
import csv
import pprint
import optparse
from django.core.files.storage import get_storage_class
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.text import slugify
from pages.models import Slide, slide_show_image
from dja... |
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1NodeCondition(obje... |
"""
Conll05 dataset.
Paddle semantic role labeling Book and demo use this dataset as an example.
Because Conll05 is not free in public, the default downloaded URL is test set
of Conll05 (which is public). Users can change URL and MD5 to their Conll
dataset. And a pre-trained word vector model based on Wikipedia corpus ... |
import torch
import torch.onnx
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.linear = torch.nn.Linear(in_features=3, out_features=1)
self.logistic = torch.nn.Sigmoid()
def forward(self, vec):
return self.logistic(self.linear(vec))
def ma... |
import win32serviceutil
import subprocess
import os
import os.path
import sys
import platform
import multiprocessing.forking
import logging
import ConfigParser
import ctypes
import traceback
import win32service
import win32event
import win32con
import win32file
from os.path import abspath, dirname
from multiprocessing ... |
""" Miscelaneous helper libraries for testing """
def import_depends():
""" Set up the sys.path for loading library dependencies """
import os
import sys
_DIR = os.path.dirname(os.path.realpath(__file__))
_LIBDIR = os.path.join(_DIR, "..", "..", "lib", "python2.6")
_TESTDIR = os.path.join(_DIR, ... |
import mock
import pytest
from api_tests import utils as test_utils
from osf_tests.factories import (
PreprintFactory,
AuthUserFactory,
SubjectFactory,
)
@pytest.mark.django_db
class PreprintListMatchesPreprintDetailMixin:
@pytest.fixture()
def user_write_contrib(self):
return AuthUserFactor... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
extensions = [
'reno.sphinxext',
'openstackdocstheme',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Kolla Release Notes'
copyright = '2015, Kolla developers'
version = ''
release = ''
exclude_patterns =... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("trackers", "0002_auto_20181025_0210")]
operations = [
migrations.AlterField(
model_name="commonapptracker",
name="status",
field=models.PositiveIntegerField(
... |
import json
import logging
import sys
import uuid
from redash.query_runner import *
from redash.utils import JSONEncoder
logger = logging.getLogger(__name__)
try:
import pymssql
enabled = True
except ImportError:
enabled = False
types_map = {
1: TYPE_STRING,
2: TYPE_BOOLEAN,
3: TYPE_INTEGER,
... |
"""
Pythagoras tree viewer for visualizing tree structures.
The pythagoras tree viewer widget is a widget that can be plugged into any
existing widget given a tree adapter instance. It is simply a canvas that takes
and input tree adapter and takes care of all the drawing.
Types
-----
Square : namedtuple (center, length... |
"""
=============================================
I/O functions (:mod:`sknano.core._io`)
=============================================
.. currentmodule:: sknano.core._io
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
__docformat__ = 'restructuredtext en'
import json
import ... |
from django.test import TestCase
from django_factory_boy import auth
from journalmanager.tests import modelfactories
from journalmanager.backends import ModelBackend
HASH_FOR_123 = 'sha1$93d45$5f366b56ce0444bfea0f5634c7ce8248508c9799'
class ModelBackendTest(TestCase):
def setUp(self):
self.user = auth.UserF... |
try:
from misp_stix_converter.converters.buildMISPAttribute import buildEvent
from misp_stix_converter.converters import convert
from misp_stix_converter.converters.convert import MISPtoSTIX
has_misp_stix_converter = True
except ImportError:
has_misp_stix_converter = False
def load_stix(stix, distri... |
from collections import defaultdict
from django.contrib.sites.models import Site
from django.utils.translation import get_language
from cms.apphook_pool import apphook_pool
from cms.models.permissionmodels import ACCESS_DESCENDANTS
from cms.models.permissionmodels import ACCESS_PAGE_AND_DESCENDANTS
from cms.models.perm... |
import datetime
import factory
import pytz
from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.core import mail
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import resolve, reverse
from django.http import Http404
fro... |
from __future__ import absolute_import, unicode_literals
import base64
import hashlib
import hmac
import imghdr
from wsgiref.util import FileWrapper
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.http import HttpResponse, HttpResponsePermanentRedir... |
import sys
from setuptools import setup
if sys.version < '3':
raise ImportError(
'This version of autodiff only support Python 3+. Please check out an '
'earlier branch for use with Python 2.')
setup(
name='autodiff',
version='0.5',
maintainer='Lowin Data Company',
maintainer_email='... |
from __future__ import print_function
import feedparser
import listparser
import time
import hashlib
import os
import sys
from os.path import expanduser
import logging
import re
import requests
import argparse
import shutil # To get around "cross-device" rename error when moving to dest. dir.
from datetime import datet... |
"""
Experiment control
==================
Experiment control functions.
"""
from ._version import __version__
from ._utils import (set_log_level, set_log_file, set_config, check_units,
get_config, get_config_path, fetch_data_file,
run_subprocess, verbose_dec as verbose, buildin... |
import mock
from mk_livestatus import Socket
@mock.patch('mk_livestatus.livestatus.socket.socket')
def test_socket(socket_mock):
socket_mock.return_value.makefile.return_value.read.return_value = (
'[["name","groups","perf_data"],'
'["hbops",["archlinux","linux","hashbang"],'
'"rta=0.168000m... |
"""
Discrete Fourier Transforms - helper.py
"""
__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq']
from numpy.core import asarray, concatenate, arange, take, \
integer, empty
import numpy.core.numerictypes as nt
import types
def fftshift(x, axes=None):
"""
Shift the zero-frequency component to the c... |
from django.conf.urls.defaults import *
urlpatterns = patterns('profile.views',
url(r'^detail/(?P<username>[a-zA-Z0-9_-]+)/$', 'detail',
name='profile_detail'),
) |
"""
=============================
Reading and writing raw files
=============================
In this example, we read a raw file. Plot a segment of MEG data
restricted to MEG channels. And save these data in a new
raw file.
"""
print(__doc__)
import mne
from mne.datasets import sample
data_path = sample.data_path()
fn... |
from __future__ import absolute_import
import warnings
from feincms.urls import urlpatterns, Handler, handler
__all__ = ('urlpatterns', 'Handler', 'handler')
warnings.warn(
'feincms.views.cbv has been deprecated. Use feincms.urls and feincms.views'
' directly instead.', DeprecationWarning, stacklevel=2) |
import atexit
import tempfile
from mkt.settings import * # noqa
_tmpdirs = set()
def _cleanup():
try:
import sys
import shutil
except ImportError:
return
tmp = None
try:
for tmp in _tmpdirs:
shutil.rmtree(tmp)
except Exception, exc:
sys.stderr.wri... |
from telemetry.page import page as page_module
from telemetry.page.actions import navigate
from telemetry.unittest import tab_test_case
class NavigateActionTest(tab_test_case.TabTestCase):
def CreatePageFromUnittestDataDir(self, filename):
self.Navigate(filename)
return page_module.Page(
self._browser... |
from __future__ import unicode_literals
try:
from django.conf.urls.defaults import patterns, include, handler500
except ImportError:
from django.conf.urls import patterns, include, handler500
from django.conf import settings
from django.contrib import admin
from moderation.helpers import auto_discover
admin.aut... |
import datetime
import functools
import logging
import os
import shutil
import tempfile
import threading
import devil_chromium
from devil import base_error
from devil.android import device_denylist
from devil.android import device_errors
from devil.android import device_utils
from devil.android import logcat_monitor
fr... |
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as auth_logout, ... |
from __future__ import unicode_literals
import unittest
from django.test.testcases import TestCase
from tests.models import UserProfile,\
ModelWithVisibilityField, ModelWithWrongVisibilityField
from moderation.moderator import GenericModerator
from moderation.managers import ModerationObjectsManager
from django.cor... |
def slugify(text, delim=u'_'):
u"""'Generates an ASCII-only slug.''"""
import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t :;!"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
result = []
for word in _punct_re.split(text.lower()):
word = normalize('NFKD', word).encode('ascii', 'i... |
"""Top-level presubmit script for Chromium.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import re
import sys
_EXCLUDED_PATHS = (
r"^breakpad[\\\/].*",
r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
... |
"""
This file contains the spec for the XML for mobile auth
(from https://bitbucket.org/commcare/commcare/wiki/CentralAuthAPI)
<!-- Exactly one. The block of auth key records.-->
<!-- @domain: Exactly one. The client should only accept keys from domains that match the request -->
<!-- @issued: Exact... |
from __future__ import unicode_literals
import inspect
import os
import re
import shutil
import sys
from tempfile import NamedTemporaryFile, mkdtemp, mkstemp
from unittest import skipIf
from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import revers... |
from __future__ import unicode_literals
from django.template.defaultfilters import force_escape
from django.test import SimpleTestCase
from django.utils.safestring import SafeData
from ..utils import render, setup
class ForceEscapeTests(SimpleTestCase):
"""
Force_escape is applied immediately. It can be used to... |
import os
from setuptools import setup
try:
versionstring = os.popen("git describe").read().strip()
open("smop/version.py","w").write("__version__ = '%s'\n" % versionstring)
except:
versionstring = "'0.26'"
setup(
author = 'Victor Leikehman',
author_email = 'victorlei@gmail.com',
description = '... |
from os.path import dirname, abspath, join
from flask.ext.sqlalchemy import SQLAlchemy
_cwd = dirname(abspath(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + join(_cwd, 'flask_temp.db')
db.create_all()
class Person(db.Model):
__tablename__ = 'people'
id = db.Column(db.Integer, primary_key=True)
name = d... |
from xml.sax.saxutils import escape
from pybtex.backends import BaseBackend
import pybtex.io
file_extension = 'html'
PROLOGUE = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head><meta name="generator" content="Pybtex">
<meta http-equiv="Content-Type" content="text/html; charset=%s">
<title>Bibliograph... |
from typing import Any
from typing import List
from typing import MutableMapping # noqa
from mitmproxy.types import serializable
def _is_list(cls):
# The typing module is broken on Python 3.5.0, fixed on 3.5.1.
is_list_bugfix = getattr(cls, "__origin__", False) == getattr(List[Any], "__origin__", True)
ret... |
from direct.directnotify import DirectNotifyGlobal
class EntityCreatorBase:
notify = DirectNotifyGlobal.directNotify.newCategory('EntityCreator')
def __init__(self, level):
self.level = level
self.entType2Ctor = {}
def createEntity(self, entId):
entType = self.level.getEntityType(ent... |
import pytest
from libqtile import layout
import libqtile.config
import libqtile.hook
from .layout_utils import assert_focused, assert_focus_path_unordered
class AllLayoutsConfig:
"""
Ensure that all layouts behave consistently in some common scenarios.
"""
groups = [
libqtile.config.Group("a"),... |
"""
To use:
1. Clone a production copy of TBA in the same directory as the development copy by running: `git clone git@github.com:the-blue-alliance/the-blue-alliance.git the-blue-alliance-prod`
2. Ensure you have gcloud available and in your PATH (https://cloud.google.com/sdk/gcloud/)
3. If you want to allow travis sup... |
"""This module provides the default commands for beets' command-line
interface.
"""
from __future__ import division, absolute_import, print_function
import os
import re
from collections import namedtuple, Counter
from itertools import chain
import beets
from beets import ui
from beets.ui import print_, input_, decargs,... |
"""
Simple script to convert older-style bulk forcing files with
multiple time dimensions to a new, single, unlimited time dimension
for all fields.
"""
import sys
import seapy
import numpy as np
try:
infile = sys.argv[1]
outfile = sys.argv[2]
except:
print("Usage: {:s} input_file output_file".format(sys.ar... |
from tests.test_lagesonum import LagesonumTests
from tests.test_input_number import InputTests
from unittest import main
main() |
from __future__ import unicode_literals, print_function
import os
import shutil
from xml.dom import minidom
from . import (
process_atlas, process_font, process_starling_atlas, oxygine_helper
)
def as_bool(attr):
if not attr:
return False
lw = attr.lower()
return lw == "true" or lw == "1"
class ... |
"""Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact blocks are post-segwit (wtxids)
"""
from decimal import Decimal
import random
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
from test_framework.messages import BlockTransacti... |
from __future__ import absolute_import
from __future__ import print_function
__author__ = "Filippo Rivato"
__email__ = "f.rivato@gmail.com"
__name__ = _("Heightmap")
__version__= "0.0.1"
import math
from CNC import CNC,Block
from ToolsPage import Plugin
from imageToGcode import *
class Heightmap:
def __init__(self,na... |
import urlparse
import re
DOWNLOAD_URL = re.compile(".*\/download\/[0-9]+")
STATIC_URL = re.compile(".*\/\w+-static\/.*")
SET_CURRENT_FORM = re.compile(".*\/set_current_form_page.*")
REST_URLS = re.compile(".*\/rest\/.*")
FAVICON = re.compile(".*\/favicon\.ico")
def handle_history(event):
"""Is called per subscribe... |
"""
**********
Matplotlib
**********
Draw networks with matplotlib (pylab).
See Also
--------
matplotlib: http://matplotlib.sourceforge.net/
pygraphviz: http://networkx.lanl.gov/pygraphviz/
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__all__ = ['draw',
'draw_networkx',
'draw_net... |
import logging
import os
from pulp_ostree.common import constants
_LOG = logging.getLogger(__name__)
def validate_config(config):
"""
Validate a configuration
:param config: Pulp configuration for the distributor
:type config: pulp.plugins.config.PluginCallConfiguration
:raises: PulpCodedValidation... |
import unittest
from PyFoam.Applications.WriteDictionary import WriteDictionary
theSuite=unittest.TestSuite() |
from __future__ import division
import sys
import re
import logging
import numbers
logger = logging.getLogger(__name__)
from gi.repository import GObject
from ..overrides import override
from ..module import get_introspection_module
Vips = get_introspection_module('Vips')
__all__ = []
Vips.init(sys.argv[0])
vips_type_a... |
"""
Clone of queso OS fingerprinting
"""
from scapy.data import KnowledgeBase
from scapy.config import conf
from scapy.layers.inet import IP,TCP
from scapy.error import warning
from scapy.volatile import RandInt
from scapy.sendrecv import sr
conf.queso_base ="/etc/queso.conf"
def quesoTCPflags(flags):
if flags == "... |
"""
Convenience class for dequeuing messages from a gr.msg_queue and
invoking a callback.
Creates a Python thread that does a blocking read on the supplied
gr.msg_queue, then invokes callback each time a msg is received.
If the msg type is not 0, then it is treated as a signal to exit
its loop.
If the callback raises a... |
from bs4 import BeautifulSoup
import urllib.request
import re
import sys
if len(sys.argv) != 2 :
print("invalid syntax")
else :
#url = "http://www.oreilly.com/web-platform/free/"
url = sys.argv[1]
page = urllib.request.urlopen(url).read()
soup = BeautifulSoup(page, "html.parser")
for anchor in s... |
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x02\x55\
\x3c\
\x72\x65\x63\x69\x70\x65\x3e\x0a\x20\x20\x20\x20\x3c\x74\x69\x74\
\x6c\x65\x3e\x43\x68\x65\x65\x73\x65\x20\x6f\x6e\x20\x54\x6f\x61\
\x73\x74\x3c\x2f\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x3c\
\x69\x6e\x67\x72\x65\x64\x69\x65\x6e\x74\x20\x6e\x... |
import urllib2
def openurl(address):
try:
urlresponse = urllib2.urlopen(address).read()
return urlresponse
except urllib2.HTTPError, e:
print("HTTPError = " + str(e.code))
except urllib2.URLError, e:
print("URLError = " + str(e.code))
except Exception:
import trac... |
import os
import string
import sys
from argparse import ArgumentParser, HelpFormatter
from copy import copy
from functools import partial
from enum import Enum
from ..core.Import_Manager import Import_Manager
from Settings import Settings
class ArgumentsHelpFormatter(HelpFormatter):
"""
A help formatter that ca... |
import unittest
class TestMaintenanceTeamMember(unittest.TestCase):
pass |
"""Virtual environment management."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import sys
from . import types as t
from .config import (
EnvironmentConfig,
)
from .util import (
find_python,
SubprocessError,
get_available_python_versio... |
from askbot.deps.django_authopenid.models import UserAssociation
from askbot.management.commands.base import BaseImportXMLCommand
from askbot.models import Award
from askbot.models import BadgeData
from askbot.models import Post
from askbot.models import PostRevision
from askbot.models import Thread
from askbot.models ... |
"""Generate template values for a callback interface.
Extends IdlTypeBase with property |callback_cpp_type|.
Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
"""
from idl_types import IdlTypeBase
from v8_globals import includes
import v8_types
import v8_utilities
CALLBACK_INTERFACE_H_INCLUDE... |
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import util
apkFile = '../common/main/bin/bbct-android-common-debug.apk'
package = 'bbct.android.common'
activity = '.activity.BaseballCardList'
runComponent = package + '/' + activity
delay = 10.0
print("Connecting to device...")
device = MonkeyRunner.wai... |
__version__ = "0.1"
import string
import Image, ImageFile
from OleFileIO import *
MODES = {
# opacity
(0x00007ffe): ("A", "L"),
# monochrome
(0x00010000,): ("L", "L"),
(0x00018000, 0x00017ffe): ("RGBA", "LA"),
# photo YCC
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
(0x0002800... |
"""
set of functions and classes useful for management of domain level 1 topology
"""
from copy import deepcopy
from ipalib import _
from ipapython.graph import Graph
CURR_TOPOLOGY_DISCONNECTED = _("""
Replication topology in suffix '%(suffix)s' is disconnected:
%(errors)s""")
REMOVAL_DISCONNECTS_TOPOLOGY = _("""
Remov... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cdr_stats.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
Unit tests for gating.signals module
"""
from ddt import data, ddt, unpack
from milestones import api as milestones_api
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from nose.plugins.attrib import attr
from courseware.tests.helpers import LoginEnrollmentTestCase
from gatin... |
import collections
import math
import numpy as np
import torch
Rect = collections.namedtuple("Rect", ["top", "left", "height", "width"])
class RandomImage:
"""
Coordinates use matrix indexing [row][column], so objects are placed by
specifying their "top" and "left".
"""
def __init__(self, viewport_h... |
from sqlalchemy import Integer, Boolean, Unicode, Float, UnicodeText, Text
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy.ext.mutable import MutableDict
from pybossa.core import db, signer
from pybossa.mod... |
'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later versio... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django_pgjson.fields import JsonField
from taiga.projects.occ.mixins import OCCModelMixin
from . import choices
class AbstractCustomAttribute(models.Model):
name = models.CharField(null=False,... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from authentic2.compat import user_model_label
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'KeyValue.key'
db.alter_column(u'saml_keyvalue', 'key', self.gf('django... |
from openerp.tools.translate import _
class mem_bank_statement(object):
'''
A mem_bank_statement is a real life projection of a bank statement paper
containing a report of one or more transactions done. As these reports can
contain payments that originate in several accounting periods, period is an
... |
from mako.lookup import TemplateLookup
import tempdir
from django.template import RequestContext
from django.conf import settings
requestcontext = None
lookup = {}
class MakoMiddleware(object):
def __init__(self):
"""Setup mako variables and lookup object"""
# Set all mako variables based on django ... |
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^$',
views.CantonSelectorView.as_view(),
name='canton-frontpage',
),
] |
import os
import unittest
from coala_utils.ContextManagers import make_temp, prepare_file
from coalib.io.FileProxy import (
FileProxy, FileProxyMap, FileDictGenerator)
class FileProxyTest(unittest.TestCase):
def test_fileproxy_relative_name(self):
with prepare_file(['coala'], None) as (_, file):
... |
from odoo import api, models, fields
class SdsFollowerSettings(models.TransientModel):
""" Settings configuration for any Notifications."""
_name = 'sds.follower.settings'
_inherit = 'res.config.settings'
_description = 'SDS Followers Settings'
# Users to notify after Child Departure
sub_fr = fi... |
from nupic.research.frameworks.backprop_structure.modules import (
BinaryGatedConv2d,
BinaryGatedLinear,
HardConcreteGatedConv2d,
HardConcreteGatedLinear,
)
def constrain_parameters(module):
if isinstance(module, (BinaryGatedConv2d,
BinaryGatedLinear,
... |
from spack import *
class Libffi(AutotoolsPackage, SourcewarePackage):
"""The libffi library provides a portable, high level programming
interface to various calling conventions. This allows a programmer
to call any function specified by a call interface description at
run time."""
homepage = "https... |
import pyuaf
import unittest
from pyuaf.util.unittesting import parseArgs, testVector
ARGS = parseArgs()
def suite(args=None):
if args is not None:
global ARGS
ARGS = args
return unittest.TestLoader().loadTestsFromTestCase(PkiCertificateInfoTest)
class PkiCertificateInfoTest(unittest.TestCase):
... |
from __future__ import unicode_literals
import os.path
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
from ..utils import url_basename
class DropboxIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dropbox[.]com/sh?/(?P<id>[a-zA-Z0-9]{15})/.*'
_TESTS = [{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.