content stringlengths 4 20k |
|---|
"""
sentry.web.frontend.events
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import urlparse
from django.core.context_processors import csrf
from django.core.urlresolvers i... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
def GetRGBColor(colorName):
'''
Return the red, green and blue components for a
color as doubles.
'''
rgb = [0.0, 0.0, 0.0] # black
vtk.vt... |
import logging
from django.contrib.sessions.backends.base import CreateError, SessionBase
from django.core.exceptions import SuspiciousOperation
from django.db import IntegrityError, router, transaction
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.functional import c... |
"""
PyTag
Version: 2005-06-11
Author: Terry Stewart <EMAIL> http://terrystewart.ca
This software is released under the GNU General Public License.
See http://www.gnu.org/copyleft/gpl.html for more details.
This is a utility for easily generating valid XHTML from within
a Python program. It is inspired by Nevow's <ht... |
"""
Test makefile_writer.py
"""
import argparse
import os
import shutil
import sys
import tempfile
import test_variables
import unittest
import utils
sys.path.append(test_variables.GYP_GEN_DIR)
import makefile_writer
import tool_makefile_writer
import vars_dict_lib
MAKEFILE_NAME = test_variables.ANDROID_MK
REBASELI... |
from unittest import TestCase
from myhdl import *
from hardware.jumpunit import *
class DutClass():
"""Wrapper around DUT"""
def __init__(self):
self.code = Signal(intbv(0)[5:])
self.Z, self.N, self.C, self.V, self.out = [Signal(bool(0)) for _ in range(5)]
def Gens(self, trace = False):
... |
import contextlib
import functools
import jqsh.context
import queue
import threading
class Terminator:
"""a special value used to signal the end of a channel"""
def coerce_other(f):
@functools.wraps(f)
def wrapper(self, other):
import jqsh.values
return f(self, jqsh.values.from_na... |
from __future__ import unicode_literals
import ast
import socket
import time
from requests.compat import urlencode
from six.moves.http_client import HTTPException, HTTPSConnection
import sickbeard
from sickbeard import common, db, logger
from sickrage.helper.encoding import ss
try:
# this only exists in 2.6
... |
import os
import imp
from itertools import product, starmap
import distutils.command.install_lib as orig
class install_lib(orig.install_lib):
"""Don't add compiled flags to filenames of non-Python files"""
def run(self):
self.build()
outfiles = self.install()
if outfiles is not None:
... |
"""
This module houses the GEOS ctypes prototype functions for the
topological operations on geometries.
"""
__all__ = ['geos_boundary', 'geos_buffer', 'geos_centroid', 'geos_convexhull',
'geos_difference', 'geos_envelope', 'geos_intersection',
'geos_linemerge', 'geos_pointonsurface', 'geos_pre... |
MODEL_PARAMS = {'aggregationInfo': {'days': 0,
'fields': [(u'timestamp', 'first'),
(u'wavelet_value', 'sum'),
(u'raw_value', 'first')],
'hours': 0,
'microseconds': 0,
'mill... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from nipype.testing import (assert_equal, assert_false,assert_raises,
assert_true, skipif, example_data)
from nipype.interfaces.spm import no_spm
import nipype.interfaces.spm.utils as spmu
... |
# -*- coding: utf-8 -*-
__license__ = 'GPL 3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>, ' \
'2009, John Schember <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import errno, os, sys, subprocess, shutil, re
from functools import partial
from calibre.ebooks import ConversionError,... |
from ctypes import POINTER, c_char_p, c_int, c_void_p
from django.contrib.gis.gdal.libgdal import lgdal, std_call
from django.contrib.gis.gdal.prototypes.generation import (
const_string_output, double_output, int_output, srs_output, string_output,
void_output,
)
# Shortcut generation for routines with known... |
import create_bwc_index
import logging
import os
import shutil
import subprocess
import sys
import tempfile
def fetch_version(version):
logging.info('fetching ES version %s' % version)
if subprocess.call([sys.executable, os.path.join(os.path.split(sys.argv[0])[0], 'get-bwc-version.py'), version]) != 0:
raise R... |
# MySQL Connector/Python - MySQL driver written in Python.
import django
import subprocess
from django.db.backends.base.client import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'mysql'
@classmethod
def settings_to_cmd_args(cls, settings_dict):
args = [cls.exe... |
# -*- coding: utf-8 -*-
"""
advancedTypes.py - Basic data structures not included with python
Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.
Includes:
- OrderedDict - Dictionary which preserves the order of its elements
- BiDict, ReverseDict - Bi-directiona... |
# -*- coding: utf-8 -*-
# Mimic the sqlite3 console shell's .dump command
def _iterdump(connection):
"""
Returns an iterator to the dump of the database in an SQL text format.
Used to produce an SQL dump of the database. Useful to save an in-memory
database for later restoration. This function shou... |
__author__ = '<EMAIL> (Takashi Matsuo)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import atom.service
import atom.mock_service
import gdata.apps
import gdata.apps.service
import getpass
import time, os
apps_domain = 'test.shehas.net'... |
from __future__ import unicode_literals, with_statement
import decimal
from django.db import models
from django.http.response import HttpResponseRedirect
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from enumfields import Enum, EnumField
from parler.models import Trans... |
"""The step function abstraction represents a single training step."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import backprop
from tensorflow.python.training import optimizer as optimizer_lib
class Step(object):
"""... |
from sys import version_info
if version_info[0:2] > (2, 2):
from unicodedata import normalize
else:
normalize = None
from rdflib.Identifier import Identifier
from rdflib.exceptions import Error
class Literal(Identifier):
"""
http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal
"""
d... |
"""
Functions that modify an HTTP request or response in some way.
"""
# This group of functions are run as part of the response handling, after
# everything else, including all response middleware. Think of them as
# "compulsory response middleware". Be careful about what goes here, because
# it's a little fiddly to ... |
"""Provides OpenStack config generators
This module defines a class for configuration
generators for generating the model in
:mod:`openstack.common.report.models.conf`.
"""
from oslo_config import cfg
from nova.openstack.common.report.models import conf as cm
class ConfigReportGenerator(object):
"""A Configura... |
from odoo import tools
from odoo import models, fields, api
class StockAnalysis(models.Model):
_name = 'stock.analysis'
_auto = False
_rec_name = 'product_id'
_description = 'Stock analysis view'
product_id = fields.Many2one(
'product.product', string='Product', readonly=True)
locatio... |
import pytest
import argparse
import inspect
from . import plugin_base
import collections
def pytest_addoption(parser):
group = parser.getgroup("sqlalchemy")
def make_option(name, **kw):
callback_ = kw.pop("callback", None)
if callback_:
class CallableAction(argparse.Action):
... |
#!/usr/bin/env python
from __future__ import print_function
from time import time
from collections import deque
from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.resource import Resource
from twisted.internet import reactor
class Root(Resource):
def __init__(self):
Resource.__init__(self... |
"""A library for retrieving and modifying configuration settings."""
import os
import textwrap
from google_compute_engine import constants
from google_compute_engine import file_utils
from google_compute_engine.compat import parser
CONFIG = constants.SYSCONFDIR + '/instance_configs.cfg'
class ConfigManager(object)... |
"""Cryptlib 3DES implementation."""
from .cryptomath import *
from .TripleDES import *
if cryptlibpyLoaded:
def new(key, mode, IV):
return Cryptlib_TripleDES(key, mode, IV)
class Cryptlib_TripleDES(TripleDES):
def __init__(self, key, mode, IV):
TripleDES.__init__(self, key, mod... |
import urllib2
import urllib
import hashlib
import os.path
from django.core.cache import get_cache, InvalidCacheBackendError
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext
from django.core.urlresolvers import reverse
from django.conf impo... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import signal
import sys
import termios
import time
import tty
from os import isatty
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_text, to_native
from ansible.module_utils.parsi... |
from numpy.testing import assert_array_equal
from pytest import raises as assert_raises
import numpy as np
from scipy.optimize import linear_sum_assignment
def test_linear_sum_assignment():
for cost_matrix, expected_cost in [
# Square
([[400, 150, 400],
[400, 450, 600],
[300,... |
import logging
import os
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
def tests_resource_path(local_path=''):
this_file = os.path.dirname(os.path.abspath(__file__))
return os.path.join(this_file, local_path)
# Full path to the fixtures directory underne... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('auth', '__first__'),
]
operations = [
migrations.CreateModel(
name='MyUser',
fields=[
... |
import re
import uuid
import ovs.poller
import ovs.socket_util
import ovs.json
import ovs.jsonrpc
import ovs.ovsuuid
import ovs.db.parser
from ovs.db import error
import ovs.db.types
class ConstraintViolation(error.Error):
def __init__(self, msg, json=None):
error.Error.__init__(self, msg, json, tag="co... |
DATE_FORMAT = 'N j, Y'
TIME_FORMAT = 'P'
DATETIME_FORMAT = 'N j, Y, P'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'F j'
SHORT_DATE_FORMAT = 'm/d/Y'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
FIRST_DAY_OF_WEEK = 0 # Sunday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/librar... |
from PIL import Image
from PIL import _imagingmorph
import re
LUT_SIZE = 1 << 9
class LutBuilder(object):
"""A class for building a MorphLut from a descriptive language
The input patterns is a list of a strings sequences like these::
4:(...
.1.
111)->1
(whitespa... |
from __future__ import absolute_import
import logging
import sys
import textwrap
from collections import OrderedDict
from pip._vendor import pkg_resources
from pip._vendor.packaging.version import parse as parse_version
# NOTE: XMLRPC Client is not annotated in typeshed as on 2017-07-17, which is
# why we ignor... |
import xml.dom.minidom
import commands
import math
class HostSpecsManager:
"""\brief Retrieves hardware specs from the local host
"""
def __init__(self):
pass
def get_host_specs(self):
"""\brief Parses lshw output for the local host and populates a
HostSpecsInfo obj... |
# -*- coding: utf-8 -*-
"""
werkzeug.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements a number of Python exceptions you can raise from
within your views to trigger a standard non-200 response.
Usage Example
-------------
::
from werkzeug.wrappers import BaseRequest
... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import render
from .models import EmailAddress
from .utils import send_email_confirmation
def verified_email_required(function=None,
login_url=None,
... |
from typing import NamedTuple, Iterable, TYPE_CHECKING
import os
import asyncio
from enum import IntEnum, auto
from typing import NamedTuple, Dict
from . import util
from .sql_db import SqlDB, sql
from .wallet_db import WalletDB
from .util import bh2u, bfh, log_exceptions, ignore_exceptions, TxMinedInfo
from .address_... |
'''
Created on Aug 20, 2014
@author: valeriu
'''
import unittest
from datetime import datetime, timedelta
from activitytracker import Activity, ActivityError
class TestActivity(unittest.TestCase):
def setUp(self):
self.activity = Activity([])
def tearDown(self):
self.activ... |
"""
Test Selection
--------------
Test selection is handled by a Selector. The test loader calls the
appropriate selector method for each object it encounters that it
thinks may be a test.
"""
import logging
import os
import unittest
from nose.config import Config
from nose.util import split_test_name, src, getfilenam... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.ing... |
"""
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option... |
""" Configuration file for miscutil module.
- Contains standard error messages for errorlib
e.g. No error message given, etc.
"""
__revision__ = "$Id$"
# Exceptions: errors
class InvenioMiscUtilError(Exception):
"""A generic error for MiscUtil."""
def __init__(self, message):
"""Initialisation."""
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Principal components analysis (PCA)
=========================================================
These figures aid in illustrating how a point cloud
can be very flat in one direction--which is where PCA
comes in to ch... |
"""
Sources:
Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland
"""
from django.utils.translation import ugettext_lazy as _
IE_COUNTY_CHOICES = (
('antrim', _('Antrim')),
('armagh', _('Armagh')),
('carlow', _('Carlow')),
('cavan', _('Cavan')),
('clare', _('Clare')),... |
import os
import pytest
import numpy as np
from astropy.utils.data import get_pkg_data_filenames, get_pkg_data_contents
from astropy.utils.misc import NumpyRNGContext
from astropy import wcs
from astropy.wcs.wcs import FITSFixedWarning
# use the base name of the file, because everything we yield
# will show up in t... |
#!/usr/bin/env python
""" Python Character Mapping Codec for ROT13.
See http://ucsub.colorado.edu/~kominek/rot13/ for details.
Written by Marc-Andre Lemburg (<EMAIL>).
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_e... |
"""
Check that all of the certs on all service endpoints validate.
"""
import unittest
from tests.integration import ServiceCertVerificationTest
import boto.sdb
class SDBCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest):
sdb = True
regions = boto.sdb.regions()
def sample_service_call... |
# Author Michele Mattioni
# Fri Jan 30 15:57:01 GMT 2009
#import ecell.Session as Session
#from ecell.Session import Session
try:
from mySession import Session
import ecell.ecs
import ecell.config
import ecell.emc
except ImportError, e:
print "IMPORT ERROR: Ecell not available. Run the model the `... |
from panda3d.core import Vec3,Point3,NodePath
class BaseCamera():
def __init__(self,scene):
self.scene=scene
base.disableMouse()
self.scene.Base.taskMgr.add(self.execute,"CameraAI",priority=128)
def execute(self,t):
pass
class ThirdPersonCamera(BaseCamera):
def __init__(se... |
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
# ------------------------------------------------------------------
# Helper Functions
def id_func(x):
if isinstance(x, tuple):
assert len(x) == 2
return x[0].__name__ + "-" + str(x[1])
else:
return x.... |
import logging
import datetime
from pylons import request, response, session, tmpl_context as c
from zkpylons.lib.helpers import redirect_to
from pylons.decorators import validate
from pylons.decorators.rest import dispatch_on
from pylons.decorators import jsonify
from formencode import validators, htmlfill, ForEach,... |
from __future__ import unicode_literals
from guessit import Guess
from guessit.transfo import SingleNodeGuesser
from guessit.language import search_language
import logging
log = logging.getLogger(__name__)
def guess_language(string, node, skip=None):
if skip:
relative_skip = []
for entry in skip:... |
# -*- coding: utf-8 -*-
# This module is based on the excellent work by Adam Bartoš who
# provided a lot of what went into the implementation here in
# the discussion to issue1602 in the Python bug tracker.
#
# There are some general differences in regards to how this works
# compared to the original patches as we do n... |
# -*- coding: utf-8 -*-
__author__ = 'Sal Aguinaga'
__license__ = "GPL"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
import shelve
import numpy as np
import pandas as pd
import networkx as nx
import math
import argparse
import os
import sa_net_metrics as snm
import matplotlib
import itertools
import pprint as pp
matp... |
from twisted.internet import reactor, error
def listen_tcp(portrange, host, factory):
"""Like reactor.listenTCP but tries different ports in a range."""
assert len(portrange) <= 2, "invalid portrange: %s" % portrange
if not hasattr(portrange, '__iter__'):
return reactor.listenTCP(portrange, factory... |
'''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program i... |
from distutils.command.install_lib import install_lib as _install_lib
import os
class install_lib(_install_lib):
"""Don't add compiled flags to filenames of non-Python files"""
def _bytecode_filenames (self, py_filenames):
bytecode_files = []
for py_file in py_filenames:
if not py_... |
#!/usr/bin/env python
from __future__ import print_function, division
import sys
from abstractclass_unittest_dyadic import Abstractclass_Unittest_Dyadic
class RCC3_Test(Abstractclass_Unittest_Dyadic):
def __init__(self, *args):
super(RCC3_Test, self).__init__(*args)
self._unique_id = "rcc3"
... |
from collections import defaultdict
from django.contrib.gis import forms, gdal
from django.contrib.gis.db.models.lookups import (
RasterBandTransform, gis_lookups,
)
from django.contrib.gis.db.models.proxy import SpatialProxy
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geometry.... |
#! /usr/bin/env python
# This script is intended to load a JSON dict containing resistotypes,
# a list of comids and a list of drugs of interest. It will return a column for each drug,
# Where 1 = R, 0 S, 0 unknown.
import argparse
import json
import csv
import os
parser = argparse.ArgumentParser(description='''load a... |
"""
Search related key bindings.
"""
from prompt_toolkit import search
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition, control_is_searchable, is_searching
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from ..key_bindings import key_binding
__al... |
"""Classes and methods to create and manage Announcements."""
__author__ = 'Saifu Angto (<EMAIL>)'
import datetime
import urllib
from controllers.utils import BaseHandler
from controllers.utils import BaseRESTHandler
from controllers.utils import ReflectiveRequestHandler
from controllers.utils import XsrfTokenManag... |
import sqlalchemy as sa
from ceilometer.storage.sqlalchemy import migration
from ceilometer.storage.sqlalchemy import models
def _convert_data_type(table, col, from_t, to_t, pk_attr='id', index=False):
temp_col_n = 'convert_data_type_temp_col'
# Override column we're going to convert with from_t, since the t... |
#!/usr/bin/env python
# encoding: utf-8
"""
The Play management
"""
import datetime
from mongokit import Document, DocumentMigration
class PlayMigration(DocumentMigration):
"""A DocumentMigration for the Play class"""
def __init__(self, *args):
DocumentMigration.__init__(self, *args)
def ... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
from mod import dispatch_module_hook
urlpatterns = []
dispatch_module_hook("www_url_hook", urlpatterns=urlpatterns)
urlpatterns += [
url("^login/$",
auth_views.LoginView.as_view(template_name="login.ht... |
from . import ir_exports_line |
import sys
import os.path
import fnmatch
import cv2
import numpy as np
import face
import shutil
from picamera import PiCamera
from picamera.array import PiRGBArray
import time
TRAINING_FILE='train_LBPH.xml'
BASE_PATH="training/negative"
cascadePath = "haarcascade_frontalface_alt.xml"
LOOKUP_FILE='lookup_table.tx... |
""" Starting point for DEM retrieval utilities.
"""
from math import pi, sin, cos
from os import unlink, close
from itertools import product
from tempfile import mkstemp
import NED10m, NED100m, NED1km, SRTM1, SRTM3
from ModestMaps.Core import Coordinate
from TileStache.Geography import SphericalMercator
from TileStac... |
# -*- coding:utf-8 -*-
'''
Author: Bu Kun
E-mail: <EMAIL>
CopyRight: http://www.yunsuan.org
'''
import time
import tornado.escape
import config
import peewee
import datetime
from torlite.model.core_tab import CabPost2Catalog
from torlite.core import tools
from torlite.model.core_tab import CabPost
class MPost():
... |
DEFAULT_WEB_CONTENTS_TIMEOUT = 60
# TODO(achuith, dtu, nduca): Add unit tests specifically for WebContents,
# independent of Tab.
class WebContents(object):
"""Represents web contents in the browser"""
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backend
def __del__(self):
... |
#!/usr/bin/env python
# To run this script, first make webdocs in the toplevel of the checkout. This will generate all
# rst files from their sources. Then run this script ./docs/bin/find-plugin-refs.py
#
# No output means that there are no longer any bare module and plugin names referenced via :ref:
#
# For my list... |
# -*- coding: utf-8 -*-
"""
pygments.scanner
~~~~~~~~~~~~~~~~
This library implements a regex based scanner. Some languages
like Pascal are easy to parse but have some keywords that
depend on the context. Because of this it's impossible to lex
that just by using a regular expression lexer like ... |
from openerp.osv import fields, osv
class ir_default(osv.osv):
_name = 'ir.default'
_columns = {
'field_tbl': fields.char('Object',size=64),
'field_name': fields.char('Object Field',size=64),
'value': fields.char('Default Value',size=64),
'uid': fields.many2one('res.users', 'Use... |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
__noninteractive = True
class TestTextureGrid(unittest.TestCase):
def set_grid_image(self, itemwidth, itemheight, rows, cols, r... |
#!/usr/bin/python
import sys
import codecs
import json
DELIN = '|'
META_MARK = 'META:'
SOURCE_LANGUAGE_KEY = 'source_language'
DEFAULT_SOURCE_LANG = 'en'
# put key names in order they appear in the meta row of the pipe csv
meta_keys = [
'deck_label',
'publisher',
'id',
'timestamp',
SOURCE_LANGUAG... |
from datetime import datetime, timedelta
import random
from urlparse import urljoin
import werkzeug
from openerp.addons.base.ir.ir_mail_server import MailDeliveryException
from openerp.osv import osv, fields
from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT, ustr
from ast import literal_eval
from openerp.t... |
"""Package Index Tests
"""
import sys
import unittest
import urllib2
import pkg_resources
import httplib
import distutils.errors
import setuptools.package_index
from server import IndexServer
class TestPackageIndex(unittest.TestCase):
def test_bad_url_bad_port(self):
index = setuptools.package_index.Packa... |
# coding: utf-8
from __future__ import unicode_literals
import json
import re
from copy import deepcopy
from django.conf import settings
from django.contrib.gis.gdal import OGRGeometry
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from django.test import TestCase
from django.utils.encoding import pyt... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from entropyfw import System
from .simplemod import SimpleModule
from entropyfw.common.request import Request
__author__ = 'otger'
class SystemActions(System):
def __init__(self):
System.__init__(self)
self.add_module(SimpleModule(name='adder'))
def... |
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import asse... |
"""
Mock pynestkernel.pyx into dummy python file.
"""
import ast
import re
def has_return(ast_func):
b = False
for node in ast.walk(ast_func):
if isinstance(node, ast.Return):
b = True
return b
def convert(infile):
"""Turn cython file into python
Munge the cython file int... |
import os
import re
import time
import psutil
import requests
from glance.tests import functional
from glance.tests.utils import execute
TEST_VAR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../', 'var'))
def set_config_value(filepath, key, value):
... |
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
def define_options(parser):
# By default, ruby uses the simple timing cpu
parser.set_defaults(cpu_type="timing")
# ruby network options
parser.add_option("--topology", type="string", default="Crossbar",
hel... |
"""
Robots.txt semi-passive plugin, parses robots.txt file to generate on-screen
links and save them for later spidering and analysis
"""
from framework.utils import OWTFLogger
from framework.dependency_management.dependency_resolver import ServiceLocator
DESCRIPTION = "Normal request for robots.txt analysis"
def r... |
"""ImageNet preprocessing for ResNet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
IMAGE_SIZE = 224
CROP_PADDING = 32
def distorted_bounding_box_crop(image_bytes,
bbox,
... |
"""
Microsoft Windows Portable Executable (PE) file parser.
Informations:
- Microsoft Portable Executable and Common Object File Format Specification:
http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
Author: Victor Stinner
Creation date: 2006-08-13
"""
from lib.hachoir_parser import HachoirParser... |
'''
Copyright 2013 Cosnita Radu Viorel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute... |
from __future__ import absolute_import
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.core.exceptions import FieldError
from django.db import models, DEFAULT_DB_ALIAS
from django.db.models import signals
from django.test import TestCase
from .models import (... |
import discord
import asyncio
import logging
import sys
import time
import threading
import json
import uniirc
import uniformatter
print(sys.version)
print(discord.__version__)
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8',... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import time
import os
from time import sleep
import constants as const
import loginView
import helpGuideView
import filesView
from appium import webdriver
def getWebDriver():
wd = None
desired_caps = {}
desired_caps['appium-version'] = const.K_APPIUM_VER
d... |
import csv
import MySQLdb
import getpass
import traceback
mydb = MySQLdb.connect(host='sql.mit.edu',
user='amcdunn',
passwd=getpass.getpass("Password for sql.mit.edu:"),
db='amcdunn+LL_dictionary')
cursor = mydb.cursor()
test_csv_path = "reload_test.csv"
num_header_rows = 3
tbl_name = "reload_test"
creat... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
try:
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = Fal... |
"""
Code writers and formatters. Subclass CodeWriter to suit the needs of
a certain code generator backend.
"""
try:
from Cython.Compiler import Tempita as tempita
except ImportError:
try:
import tempita
except ImportError:
tempita = None
class CodeWriter(object):
"""
Write code as... |
"""
Main program for the child process run by
L{twisted.test.test_stdio.StandardInputOutputTestCase.test_producer} to test
that process transports implement IProducer properly.
"""
import sys, _preamble
from twisted.internet import stdio, protocol
from twisted.python import log, reflect
class ProducerChild(protocol.... |
r"""
*****************************
espressopp.FixedQuadrupleList
*****************************
.. function:: espressopp.FixedQuadrupleList(storage)
:param storage:
:type storage:
.. function:: espressopp.FixedQuadrupleList.add(pid1, pid2, pid3, pid4)
:param pid1:
:param pid2:
:param pid3:
:param p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.