code
stringlengths
1
199k
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['BoxCox'] , ['Lag1Trend'] , ['Seasonal_Second'] , ['NoAR'] );
from __future__ import absolute_import, division, print_function from future.builtins import zip import numpy as np from skbio.io import FileFormatError from skbio.io.util import open_file class OrdinationResults(object): """Store ordination results Attributes ---------- eigvals : 1-D numpy array ...
import unittest import IECore import IECoreGL import Gaffer import GafferTest import GafferUI import GafferUITest class StandardStyleTest( GafferUITest.TestCase ) : def testColorAccessors( self ) : s = GafferUI.StandardStyle() i = 0 for n in GafferUI.StandardStyle.Color.names : if n=="LastColor" : continu...
"""Equality-constrained quadratic programming solvers.""" from __future__ import division, print_function, absolute_import from scipy.sparse import (linalg, bmat, csc_matrix) from math import copysign import numpy as np from numpy.linalg import norm __all__ = [ 'eqp_kktfact', 'sphere_intersections', 'box_in...
from datetime import datetime from dateutil import rrule from dateutil.relativedelta import relativedelta import pytz from corehq.apps.locations.models import SQLLocation from corehq.apps.products.models import SQLProduct from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.sqlreport im...
""" Incrementally tweak specified axes. Build new faces! """ from argparse import ArgumentParser import pprint import numpy as np from pylearn2.gui.patch_viewer import PatchViewer import theano from adversarial import sampler, util parser = ArgumentParser(description=('Experiment with tweaking each ' ...
import base64 import logging from django.conf import settings from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from djzendesk.signals import target_callback_received def is_authenticated(request, username, pa...
""" Created on Fri Mar 01 14:56:56 2013 Author: Josef Perktold """ import warnings import numpy as np from numpy.testing import assert_almost_equal, assert_equal, assert_array_less from statsmodels.stats.proportion import proportion_confint import statsmodels.stats.proportion as smprop from statsmodels.tools.sm_excepti...
from django.conf import settings from django.core.urlresolvers import reverse from django.db import connection, transaction from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from nepal.account.decorators import role_required from nepal.contrib.shortcuts import render_t...
from __future__ import unicode_literals from django.test import SimpleTestCase from localflavor.lt.forms import (LTIDCodeField, LTMunicipalitySelect, LTCountySelect) class LTLocalFlavorTests(SimpleTestCase): def test_LTIDCodeField(self): error_len = ['ID Code consists of ex...
from zeit.cms.i18n import MessageFactory as _ from zope.browserpage import ViewPageTemplateFile import pkg_resources import zeit.cms.browser.objectdetails import zeit.edit.browser.form import zope.formlib.form import zope.formlib.interfaces class ReferenceDetailsHeading(zeit.cms.browser.objectdetails.Details): temp...
""" WSGI config for django_export_xls project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLI...
from math import sqrt from shapely import affinity GM = (sqrt(5) - 1.0) / 2.0 W = 8.0 H = W * GM SIZE = (W, H) BLUE = "#6699cc" GRAY = "#999999" DARKGRAY = "#333333" YELLOW = "#ffcc33" GREEN = "#339933" RED = "#ff3333" BLACK = "#000000" COLOR_ISVALID = { True: BLUE, False: RED, } def plot_line(ax, ob, color=GRA...
from django.core.exceptions import ValidationError def validate_approximatedate(date): if date.month == 0: raise ValidationError( 'Event date can\'t be a year only. ' 'Please, provide at least a month and a year.' )
import pickle import numpy as np import os from vec_hsqc import pred_vec curdir = os.path.dirname( os.path.abspath( __file__ ) ) with open( os.path.join( curdir, 'training_eg_01.pickle'), 'r' ) as f: fdd = pickle.load(f).full_data_dict a = pred_vec.ProbEst( ) a.import_data( fdd ) a.extract_features( ) np.savetxt(...
from enum import IntEnum import datetime from project.bl.utils import Resource from project.extensions import db from project.lib.orm.types import TypeEnum, GUID from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy.ext.associationproxy import association_proxy from project.lib.orm.conditions import Con...
import argparse import numpy as np import matplotlib.pyplot as plt argParser = argparse.ArgumentParser() argParser.add_argument('datafile') args = argParser.parse_args() time,signal = [],[] fin = open(args.datafile, 'r') for line in fin: words = line.split(',') time.append(float(words[1])) signal.append(flo...
from __future__ import unicode_literals try: from bs4 import BeautifulSoup except ImportError: from BeautifulSoup import BeautifulSoup import lxml.html import lxml.html.clean import re import unicodedata VERSION = (8,) __version__ = '.'.join(map(str, VERSION)) __all__ = ('cleanse_html', 'Cleanse') class Cleanse...
import numpy as np import pandas as pd import vtk from vtk.numpy_interface import dataset_adapter as dsa from base import TestBase from PVGeo import interface from PVGeo._helpers import xml RTOL = 0.000001 class TestXML(TestBase): """ Test the XML Helpers to make sure no errors are thrown """ def test_s...
""" Download articles from RSS feeds """ from django.apps import AppConfig class RssSyncAppConfig(AppConfig): name = 'coop_cms.apps.rss_sync' verbose_name = "RSS Synchronization"
"""Added short name Revision ID: 1f5a646334e1 Revises: 1e9f6460c977 Create Date: 2014-05-09 10:17:17.150660 """ revision = '1f5a646334e1' down_revision = '1e9f6460c977' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('statio...
import sys import os import traceback import time import tempfile import threading import logging import platform import atexit import shutil import inspect from collections import deque, OrderedDict from ginga import cmap, imap from ginga.misc import Bunch, Timer, Future from ginga.util import catalog, iohelper, loade...
import calendar import collections import contextlib import datetime import errno import functools import itertools import json import operator import os import random import re import shutil import time import unicodedata import urllib import urlparse import string import subprocess import scandir import django.core.m...
import os from setuptools import setup, find_packages __version__ = None exec(open('opentaxii/_version.py').read()) def here(*path): return os.path.join(os.path.dirname(__file__), *path) def get_file_contents(filename): with open(here(filename), encoding='utf8') as fp: return fp.read() install_requires ...
from slicc.ast.ExprAST import ExprAST class MethodCallExprAST(ExprAST): def __init__(self, slicc, proc_name, expr_ast_vec): super(MethodCallExprAST, self).__init__(slicc) self.proc_name = proc_name self.expr_ast_vec = expr_ast_vec def generate(self, code): tmp = self.slicc.codeFo...
""" The tightest known upper bound on two-way secret key agreement rate. """ from __future__ import division from .base_skar_optimizers import BaseTwoPartIntrinsicMutualInformation from ... import Distribution __all__ = [ 'two_part_intrinsic_total_correlation', 'two_part_intrinsic_dual_total_correlation', '...
from __future__ import division, print_function, unicode_literals, \ absolute_import import os import abc import io import subprocess import itertools import six import numpy as np from monty.tempfile import ScratchDir from pymatgen import Element from pymatgen.io.lammps.data import LammpsData from veidt.potential....
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_fsm class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
import htmls from django import test from model_bakery import baker from devilry.devilry_cradmin import devilry_listbuilder class TestItemValue(test.TestCase): def test_title_without_fullname(self): relatedstudent = baker.make('devilry_account.PermissionGroupUser', user__...
__author__ = 'sandlbn' from django.conf.urls import url from views import CalendarJsonListView, CalendarView urlpatterns = [ url( r'^json/$', CalendarJsonListView.as_view(), name='calendar_json' ), url( r'^$', CalendarView.as_view(), name='calendar' ), ]
"""Tests of the pnacl driver. This tests that @file (response files) are parsed as a command shell would parse them (stripping quotes when necessary, etc.) """ import driver_tools import os import tempfile import unittest class TestExpandResponseFile(unittest.TestCase): def setUp(self): self.tempfiles = [] def ...
from __future__ import print_function from collections import namedtuple from itertools import islice import types import os import re import argparse parser = argparse.ArgumentParser(description='Program description.') parser.add_argument('-p', '--path', metavar='PATH', type=str, required=False, de...
''' Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. ''' class Solution: # @param num, a list of integers # @return an integer def maxProduct(self, ...
logfile = 'tmp_output.log' # store all output of all operating system commands f = open(logfile, 'w'); f.close() # touch logfile so it can be appended import subprocess, sys def system(cmd): """Run system command cmd.""" print cmd try: output = subprocess.check_output(cmd, shell=True, ...
"""Command-line helper for setuptools and PyPI.""" import os import os.path as op import re import click import requests __version__ = '0.1.0' VERSION_REGEX = re.compile(r"__version__ = '(\d+)\.(\d+)\.(\d+)'") def lib_name(): """Return the library name.""" return op.basename(os.getcwd()) def lib_file_path(): ...
from PySide import QtGui from jukedj import models from jukeboxmaya.menu import MenuManager from jukeboxcore.djadapter import FILETYPES from jukeboxcore.action import ActionUnit, ActionCollection from jukeboxcore.release import ReleaseActions from jukeboxcore.gui.widgets.releasewin import ReleaseWin from jukeboxmaya.pl...
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class SimpleTagTests(SimpleTestCase): libraries = {'custom': 'template_tests.templatetags.custom'} @setup({'simpletag-renamed01': '{% load custom %}{% minusone 7 %}'}) def test_simpletag_renamed0...
from __future__ import print_function import os import sqlite3 from django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction from trees.models import FVSAggregate def get_gyb_rows(db_path, fields, arraysize=1000): ''' Fetches GYB data from the sqlite db yiel...
"""Admin extensions for django-reversion.""" from __future__ import unicode_literals from contextlib import contextmanager from django.db import models, transaction, connection from django.conf.urls import url from django.contrib import admin from django.contrib.admin import options from django.contrib.admin.utils impo...
import unittest from simplemonitor import util from simplemonitor.Alerters import fortysixelks class Test46Elks(unittest.TestCase): def test_46elks(self): config_options = {"username": "a", "password": "b", "target": "c"} config_options["sender"] = "ab" with self.assertRaises(util.AlerterCon...
from pathlib import Path from niworkflows.reports.core import Report as _Report class Report(_Report): def _load_config(self, config): from yaml import safe_load as load settings = load(config.read_text()) self.packagename = self.packagename or settings.get("package", None) # Removed...
""" Test functions for multivariate normal distributions. """ from __future__ import division, print_function, absolute_import import pickle from numpy.testing import (assert_allclose, assert_almost_equal, assert_array_almost_equal, assert_equal, assert_array_less, ...
import re from django.conf import settings from django.utils import translation from haystack import connections from haystack.backends import BaseEngine, BaseSearchBackend, BaseSearchQuery from haystack.constants import DEFAULT_ALIAS from haystack.utils.loading import load_backend class MultilingualSearchBackend(BaseS...
"""Provides an interface to communicate with the device via the adb command. Assumes adb binary is currently on system path. Usage: python android_commands.py wait-for-pm """ import collections import datetime import logging import optparse import os import pexpect import re import subprocess import sys import tempfi...
from django.db import models import re from django.conf import settings class StatusUpdate(models.Model): summary = models.CharField('Short Summary', max_length=255, blank=False) posted_by = models.CharField(max_length=255, blank=False) duration_minutes = models.IntegerField(null = True, blank=True) adm...
from __future__ import annotations from typing import TYPE_CHECKING, Any, Sequence, Union from packaging.version import parse from pandas import DataFrame, Series if TYPE_CHECKING: import numpy as np if parse(np.__version__) < parse("1.22.0"): raise NotImplementedError( "NumPy 1.22.0 or late...
"""Testing facility for conkit.io.a2m""" __author__ = "Felix Simkovic" __date__ = "30 Jul 2018" import os import unittest from conkit.io.a2m import A2mParser from conkit.io._iotools import create_tmp_f class TestA2mParser(unittest.TestCase): def test_read_1(self): msa = """GSMFTPKPPQDSAVI--GYCVKQGAVMKNWKRRY...
import os try: from xml.parsers.expat import ParserCreate except ImportError: _haveExpat = 0 from xml.parsers.xmlproc.xmlproc import XMLProcessor else: _haveExpat = 1 class XMLParser: def __init__(self): self.root = [] self.current = (self.root, None) def getRoot(self): assert len(self.root) == 1 return s...
from django.contrib.messages import *
from django import http from django.db.transaction import non_atomic_requests from django.shortcuts import get_list_or_404, get_object_or_404, redirect from django.utils.translation import ugettext from django.utils.cache import patch_cache_control from django.views.decorators.cache import cache_control from django.vie...
from decimal import Decimal import graphene import pytest from django_countries.fields import Country from saleor.checkout import calculations from saleor.graphql.payment.enums import OrderAction, PaymentChargeStatusEnum from saleor.payment.interface import CreditCardInfo, CustomerSource, TokenConfig from saleor.paymen...
import os import argparse from .. lib import ( eb, s3, parameters ) import boto def get_argument_parser(): parser = argparse.ArgumentParser("ebzl delete") parameters.add_profile(parser, required=False) parameters.add_app_name(parser) parameters.add_version_label(parser, required=True) pa...
class SenderNotCallable(Exception): pass
import io import qi import time import vision_definitions from django.conf import settings from django.core.files.images import ImageFile from django.utils.functional import cached_property from django.utils.six import BytesIO from mock import MagicMock from PIL import Image from wagtail.wagtailimages.models import Ima...
from __future__ import absolute_import import six from sentry.api.serializers import serialize, SimpleEventSerializer from sentry.api.serializers.models.event import SharedEventSerializer from sentry.models import EventError from sentry.testutils import TestCase from sentry.utils.samples import load_data from sentry.te...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='R_Old_Navy', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Source.reference' db.alter_column('payment_source', 'reference', self.gf('django.db.models.fields.CharField')(default...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "BoxCox", sigma = 0.0, exog_count = 20, ar_order = 12);
""" Dependencies lists the functions and types required by a function """ from pythran.passmanager import ModuleAnalysis from pythran.tables import MODULES import ast import math class Dependencies(ModuleAnalysis): def __init__(self): self.result = set() super(Dependencies, self).__init__() def ...
from pysal.model.spvcm._constants import TEST_SEED, CLASSTYPES from pysal.model.spvcm.tests.utils import run_with_seed from pysal.model.spvcm import lower_level as M from pysal.model.spvcm.abstracts import Sampler_Mixin from pysal.model.spvcm.utils import south import pandas as pd import os FULL_PATH = os.path.dirname(...
""" Verifies that msvs_prebuild and msvs_postbuild can be specified in both VS 2008 and 2010. """ import TestGyp test = TestGyp.TestGyp(formats=['msvs'], workdir='workarea_all') test.run_gyp('buildevents.gyp', '-G', 'msvs_version=2008') test.must_contain('main.vcproj', 'Name="VCPreBuildEventTool"') test.must_contain('m...
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailModelBackend(ModelBackend): """Бэкэнд для авторизации пользователей при помощи пары email и пароль """ def authenticate(self, email=None, password=None): UserModel = get_user_model() ...
from mustaine import protocol from mustaine.client import HessianProxy test = HessianProxy("http://hessian.caucho.com/test/test") # assert test.argDouble_0_001(0.001) is True def test_encode_double_127_0(): assert test.argDouble_127_0(127.0) is True
import os PROJECT_DIR = os.path.dirname(__file__) location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) USE_TZ = True DEBUG = True TEMPLATE_DEBUG = True SQL_DEBUG = True SEND_BROKEN_LINK_EMAILS = False ADMINS = ( ('David Winterbottom', 'david.winterbottom@tangentlabs.co.uk'), ) EMAI...
'''misc routines for dealing with binary data''' def hex2bin(str): ''' take a hexadecimal number as a string and convert it to a binary string ''' bin = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110...
import nbformat def empty_notebook(fname): with open(fname, 'r') as fp: nb = nbformat.read(fp, as_version=4) for cell in nb.cells: if cell['cell_type'] == 'code': source = cell['source'] if ('# preserve' in source) or ('#preserve' in source): continue ...
import subprocess import sys import os import hashlib import Alfred import romkan handler = Alfred.Handler(sys.argv, use_no_query_string=False) anything_matched = False playlist_name = "" recache_identifier = ".disallow-recache" user_home = os.path.expanduser("~") artwork_cache_path = os.path.join(user_home, ".maestro-...
""" Facilities for diffing two FITS files. Includes objects for diffing entire FITS files, individual HDUs, FITS headers, or just FITS data. Used to implement the fitsdiff program. """ import fnmatch import glob import io import operator import os.path import textwrap import warnings from collections import defaultdic...
""" Copyright (C) 2014, Alex Izvorski All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the followi...
from .providers import METRICS_PROVIDERS def get_provider_choices(): """Returns a list of currently available metrics providers suitable for use as model fields choices. """ choices = [] for provider in METRICS_PROVIDERS: choices.append((provider.alias, provider.title)) return choices de...
import pandas as pd def concurrent_cagetreatment(df, cagestays, protect_duplicates=[ 'Animal_id', 'Cage_id', 'Cage_Treatment_start_date', 'Cage_Treatment_end_date', 'Cage_TreatmentProtocol_code', 'Treatment_end_date', 'Treatment_end_date', 'TreatmentProtocol_code', ], ): """ Return a `pandas.DataF...
"""A utility for generating classes for structured metrics events. It takes as input a structured.xml file describing all events and produces a c++ header and implementation file exposing builders for those events. """ import argparse import sys import model import events_template import compile_time_validation parser ...
from django.utils.translation import ugettext_noop from django.utils.translation import ugettext as _ import pytz from corehq.apps.hqcase.dbaccessors import get_cases_in_domain from corehq.apps.reports.standard import CustomProjectReport from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.repo...
""" Classe for reading data in CED spike2 files (.smr). This code is based on: - sonpy, written by Antonio Gonzalez <Antonio.Gonzalez@cantab.net> Disponible here :: http://www.neuro.ki.se/broberger/ and sonpy come from : - SON Library 2.0 for MATLAB, written by Malcolm Lidierth at King's College London. ...
import numpy as np from holoviews.element import Bivariate from .testplot import TestPlotlyPlot class TestBivariatePlot(TestPlotlyPlot): def test_bivariate_state(self): bivariate = Bivariate(([3, 2, 1], [0, 1, 2])) state = self._get_plot_state(bivariate) self.assertEqual(state['data'][0]['ty...
"""Auto-generated file, do not edit by hand. IQ metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_IQ = PhoneMetadata(id='IQ', country_code=964, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[1-7]\\d{7,9}', possible_number_pattern='...
"""Test segzufy.""" from segzify import __version__ def test_version(): """Test version.""" assert __version__ == "0.1.0"
import os from flask.ext.script import Manager, Shell from flask.ext.migrate import MigrateCommand from widelanguagedemo.app import create_app from widelanguagedemo.settings import DevConfig, ProdConfig from widelanguagedemo.database import db if os.environ.get("WIDELANGUAGEDEMO_ENV") == 'prod': app = create_app(Pr...
from gevent import monkey; monkey.patch_all() import argparse import beaker.middleware from contextlib import closing from datetime import datetime, timedelta import functools import getpass import json import logging import os import re import sys import tempfile import bottle import gevent import geventwebsocket impo...
import os import shutil import glob import time import sys import subprocess from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PARAMETERS = None ADB_CMD = "adb" def doCMD(cmd): # Do not need handle timeout in this short script, let tool do it print "-->> \"%s...
sleep(5) type('o', KeyModifier.CTRL) sleep(1) path2VanessaBehavoir = sys.argv[1] paste(path2VanessaBehavoir) sleep(2) type(Key.ENTER) sleep(3) type(Key.F4, KeyModifier.ALT) exit(0)
""" custom QToolButton icon Tested environment: Mac OS X 10.6.8 """ import sys try: from PySide import QtCore from PySide import QtGui except ImportError: from PyQt4 import QtCore from PyQt4 import QtGui class Demo(QtGui.QWidget): def __init__(self): super(Demo, self).__init__() ...
"""Main entry point """ import os import logging import pkg_resources __version__ = pkg_resources.get_distribution(__package__).version logger = logging.getLogger(__name__) import six from cornice import Service from pyramid import httpexceptions from pyramid.config import Configurator from pyramid.events import NewReq...
import errno import json import os import socket import stat import sys import time from contextlib import contextmanager from datetime import datetime, timezone, timedelta from functools import partial from getpass import getuser from io import BytesIO from itertools import groupby from shutil import get_terminal_size...
"""Tests for the pages app.""" from datetime import timedelta from cms.externals import External from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.db import models from django.test import TestCase from django.utils.timezone import now from .... import...
from __future__ import unicode_literals import os.path import difflib from common import GitChangelogTestCase, w, cmd class TestEnvironmentCornerCases(GitChangelogTestCase): def test_config_file_is_not_a_file(self): w(""" mkdir .gitchangelog.rc """) out, err, errlvl = cmd('$tprog...
from .models import * from .api import * from . import grade_file
import numpy as np import pandas as pd from math import sqrt from sklearn import ensemble from sklearn.metrics import mean_squared_error df_train = pd.read_csv("train_numerical_head.csv") df_train.head() feats = df_train.drop(str(42), axis=1) X_train = feats.values #features y_train = df_train[str(42)].values #target d...
try: import urllib2 as urllib except ImportError: # For Python 3+ import urllib.request as urllib import numpy as np import json BASE_PATH = "http://starserver.thelangton.org.uk/lucid-data-browser/api/" def get_data_files(run = None): stream = urllib.urlopen(BASE_PATH + "get/data_files") if not stream.getcode() ==...
from msrest.serialization import Model class Operation(Model): """Storage REST API operation definition. :param name: Operation name: {provider}/{resource}/{operation} :type name: str :param display: Display metadata associated with the operation. :type display: ~azure.mgmt.storage.v2017_10_01.model...
""" Script para generar documento con la historia de los cambios. """ import os import subprocess SRC_DIR = os.path.join(os.path.dirname(__file__), os.pardir) DOCS_DIR = os.path.abspath(os.path.join(SRC_DIR, 'docs')) TMP_FILE = os.path.join(DOCS_DIR, 'changelog-tmp.tex') GIT_CMD = ['git', 'log', '--no-merges', '--date-...
from __future__ import absolute_import, print_function import traceback from autobahn.websocket import protocol from autobahn.websocket import http from autobahn.wamp.interfaces import ITransport from autobahn.wamp.exception import ProtocolError, SerializationError, TransportLost __all__ = ('WampWebSocketServerProtocol...
from datetime import datetime from itertools import groupby from operator import itemgetter import dateutil.parser from flask import render_template from pytz import timezone from indico.web.http_api.metadata.serializer import Serializer def _deserialize_date(date_dict): if isinstance(date_dict, datetime): ...
import logging import sys LOGGER = logging.getLogger('PYWPS') PY2 = sys.version_info[0] == 2 if PY2: LOGGER.debug('Python 2.x') text_type = unicode from StringIO import StringIO from flufl.enum import Enum from urlparse import urlparse from urlparse import urljoin from urllib2 import urlopen...
import pytest from molecule.command import check def test_execute_raises_when_instance_not_created( patched_check_main, patched_print_error, molecule_instance): c = check.Check({}, {}, molecule_instance) with pytest.raises(SystemExit): c.execute() msg = ('Instance(s) not created, `check` sho...
import pysam import sys from re import sub from random import random from uuid import uuid4 if len(sys.argv) == 2: assert sys.argv[1].endswith('.bam') inbamfn = sys.argv[1] outbamfn = sub('.bam$', '.renamereads.bam', inbamfn) inbam = pysam.Samfile(inbamfn, 'rb') outbam = pysam.Samfile(outbamfn, 'wb'...
try: import importlib except ImportError: from django.utils import importlib import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str text_type = str else: string_types = basestring text_type = unicode def import_attribute(name): """Return an attrib...
"""Add rsa_license_plate field Revision ID: 98ad75de45b2 Revises: caae04cdec5c Create Date: 2020-01-15 03:25:27.864784 """ revision = '98ad75de45b2' down_revision = 'caae04cdec5c' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Al...
import numpy as np def get_distribution(GC_fraction): from simdna.util import DiscreteDistribution return DiscreteDistribution({ 'A': (1 - GC_fraction) / 2, 'C': GC_fraction / 2, 'G': GC_fraction / 2, 'T': (1 - GC_fraction) / 2 }) def simple_motif_embedding(motif_name, seq_length, num_seqs...
from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): help = u"Convert user passwords to use built-in Django bcrypt." def handle(self, *args, **options): users = User.objects.all() self.stdout.write(u"Updating %s user password...