content
string
from bs4 import BeautifulSoup import requests import sqlite3 import time def db_init(dbfile): """Initializes SQLite database. This function creates required tables. Args: file (str): Name of SQLite database. Returns: bool: True if successful, False otherwise. """ conn = sqli...
__author__ = 'chris' """ Just using this class for testing the DHT for now. We will fit the actual implementation in where appropriate. """ import pickle import stun from twisted.internet import reactor from twisted.python import log from os.path import expanduser from bitcoin import * from txjsonrpc.netstring import j...
import unittest class TestInjection(unittest.TestCase): @unittest.expectedFailure def test___init__(self): # injection = Injection(number, volume, duration, spacing, filter_period, titrant_concentration) assert False # TODO: implement your test here @unittest.expectedFailure def test_...
from __future__ import division import hashlib import time import math import stripe from django.conf import settings from django.utils import timezone from rest_framework import serializers from crowdsourcing.exceptions import daemo_error from crowdsourcing.models import StripeAccount, StripeCustomer, StripeTransfe...
import cl_todo_wizard
import datetime from oslo_utils import uuidutils from neutron.objects import quota from neutron.tests.unit.objects import test_base as obj_test_base from neutron.tests.unit import testlib_api class ResourceDeltaObjectIfaceTestCase(obj_test_base.BaseObjectIfaceTestCase): _test_class = quota.ResourceDelta clas...
from __future__ import absolute_import import numpy as np import mdtraj from six import string_types from pyemma.coordinates.util import patches from pyemma.coordinates.data.interface import ReaderInterface from pyemma.coordinates.data.featurizer import MDFeaturizer from pyemma import config __author__ = 'noe, marsche...
import datetime from unittest import mock from django.test import TestCase, override_settings from django.utils.encoding import force_text from ..forms import PrivateMessageForm, UserChangeForm from ..models import PrivateMessage, User class TestDataMixin(object): """ Create test users. Taken from Django te...
import segment import transform_mfcc as transform from sklearn.svm import SVC, LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import train_test_split, KFold from sklearn.externals import joblib from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt impo...
#!/usr/bin/env python3 '''NVIDIA native query extension for EGL. This extension provides a means of getting the native display, window, or pixmap corresponding to an EGL display, window surface, or pixmap surface, respectively. http://www.khronos.org/registry/egl/extensions/NV/EGL_NV_native_query.txt ''' # Copyrigh...
from setuptools import setup from djangochurch_docs_theme import __version__ setup( name='djangochurch-docs-theme', version=__version__, url='https://github.com/djangochurch/djangochurch_docs_theme/', license='MIT', author='Django Church', author_email='<EMAIL>', description='Django Church...
# -------------------------------------------------------------------- # visualize.py # Paolo Frasconi - <EMAIL> # Time-stamp: <2010-06-16 14:17:35 paolo> # # Extracts a named graph from a gspan file and converts into .dot # format. Some naive colorization to distinguish nodes by label. # Special format: V (uppercase) ...
import os if os.name != "nt": raise Exception("Wrong OS") import ctypes as ctypes import ctypes.wintypes as wintypes def convert_cdef_to_pydef(line): """\ convert_cdef_to_pydef(line_from_c_header_file) -> python_tuple_string 'DWORD var_name[LENGTH];' -> '("var_name", DWORD*LENGTH)' doesn't work ...
from django.template.loader import render_to_string from oioioi.contests.utils import is_contest_admin from oioioi.programs.controllers import ProgrammingContestController class OiSubmitContestControllerMixin(object): """ContestController mixin that adds extra information about submission from the oisubmit a...
#!/usr/bin/env python # -*- coding: utf-8 -*- import collections import json import os import re import traceback from contextlib import contextmanager from datetime import datetime from itertools import chain, izip, product from tempfile import NamedTemporaryFile from os.path import abspath, basename, dirname, join ...
"""This is the standard, placeful Translation Domain for TTW development. $Id: translationdomain.py 68769 2006-06-20 10:19:22Z hdima $ """ __docformat__ = 'restructuredtext' import re from BTrees.OOBTree import OOBTree import zope.component from zope.interface import implements from zope.i18n import interpolate from...
# elastic_search.py # A module that handles elasticsearch connection ES_CONFIG_FILE = "./env.cfg" from elasticsearch import Elasticsearch, RequestsHttpConnection import ConfigParser import json from datetime import datetime INDEX_PREFIX = "twitter-" def json_pretty_print(json_obj): print json.dumps(json_obj, i...
#!/usr/bin/env python # coding: utf8 """ Oneall Authentication for web2py Developed by Nathan Freeze (Copyright © 2013) Email <<EMAIL>> This file contains code to allow using onall.com authentication services with web2py """ import os import base64 from gluon import * from gluon.storage import Storage...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateMode...
import encodedcc import argparse import os import csv import decimal def getArgs(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument('--query', help="takes the @type you want (type is ...
#!/usr/bin/env python """ Convert between FASTA-formatted input and one-sequence-per-line output so that the sequences can be easily manipulated with UNIX text tools (e.g., grep, head, wc, split, sort, etc.). In order for '--inverse' to work correctly, the same flags must be supplied as were supplied during the forwa...
import zipfile import tarfile import os import urllib class PrepareRawData: def __init__(self): self.file_list = [] self.dataset_path = './data/RoadImages/' if not os.path.isdir(self.dataset_path): print("Dataset folder {} is not existing. Creating...".format(self.dataset_path)...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, exc, joinedload from neutron.common import constants from neutron.common import exceptions as q_exc from neutron.plugins.cisco.db import models _ENGINE = None _MAKER = None BASE = models.BASE def configure_db(options): """Configure da...
import tensorflow as tf import numpy as np def l2_distance(a,b): return tf.square(a-b) def l1_distance(a,b): return tf.abs(a-b) def bicubic_interp_2d(input_, new_size, endpoint=False): """ Args : input_ : Input tensor. Its shape should be [batch_size, height, width, channel]. In this ...
from hashlib import md5 from collections import MutableMapping def md5digest(*args): return md5(':'.join(args).encode()).hexdigest() class Auth(MutableMapping): def __init__(self, mode='Digest', **kwargs): self._auth = kwargs self.mode = mode if self.mode != 'Digest': ra...
"""SCons.Tool.sunc++ Tool-specific initialization for C++ on SunOS / Solaris. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons ...
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf8') import scrapy import json import re import time import math import os import datetime import random class DealListSpider(scrapy.Spider): def __init__(self, domain="qd", date=time.strftime("%Y.%m", time.localtime())): self.c...
import time from minezy_api import app from minezy_api import neo4j_conn from query_common import prepare_date_range, prepare_date_clause def query_words(account, params, countResults=False): t0 = time.time() if params['rel'] == 'SENDER': relL = 'SENT' relR = 'TO|CC|BCC' elif params['rel...
import argparse import sys from logger import Logger from shapefile_loader import * """ <centerline> <parts> <part> <id>1</id> <type>Main</type> <length>214.73</length> <sinuosity>1.30</sinuosity> </part> </parts> <summary> <channel_count units="0.0#...
#!/usr/bin/env python """The report builders are classes that coordinate report productions""" import warnings import numpy as np import scipy.spatial.distance as dist import scipy.cluster.hierarchy as hier import fseq class ReportBuilderBase(object): """Base class for common report builder features. Most...
__author__ = 'thorsteinn' from db_to_file_helpers.jsonDicts_to_file import file_to_db def mc_db_extract_subtable_db(db, **kwargs): """ A method for extracting a sub-table information from a mc-db object. :param db: a database object of the type {ship1:{ship database},ship2:{ship database} one of the ...
# -*- coding: utf-8 -*- import datetime from openfisca_core import periods from openfisca_france.scenarios import init_single_entity from openfisca_france.reforms.plfr2014 import plfr2014 from ..cache import tax_benefit_system def test(year = 2013): max_sal = 18000 count = 2 people = 1 reform = pl...
import gobject from flumotion.common import testsuite try: import gtk from flumotion.ui.fvumeter import FVUMeter except RuntimeError: import os os._exit(0) INTERVAL = 100 # in ms class VUTest(testsuite.TestCase): def testScale(self): w = FVUMeter() self.assertEquals(w.iec_sca...
"""Test case for create volume from snapshot.""" import copy import mock import time from jacket.storage import exception from jacket.tests.storage.unit import fake_snapshot from jacket.tests.storage.unit import utils as utils from jacket.tests.storage.unit.volume.drivers import disco class CreateVolumeFromSnapshot...
# -*- coding: utf-8 -*- """ kodiswift.cli.app ---------------- This package contains the code which runs plugins from the command line. :copyright: (c) 2012 by Jonathan Beluch :license: GPLv3, see LICENSE for more details. """ from __future__ import absolute_import import logging import os import sys from xml.etree ...
"""Various implementations of a Count custom PTransform. These example show the different ways you can write custom PTransforms. """ from __future__ import absolute_import import argparse import logging import google.cloud.dataflow as df from google.cloud.dataflow.utils.options import PipelineOptions # pylint do...
from datetime import datetime from django.contrib.contenttypes.models import ContentType from django.db import transaction from django.test import TestCase, TransactionTestCase from django.test.utils import override_settings from django_dynamic_fixture import G from freezegun import freeze_time from mock import patch ...
#coding:utf8 """ proxiex.py ~~~~~~~~~~~~~ 该模块包含所有代理服务器列表,提供代理选择功能。 """ from threadPool import ThreadPool import requests #代理服务器列表 proxiex = [ '122.72.112.148:80', '122.72.112.166:80', '113.207.124.165:8080', '222.83.160.45:8080', '219.130.39.9:3128', '211.161.152.100:80', '221.176.14.72:80', '222.124.147.105:8080'...
from UM.Scene.Scene import Scene from UM.Event import Event, MouseEvent, ToolEvent, ViewEvent from UM.Signal import Signal, signalemitter from UM.Logger import Logger from UM.PluginRegistry import PluginRegistry ## Glue class that holds the scene, (active) view(s), (active) tool(s) and possible user inputs. # # ...
from pynomo import * """ Example nomograph z=x*x+2*y. It is of type F2(v)=F1(u)+F3(w) """ nomo_type='F2(v)=F1(u)+F3(w)' functions={ 'filename':'nomogram3.pdf', 'F2':lambda z:z, 'v_start':1.0, 'v_stop':15.0, 'v_title':'z', 'F1':lambda x:x*x, 'u_start':1.0, 'u_stop'...
import gevent import argparse import os import sys #import discovery.services as services import discoveryclient.client as client import uuid import time import signal class TestDiscService(): def __init__(self, args_str=None): self.args = None if not args_str: args_str = ' '.join(sys....
# This script is used to fix up the Isles of Scilly, as Boundary-Line only contains # the Isles alone. We have to generate the COP parishes within it. from __future__ import print_function import csv import re from django.core.management.base import LabelCommand from mapit.models import Postcode, Area, Country, Type,...
import os import pytest import numpy as np import numpy.testing as npt from skmisc.loess import loess, loess_anova data_path = os.path.dirname(os.path.abspath(__file__)) def madeup_data(): dfile = os.path.join(data_path, 'madeup_data') rfile = os.path.join(data_path, 'madeup_result') with open(dfile, ...
import requests from compair.core import celery, db from compair.models import LTIConsumer, LTIOutcome, CourseGrade, AssignmentGrade from flask import current_app @celery.task(bind=True, autoretry_for=(Exception,), ignore_result=True, store_errors_even_if_ignored=True) def update_lti_course_grades(self, lti_consu...
"""The cli_front is a the command line utility that is used to list all the accessable command line utilities and to call the command line utility you want to run.""" import sys, argparse, pkgutil from importlib import import_module import os.path import seqtools.cli.utilities def main(): # Get the tasks avail...
from __future__ import absolute_import EXAMPLE_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQC1cd9t8sA03awggLiX2gjZxyvOVUPJksLly1E662tttTeR3Wm9 eo6onNeI8HRD+O4wubUp4h4Chc7DtLDmFEPhUZ8Qkwztiifm99Xo3s0nUq4Pygp5 AU09KXTEPbzHLh1dnXLcxVLmGDE4drh0NWmYsd/Zp7XNIZq2TRQQ3NTdVQIDAQAB AoGAFwMyS0eWiR30TssEnn3Q0Y4p...
from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.internet.error import TimeoutError def add_timeout(deferred, timeout): ''' Raise TimeoutError on deferred after timeout seconds. Returns original deferred. ''' def timeout_deferred(): if not defe...
""" URL redirection example. """ import BaseHTTPServer import time import sys HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!! PORT_NUMBER = 80 # Maybe set this to 9000. REDIRECTIONS = {"/slashdot/": "http://slashdot.org/", "/freshmeat/": "http://freshmeat.net/", "":"http://loc...
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 13:41:37 2020 @author: wantysal """ # Standard imports import pytest # Local application imports from mosqito.functions.roughness_danielweber.comp_roughness import comp_roughness from mosqito.tests.roughness.signals_test_generation import signal_test @pytest.mark.r...
from __future__ import unicode_literals from django.db import models from datetime import datetime from django.utils import timezone from django.db.models import Model, CharField, ForeignKey, IntegerField, DecimalField, BooleanField, DateTimeField class School(Model): ''' Stores information on a single sch...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import functools import mock import unittest from chainer i...
"""User and repository tokens Revision ID: b3eb342cfd7e Revises: 83dc0a466da2 Create Date: 2017-11-08 15:33:52.810846 """ import zeus from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "b3eb342cfd7e" down_revision = "83dc0a466da2" branch_labels = () depends_on = None ...
# -*- coding: utf-8 -*- """ OneLogin_Saml2_Auth class Copyright (c) 2014, OneLogin, Inc. All rights reserved. Main class of OneLogin's Python Toolkit. Initializes the SP SAML instance """ from base64 import b64encode from urllib import quote_plus import dm.xmlsec.binding as xmlsec from onelogin.saml2.settings i...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'valerio cosentino' from datetime import datetime import multiprocessing from util import multiprocessing_util from querier_stackoverflow import StackOverflowQuerier from stackoverflow2db_extract_topic import StackOverflowTopic2Db from stackoverflow_dao impor...
import asyncio import datetime import json import logging import os from pprint import pprint import config from homematicip.aio.home import AsyncHome from homematicip.base.base_connection import HmipConnectionError def on_update_handler(data, event_type, obj): if obj: data["api_name"] = ob...
import Image import ImageDraw import ImageFont from kelpy.DotStimulus import DotStimulus class LTStimulus(DotStimulus): def __init__(self, screen, letter2count, pad=30, fontpath='./FreeSans.ttf', fontsize=60): """ screen -- not implemented; if we want to render in computer experiments this should be filled ...
# -*- encoding: utf-8 -*- # Module iaconcat from numpy import * def iaconcat(DIM, X1, X2, X3=None, X4=None): aux = 'newaxis,' d = len(X1.shape) if d < 3: X1 = eval('X1[' + (3-d)*aux + ':]') d1,h1,w1 = X1.shape d = len(X2.shape) if d < 3: X2 = eval('X2[' + (3-d)*aux + ':]') d2,h2,w2 = X2.s...
def encode_unicode(path): """ Check if given path is a unicode and if yes, return utf-8 encoded path """ if type(path) is unicode: path = path.encode('utf-8') return path def decode_unicode(path): """ Check if given path is of type str and if yes, convert it to unicode """ ...
import csv import pymysql from itertools import groupby import sys def Mysql(user, pwd, db, port=3306): conn = pymysql.connect(host='127.0.0.1', port=int(port), user=user, passwd=pwd, db=db, charset='utf8') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXIS...
import numpy as np from sklearn.ensemble import RandomForestClassifier, VotingClassifier from sklearn.model_selection import train_test_split from sklearn.naive_bayes import BernoulliNB from sklearn.pipeline import make_pipeline, make_union from sklearn.preprocessing import FunctionTransformer # NOTE: Make sure that ...
"""Tests for distutils.command.config.""" import unittest import os import sys from test.support import run_unittest from distutils.command.config import dump_file, config from distutils.tests import support from distutils import log class ConfigTestCase(support.LoggingSilencer, suppor...
#!/usr/bin/python import sys import Image def enc_backbuffer(backbuffer): compdata = [] if len(backbuffer) == 0: return compdata while len(backbuffer) > 128: compdata.append(127) compdata.extend(backbuffer[0:128]) backbuffer = backbuffer[128:] compdata.append(len(backbu...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from data.fixtures.test_data import LTITestData, BasicTestData from compair.tests.test_compair import ComPAIRAPITestCase class LTIConsumersAPITests(ComPAIRAPITestCase): def setUp(self): super(LTIConsumersAPITests, self).setUp() ...
##################################################################### # # # File: csvtoqbo.py # # Developer: Paul Puey # # Original Code by: Justin Leto # # Forked from https://github.com/jleto/csvtoqbo # # # # main utility script file Python scrip...
import matplotlib matplotlib.rc('text', usetex=True) import matplotlib.pyplot as plt import numpy as np # interface tracking profiles N = 500 delta = 0.6 X = np.linspace(-1, 1, N) plt.plot(X, (1 - np.tanh(4.*X/delta))/2, # phase field tanh profiles X, (X + 1)/2, # level set distance ...
import random import aiohttp import discord from lxml import html async def grab_post_list(tags): links = [] for x in range(0, 20): resource = f'http://safebooru.org/index.php?page=dapi&s=post&q=index&tags={tags}&pid={x}' async with aiohttp.ClientSession() as session: async with se...
""" Decentralized Distributed PPO (DD-PPO) ====================================== Unlike APPO or PPO, learning is no longer done centralized in the trainer process. Instead, gradients are computed remotely on each rollout worker and all-reduced to sync them at each mini-batch. This allows each worker's GPU to be used ...
# -*- coding: utf-8 -*- from odoo.tests.common import TransactionCase import time class TestHrTimesheetSheet(TransactionCase): """Test for hr_timesheet_sheet.sheet""" def setUp(self): super(TestHrTimesheetSheet, self).setUp() self.attendance = self.env['hr.attendance'] self.timesheet...
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from projectile.models import Project def index(request, template_name='front/index.html'): # Show at most INT featured projects listed_featured = 8 # Show at most INT thumbnail projects liste...
"""Network allocator This module supplies an interface for an allocator of network identifiers to be used by API calls such as ``network_create``. For HIL to operate correctly, a network allocator must be registered by calling ``set_network_allocator`` exactly once -- typically this is done by an extension. """ impo...
import test import os from os.path import join, exists, basename, isdir import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") class MessageTestCase(test.TestCase): def __init__(self, path, file, expected, arch, mode, context, config): super(MessageTestCase, self).__init__(context, path, arch, mode) self...
# -*- coding: utf-8 -*- from __future__ import print_function from collections import namedtuple from ethereum import slogging from raiden.settings import DEFAULT_SETTLE_TIMEOUT from raiden.utils import sha3, profiling from raiden.network.transport import UDPTransport from raiden.tests.utils.network import ( cre...
import warnings import os import pipes import socket import random from ansible.callbacks import vvv from ansible import errors from ansible import utils # prevent paramiko warning noise -- see http://stackoverflow.com/questions/3920502/ HAVE_PARAMIKO=False with warnings.catch_warnings(): warnings.simplefilter("ig...
from pywps.Wps import Request from pywps import config from pywps.Template import TemplateError import os,types,traceback import logging class DescribeProcess(Request): """ Parses input request obtained via HTTP POST encoding - should be XML file. """ def __init__(self,wps,processes=None): ...
""" A Python GitModel Serializer. Handles serialization of GitModel objects to/from native python dictionaries. """ try: from collections import OrderedDict except ImportError: OrderedDict = dict from gitmodel.exceptions import ValidationError, ModelNotFound from gitmodel.serializers import ABORT, SET_EMPTY, I...
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'pyramid', 'pyramid_jinja2', 'py2neo', ...
import os import pickle import numpy as np import sklearn.metrics from itertools import islice, zip_longest import numpy as np from IPython.display import HTML, Markdown from bing_maps import * import pandas as pd import mapswipe from pathlib import Path from collections import defaultdict, namedtuple import bing_ma...
import os,sys,platform,logging import gtk,gobject,pango from hotwire.logutil import log_except import hotwire_ui.widgets as hotwidgets from hotwire.state import Preferences from hotvte.vteterm import VteTerminalWidget _logger = logging.getLogger("hotwire.sysdep.VteTerminal") class VteTerminalFactory(object): d...
import networkx as nx import os import csv import errno import sys from networkx.readwrite import json_graph import json sys.path.append('../lib') import lib.config as config from shutil import copy2 def check_if_dir_exists(output_directory): """ Creates the directory for output if not there Args: ...
import time from google.appengine.api import users from google.appengine.ext import ndb from framework.utils import now from mcfw.rpc import returns, arguments from plugins.rogerthat_api.exceptions import BusinessException from plugins.tff_backend.models.payment import ThreeFoldTransaction, ThreeFoldPendingTransactio...
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from SimPEG import Mesh, Utils import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from scipy.sparse import spdiags,csr_matrix, eye,kron,hstack,vstack,eye,diags impor...
import sys import pytest from pytest_django.lazy_django import get_django_version from pytest_django_test.db_helpers import (db_exists, drop_database, mark_database, mark_exists, skip_if_sqlite_in_memory) skip_on_python32 = pytest....
import random from six import moves import testtools from tempest.api.object_storage import base from tempest import clients from tempest.common import custom_matchers from tempest.common.utils import data_utils from tempest import config from tempest import test CONF = config.CONF class AccountTest(base.BaseObject...
from pysb.testing import * import numpy as np from pysb import Monomer, Parameter, Initial, Observable, Rule, Expression from pysb.simulator.bng import BngSimulator, PopulationMap from pysb.bng import generate_equations from pysb.examples import robertson, expression_observables _BNG_SEED = 123 class TestBngSimulato...
import os import sys from yusuke.notify import notify from yusuke import __version__ def versionInfo(): print("Yusuke", __version__) print("Copyrig ht (C) 2016 graypawn <choi.pawn @gmail.com>") print("GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.") print("This is free software: you ar...
import supybot.conf as conf import supybot.registry as registry try: from supybot.i18n import PluginInternationalization _ = PluginInternationalization('LogTail') except: # Placeholder that allows to run the plugin on a bot # without the i18n module _ = lambda x:x def configure(advanced): # Thi...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import re import argparse from argparse import RawDescriptionHelpFormatter import os from ping import do_ping from sshcmd import sshcmd import logging from logging.handlers import SysLogHandler as syslog _NAME="ipsec-healt...
def madlib(): name = "Mark" pet = "Baxter" verb = "ate" snack = "Krispy Kreme Doughnuts" line1 = "Once upon a time, "+name+" was walking" line2 = " with "+pet+", a trained dragon. " line3 = "Suddenly, "+pet+" stopped and announced," line4 = "'I have a desperate need for "+snack+"...
from __future__ import print_function, division import os import numpy as np import numpy.testing as npt from msmbuilder.msm import MarkovStateModel from msmbuilder.utils import param_sweep from msmbuilder.msm import implied_timescales def test_both(): model = MarkovStateModel( reversible_type='mle', la...
from construct import * # The format of the string storage format (the *.gstr files). This is where # the bulk of localization efforts would go, though there are localized strings # in other files as well. GSTLFormat = Struct('gstl', Struct('header', Magic('GSTL'), Magic('\x01\x00\x00\x00'), ...
import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import db from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'cloudpipe_update') class CloudpipeUpdateController(wsgi.Contro...
#!/usr/bin/env python3 import unittest from game import Game, TEAMS, DEFAULT_START_POSITIONS from move import Move from copy import deepcopy from literals import INVALID_MOVE_MESSAGES class TestMove(unittest.TestCase): def setUp(self): self.game, self.piece, self.move = None, None, None self.max...
import os import numpy as np from urllib import request from . import CACHE_DIR def maybe_download(source_url, filename, destdir): """Download the data from Yann's website, unless it's already here.""" destdir = os.path.join(CACHE_DIR, destdir) if not os.path.exists(destdir): os.makedirs(destdir,...
# this is needed to load helper from the parent folder import sys sys.path.append('..') # the rest of the imports import helper as hlp import pandas as pd import mlpy as ml import numpy as np @hlp.timeit def findClusters_ward(data): ''' Cluster data using Ward's hierarchical clustering ''' # creat...
# coding=utf-8 """ Various configuration handlers. These work like the data handlers, except you can't write to them, and they load files from a different folder. You should absolutely use this if you're loading a user-supplied configuration that never needs to be written to programmatically. There is no in-between r...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ fasta-stats.py: Utility script to count number of nucleotides/Aminoacids in a FASTA files. Version 1.0 """ from __future__ import with_statement import sys import argparse import gzip #Counter is used for per-character statistics from collections import Counter impo...
import unittest import os.path from subprocess import check_output from tempfile import NamedTemporaryFile from crumbs.seq.mate_chimeras import (classify_mapped_reads, classify_chimeras, calculate_distance_distribution) from crumbs.utils.bin_utils import SEQ_BIN_DIR from crumbs.u...
from openerp.osv import orm, fields class stock_move(orm.Model): _inherit = "stock.move" def _get_direction(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} res = {} for move in self.browse(cr, uid, ids, context=context): ...
# -*- coding: utf-8 -*- # import re import time from django.http import HttpResponseRedirect, JsonResponse from django.conf import settings from django.views.generic import View from django.utils.translation import ugettext_lazy as _ from rest_framework.views import APIView from django.views.decorators.csrf import csr...
import logging from . import db import itertools _log = logging.getLogger(__name__) class SQLMappingTable(object): def __init__(self, mapping, engine): self.from_idtype = mapping.from_idtype self.to_idtype = mapping.to_idtype self._engine = engine self._query = mapping.query self._integer_ids =...