code
stringlengths
1
199k
""" WSGI config for webapi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapi.settings") from django.core.wsgi im...
"""Trim signal file to only have signal aligned from label file""" from __future__ import print_function import sys import os import collections import re from timeit import default_timer as timer from chiron.chiron_input import read_signal from nanotensor.utils import list_dir from Bio import pairwise2 from Bio.pairwi...
import sys from os.path import abspath, dirname, join from django.core.management import execute_manager PROJECT_ROOT = abspath(dirname(__file__)) sys.path.insert(0, join(PROJECT_ROOT, "../")) try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error:...
class Config(object): TESTING = False MAIL_SERVER = "smtp.gmail.com" MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = 'jonjc22@gmail.com' ADMINS = ['jonjc22@gmail.com'] class Production(Config): DEBUG = True MAIL_PASSWORD = 'brem zeca tivu czzt' #LESS_BIN = './node_modules/less/bi...
import pytest @pytest.fixture def software_0(): return{ "name": "star", "title": "STAR", "description": "STAR (Spliced Transcript Alignment to a Reference)." } @pytest.fixture def software_1(software_0): item = software_0.copy() item.update({ 'schema_version': '1', })...
import os from collections import OrderedDict DEBUG = True ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'tenant_schemas.postgresql_backend', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'tenant_tutorial', ...
"""Test the dumpwallet RPC.""" import datetime import os import time from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) def read_dump(file_name, addrs, script_addrs, hd_master_addr_old): """ Read the given dump, count...
import abc import subprocess import sys import os class BleCommunication(object): '''Bluetooth LE communication''' __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_data(mac): pass @abc.abstractmethod def get_datas(): pass class BleCommunicationDummy(BleCommunication): ...
import re import requests from flask_script import Manager from salvemais import create_app app = create_app(env='dev') manager = Manager(app) @manager.command def load_hemocenters(): from salvemais.models import Hemocenter, Address from salvemais.util.maps import GoogleMaps from salvemais.util.postmon_api ...
from climb.exceptions import UnknownCommand def command(function): function.command = True return function def completers(*compl): def wrapper(function): function.completers = compl return function return wrapper class Commands(object): def __init__(self, cli): self._cli = cl...
try: import pytesseract from PIL import Image except ImportError: print '模块导入错误,请使用pip安装,pytesseract依赖以下库:' print 'http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil' print 'http://code.google.com/p/tesseract-ocr/' raise SystemExit image = Image.open('random_img.jpg') vcode = pytesseract.image_to_string(image) ...
import usb.core import time dev = usb.core.find() dev.read(0x81, 576) def get_next(): global dev ret = dev.read(0x81, 576) return ret
from django.shortcuts import render from concerts.models import Concert def index(request): concert_list = Concert.objects.all().order_by('date') upcoming_concerts = [concert for concert in concert_list if concert.is_upcoming()] past_concerts = [concert for concert in concert_list if concert not in upcoming...
from __future__ import absolute_import import requests from v2ex_daily_mission.notifier.abc import Notifier class NoneNotifier(Notifier): def __init__(self, config): self.config = config def send_notification(self): pass
from __future__ import unicode_literals, print_function """ Sync's doctype and docfields from txt files to database perms will get synced only if none exist """ import frappe import os from frappe.modules.import_file import import_file_by_path from frappe.modules.patch_handler import block_user from frappe.utils impo...
from datetime import date from dateutil.easter import easter from dateutil.relativedelta import relativedelta as rd from holidays.constants import JAN, MAY, JUL, AUG, NOV, DEC from holidays.holiday_base import HolidayBase class Belgium(HolidayBase): """ https://www.belgium.be/nl/over_belgie/land/belgie_in_een_n...
from requests import request from .api_map import api_map from .exceptions import ( BadRequest, ResourceNotFound, Unauthorized, InternalServerError ) class Api: def __init__(self): self.base_endpoint = api_map['current']['api_root'] def request(self, url, method, api_key, **kwargs): ...
from couchAPI import * from rpcdump import * import json import sys import getopt class dump2couch: def __init__(self,conf): self.conf=conf url = "%s:%s@127.0.0.1:%d" % (conf['rpcuser'],conf['rpcpass'],conf['rpcport']) print "connect rpc :",url self.rd = rpcdump(url) self.db = couchAPI(conf['couchdbuser'],co...
from . import plugins # NOQA from .trainer import Trainer # NOQA from .updater import Updater # NOQA from .metrics import Accuracy, Loss # NOQA from . import converters # NOQA
import os import urllib import requests import Foundation from appscript import app, mactypes import subprocess class BingImageInfo: def __init__(self): self.jsonUrl = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US" self.response = requests.get(self.jsonUrl).json() def get_image_url(self):...
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import pytest import yaml class TestInputRSS(object): config = """ tasks: _: rss: &rss url: rss.xml silent: yes ...
from PyQt4 import QtGui, QtCore import Polyomino class GameWidget(QtGui.QWidget): def __init__(self): super().__init__() self.currentPolyomino, self.nextPolyominos = None, [] self.keyPressed = False self.setFocusPolicy(QtCore.Qt.ClickFocus) def minimumSizeHint(self): minX = 100 minY = 100 if self.field ...
import glopen def MR_init(args, params, frame): from copy import deepcopy ans = {"words" : {}} base = deepcopy(ans) jobs = [] ans["fname"] = "/tmp/Dickens/TaleOfTwoCities.txt" jobs.append(((0, 16271), params, args, deepcopy(ans))) ans["fname"] = "/tmp/Dickens/ChristmasCarol.txt" jobs.append(((0, 4236), ...
from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR import logging from aps...
""" Created on Mon Feb 15 11:26:41 2016 @author: ih3 State class The fluid State (key variables plus equation of state) at a point. """ from __future__ import division import numpy class State(object): r""" A state at a point. Initialized with the rest mass density, velocity, and specific internal energy, a...
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1036, 712) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self...
LOG_FILE = 'spider2.log' JOBDIR='spider2_job' START_URLS = ['http://www.bing.com/knows'] TITLE_PATH = 'html head title::text'
from flask import jsonify from app.exceptions import ValidationError def bad_request(message): response = jsonify({'error': 'bad request', 'message': message}) response.status_code = 400 return response def unauthorized(message): response = jsonify({'error': 'unauthorized', 'message': message}) resp...
import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'robotgear.settings') application = get_asgi_application()
""" SoftLayer.tests.CLI.modules.call_api_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import testing import json class CallCliTests(testing.TestCase): def test_options(self): mock = self.set_mock('SoftLayer_Service', 'method') ...
from base64 import b64decode from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from os.path import join from .base import MessageModel, Model, ModelManager, SubModelManager class Open(MessageModel): def __str__(self): return "Open from %...
import serial import time import math ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) ser.open() class MoveCtrl: #def __init__(self, direction): #direction == 'stop' def move(self, direction): if ser.isOpen(): ser.write(direction) print direction else: ...
import os from aiotg import Bot bot = Bot(os.environ["API_TOKEN"]) @bot.command(r"/getimage") def getimage(chat, match): return chat.send_photo(photo=open("cc.large.png", "rb"), caption="Creative commons") if __name__ == '__main__': bot.run(debug=True)
import sys, requests, bs4, urllib, re, datetime user = sys.argv[1] nick = user.split('!')[0] msg = sys.argv[3] command, args = msg.partition(' ')[::2] s = requests.Session() s.headers = {'User-agent': 'DevBot (https://github.com/Peetz0r/DevBot)'} if(command == '.help'): print('Use the source, luke! https://github.com/...
from __future__ import unicode_literals import inspect def is_static_method(obj): klass = get_class_from_method(obj) if not klass: return False for cls in inspect.getmro(klass): if inspect.isroutine(obj): binded_value = cls.__dict__.get(obj.__name__) if isinstance(bin...
''' 知识点: 偏导数:点 x轴、y轴 斜率;极值:极大值、极小值。 最小二乘法:目标函数-偏差平方和最小,这种根据偏差平方和为最小的条件来选择常数a、b的方法叫做最小二乘法。 偏差:真实值(实际测量值)与经验公式估算值的差。 均方误差:它的大小在一定程度上反映了用经验公式来近似表达原来函数的关系的近似程度的好坏。 ''' import numpy as np import pandas as pd from scipy import optimize import matplotlib.pyplot as plt import numpy as np ''' 第十节 最小二乘法 工程问题:根据两个变量的多组实验数据(样本数据)来...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import pytest import httpretty import tests.test_helpers as test_helpers import datapackage.exceptions import datapackage.resource_file InlineReso...
__revision__ = "test/MSVC/generate-rc.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Test adding a src_builder to the RES builder so that RC files can be generated. """ import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() fake_rc = test.workpath('fake_rc.py') test.write(fake_rc,...
from sys import platform as _platform if _platform in ("linux", "linux2"): try: from twisted.internet import epollreactor epollreactor.install() except Exception, e: pass elif _platform == "darwin": try: import twisted_kqueue twisted_kqueue.install() except Except...
import os import sys apache_configuration = os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.join(project, "..") sys.path.append(project) sys.path.append(workspace) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "froide.settings") os.environ.setdefault("DJANGO_CONFIGURATION...
import unittest class TestEncodingError(unittest.TestCase): def _makeOne(self): from tgext.mailer.exceptions import EncodingError return EncodingError() def test_it(self): inst = self._makeOne() self.assertTrue(isinstance(inst, Exception))
import sqlite3 as lite class Controler(): def __init__(self): print("controler created") def create_connection(self): return lite.connect('konsultanci.db') def print_consultants(self): try: with self.create_connection() as con: cur = con.cursor() ...
import os from conans import ConanFile, CMake, tools class LuaTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "cmake" def build(self): cmake = CMake(self) cmake.configure() cmake.build() def imports(self): self.copy("*.dll", dst="bin",...
<testbank name="HI 101"> <chapter name="1"> <section name="1"> <category type="multiple_choice"> <fact type="date"> <question>When was the world created?</question> <answer>4000 BC</answer> </fact> <fact type...
import sys sys.path.append('/opt/lib/python2.7/site-packages/') import math import numpy as np import pylab import nest import nest.raster_plot import nest.voltage_trace import nest.topology as tp import ggplot t_sim = 500 populations = [1, 100] no_recurrent = True neuron_model = 'iaf_psc_exp' model_params = { 'tau_m...
# we use the tplquad command to integrate f(x,y,z)=ysin(x)+zcos(x) from scipy.integrate import tplquad import numpy as np def integrand(z, y, x): return y * np.sin(x) + z * np.cos(x) ans, err = tplquad(integrand, 0, np.pi, # x limits lambda x: 0, lambda x: ...
import math def f_area(a, b, c): sol = 0 s = (a + b + c)/2 r = s*(s - a)*(s - b)*(s - c) if r > 0: sol = math.sqrt(r) return sol a, b = str(input()).split(" ") a = int(a) b = int(b) while(a != 0 and b != 0): c = 1 area = f_area(a, b, c) max = 0 while (max == 0 or area > max)...
num, fac = 600851475143, 2 while fac*fac <= num: if num%fac==0: num //= fac else: fac+=1 print "Project Euler #3:" print "The largest prime factor of the number 600851475143 is", num
class Base: def fun1Base(self): print('Fun1Base') def fun2Base(self): print('Fun2Base') class Derived(Base): def fun1Derived(self): print('Fun2Derived') def fun2Base(self): # super(self) # Throws Exception print('Fun2Derived') if __name__ == '__main__': # o...
import cgi import logging class EntityReference(object): def __init__(self, span, match, references, extra_attr=None): self.span = span self.match = match self.references = references self.extra_attr = extra_attr class MarkupChunk(object): def __init__(self, text): self.c...
import numpy as np class MultivariateNormal(object): """ Normal distribution for multidimensional data @param mean: mean array @param cov: covariance matrix """ def __init__(self, mean, cov): mean = np.array(mean) if len(mean.shape) == 1: mean = mean[None, :] ...
'''DGCastle: A disc golf statistics tracking tool''' import os import pymongo from dgcastle.handlers.match_play import MatchPlay from dgcastle.handlers.challonge import Challonge class DGCastle(Challonge, MatchPlay): def __init__(self, testDb=None): super().__init__() self.testDb = testDb if...
""" Command Executioner tests """ from django.test import TestCase from django.conf import settings from app.logic.bluesteelworker.download.core.CommandExecutioner import CommandExecutioner import os import shutil import mock class CommandExecutionerTestCase(TestCase): def setUp(self): self.tmp_folder = os....
import logging logger = logging.getLogger(__name__) class Application: def __init__(self, message): self.message = message def __call__(self, environ, start_response): logger.debug("accessed") start_response( "200 OK", [('Content-type', 'text/plain;charset=utf8')]...
import requests import json class UserGetOrCreateMixin(object): """ The User Mixin that allows us to communicate with Abridge as a user """ _subscriber = None _email = None _email_hash = None _first_name = None _last_name = None def subscriber_in_kwargs(self, **kwargs): """ ...
"""Tools for working with MongoDB `ObjectIds <http://dochub.mongodb.org/core/objectids>`_. """ import binascii import calendar import datetime try: import hashlib _md5func = hashlib.md5 except ImportError: # for Python < 2.5 import md5 _md5func = md5.new import os import random import socket import str...
import sys, time, requests, json from fping_api import * time_stamp = time.strftime("%Y-%m-%d %H:%M:%S") file = open('fping_prefixes', 'r+') for prefixes in ipv4_prefix(): file.write(str(prefixes) + '\n') file.close
import os import sys if os.path.exists(os.path.expanduser('~/plutokore')): sys.path.append(os.path.expanduser('~/plutokore')) else: sys.path.append(os.path.expanduser('~/uni/plutokore')) import plutokore as pk import matplotlib as mpl mpl.use('PS') import matplotlib.pyplot as plot import numpy as np import argp...
from src.Numbers.prime import primes class TestPrime: def test_primes(self): assert primes(6) == [2, 3, 5] def test_prime_of_one(self): assert primes(1) == [] def test_prime_of_19(self): assert primes(19) == [2, 3, 5, 7, 11, 13, 17]
"""Flatten lists.""" def flatten_me(lst): """Flatten the list.""" new_list = [] for value in lst: if type(value) == list: new_list.extend(value) else: new_list.append(value) return new_list
from __future__ import absolute_import, print_function, unicode_literals import os from linkat.ffi import ffi, ffi_lib AT_FDCWD = ffi_lib.AT_FDCWD if ffi_lib.AT_SYMLINK_FOLLOW != 0: AT_SYMLINK_FOLLOW = ffi_lib.AT_SYMLINK_FOLLOW if ffi_lib.AT_EMPTY_PATH != 0: AT_EMPTY_PATH = ffi_lib.AT_EMPTY_PATH def link_at(old...
class Vec2(object): def __init__(self, x, y): self.x = x or 0.0 self.y = y or 0.0 def __eq__(self, other): return (isinstance(other, self.__class__) and self.x == other.x and self.y == other.y) class Rect(object): def __init__(self, start, end): assert...
from ming import Session from ming.orm import ThreadLocalORMSession mainsession = Session() DBSession = ThreadLocalORMSession(mainsession)
""" Created on Wed Mar 16 14:32:12 2016 @author: Pedro Leal """ ''' Solves Langermann Multimodal Problem with Automatic Optimization Refinement. ''' import os, sys, time from scipy.optimize import minimize from pyOpt import Optimization from pyOpt import NSGA2 from pyOpt import SLSQP import matlab.engine lib_path = os....
import logging from contextlib import suppress from pabiana import Area, repo from pabiana.utils import multiple from . import utils area = Area(repo['area-name'], repo['interfaces']) premise = utils.setup config = { 'clock-name': 'clock', 'clock-slots': multiple(2, 6), 'subscriptions': { 'smarthome': None, 'wea...
def is_nice(arr): return all(i+1 in arr or i-1 in arr for i in arr) if arr else 0
from __future__ import unicode_literals from datetime import timedelta from indico.core.db import db from indico.modules.news import news_settings from indico.modules.news.models.news import NewsItem from indico.util.caching import memoize_redis from indico.util.date_time import now_utc @memoize_redis(3600) def get_rec...
import json import requests import traceback import six class StanfordCoreNLP: def __init__(self, server_url): if server_url[-1] == '/': server_url = server_url[:-1] self.server_url = server_url def annotate(self, text, properties=None): if isinstance(text, six.text_type): ...
import tkinter import tkinter.ttk as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" ...
import sys, json, copy import re from warnings import warn DEFAULTS = {'runas_uid': None, 'runas_gid': None, } DEFAULTS_FOR_OXM = { 'regexes': [r'(.*)'], 'priority': 0, 'backup': False } def load_config(): # Load configuration with open(sys.argv[1], 'rb') as json_config: ...
''' Module for handling the data anc coavariance matrices ''' import numpy as np import util def load_data(Mr): '''loads wp and nbar ''' return [load_nbar(Mr) , load_wp(Mr)] def load_covariance(Mr): '''loads wp and nbar ''' return [load_nbar_variance(Mr) , load_wp_covariance(Mr)] def load_wp(Mr)...
''' Offline tests ''' from unittest import TestCase import mock from mock import MagicMock from crawling.log_retry_middleware import LogRetryMiddleware class TestLogRetryMiddlewareStats(TestCase): @mock.patch('crawling.log_retry_middleware.LogRetryMiddleware' \ '.setup') def setUp(self, s): ...
import os.path as osp import multiworld.envs.mujoco as mwmj import rlkit.util.hyperparameter as hyp from multiworld.envs.mujoco.cameras import sawyer_door_env_camera_v0 from rlkit.launchers.launcher_util import run_experiment import rlkit.torch.vae.vae_schedules as vae_schedules from rlkit.launchers.skewfit_experiments...
''' Created on 1.11.2016 @author: Samuli Rahkonen ''' def kbinterrupt_decorate(func): ''' Decorator. Adds KeyboardInterrupt handling to ControllerBase methods. ''' def func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except KeyboardInterrupt: t...
import matplotlib.colors as mplc kthcolors = { 'blue': '#1954a6', 'lightblue': '#24a0d8', 'green': '#62922e', 'lightgreen': '#b0c92b', 'red': '#9D102D', 'lightred': '#e4363e', 'yellow': '#fab919', 'pink': '#d85497', 'darkgray': '#65656c', 'middlegray': '#bdbcbc', 'lightgray': '#e3e5e3' } mplc.cnames.update(kthcolors)
import pandas as pd import psycopg2 from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer from scipy import sparse from sklearn.cluster import KMeans from sklearn.externals import joblib import os true_k = 5 if __name__ == '__main__': if not os.path.exists('model'): os.makedi...
from pylab import * from plotly.tools import FigureFactory as FF import plotly.graph_objs as go from scipy.spatial.distance import pdist, squareform, cdist from pyvtk import * from ..io.read_vtk import ReadVTK from .landmarks import Landmarks from ..data_attachment.measures import Measures, Measure from ..data_attachme...
import os import py class LayerField(object): """ Holds all data about a field of a layer, both its actual value and its name and nice representation. """ # Note: We use this object with slots and not just a dict because # it's much more memory-efficient (cuts about a third of the memory). __slo...
''' Create PV-slices of the spectrally down-sampled HI cube. ''' from spectral_cube import SpectralCube, Projection import pvextractor as pv from astropy.utils.console import ProgressBar from astropy.io import fits from astropy import units as u import numpy as np import matplotlib.pyplot as plt from paths import fourt...
"""Grid element mappers that are specific to raster grids. Mapping functions unique to raster grids ++++++++++++++++++++++++++++++++++++++++ .. autosummary:: ~landlab.grid.raster_mappers.map_sum_of_inlinks_to_node ~landlab.grid.raster_mappers.map_mean_of_inlinks_to_node ~landlab.grid.raster_mappers.map_max_...
import sys import os import numpy as np from pprint import pprint from datetime import datetime from datetime import timedelta import mysql.connector import math import matplotlib.pyplot as plt import matplotlib.colors import matplotlib.cm as cm from matplotlib import dates import calendar cnx = mysql.connector.connect...
"""Test the ZMQ notification interface.""" import struct from test_framework.test_framework import DigiByteTestFramework from test_framework.messages import CTransaction from test_framework.util import ( assert_equal, bytes_to_hex_str, hash256, ) from io import BytesIO class ZMQSubscriber: def __init__(...
""" Posix reactor base class """ from __future__ import division, absolute_import import socket import errno import os import sys from zope.interface import implementer, classImplements from twisted.python.compat import _PY3 from twisted.internet.interfaces import IReactorUNIX, IReactorUNIXDatagram from twisted.interne...
def auto_join(autos, makes): import pandas as pd key = ['make-id'] ## Define key column ## Return the joined dataframe return pd.merge(autos, makes, on = key, how = 'left') def prep_auto(df, col_names): import pandas as pd import numpy as np ## Assign names to columns df.columns = col_na...
def test_hello(client): result = client.get('/') assert result.data == b'Hello, world!'
import unittest import os import handler as sut class TestLaunchIntentHandler(unittest.TestCase): def setUp(self): os.environ['SKILL_ID'] = "TEST_SKILL_ID" self.context = {} self.event = { 'session': { 'sessionId': 'unittest', 'application': { ...
import discord import kadal from discord.ext import commands from kadal import MediaNotFound MAL_ICON = 'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png' AL_ICON = 'https://avatars2.githubusercontent.com/u/18018524?s=280&v=4' class Anilist(commands.Cog): def __init__(self, bot): self.b...
from numpy import mean, cumsum from novainstrumentation.peaks import bigPeaks from novainstrumentation.smooth import smooth from novainstrumentation.tools import plotfft def fundamental_frequency(s,FS): # TODO: review fundamental frequency to guarantee that f0 exists # suggestion peak level should be bigger ...
"""Render image galleries.""" import datetime import glob import io import json import mimetypes import os try: from urlparse import urljoin except ImportError: from urllib.parse import urljoin # NOQA import natsort try: from PIL import Image # NOQA except ImportError: import Image as _Image Image...
import logging import os import socket from unittest import mock, TestCase, skipUnless from urllib.parse import urlparse from mtp_transaction_uploader import upload, settings logger = logging.getLogger('mtp') @skipUnless('RUN_FUNCTIONAL_TESTS' in os.environ, 'functional tests are disabled') class FileUploadFunctionalTe...
from __future__ import print_function, absolute_import, division import numpy as np from . import tt_eigb from tt import tensor def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1): """ Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squa...
""" inputpy.exceptions This module exports exceptions specific to InPUT. Right now, the only exception that exists is InPUTException. :copyright: (c) 2013 by Christoffer Fink. :license: MIT. See LICENSE for details. """ class InPUTException(Exception): """ A generic exception for all InPUT-related errors. "...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from tastypie.api import Api from django_dynamic_usersettings.api import UserSettingResource v1_api = Api(api_name='v1') v1_api.register(UserSettingResource()) urlpatterns = patterns('', # Examples: # url(r...
from sanity.initializer import BaseInitializer class Initializer(BaseInitializer): @property def requirements(self): return ['alacritty', 'tmux'] def build(self): self.inject('alacritty.yml') def install(self): self.link_dist('alacritty.yml', '.config/alacritty/alacritty.yml')
from __future__ import division from builtins import range import numpy as np np.seterr(divide='ignore') # these warnings are usually harmless for this code from matplotlib import pyplot as plt import matplotlib import os matplotlib.rcParams['font.size'] = 8 import pyhsmm from pyhsmm.util.text import progprint_xrange s...
from tsdb.dictdb import * from tsdb.tsdb_client import TSDBClient from tsdb.tsdb_server import * from tsdb.tsdb_serialization import * from tsdb.tsdb_ops import * from tsdb.tsdb_rest_client import TSDB_REST_Client
from .a_div import ADiv class ARow(ADiv): def __init__(self, *args, **kwargs): self.attrs["class"] = "row" super().__init__(*args, **kwargs)
''' KBA pipeline transform that holds a list of known stream_ids and prints lines to a file of the form: stream_id,i_str where i_str is the input task path for the chunk containing the stream_id. This software is released under an MIT/X11 open source license. Copyright 2012-2014 Diffeo, Inc. ''' from __future__ import ...
import random import unittest def HasElement(vector, element): # It seems that binary search is not hard to write correctly anymore with Python vector.sort() def _BinarySearch(begin, end, element): if begin == end: return False elif end - begin == 1: return vector[beg...
import pdb import time import sys import scipy.io as sio import numpy import theano import pylab as pl from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix cmap = numpy.asarray( [[0, 0, 0], [0, 205, 0], [127, 255, 0], [46...