code stringlengths 1 199k |
|---|
import sys
import click
from solar.core import testing
from solar.core import resource
from solar.system_log import change
from solar.system_log import operations
from solar.system_log import data
from solar.cli.uids_history import get_uid, remember_uid, SOLARUID
@click.group()
def changes():
pass
@changes.command(... |
from __future__ import with_statement
from os.path import basename, splitext
import codecs
from robot.htmldata import HtmlFileWriter, ModelWriter, LOG, REPORT
from robot.utils import utf8open
from .jswriter import JsResultWriter, SplitLogWriter
class _LogReportWriter(object):
def __init__(self, js_model):
s... |
""" Contains the logic for `aq del cluster systemlist --hostname`. """
from aquilon.aqdb.model import SystemList
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.del_cluster_member_priority import \
CommandDelClusterMemberPriority
class CommandDelClusterSystemLis... |
from __future__ import with_statement
import argparse
import sys
import logging
import urllib, urllib2
import json
from fabric.operations import local
from fabric.api import hide
import yaml
VERSION = "0.0.1"
SERVER_FILE = ".server"
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
def get_repo_info():
wi... |
from typing import Dict, List, Optional
from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter
from ray.tune.suggest.search_generator import SearchGenerator
from ray.tune.trial import Trial
class _MockSearcher(Searcher):
def __init__(self, **kwargs):
self.live_trials = {}
self.counter ... |
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, an... |
import sys
sys.path.insert(1, "../../../")
import h2o
def binop_plus(ip,port):
# Connect to h2o
h2o.init(ip,port)
iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader_65_rows.csv"))
rows, cols = iris.dim()
iris.show()
##############################################################... |
from __future__ import print_function
from guild.actor import Actor, actor_method, process_method, late_bind
class Dog(Actor):
@actor_method # Input - triggered by data coming in
def woof(self):
print("Woof", self)
@process_method # Process - triggered each time it's run
def process(self):
... |
import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch, Mock
import re
import rdflib
from rdflib import RDF
from urllib import urlencode, u... |
ALIAS = 'tag-ports-during-bulk-creation'
IS_SHIM_EXTENSION = True
IS_STANDARD_ATTR_EXTENSION = False
NAME = 'Tag Ports During Bulk Creation'
DESCRIPTION = 'Allow to tag ports during bulk creation'
UPDATED_TIMESTAMP = '2019-12-29T19:00:00-00:00'
RESOURCE_ATTRIBUTE_MAP = {}
SUB_RESOURCE_ATTRIBUTE_MAP = {}
ACTION_MAP = {}... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
from textwrap import dedent
from pants.backend.jvm.register import build_file_aliases as register_jvm
from pants.backend.jvm.targets.exclude import Excl... |
"""
Watch a running build job and output changes to the screen.
"""
import fcntl
import os
import select
import socket
import sys
import tempfile
import termios
import time
import traceback
from rmake import errors
from rmake.build import buildjob, buildtrove
from rmake.cmdline import query
def _getUri(client):
if ... |
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "C... |
from .inventory import (
GetInventoryRequest,
Inventory,
ListInventoriesRequest,
ListInventoriesResponse,
InventoryView,
)
from .os_policy import OSPolicy
from .os_policy_assignment_reports import (
GetOSPolicyAssignmentReportRequest,
ListOSPolicyAssignmentReportsRequest,
ListOSPolicyAss... |
import pytest
import numpy as np
from test.zoo.pipeline.utils.test_utils import ZooTestCase
from zoo.chronos.detector.anomaly.ae_detector import AEDetector
class TestAEDetector(ZooTestCase):
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
def create_data(self):
... |
from __future__ import absolute_import, unicode_literals
import os
from django import VERSION as DJANGO_VERSION
from django.utils.translation import ugettext_lazy as _
USE_MODELTRANSLATION = False
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '111.222.333.444']
TIME_ZONE = 'UTC'
USE_TZ = True
LANGUAGE_CODE = "en"
LANGUAGE... |
import pyautogui, win32api, win32con, ctypes, autoit
from PIL import ImageOps, Image, ImageGrab
from numpy import *
import os
import time
import cv2
import random
from Bot import *
def main():
bot = Bot()
autoit.win_wait(bot.title, 5)
counter = 0
poitonUse = 0
cycle = True
fullCounter = 0
w... |
def fibs():
previous, current = 0, 1
while True:
previous, current = current, previous + current
yield current
def problem2(bound):
sum = 0
for n in fibs():
if n >= bound:
break
if n % 2 == 0:
sum += n
return sum
print problem2(4000000) |
from click.testing import CliRunner
from twelve_tone.cli import main
def test_main():
runner = CliRunner()
result = runner.invoke(main, [])
assert result.exit_code == 0 |
import numpy as np
from numba import cuda, float32
from numba.cuda.testing import unittest, CUDATestCase
def generate_input(n):
A = np.array(np.arange(n * n).reshape(n, n), dtype=np.float32)
B = np.array(np.arange(n) + 0, dtype=A.dtype)
return A, B
class TestCudaNonDet(CUDATestCase):
def test_for_pre(se... |
from setuptools import setup, find_packages
setup(
name = 'wechat-python-sdk',
version = '0.5.7',
keywords = ('wechat', 'sdk', 'wechat sdk'),
description = u'微信公众平台Python开发包',
long_description = open("README.rst").read(),
license = 'BSD License',
url = 'https://github.com/doraemonext/wechat-... |
import sys
import itertools
from functools import reduce
from operator import iadd
import numpy
from PyQt4.QtGui import (
QFormLayout, QGraphicsRectItem, QGraphicsGridLayout,
QFontMetrics, QPen, QIcon, QPixmap, QLinearGradient, QPainter, QColor,
QBrush, QTransform, QGraphicsWidget, QApplication
)
from PyQt4... |
from rdflib import Graph, BNode, Literal, URIRef
from rdflib.namespace import FOAF
from flask import Flask
import flask_rdf
import random
app = Flask(__name__)
custom_formatter = flask_rdf.FormatSelector()
custom_formatter.wildcard_mimetype = 'text/plain'
custom_formatter.add_format('text/plain', 'turtle')
custom_decor... |
"""
Commands for X-ray Diffraction
Note that an XRD camera must be installed!
"""
def setup_epics_shutter(prefix='13MARCCD4:'):
"""
Setup Epics shutter for CCD camera
open /close pv = 13IDA:m70.VAL (SSA H WID)
open val = 0.080, close val = -0.020
"""
caput(prefix+'cam1:ShutterOpenEPICS.OU... |
import os
import sys
import test_common
def main():
ast = test_common.Ami()
ast.username = sys.argv[1]
ast.password = sys.argv[2]
if ast.conn() == False:
print("Could not connect.")
return 1
# create dlma
ret = ast.sendCmd("OutQueueCreate", Name="TestDlma", Detail="TestDetail")
... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_title01.xlsx'
... |
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fiel... |
"""Widget for creating classes from non-numeric attribute by substrings"""
import re
from itertools import count
import numpy as np
from AnyQt.QtWidgets import QGridLayout, QLabel, QLineEdit, QSizePolicy
from AnyQt.QtCore import QSize, Qt
from Orange.data import StringVariable, DiscreteVariable, Domain
from Orange.data... |
"""
This is a subfile for IsyClass.py
These funtions are accessable via the Isy class opj
"""
__author__ = 'Peter Shipley <peter.shipley@gmail.com>'
__copyright__ = "Copyright (C) 2013 Peter Shipley"
__license__ = "BSD"
import time
def load_clim(self):
""" Load climate data from ISY device
args: none
... |
from zested.main import main
if __name__ == "__main__":
main() |
from __future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, useragents
from streamlink.stream import HDSStream
from streamlink.stream import HLSStream
class TF1(Plugin):
url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)... |
import bcrypt
def hash_password(password):
default_rounds = 14
bcrypt_salt = bcrypt.gensalt(default_rounds)
hashed_password = bcrypt.hashpw(password, bcrypt_salt)
return hashed_password
def check_password(password, hashed):
return bcrypt.checkpw(password, hashed) |
import os
import requests
import time
import math
import datetime
import random
import envoy
import jsonfield
import logging
import urllib
from collections import defaultdict
from magic_repr import make_repr
from hashlib import md5, sha1
from django.db import models
from django.db.models import Q
from django.utils impo... |
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Shield"
prefix = "shield"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "", account: st... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20150326_1433'),
]
operations = [
migrations.RemoveField(
model_name='problem',
name='id',
),
mi... |
from app import app
import gevent
from gevent.pywsgi import WSGIServer
from gevent.pool import Pool
from gevent import monkey
import signal
monkey.patch_all()
server = WSGIServer(('', 5000), app, spawn=Pool(None))
def stop():
server.stop()
gevent.signal(signal.SIGINT, stop)
if __name__ == "__main__":
server.ser... |
"""
"""
from datetime import datetime
from ... import SEQUENCE_TYPES, STRING_TYPES
from .formatters import format_time
from ...utils.conv import to_raw
def check_type(input_value, value_type):
if isinstance(input_value, value_type):
return True
if isinstance(input_value, SEQUENCE_TYPES):
for val... |
"""
LeBLEU - Letter-edit / Levenshtein BLEU
"""
import logging
__version__ = '0.0.1'
__author__ = 'Stig-Arne Gronroos'
__author_email__ = "stig-arne.gronroos@aalto.fi"
_logger = logging.getLogger(__name__)
def get_version():
return __version__
from .lebleu import LeBLEU
def eval_single(*args, **kwargs):
lb = Le... |
import cStringIO
import zlib
import wx
def getMailData():
return zlib.decompress(
"x\xda\x01M\x01\xb2\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\
\x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\
\x08d\x88\x00\x00\x01\x04IDATX\x85\xed\x941\x0e\x82@\x10E\x9f\xc6`,\x88\xad\
\x8d\... |
import flask; from flask import request
import os
import urllib.parse
from voussoirkit import flasktools
from voussoirkit import gentools
from voussoirkit import stringtools
import etiquette
from .. import common
site = common.site
session_manager = common.session_manager
@site.route('/album/<album_id>')
def get_album_... |
import sys
def ip2str(ip):
l = [
(ip >> (3*8)) & 0xFF,
(ip >> (2*8)) & 0xFF,
(ip >> (1*8)) & 0xFF,
(ip >> (0*8)) & 0xFF,
]
return '.'.join([str(i) for i in l])
def str2ip(line):
a, b, c, d = [int(s) for s in line.split('.')]
ip = 0
ip += (a << (3*8))
ip +=... |
"""
Workaround for a conda-build bug where failing to compile some Python files
results in a build failure.
See https://github.com/conda/conda-build/issues/1001
"""
import os
import sys
py2_only_files = []
py3_only_files = [
'numba/tests/annotation_usecases.py',
]
def remove_files(basedir):
"""
Remove u... |
import datetime
import random
import sys
class DayLife:
"""Life in a day."""
def __init__(self, date, life):
"""Set birth datetime and life."""
self.birthdate = date
self.life = life
finalyear = self.birthdate.year + self.life
finaldate = datetime.datetime(finalyear, self... |
"""
The scheduler is responsible for the module handling.
"""
import modules
from importlib import import_module
from additional.Logging import Logging
class Scheduler():
"""
This class instantiates the modules, takes care of the module's versions
and gets the module's select queries.
"""
# dictonar... |
from django.conf.urls import patterns, include, url
from django.shortcuts import redirect, render_to_response
from django.template.context import RequestContext
from django.contrib import admin
admin.autodiscover()
def to_blog(request):
return redirect('/blog/', permanent=False)
def sslicense(request):
slicense... |
import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field r... |
from setuptools import setup
from djangocms_carousel import __version__
INSTALL_REQUIRES = [
]
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Ope... |
from scout.parse.variant.rank_score import parse_rank_score
from scout.parse.variant.variant import parse_variant
def test_parse_rank_score():
## GIVEN a rank score string on genmod format
rank_scores_info = "123:10"
variant_score = 10.0
family_id = "123"
## WHEN parsing the rank score
parsed_ra... |
import amitgroup as ag
import numpy as np
ag.set_verbose(True)
data, digits = ag.io.load_mnist('training', selection=slice(0, 100))
pd = ag.features.PartsDescriptor((5, 5), 20, patch_frame=1, edges_threshold=5, samples_per_image=10)
pd.train_from_images(data)
ag.plot.images(pd.visparts) |
from django.contrib.gis.geoip2 import GeoIP2
from geoip2.errors import GeoIP2Error
from ipware import get_client_ip
def get_location_from_ip(request):
client_ip, is_routable = get_client_ip(request)
if client_ip is not None:
g = GeoIP2()
try:
record = g.city(client_ip)
except... |
import sys, os, time, argparse
import re
import pprint
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(function):
return function.replace("?", "")[:100]
def mkdir(dirname):
if not os.path... |
import os
import os.path as osp
import textwrap
import waflib.Utils
import waflib.Logs as msg
from waflib.Configure import conf
_heptooldir = osp.dirname(osp.abspath(__file__))
def options(opt):
opt.load('hwaf-base', tooldir=_heptooldir)
opt.add_option(
'--with-cmake',
default=None,
help... |
import ctypes
import pyglet
from pyglet.window.xlib import xlib
import lib_xinput as xi
class XInputDevice:
def __init__(self, display, device_info):
self._x_display = display._display
self._device_id = device_info.id
self.name = device_info.name
self._open_device = None
# TO... |
from __future__ import absolute_import
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class ImageModelForm(ModelForm):
"""
Defines the form used to create a new ImageModelJob
"""
crop_size = utils.forms.IntegerField(
'Crop Size',
validators=[
... |
from setuptools import setup, find_packages
import os
version = '0.9.7rt'
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
long_description = (
read('README.txt')
+ '\n' +
read('js', 'chosen', 'test_chosen.txt')
+ '\n' +
read('CHANGES.txt'))
setup(
name... |
"""myproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
__author__ = 'Cedric Da Costa Faro'
from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@main.app_errorhandler(405)
def method_not_allowed(e):
return render_template('405.html'), 405
@main.app_errorhandler(500)
def inter... |
"""
PostgreSQL Session API
======================
The Session classes wrap the Queries :py:class:`Session <queries.Session>` and
:py:class:`TornadoSession <queries.tornado_session.TornadoSession>` classes
providing environment variable based configuration.
Environment variables should be set using the ``PGSQL[_DBNAME]`... |
__author__ = 'Robert Meyer'
try:
import scoop
except ImportError:
scoop = None
def scoop_not_functional_check():
if scoop is not None and scoop.IS_RUNNING:
print('SCOOP mode functional!')
return False
else:
print('SCOOP NOT running!')
return True
from pypet.tests.integrat... |
"""
These URL patterns are included in two different ways in the main urls.py, with
an extra argument present in one case. Thus, there are two different ways for
each name to resolve and Django must distinguish the possibilities based on the
argument list.
"""
from django.conf.urls import url
from .views import empty_v... |
"""
New Drawing class to create new mark and style on axes.
"""
from decimal import Decimal
import numpy as np
import toyplot
ITERABLE = (list, tuple, np.ndarray)
class GridSetup:
"""
Returns Canvas and Cartesian axes objects to fit a grid of trees.
"""
def __init__(self, nrows, ncols, width, height, la... |
import numpy
import scipy.stats
from collections import defaultdict
def scores_to_probs(scores):
scores = numpy.array(scores)
scores -= scores.max()
probs = numpy.exp(scores, out=scores)
probs /= probs.sum()
return probs
def score_to_empirical_kl(score, count):
"""
Convert total log score to... |
"""
Read a dictionary from a JSON file,
and add its contents to a Python dictionary.
"""
import json
import types
from instmakelib import rtimport
INSTMAKE_SITE_DIR = "instmakesite"
CONFIG_USAGE_LOGGER = "usage-logger"
CONFIG_CLIDIFF_NORMPATH = "clidiff-normpath"
def update(caller_config, json_filename):
# This wil... |
''' Renderers for various kinds of annotations that can be added to
Bokeh plots
'''
from __future__ import absolute_import
from six import string_types
from ..core.enums import (AngleUnits, Dimension, FontStyle, LegendClickPolicy, LegendLocation,
Orientation, RenderMode, SpatialUnits, Vertical... |
import unittest
from interval import interval, fpu
class FpuTestCase(unittest.TestCase):
def test_third(self):
"Nearest rounding of 1/3 is downwards."
self.assertEqual(1/3.0, fpu.down(lambda: 1.0 / 3.0))
self.assertTrue(1/3.0 < fpu.up(lambda: 1.0 / 3.0))
self.assertEqual(-1/3.0, fpu.... |
import threading
from ctypes import POINTER, Structure, byref, c_char, c_char_p, c_int, c_size_t
from django.contrib.gis.geos.base import GEOSBase
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import (
check_geom, check_sized_string, check_str... |
"""
Downloads the following:
- Korean Wikipedia texts
- Korean
"""
from sqlparse import parsestream
from sqlparse.sql import Parenthesis
for statement in parsestream(open('data/test.sql')):
texts = [str(token.tokens[1].tokens[-1]).decode('string_escape') for token in statement.tokens if isinstance(token, Parenthesi... |
"""
Methods to characterize image textures.
"""
import numpy as np
from ._texture import _glcm_loop, _local_binary_pattern
def greycomatrix(image, distances, angles, levels=256, symmetric=False,
normed=False):
"""Calculate the grey-level co-occurrence matrix.
A grey level co-occurence matrix is... |
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_inherit',
'south',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backe... |
from ...models import GPModel
import numpy as np
class CostModel(object):
"""
Class to handle the cost of evaluating the function.
param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default
no cost is used. Options are:
- cost_withGradients ... |
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
from selenium import webdriver
import os
import time
import logging
import re
import random
from cameo.utility import Utility
from cameo.localdb import Loc... |
import itertools
import os
import re
from abc import ABC, abstractmethod
from glob import glob
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from ..io.image import _read_png_16
from .utils import verify_str_arg
from .vision import VisionDataset
__all__ = (
"KittiFlow",
"Sintel",... |
__version__ = "1.2.0.11" |
from __future__ import absolute_import
class BadOption(Exception):
""" Incorrect HTTP API arguments """
pass
class RenderError(Exception):
""" Error rendering page """
pass
class InternalError(Exception):
""" Unhandled internal error """
pass
class GlobalTimeoutError(Exception):
""" Timeout ... |
"Yang/Wu's OEP implementation, in PyQuante."
from math import sqrt
import settings
from PyQuante.NumWrap import zeros,matrixmultiply,transpose,dot,identity,\
array,solve
from PyQuante.Ints import getbasis, getints, getJ,get2JmK,getK
from PyQuante.LA2 import geigh,mkdens,trace2,simx
from PyQuante.hartree_fock impor... |
def extractLittlebambooHomeBlog(item):
'''
Parser for 'littlebamboo.home.blog'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('FW', 'Fortunate Wife', 'translated'),
('... |
from __future__ import print_function, division
from sympy.core import S, sympify, cacheit, pi, I, Rational
from sympy.core.add import Add
from sympy.core.function import Function, ArgumentIndexError, _coeff_isneg
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.eleme... |
"""
Single trace Analysis
"""
__author__ = "Yanlong Yin (yyin2@iit.edu)"
__version__ = "$Revision: 1.4$"
__date__ = "$Date: 02/08/2014 $"
__copyright__ = "Copyright (c) 2010-2014 SCS Lab, IIT"
__license__ = "Python"
import sys, os, string, getopt, gc, multiprocessing
from sig import *
from access import *
from accList ... |
"""
This package contains various tools for Japanese NLP tasks, although some
may be applicable to any python project. See documentation of each module for
details.
"""
__all__ = [
'alternations',
'common',
'enum',
'exceptions',
'kana_table',
'maps',
'scripts',
'smart_cache',
'resour... |
import errno
import os
import types
import typing as t
from werkzeug.utils import import_string
class ConfigAttribute:
"""Makes an attribute forward to the config"""
def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
self.__name__ = name
self.get_converter = get... |
from sympy.core.numbers import comp, Rational
from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
deviation, brewster_angle, critical_angle, lens_makers_formula,
mirror_formula, lens_formula, hyperfocal_distance,
transverse_magnification)
from sympy.physics.optics.med... |
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib2
_DISCOVERY_URI = ('https://monorail-prod.appspot.com'
'/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest')
class IssueTrackerService(object):
... |
from flask import render_template, redirect, url_for, flash, abort
from purchasing.decorators import requires_roles
from purchasing.data.stages import Stage
from purchasing.data.flows import Flow
from purchasing.conductor.forms import FlowForm, NewFlowForm
from purchasing.conductor.manager import blueprint
@blueprint.r... |
import threading
from collections import defaultdict
from funcy import once, decorator
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.backends.utils import CursorWrapper
from django.db.transaction import Atomic, get_connection, on_commit
from .utils import monkey_mix
__all__ = ('queue_when_in_tran... |
"""
flaskbb.management.views
~~~~~~~~~~~~~~~~~~~~~~~~
This module handles the management views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import sys
from flask import (Blueprint, current_app, request, redirect, url_for, flash,
jsoni... |
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configur... |
"""Schedule models.
Much of this module is derived from the work of Eldarion on the
`Symposion <https://github.com/pinax/symposion>`_ project.
Copyright (c) 2010-2014, Eldarion, Inc. and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted prov... |
from apptools.logger.util import * |
import re
from django import template
from django.core.urlresolvers import NoReverseMatch
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, name):
try:
pattern = reverse(name)
except NoReverseMatch:
return ''
... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Difference'] , ['LinearTrend'] , ['Seasonal_Hour'] , ['NoAR'] ); |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('commtrack', '0005_populate_config_models'),
]
operations = [
migrations.RemoveField(
model_name='sqlcommtrackconfig',
name='couch_id',
... |
'''
isobands_matplotlib.py is a script for creating isobands.
Works in a similar way as gdal_contour, but creating polygons
instead of polylines
This version requires matplotlib, but there is another one,
isobands_gdal.py that uses only GDAL python
Originally created by Roger Veciana i Rovira, made available via his
bl... |
from __future__ import division
from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import ActorNode
from panda3d.core import WindowProperties, NodePath, LVector3
from panda3d.core import LineSegs, OrthographicLens, CardMaker
from inputs import Inputs
from sys import path
import square
try:
path.i... |
'''
from sc2casts_client import *
import json
from pprint import *
parser = SC2CastsParser()
client = SC2CastsClient()
TEST_DATA_DIR = 'data'
def test_titles():
pass
def test_casts():
with open(TEST_DATA_DIR + '/all', 'r') as f:
test_data = f.read()
#print test_data
actual = parser.casts(tes... |
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
__doc__="""
These help format numbers and dates in a user friendly way.
Used by the graphics framework.
"""
import string, sys, os, re
class Formatter:
"Base formatter - simply applies python format str... |
from datetime import datetime, timedelta, tzinfo
import unittest
import pytz
import re
from nose.tools import assert_equal, assert_raises # you need it for tests in form of continuations
import six
from flask_restful import inputs
def test_reverse_rfc822_datetime():
dates = [
("Sat, 01 Jan 2011 00:00:00 -0... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import django
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Justin Quick', 'justquick@gmail.com'),
)
ENGINE = os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3')
DATABASES = {
'default': {
... |
from sklearn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("DecisionTreeClassifier" , "BinaryClass_10" , "db2") |
"""Bridge the ``PropertyLoader`` (i.e. a ``relation()``) and the
``UOWTransaction`` together to allow processing of relation()-based
dependencies at flush time.
"""
from sqlalchemy.orm import sync
from sqlalchemy import sql, util, exceptions
from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE, MANYTOMANY
def cr... |
import numpy as np
import pandas as pd
import gen_fns
import math
import re
import csv
import correlation_matrix as co
def reformat_raw_data(file, n_header=1, outfile=None):
from gen_fns import get_data
from numpy.lib.recfunctions import append_fields
countries, columns, raw_data = get_data(file, n_header, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.