content string |
|---|
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack im... |
"""Fixer that changes map(F, ...) into list(map(F, ...)) unless there
exists a 'from future_builtins import map' statement in the top-level
namespace.
As a special case, map(None, X) is changed into list(X). (This is
necessary because the semantics are changed in this case -- the new
map(None, X) is equivalent to [(x... |
from bot_tests import BotTests
class ValidPostTests(BotTests):
def test_two_column_works(self):
resp = self.app.post_json('/', {
"data": [
[1,2,3,4,6,7,8,9],
[2,4,6,8,10,12,13,15],
]
})
self.assertEqual(resp.status_int, 200)
... |
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from django_elasticsearch.models import EsIndexable
from django_elasticsearch.serializers import EsJsonSerializer
class TestSerializer(EsJsonSerializer):
# Note: i want this field to be null instead of u''
... |
"""Testing extensions.
this module is designed to work as a testing-framework-agnostic library,
so that we can continue to support nose and also begin adding new functionality
via py.test.
"""
from __future__ import absolute_import
try:
# unitttest has a SkipTest also but pytest doesn't
# honor it unless nos... |
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import ... |
# -*- coding: utf-8 -*-
"""
flaskext_compat
~~~~~~~~~~~~~~~
Implements the ``flask.ext`` virtual package for versions of Flask
older than 0.7. This module is a noop if Flask 0.8 was detected.
Usage::
import flaskext_compat
flaskext_compat.activate()
from flask.ext import ... |
# -*- coding: utf-8 -*-
import lxml.html
import re
from functions import goUrl
class UrlHead:
_marvinModule = True
public = ['urlhead']
def urlhead():
None
def _urlhead(self,message):
if 'http://' or 'https://' in message.text:
try:
foo = re.findall(r'... |
import logging
from typing import Any, Dict
# An example discovery class which would could be extended to register which
# the started service' HTTP endpoints are.
class DummyRegistry(object):
http_endpoints: Dict = {}
@classmethod
async def add_http_endpoint(cls, service: Any, host: str, port: int, meth... |
import datetime
import unittest
from search.ql import Query, Q, GeoQueryArguments
from search.fields import TextField, GeoField, DateField
from search.indexes import DocumentModel
class FakeDocument(DocumentModel):
foo = TextField()
bar = DateField()
class FakeGeoDocument(DocumentModel):
my_loc = GeoFi... |
import unittest
import pydoop
from pydoop.pipes import InputSplit
example_input_splits = [
('/hdfs://localhost:9000/user/zag/in-dir/FGCS-1.ps\x00\x00\x00\x00\x00'
'\x08h(\x00\x00\x00\x00\x00\x08h\x05',
'hdfs://localhost:9000/user/zag/in-dir/FGCS-1.ps', 550952, 550917),
('/hdfs://localhost:9000/user/... |
from ctypes import c_uint
from django.contrib.gis.geos.error import GEOSException
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.geos import prototypes as capi
class Point(GEOSGeometry):
_minlength = 2
_maxlength = 3
def __init__(self, x, y=None, z=None, srid=None):
... |
"""Convert a argparse parser to option directives.
Inspired by sphinxcontrib.autoprogram but with a few differences:
- Instead of relying on private argparse structures uses hooking
to extract information from a argparse parser.
- Contains some simple pre-processing on the help messages to make
the Sphinx versio... |
block=False# function call to the transformation functions of relevance for the hpsModel
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import get_window
import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../models/'))
sys.path.append(os.path.join(os.path.di... |
import CoolProp
from CoolProp.CoolProp import PropsSI
from CoolProp.CoolProp import set_reference_state
print("CoolProp version %s" % CoolProp.__version__)
print("CoolProp revision %s" % CoolProp.__gitrevision__)
REF = 'R134a'
T0 = 273.15
RefState = 'IIR'
set_reference_state(REF, RefState)
print(REF, RefState)
print... |
"""
A Django settings file for use on AWS while running
database migrations, since we don't want to normally run the
LMS with enough privileges to modify the database schema.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=... |
from __future__ import with_statement
import textwrap
import os
import sys
import pytest
from os.path import join, normpath
from tempfile import mkdtemp
from mock import patch
from tests.lib import assert_all_changes, pyversion
from tests.lib.local_repos import local_repo, local_checkout
from pip.utils import rmtree
... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2016 (ita)
# Ralf Habacker, 2006 (rh)
# Yinon Ehrlich, 2009
# Michael Kuhn, 2009
from waflib.Tools import ccroot, ar
from waflib.Configure import conf
@conf
def find_xlcxx(conf):
"""
Detects the Aix C++ compiler
"""
cxx = conf.find_program(['xlc++_r', 'x... |
from __future__ import unicode_literals
from datetime import timedelta
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.contrib.auth.models import AbstractUser as _AbstractUser, UserManager as _... |
# -*- coding: utf-8 -*-
'''
Funimation|Now Add-on
Copyright (C) 2016 Funimation|Now
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 yo... |
"""Utilities for dealing with Tensors.
## Miscellaneous Utility Functions
@@constant_value
@@make_tensor_proto
@@make_ndarray
@@ops_used_by_graph_def
@@stripped_op_list_for_graph
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unuse... |
#!/usr/bin/python
import numpy as np
from scipy.sparse import csr_matrix
def numba_jit_if_available():
try:
from numba import jit
return jit
except ImportError:
return lambda f: f
#----------------------------------------------------------------------------
# Assemble matrix for Poiss... |
# pylint: skip-file
class ManageNodeException(Exception):
''' manage-node exception class '''
pass
class ManageNodeConfig(OpenShiftCLIConfig):
''' ManageNodeConfig is a DTO for the manage-node command.'''
def __init__(self, kubeconfig, node_options):
super(ManageNodeConfig, self).__init__(None... |
"""Python wrapper for input_pipeline_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
from tensorflow.contrib.input_pipeline.ops import gen_input_pipeline_ops
from tensorflow.contrib.util import loader
from tensorflow.python.framework i... |
#!/usr/bin/env python
class RoiRecord(object):
"""Represent one record in a ROI file."""
def __init__(self, ref, start_pos, end_pos, region_name, region_length,
strand, max_count, data, points):
"""Initialize RoiRecord."""
self.ref = ref
self.start_pos = start_pos
... |
import uuid
from django.db import models
from django.contrib.auth.models import User
STATE_CODE_CHOICES = (
('AL','Alabama'),
('AK','Alaska'),
('CO','Colorado'),
('CT','Connecticut'),
('DE','Delaware'),
('FL','Florida'),
('GA','Georgia'),
('LA','Lousiana'),
('MA','Massachusetts'),
('ME','Maine'),
('MI','Mic... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleParserError
from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.become import Become
from ansible.playbook.conditional impo... |
import time
from openerp.osv import fields, osv
from openerp.tools import float_compare
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class account_cashbox_line(osv.osv):
""" Cash Box Details """
_name = 'account.cashbox.line'
_description = 'CashBox Line'
_rec_... |
__version__ = "0.2"
import re
import Image, ImageFile
#
# --------------------------------------------------------------------
field = re.compile(r"([a-z]*) ([^ \r\n]*)")
##
# Image plugin for IM Tools images.
class ImtImageFile(ImageFile.ImageFile):
format = "IMT"
format_description = "IM Tools"
de... |
''' instead of allocating a new one.
required: false
default: false
version_added: "1.6"
extends_documentation_fragment: aws
author: "Lorin Hochstein (@lorin) <<EMAIL>>"
notes:
- This module will return C(public_ip) on success, which will contain the
public IP address associated with the instance.
... |
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... |
"""
This file contains everything needed to send and receive JSON requests.
"""
from django.utils.functional import Promise
from django.utils import simplejson
class JSMessage(object):
"""
The JSMessages class is used to pass JSON messages to client JavaScripts.
Use this as a vessel for JSON stuff instead ... |
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.glacier import GlacierHook
from airflow.utils.decorators import apply_defaults
class GlacierCreateJobOperator(BaseOperator):
"""
Initiate an Amazon Glacier inventory-retrieval job
.. seealso::
For more information on ... |
"""
__init__.py
Created by Shawn Douglas on 2011-01-23.
""" |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
lut = vtk.vtkLookupTable()
lut.SetHueRange(0.6, 0)
lut.SetSaturationRange(1.0, 0)
lut.SetValueRange(0.5, 1.0)
# Read the data: a height field results
demReader = vtk.vtkDEMReader()
d... |
import logging
import os
import sys
from optparse import OptionParser, OptionGroup
from gntp.notifier import GrowlNotifier
from gntp.shim import RawConfigParser
from gntp.version import __version__
DEFAULT_CONFIG = os.path.expanduser('~/.gntp')
config = RawConfigParser({
'hostname': 'localhost',
'password': None,
... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
import os
import sys
import shutil as module
import xml.sax as package
correct_mod = os.path.join(sys.prefix, 'shutil.pyc')
correct_pkg = os.path.join(sys.prefix, 'xml', 'sax', '__init__.pyc')
# Print.
print(' mod.__file__: %s' % module.__file__)
print(' mod.__file__: %s' % correct_mod)
print(' pkg.__file__: %s... |
"""
Anaconda McCabe
"""
import ast
from .mccabe import McCabeChecker
class AnacondaMcCabe(object):
"""Wrapper object around McCabe python script
"""
checker = McCabeChecker
def __init__(self, code, filename):
self.code = code
self.filename = filename
@property
def tree(sel... |
import os
import shutil
import tarfile
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[]]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
class basicTest(... |
"""
homeassistant.components.device_tracker.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform for the device tracker.
device_tracker:
platform: demo
"""
import random
from homeassistant.components.device_tracker import DOMAIN
def setup_scanner(hass, config, see):
""" Set up a demo tracker. """
... |
from osv import osv, fields
from tools.translate import _
from openbase.openbase_core import OpenbaseCore
#class account_analytic_account(OpenbaseCore):
# _inherit = "account.analytic.account"
# _name = "account.analytic.account"
#
# _columns = {
# 'code_antenne':fields.char('Antenne Code', size=16... |
from setuptools import find_packages, setup
VERSION = "4.0.0"
LONG_DESCRIPTION = """
.. image:: http://pinaxproject.com/pinax-design/patches/pinax-announcements.svg
:target: https://pypi.python.org/pypi/pinax-announcements/
===================
Pinax Announcements
===================
.. image:: https://img.shield... |
#!/usr/bin/env python
"""
@package mi.core.driver_scheduler Event Scheduler used in drivers
@file mi/core/driver_scheduler.py
@author Bill French
@brief Provides task/event scheduling for drivers
uses the PolledScheduler and provides a common, simplified interface
for instrument and platform drivers.
The scheduler is... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'Y년 n월 j일'
TIME_FORMAT = 'A g:i:s'
DATETIME_FORMAT = 'Y년 n월 j일 g:i:s A'
YEAR_MONTH_FORMAT = 'Y년 F월'
MONTH_DAY_FORMAT = 'F월 j일'
SHORT_DA... |
#!/usr/bin/env python
import fnmatch
import os
import sys
from lib.util import execute
IGNORE_FILES = [
os.path.join('atom', 'app', 'atom_main.cc'),
os.path.join('atom', 'browser', 'mac', 'atom_application.h'),
os.path.join('atom', 'browser', 'mac', 'atom_application_delegate.h'),
os.path.join('atom', 'brows... |
"""
Helper functions that convert strftime formats into more readable representations.
"""
from rest_framework import ISO_8601
def datetime_formats(formats):
format = ', '.join(formats).replace(
ISO_8601,
'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
)
return humanize_strptime(format)
... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, comma_or, nowdate, getdate
from frappe import _
from frappe.model.document import Document
def validate_status(status, options):
if status not in options:
frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
statu... |
"""
Test plot of time coord with non-gregorian calendar.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
... |
import re
import socket
import time
def RspChecksum(data):
checksum = 0
for char in data:
checksum = (checksum + ord(char)) % 0x100
return checksum
class GdbRspConnection(object):
def __init__(self, addr):
self._socket = self._Connect(addr)
def _Connect(self, addr):
# We have to poll because... |
import math
from cornice import Service
from pyramid.exceptions import HTTPNotFound
from sqlalchemy import func, distinct
from sqlalchemy.sql import or_
from bodhi import log
from bodhi.models import Build, BuildrootOverride, Package, Release, User
import bodhi.schemas
import bodhi.services.errors
from bodhi.validat... |
import numpy as np
# XXX we should be testing the public API here
from sklearn.utils.linear_assignment_ import _hungarian
def test_hungarian():
matrices = [
# Square
([[400, 150, 400],
[400, 450, 600],
[300, 225, 300]],
850 # expected cost
),
# Rect... |
import pipes
def update_package_db(module, opkg_path):
""" Updates packages list. """
rc, out, err = module.run_command("%s update" % opkg_path)
if rc != 0:
module.fail_json(msg="could not update package db")
def query_package(module, opkg_path, name, state="present"):
""" Returns whether a... |
import json
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.defaultfilters import register # noqa
from django.utils import html
from django.utils import safestring
import six
import six.moves.urllib.parse as urlparse
from openstack_dashboard.api impor... |
import argparse
import os
import time
import math
import logging
import copy
import netaddr
import boto3
import namesgenerator
import paramiko
from scp import SCPClient
import requests
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', ... |
# You want to be able to access the largest element in a stack.
# You've already implemented this Stack class:
class Stack:
# initialize an empty list
def __init__(self):
self.items = []
# push a new item to the last index
def push(self, item):
self.items.append(item)
# remove th... |
"""
This module include functions and classes for dealing with multiple layouts in
Anaconda. It wraps the libxklavier functionality to protect Anaconda from
dealing with its "nice" API that looks like a Lisp-influenced "good old C" and
also systemd-localed functionality.
It provides a XklWrapper class with several met... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
try:
from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse... |
"""Unary operations on graphs"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = """\n""".join(['Aric Hagberg <<EMAIL>>',
'Pieter Swart (<EMAIL>)',
... |
# -*- coding: utf-8 -*-
import re
from module.PyFile import PyFile
from module.plugins.internal.Addon import Addon
class SkipRev(Addon):
__name__ = "SkipRev"
__type__ = "hook"
__version__ = "0.37"
__status__ = "testing"
__config__ = [("activated", "bool" , "Activated" ... |
"""Supports checking WebKit style in cmake files.(.cmake, CMakeLists.txt)"""
import re
from common import TabChecker
class CMakeChecker(object):
"""Processes CMake lines for checking style."""
# NO_SPACE_CMDS list are based on commands section of CMake document.
# Now it is generated from
# http:/... |
import ddt
import importlib
import os
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from cloudbaseinit.metadata.services import base
from cloudbaseinit.models import network as nm
from cloudbaseinit.tests import testutils
from cloudbaseinit.utils import serialization
MODUL... |
from inspect import getmembers, isclass, isfunction
from types import FunctionType, MethodType
from json import JSONEncoder
try:
from collections import OrderedDict # must be python 2.7
except ImportError:
from ordereddict import OrderedDict # must be python 2.6
from .search_command_internals import Configu... |
"""Utilities for comparing files and directories.
Classes:
dircmp
Functions:
cmp(f1, f2, shallow=1) -> int
cmpfiles(a, b, common) -> ([], [], [])
"""
import os
import stat
from itertools import ifilter, ifilterfalse, imap, izip
__all__ = ["cmp","dircmp","cmpfiles"]
_cache = {}
BUFSIZE=8*1024
def cmp(... |
import base64
import os
import random
import sys
import time
from datetime import datetime, timedelta
try:
import cPickle as pickle
except ImportError:
import pickle
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.utils.hashcompat import md5_constructor
# Us... |
from datetime import datetime
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect
from django.contrib import messages
from django.http import Http404, HttpResponseForbidden
from django.template.response import TemplateResponse
from reversion import revision
from reversi... |
import logging
from ryu.services.protocols.bgp.operator.command import Command
from ryu.services.protocols.bgp.operator.command import CommandsResponse
from ryu.services.protocols.bgp.operator.command import STATUS_OK
from ryu.services.protocols.bgp.operator.command import STATUS_ERROR
from ryu.services.protocols.bgp.... |
"""
Tutorial: HTTP errors
HTTPError is used to return an error response to the client.
CherryPy has lots of options regarding how such errors are
logged, displayed, and formatted.
"""
import os
localDir = os.path.dirname(__file__)
curpath = os.path.normpath(os.path.join(os.getcwd(), localDir))
import cherrypy
cl... |
import sys, os
# Template used then the program is a GUI program
WINMAINTEMPLATE = """
#include <windows.h>
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // pointer to command line
int nCmd... |
#!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <EMAIL>'
__docformat__ = 'restructuredtext en'
'''
Read metadata from LRX files
'''
import struct
from zlib import decompress
from lxml import etree
from calibre.ebooks.metadata import MetaInformation, string_to_authors
def _read(f, ... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Descriptor support for NIPY.
Utilities to support special Python descriptors [1,2], in particular the use of
a useful pattern for properties we call 'one time properties'. These are
object attributes w... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/krl1to5/Work/FULL/Sequence-ToolKit/2016/resources/ui/dialogs/about/credits.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui... |
"""abydos.distance._rogot_goldberg.
Rogot & Goldberg similarity
"""
from typing import Any, Counter as TCounter, Optional, Sequence, Set, Union
from ._token_distance import _TokenDistance
from ..tokenizer import _Tokenizer
__all__ = ['RogotGoldberg']
class RogotGoldberg(_TokenDistance):
r"""Rogot & Goldberg s... |
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from bak.projects.models import Project
from bak.actions.dump_db import dump_database
from bak.actions.dump_directory import rsync_directory
from bak.actions.exceptions import ActionError
class Command(BaseCommand... |
import time
from six.moves.urllib.parse import urlencode, urlparse
from wptserve.utils import isomorphic_decode, isomorphic_encode
def main(request, response):
stashed_data = {b'count': 0, b'preflight': b"0"}
status = 302
headers = [(b"Content-Type", b"text/plain"),
(b"Cache-Control", b"no... |
from opencog.atomspace import types, TruthValue
import formulas
from pln.rule import Rule
# Todo:
# It may be better to use SubsetLinks instead of ContextLinks, or at
# least implicitly convert them.
# (Context C x).tv = (Subset C x).tv
# (Context C: Subset x y).tv = (Subset (x AND C) (y AND C))
# DeductionRule prod... |
"""
This configuration parser takes a platform argument and uses that for the sections of the config file
i.e. Production, Development, Testing
All you need to do is use the corresponding get methods for the data you need. The platform is automatically used
where applicable.
"""
from __future__ import absolute_import
... |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import logging
from sleekxmpp.stanza import Iq, StreamFeatures
from sleekxmpp.xmlstream import register_stanza_plugin
from sleekxmpp.plugins im... |
import sys
import os
from io import StringIO
import textwrap
from distutils.core import Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
from distutils.tests.support import (TempdirManager, LoggingSilencer,
copy_xxmodule_c, fixup_build_... |
#!/usr/bin/env python3
import sys
import numpy as np
from example import AmiciExample
class ExampleCalvetti(AmiciExample):
def __init__(self):
AmiciExample.__init__( self )
self.numX = 6
self.numP = 0
self.numK = 6
self.modelOptions['theta'] = []
self.modelOption... |
# -*- coding: utf-8 -*-
import os
assert sys.version_info >= (2,5), "Need at least Python 2.5."
if sys.version_info < (3,0):
from shutilwhich import which
else:
from shutil import which
### Tests ###########################################################
def exists(p):
''' Returns true if path p exists.
... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.img
~~~~~~~~~~~~~~~~~~~~~~~
Formatter for Pixmap output.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
from pygments.formatter import Formatter
from pygments.util import ge... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 23 12:12:31 2014
@author: anuj
"""
print(__doc__)
from time import time
import numpy as np
import pylab as pl
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.prep... |
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
page_set=page_set,
credentials_path='data/cre... |
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import UART as OriginalUART
# from ble import uart
from ble.uart import UART
from ble.readdata import Device
import time
import atexit
import logging
log = logging.getLogger(__name__)
class App (object):
""" A high level application object.
Any applic... |
"""
sentry.rules.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
Rules apply either before an event gets stored, or immediately after.
Basic actions:
- I want to get notified when [X]
- I want to group events when [X]
- ... |
class Neuron:
'Represents a neuron'
currentVal = 0
threshold = 1
connections = []
identity = 0
def displayVal(self):
print(self.identity,":",self.currentVal)
for c in self.connections:
print(self.identity," connected to ",c.end.identity)
def addSynapse(self,desti... |
import unittest
from StretchedExpFTTestHelper import isregistered, do_fit
class PrimStretchedExpFTTest(unittest.TestCase):
def testRegistered(self):
self.assertTrue(*isregistered('PrimStretchedExpFT'))
def testGaussian(self):
""" Test PrimStretchedExpFT against the binned-integrated of
... |
#!/usr/bin/env python
import os, util2, gen_settingsstructs, trans_langs
"""
TODO:
* for gen_langs_html, show languages that don't have enough translations
in a separate table
"""
g_version = util2.get_sumatrapdf_version()
html_tmpl = """\
<!doctype html>
<html>
<head>
<meta http-equiv="Conten... |
import json
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.utils.text import normalize_newlines
from ..models import LogRecord
from ..settings import EXTRA_DATA_INDENT, PAGINATOR_RANGE
register = template.Library()
@reg... |
import json
try:
import pymongo
MONGO = True
except ImportError:
MONGO = False
from bson.objectid import ObjectId
from gridfs import GridFS
from tanner import config
class Reporting():
def __init__(self):
if MONGO:
# Create the connection
mongo_uri = config.TannerConfi... |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
window = 0
width, height = 500, 400
theta = [0.0]
sign = [1.0]
xMin = [-10.0]
xMax = [10.0]
yMin = [-10.0]
yMax= [10.0]
def initialization():
glClearColor(0.0,0.0,0.0,0.0)
glMatrixMode(GL_... |
import os
import textwrap
from xml.etree import ElementTree
from fontTools.ttLib import TTFont, newTable
from fontTools.misc.psCharStrings import T2CharString
from fontTools.ttLib.tables.otTables import GSUB,\
ScriptList, ScriptRecord, Script, DefaultLangSys,\
FeatureList, FeatureRecord, Feature,\
LookupLis... |
# coding=utf-8
"""
Insert the collected values into a mysql table
"""
from Handler import Handler
import MySQLdb
class MySQLHandler(Handler):
"""
Implements the abstract Handler class, sending data to a mysql table
"""
conn = None
def __init__(self, config=None):
"""
Create a ne... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QAction
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.quickview import Quickview
fr... |
import unittest
from test import support
def funcattrs(**kwds):
def decorate(func):
func.__dict__.update(kwds)
return func
return decorate
class MiscDecorators (object):
@staticmethod
def author(name):
def decorate(func):
func.__dict__['author'] = name
r... |
"""
Copyright 2008-2011 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) any l... |
from sympy.core import Rational
from sympy.core.compatibility import range
from .cartan_type import Standard_Cartan
from sympy.matrices import eye
class TypeE(Standard_Cartan):
def __new__(cls, n):
if n < 6 or n > 8:
raise ValueError("Invalid value of n")
return Standard_Cartan.__new_... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 14 02:04:12 2014
@author: deokwoo
* Description
- This file defines constant values shared among python modules.
- Should be included all python modules first.
"""
###############################################################################
# Constant global variab... |
"""
Classes to represent the default SQL aggregate functions
"""
import copy
import warnings
from django.db.models.fields import FloatField, IntegerField
from django.db.models.query_utils import RegisterLookupMixin
from django.utils.deprecation import RemovedInDjango110Warning
from django.utils.functional import cache... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.