content string |
|---|
"""gp_unix -- an interface to gnuplot used for unix platforms.
This file implements a low-level interface to a gnuplot program for a
unix platform (actually it is used for any non-Windows, non-Mac
system). This file should be imported through gp.py, which in turn
should be imported via 'import Gnuplot' rather than th... |
from datetime import date, timedelta
from django.template.defaultfilters import add
from django.test import SimpleTestCase
from ..utils import setup
class AddTests(SimpleTestCase):
"""
Tests for #11687 and #16676
"""
@setup({'add01': '{{ i|add:"5" }}'})
def test_add01(self):
output = se... |
from tempest import config # noqa
from tempest import test # noqa
from manila_tempest_tests import clients_share as clients
from manila_tempest_tests.tests.api import base
CONF = config.CONF
class SharesAdminQuotasTest(base.BaseSharesAdminTest):
@classmethod
def resource_setup(cls):
cls.os = clie... |
"""Embeds Chrome user data files in C++ code."""
import base64
import optparse
import os
import StringIO
import sys
import zipfile
import cpp_source
def main():
parser = optparse.OptionParser()
parser.add_option(
'', '--directory', type='string', default='.',
help='Path to directory where the cc/h ... |
import pytest
from pytest_django.lazy_django import get_django_version
from pytest_django_test.db_helpers import (
db_exists,
drop_database,
mark_database,
mark_exists,
skip_if_sqlite_in_memory,
)
def test_db_reuse_simple(django_testdir):
"A test for all backends to check that `--reuse-db` wo... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import numpy
import pmagpy.pmag as pmag
def main():
"""
NAME
di_eq.py
DESCRIPTION
converts dec, inc pairs to x,y pairs using equal area projection
NB: do only upper or lower hemisphere at a time: does not dist... |
import os
from django import forms, http
from django.conf import settings
from django.contrib.formtools import preview, wizard, utils
from django.test import TestCase
from django.utils import unittest
success_string = "Done was called!"
class TestFormPreview(preview.FormPreview):
def get_context(self, request, ... |
from openerp.osv import orm, fields
class AccountPeriod(orm.Model):
_inherit = 'account.period'
_columns = {
'journal_period_ids': fields.one2many('account.journal.period',
'period_id', 'Journal states'),
}
def add_all_journals(self, cr, uid, ids,... |
#!/usr/bin/env python3
import sys
import re
def entry_is_device(entry):
first_arg_type = entry[1][1:].split(' ')[0]
device_types = ['VkDevice', 'VkCommandBuffer', 'VkQueue']
return (first_arg_type in device_types) and (entry[0] != 'vkGetDeviceProcAddr')
def main():
pure_entrypoints = []
entrypoin... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible.modules.unarchive import ZipArchive, TgzArchive
class AnsibleModuleExit(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class ExitJson(Ansib... |
"""Functions to parse datetime objects."""
# We're using regular expressions rather than time.strptime because:
# - They provide both validation and parsing.
# - They're more flexible for datetimes.
# - The date/datetime/time constructors produce friendlier error messages.
import datetime
import re
from django.utils... |
#!/usr/bin/env python
"""Manage site and releases.
Usage:
manage.py release [<branch>]
manage.py site
"""
from __future__ import print_function
import datetime, docopt, errno, fileinput, json, os
import re, requests, shutil, sys, tempfile
from contextlib import contextmanager
from distutils.version import LooseV... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode
class ContentTypeManager(models.Manager):
# Cache to avoid re-looking up ContentType objects all over the place.
# This cache is shared by all the get_for_* methods.
_cache ... |
import unittest
import rugby_rankings.ratings_input
class TestRatingsInput(unittest.TestCase):
def test_construct(self):
inputObj = rugby_rankings.ratings_input.RatingsInput(0.0, 0.0, 0, 0)
self.assertTrue(
isinstance(inputObj, rugby_rankings.ratings_input.RatingsInput)
)
... |
import base64
import json
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
log = CPLog(__name__)
autoload = 'Pushbullet'
class Pushbullet(Notifica... |
from __future__ import print_function
import sys
from operator import add
from pyspark.sql import SparkSession
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: wordcount <file>", file=sys.stderr)
sys.exit(-1)
spark = SparkSession\
.builder\
.app... |
# coding=utf-8
"""Example usage of custom parameters."""
import sys
from safe.definitions.constants import INASAFE_TEST
from safe.test.utilities import get_qgis_app
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)
from qgis.PyQt.QtWidgets import QApplication, QWidget, QGridLayout # NOQA
from ... |
from gnuradio import gr, gr_unittest, filter, blocks
import math
def sig_source_f(samp_rate, freq, amp, N):
t = map(lambda x: float(x)/samp_rate, xrange(N))
y = map(lambda x: math.sin(2.*math.pi*freq*x), t)
return y
def sig_source_c(samp_rate, freq, amp, N):
t = map(lambda x: float(x)/samp_rate, xran... |
from xhtml2pdf.util import pisaTempFile, getFile
import logging
log = logging.getLogger("xhtml2pdf")
class pisaPDF:
def __init__(self, capacity=-1):
self.capacity = capacity
self.files = []
def addFromURI(self, url, basepath=None):
obj = getFile(url, basepath)
if obj and (n... |
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:par... |
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import messages
from horizon import tabs
from openstack_dashboard import api
from openstack_dashboard import policy
from openstack_dashboard.dashboards.project.stacks \
import api as project_api
from openstack_dashboard.dashboard... |
"""Workbook is the top-level container for all document information."""
__docformat__ = "restructuredtext en"
# Python stdlib imports
import datetime
import os
# package imports
from .worksheet import Worksheet
from .writer.dump_worksheet import DumpWorksheet, save_dump
from .writer.strings import StringTableBuilder... |
{
'name': 'Portal Gamification',
'version': '1',
'category': 'Tools',
'complexity': 'easy',
'description': """
This module adds security rules for gamification to allow portal users to participate to challenges
=========================================================================================... |
import traceback
from openerp.osv import orm, fields
class update_child_picture_date(orm.TransientModel):
_name = 'update.child.picture.date'
def update(self, cr, uid, context=None):
count = 1
print('LAUNCH CHILD PICTURE UPDATE')
child_obj = self.pool.get('compassion.child... |
# vi: syntax=python:et:ts=4
import sys, os
from config_check_utils import backup_env, restore_env
import distutils.sysconfig
def exists():
return True
def PythonExtension(env, target, source, **kv):
return env.SharedLibrary(target, source, SHLIBPREFIX='', SHLIBSUFFIX=distutils.sysconfig.get_config_var("SO"), ... |
import sys
def is_py3():
return sys.version_info[0] == 3
if is_py3():
import xmlrpc.client as xmlrpclib
else:
import xmlrpclib |
"""Views for debugging and diagnostics"""
import pprint
import traceback
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.contrib.auth.decorators import login_required
from django.utils.html import escape
from django.views.decorators.csrf import ensure_csrf_cookie
from edxmako.shortcut... |
"""Test student engagement metrics"""
import json
import luigi
from ddt import ddt, data, unpack
from edx.analytics.tasks.student_engagement import StudentEngagementTask, SUBSECTION_VIEWED_MARKER
from edx.analytics.tasks.tests import unittest
from edx.analytics.tasks.tests.opaque_key_mixins import InitializeOpaqueKe... |
from spack import *
class Fontcacheproto(AutotoolsPackage):
"""X.org FontcacheProto protocol headers."""
homepage = "http://cgit.freedesktop.org/xorg/proto/fontcacheproto"
url = "https://www.x.org/archive/individual/proto/fontcacheproto-0.1.3.tar.gz"
version('0.1.3', '5a91ab914ffbfbc856e6fcde52... |
from pychart import *
import pychart.legend
import time
from openerp.report.misc import choice_colors
from openerp import tools
#
# Draw a graph for stocks
#
class stock_graph(object):
def __init__(self, io):
self._datas = {}
self._canvas = canvas.init(fname=io, format='pdf')
self._canvas.s... |
import os
import sys
#
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
APP_DIR=os.path.dirname(__file__)
LOG_FILE="/tmp/paloma.log" #: celery worker logfile
PID_FILE="/tmp/paloma.pid" #: celery worker PID file
PID_CAM="/tmp/paloma.pid"
NODE="celery" #: celery = default node
LOG_LEVEL="DEBU... |
"""
Purpose
The purpose of the argParseWrapper module is to create an easy way to use the native argparse module from python distribution
in order to parse command line arguments.
Description
It contains a simple wrapper class for the argparse.Action class, which adds the action attribute and a return_args me... |
'''
Default entity collection implementation
'''
import sys
import re
class BaseCollection(list):
def __init__(self, entities=None):
list.__init__(self)
if entities is not None:
self.extend(entities)
def extend(self, entities):
for e in entities:
self.append(e)
... |
"""Logging
"""
import sys
import os
import logging
from pip import backwardcompat
from pip._vendor import colorama, pkg_resources
def _color_wrap(*colors):
def wrapped(inp):
return "".join(list(colors) + [inp, colorama.Style.RESET_ALL])
return wrapped
def should_color(consumer, environ, std=(sys.s... |
from . import credit_control_emailer
from . import credit_control_marker
from . import credit_control_printer
from . import credit_control_communication
from . import credit_control_policy_changer |
"""Websocket API for mobile_app."""
import voluptuous as vol
from homeassistant.components.cloud import async_delete_cloudhook
from homeassistant.components.websocket_api import (
ActiveConnection,
async_register_command,
async_response,
error_message,
result_message,
websocket_command,
ws_... |
import os
import sys
FILTERS_MODULES = ['nova.rootwrap.compute',
'nova.rootwrap.network',
'nova.rootwrap.volume',
]
def load_filters():
"""Load filters from modules present in nova.rootwrap."""
filters = []
for modulename in FILTERS_MODULES:
... |
__all__ = ['logspace', 'linspace']
import numeric as _nx
from numeric import array
def linspace(start, stop, num=50, endpoint=True, retstep=False):
"""
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop` ].
Th... |
"""Upgrader engine."""
from __future__ import absolute_import
from datetime import datetime
import logging
import re
import sys
import warnings
from flask import current_app
from flask_registry import RegistryProxy, ImportPathRegistry
from sqlalchemy import desc
from invenio.ext.sqlalchemy import db
from .models im... |
#!/usr/bin/python
"""
Copyright 2014 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
A wrapper around the standard Python unittest library, adding features we need
for various unittests within this directory.
"""
import errno
import os
import shutil
impo... |
HAVE_FUNC=False
try:
import func.overlord.client as fc
HAVE_FUNC=True
except ImportError:
pass
import os
from ansible.callbacks import vvv
from ansible import errors
import tempfile
import shutil
class Connection(object):
''' Func-based connections '''
def __init__(self, runner, host, port, *arg... |
from oslo_config import cfg
from oslo_serialization import jsonutils
import six
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova.objects import pci_device_pool
from nova import utils
CONF = cfg.CONF
CONF.import_opt('cpu_all... |
from flask import request, session, g, redirect, url_for, abort
from . import api
from ..exceptions import ExistsError
from ..models import Category
from .main import BaseMethodView
class CategoryView(BaseMethodView):
def get(self, id=None):
if id:
instance = Category(id)
if not... |
'''
Find and delete GCE resources matching the provided --match string. Unless
--yes|-y is provided, the prompt for confirmation prior to deleting resources.
Please use caution, you can easily delete your *ENTIRE* GCE infrastructure.
'''
import os
import re
import sys
import optparse
import yaml
try:
from libclo... |
"""
This module contains classes, used internally by `pyignite` for parsing and
creating binary data.
"""
from .complex import *
from .internal import *
from .null_object import *
from .primitive import *
from .primitive_arrays import *
from .primitive_objects import *
from .standard import * |
from nir_opcodes import opcodes
from mako.template import Template
template = Template("""
#include "nir.h"
const nir_op_info nir_op_infos[nir_num_opcodes] = {
% for name, opcode in sorted(opcodes.iteritems()):
{
.name = "${name}",
.num_inputs = ${opcode.num_inputs},
.output_size = ${opcode.output_size},
... |
"""
Support for resolving command-line strings that represent different
checkers available to cred.
Examples:
- passwd:/etc/passwd
- memory:admin:asdf:user:lkj
- unix
"""
import sys
from zope.interface import Interface, Attribute
from twisted.plugin import getPlugins
from twisted.python import usage
class ICh... |
from OWWidget import *
import OWGUI
import re, os.path
from exceptions import Exception
NAME = "Save"
DESCRIPTION = "Saves data to file."
LONG_DESCRIPTION = ""
ICON = "icons/Save.svg"
PRIORITY = 90
AUTHOR = "Janez Demsar"
AUTHOR_EMAIL = "janez.demsar(@at@)fri.uni-lj.si"
INPUTS = [("Data", Orange.data.Table, "dataset",... |
import random
import time
from locust import User, TaskSet, between, constant, constant_pacing
from locust.exception import MissingWaitTimeError
from .testcases import LocustTestCase
class TestWaitTime(LocustTestCase):
def test_between(self):
class MyUser(User):
wait_time = between(3, 9)
... |
from .helper import UnitHelper
from github3.null import NullObject
import pytest
class TestNullObject(UnitHelper):
described_class = NullObject
def create_instance_of_described_class(self):
return self.described_class()
def test_returns_empty_list(self):
assert list(self.instance) == []... |
# coding: utf-8
from __future__ import absolute_import
import flask
import auth
import config
import model
import util
from main import app
twitter_config = dict(
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authorize',
base_url='https://api.twit... |
import hashlib
import math
import optparse
import os
import re
import subprocess
import sys
import time
import urllib2
try:
import json
except ImportError:
import simplejson as json
__version__ = '1.0'
EXPECTATIONS_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_CONFIG_FILE = os.path.join(EXPECTATIONS_... |
import inspect
from common import common_logging_elasticsearch_httpx
async def db_metadata_guid_from_media_guid(self, guid, db_connection=None):
await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',
message_text=... |
from django.contrib.auth import models
from django.contrib.auth.mixins import (
LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin,
)
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.test import Re... |
import os
import unittest
from checker import Checker
from processor import FileCache, Processor
ASSERT_FILE = os.path.join("..", "..", "ui", "webui", "resources", "js",
"assert.js")
CR_FILE = os.path.join("..", "..", "ui", "webui", "resources", "js", "cr.js")
UI_FILE = os.path.join("..", "..", "ui", "webui", "r... |
import base64
class Item(dict):
"""
A ``dict`` sub-class that serves as an object representation of a
SimpleDB item. An item in SDB is similar to a row in a relational
database. Items belong to a :py:class:`Domain <boto.sdb.domain.Domain>`,
which is similar to a table in a relational database.
... |
from django.conf.urls import url
from django.contrib.admindocs import views
urlpatterns = [
url('^$',
views.BaseAdminDocsView.as_view(template_name='admin_doc/index.html'),
name='django-admindocs-docroot'),
url('^bookmarklets/$',
views.BookmarkletsView.as_view(),
name='django-ad... |
from __future__ import unicode_literals
import frappe
def execute():
serialised_items = [d.name for d in frappe.get_all("Item", filters={"has_serial_no": 1})]
if not serialised_items:
return
for dt in ["Stock Entry Detail", "Purchase Receipt Item", "Purchase Invoice Item"]:
cond = ""
if dt=="Purchase Invoic... |
#!/usr/bin/env python
# File created on 09 Feb 2010
from __future__ import division
__author__ = "Justin Kuczynski"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["Justin Kuczynski"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Justin Kuczynski"
__email__ = "<EMAIL>"
from qiime... |
# -*- coding: utf-8 -*-
from cms.forms.fields import PageSelectFormField
from cms.models.pagemodel import Page
from cms.models.placeholdermodel import Placeholder
from cms.utils.placeholder import PlaceholderNoAction, validate_placeholder_name
from django.db import models
class PlaceholderField(models.ForeignKey):
... |
from __future__ import absolute_import
from __future__ import print_function
from future.utils import iteritems
import datetime
import json
import types
from twisted.internet import defer
from twisted.internet import error
from twisted.internet import reactor
from twisted.python import failure
from twisted.trial impo... |
# Input arguments: (Those with '[*]' at end are used here.)
# 2) genome : [String]: defines genome in use for project. (ex. 'Ca_a') [*]
# 3) workingDir : [String]: Directory where links in system are stored. (ex. '/home/bermanj/shared/links/) [*]
#
# Process input files:
# 1) Restriction-... |
from flumotion.component import feedcomponent
class FLVEncoder(feedcomponent.EncoderComponent):
checkTimestamp = True
checkOffset = True
def get_pipeline_string(self, properties):
return "ffmpegcolorspace ! ffenc_flv name=encoder"
def configure_pipeline(self, pipeline, properties):
e... |
# -*- coding: utf-8 -*-
"""
gshop.allegro
~~~~~~~~~~~~~~~~~~~
A lightweight wrapper around the Allegro webapi.
"""
import sys
import time
import logging
from zeep import Client
from zeep.exceptions import Fault
from requests.exceptions import ConnectionError
# from socket import error as socketError
from decimal im... |
import unittest
from yaplf.models import *
from yaplf.models.neural import *
class Test(unittest.TestCase):
"""Unit tests for models module of yaplf."""
def test_Model(self):
"""Test yaplf Model."""
from yaplf.utility.error import MSE, MaxError
from yaplf.data import LabeledExamp... |
"""distutils.bcppcompiler
Contains BorlandCCompiler, an implementation of the abstract CCompiler class
for the Borland C++ compiler.
"""
# This implementation by Lyle Johnson, based on the original msvccompiler.py
# module and using the directions originally published by Gordon Williams.
# XXX looks like there's a L... |
"""Bytecode manipulation for coverage.py"""
import opcode, types
from coverage.backward import byte_to_int
class ByteCode(object):
"""A single bytecode."""
def __init__(self):
# The offset of this bytecode in the code object.
self.offset = -1
# The opcode, defined in the `opcode` mod... |
from django.test import TestCase
from django.db.backends import BaseDatabaseWrapper
class DummyDatabaseWrapper(BaseDatabaseWrapper):
pass
class DummyObject(object):
alias = None
class DbBackendTests(TestCase):
def test_compare_db_wrapper_with_another_object(self):
wrapper = BaseDatabaseWrapper... |
import numpy as np
from astropy import units as u
from astropy.utils.decorators import format_doc
from astropy.coordinates import representation as r
from astropy.coordinates.baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
from astropy.coordinates.attributes import (TimeAttribute,
... |
__revision__ = "src/engine/SCons/Options/PackageOption.py 2014/07/05 09:42:21 garyo"
__doc__ = """Place-holder for the old SCons.Options module hierarchy
This is for backwards compatibility. The new equivalent is the Variables/
class hierarchy. These will have deprecation warnings added (some day),
and will then b... |
# URI Online Judge | 1006
# Média 2
#
# Adaptado por Neilor Tonin, URI Brasil
# Timelimit: 1
#
# Leia 3 valores, no caso, variáveis A, B e C, que são as três notas de um aluno. A seguir, calcule a média do aluno,
# sabendo que a nota A tem peso 2, a nota B tem peso 3 e a nota C tem peso 5. Considere que cada nota pode ... |
"""
Asset Management - Events: Create and update functions.
"""
__author__ = 'Edna Donoughe'
from ooiservices.app.uframe.uframe_tools import (uframe_get_asset_by_uid, get_uframe_event, uframe_put_event,
uframe_postto, uframe_create_cruise, uframe_create_calibration)
fr... |
import re
from base64 import b16encode
from collections import namedtuple
from django.contrib import messages
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import Http404, HttpResponseRedirect
from django.shortcuts... |
# This module contains abstractions for the input stream. You don't have to
# looks further, there are no pretty code.
#
# We define two classes here.
#
# Mark(source, line, column)
# It's just a record and its only use is producing nice error messages.
# Parser does not use it for any other purposes.
#
# Reader(so... |
"""
DEPRECATED since Twisted 8.0.
Utility functions for reporting bytecode frequencies to Skip Montanaro's
stat collector.
This module requires a version of Python build with DYNAMIC_EXCUTION_PROFILE,
and optionally DXPAIRS, defined to be useful.
"""
import sys, types, xmlrpclib, warnings
warnings.warn("twisted.py... |
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ActionMap import ActionMap
from Components.ConfigList import ConfigListScreen
from Components.MenuList import MenuList
from Components.Sources.StaticText import StaticText
from Components.config import config, ConfigNumber, Conf... |
data = (
'Xi ', # 0x00
'Kao ', # 0x01
'Lang ', # 0x02
'Fu ', # 0x03
'Ze ', # 0x04
'Shui ', # 0x05
'Lu ', # 0x06
'Kun ', # 0x07
'Gan ', # 0x08
'Geng ', # 0x09
'Ti ', # 0x0a
'Cheng ', # 0x0b
'Tu ', # 0x0c
'Shao ', # 0x0d
'Shui ', # 0x0e
'Ya ', # 0x0f
'Lun ', # 0x10
'Lu '... |
"""
sentry.filters
~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# Widget api is pretty ugly
from __future__ import absolute_import
from django.conf import settings as django_settings
from django.utils.datastructures import Sort... |
"""
Code for merging and munging trajectories from FAH datasets.
"""
##############################################################################
# imports
##############################################################################
from __future__ import print_function, division
import os
import glob
import tarfi... |
# -*- coding: utf-8 -*-
"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of Requests' exceptions.
"""
from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request.""... |
"""
A generic Jam-o-Drum input interface for the Jam-o-Drum that uses the OptiPAC
for both spinners and pads.
@author: U{Ben Buchwald <<EMAIL>>}
Last Updated: 2/27/2006
"""
from direct.showbase.DirectObject import DirectObject
import string, sys, md5
from pandac.PandaModules import Filename
from pandac.PandaModules i... |
from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError, SSHInvalidPortError)
from reviewboard.ssh.policy impor... |
""" CAUTION:
Running this script can take very long!
"""
from numpy import arange
from yade import pack
import pylab
# define the section shape as polygon in 2d; repeat first point at the end to close the polygon
poly=((1e-2,5e-2),(5e-2,2e-2),(7e-2,-2e-2),(1e-2,-5e-2),(1e-2,5e-2))
# show us the meridian shape
#pylab.p... |
# -*- coding: utf-8 -*-
## Very simple unit support:
## - creates variable names like 'mV' and 'kHz'
## - the value assigned to the variable corresponds to the scale prefix
## (mV = 0.001)
## - the actual units are purely cosmetic for making code clearer:
##
## x = 20*pA is identical to x = 20*1e-12
#... |
# -*- coding: utf-8 -*-
import logging
import simplejson
import os
import openerp
from openerp.addons.web.controllers.main import manifest_list, module_boot, html_template
class PointOfSaleController(openerp.addons.web.http.Controller):
_cp_path = '/pos'
@openerp.addons.web.http.httprequest
def app(self,... |
from django.db.models import Lookup, Transform
class PostgresSimpleLookup(Lookup):
def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = lhs_params + rhs_params
return '%s %s %s' % (lhs, self... |
"""Tests for extensions module."""
import unittest
import zlib
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket import common
from mod_pywebsocket import extensions
class ExtensionsTest(unittest.TestCase):
"""A unittest for non-class methods in extensions.py"""
... |
from openerp.osv import fields, osv
import time
from openerp.tools.translate import _
class res_partner(osv.osv):
""" add field to indicate default 'Communication Type' on customer invoices """
_inherit = 'res.partner'
def _get_comm_type(self, cr, uid, context=None):
res = self.pool.get('acc... |
#!/usr/bin/env python
"""
Artificial Intelligence for Humans
Volume 1: Fundamental Algorithms
Python Version
http://www.aifh.org
http://www.jeffheaton.com
Code repository:
https://github.com/jeffheaton/aifh
Copyright 2013 by Jeff Heaton
Licensed under the Apache License, Version 2... |
import sys
import numpy as np
from scipy.linalg import block_diag
from scipy.sparse import csr_matrix
from scipy.special import psi
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.decomposition._online_lda import (_dirichlet_expectation_1d,
_diri... |
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls.static import static
from Web import views as web
from GenomeViewer import views as GenomeViewer
# Config variables
import settings
urlpatterns = [
url(r'^$', web.index),
url(r'^adamGenomeViewer/(?P<chromosome>[0-9]{0,2})/... |
import unittest
from p2pool.bitcoin import getwork, data as bitcoin_data
class Test(unittest.TestCase):
def test_all(self):
cases = [
{
'target': '0000000000000000000000000000000000000000000000f2b944000000000000',
'midstate': '5982f893102dec03e374b472647c4f19b1b... |
# -*- coding: utf-8 -*-
from .structures import LookupDict
_codes = {
# Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/'... |
__all__ = ['FingerMenuWdg', 'MenuWdg', 'GearMenuWdg','Menu','MenuItem']
from pyasm.common import Common, TacticException
from pyasm.web import HtmlElement, SpanWdg, DivWdg, FloatDivWdg, WebContainer, Widget, Table
from tactic.ui.common import BaseRefreshWdg
from smart_menu_wdg import SmartMenu
class FingerMenuWdg(... |
"""Configuration system for CherryPy.
Configuration in CherryPy is implemented via dictionaries. Keys are strings
which name the mapped value, which may be of any type.
Architecture
------------
CherryPy Requests are part of an Application, which runs in a global context,
and configuration data may apply ... |
import re
import collections
class ConfigLine(object):
def __init__(self, text):
self.text = text
self.children = list()
self.parents = list()
self.raw = None
def __str__(self):
return self.raw
def __eq__(self, other):
if self.text == other.text:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pwndbg.color.theme as theme
import pwndbg.config as config
from pwndbg.color import generateColorFunction
config_int... |
"""Config Drive extension."""
from nova.api.openstack.compute.schemas import config_drive as \
schema_config_drive
from nova.api.openstack import wsgi
from nova.policies import config_drive as cd_policies
ATTRIBUTE_NAME = "config_drive"
class ConfigDriveController(w... |
import time
from shinken_test import ShinkenTest, unittest
from shinken.objects import Service
from shinken.misc.regenerator import Regenerator
class TestRegenerator(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_regenerator.cfg')
def look_for_same_values(self):
# Look at ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.