code
stringlengths
1
199k
"""Wide Residual Network models for Keras. - [Wide Residual Networks](https://arxiv.org/abs/1605.07146) """ from __future__ import print_function from __future__ import absolute_import from __future__ import division import warnings from keras.models import Model from keras.layers.core import Dense, Dropout, Activation...
import os import sys from fileinfo import FileInfo import logging import datetime import mods import xml.etree.ElementTree as ET dateTimeInfo = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") logger1 = logging.getLogger('1') logger1.addHandler(logging.FileHandler("logs/single_file_asset_to_mods_" + dateTimeInfo + ".l...
"""timeclock URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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...
"""URLs to run the tests.""" from django.contrib import admin from django.urls import path urlpatterns = [ path(r'admin/', admin.site.urls), ]
""" Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use mailgun to send emails - Use Redis on Heroku """ from __future__ import absolute_import, unicode_literals from boto.s3.connection import OrdinaryCallingFormat from django.utils import six from .common im...
__author__ = 'Сергей' from django import forms from django.forms.widgets import RadioFieldRenderer, RadioSelect from django.forms.utils import ErrorList from django.forms import ValidationError from django.utils.safestring import mark_safe from django.utils.html import format_html from django.contrib.auth import get_us...
from .availability_sets_operations import AvailabilitySetsOperations from .virtual_machine_extension_images_operations import VirtualMachineExtensionImagesOperations from .virtual_machine_extensions_operations import VirtualMachineExtensionsOperations from .virtual_machine_images_operations import VirtualMachineImagesO...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.context_processors import PermWrapper from notices import unpack, allowed_notice_types import re def notices(request): notices = {} try: for key, notice in request.GET.iteritems(): type ...
from django.conf.urls import url from . import views app_name = 'users' urlpatterns = [ url(r'^$', views.login, name='login'), url(r'logout/$', views.logout, name='logout'), url(r'register/$', views.register, name='register'), url(r'profile/$', views.profile, name='profile') ]
from __future__ import print_function import numpy as np from astropy import units as u from astropy import constants import scipy.stats from . import imf def pn11_mf(tnow=1, mmin=0.01*u.M_sun, mmax=120*u.M_sun, T0=10*u.K, T_mean=7*u.K, L0=10*u.pc, rho0=2e-21*u.g/u.cm**3, MS0=25, beta=0.4, alpha...
import os import serial import crcmod import time import time as time_ from w1thermsensor import W1ThermSensor sensor1 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "0000052cc99d") temp1 = int(round(sensor1.get_temperature())) sensor2 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "000004ce9b41") temp2 = int...
from devices.ecg import serializers from devices.ecg.models import BPM from devices.models import Device from rest_framework import permissions from rest_framework.response import Response from rest_framework.viewsets import ViewSet class DeviceEcg(ViewSet): serializer_class = serializers.BPMSerializer permissi...
r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information a...
import time import RPi.GPIO as GPIO def measure(): # This function measures a distance GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() while GPIO.input(GPIO_ECHO)==0: start = time.time() while GPIO.input(GPIO_ECHO)==1: stop = time.time() e...
__revision__ = "test/VariantDir/no-execute.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Verify that use of a VariantDir works when the -n option is used (and the VariantDir, therefore, isn't actually created) when both duplicate=0 and duplicate=1 are used. """ import os import TestSCons test = TestS...
import pytest from api import MsfLib, BaseFeed, Feed @pytest.fixture(scope="module") def config(): return MsfLib(version="1.0") @pytest.fixture(scope="module") def base(): config = MsfLib(version="1.0") base_ = BaseFeed() base_.config = config return base_ @pytest.fixture(scope="module") def feed():...
from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from .forms import NewMemberForm from django.contrib import messages def new_member_form(request): form = NewMemberForm(request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form...
import loadScripts as LS class calendarGenerator(object): def __init__(self): self.federations = [] self.federations.append(Federation(LS.VVBLoadScript, "VVB")) #return the names of the available federations def getFederations(self): res = [] for f in self.federations: ...
from app.lookups.sqlite.base import ResultLookupInterface MASTER_INDEX = 1 PROTEIN_ACC_INDEX = 2 PEPTIDE_COUNT_INDEX = 3 PSM_COUNT_INDEX = 4 PROTEIN_SCORE_INDEX = 5 COVERAGE_INDEX = 6 EVIDENCE_LVL_INDEX = 7 class PSMDB(ResultLookupInterface): def add_tables(self, tabletypes): self.create_tables(['psms', 'ps...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('product', '0002_product_created_at'), ] operations = [ migrations.AlterField( model_name='product', name='created_at', ...
from client import rest import items __author__ = 'Lann Martin' __copyright__ = 'Copyright 2011 %s' % __author__ __credits__ = [__author__] __license__ = 'MIT' __version__ = '0.1' __maintainer__ = __author__ __email__ = 'python-harvest@lannbox.com' USER_AGENT = 'python-harvest %s' % __version__ class Harvest(object): ...
def power_convert(obj, data): if obj.isSignal(): if obj._name== 'pinj': data = data / 1e3 else: data = data / 1e6 return data
"""Supporting definitions for the Python regression tests.""" import platform import unittest from typing import Any, Callable, Dict, Optional, Tuple __all__ = [ "run_with_locale", "cpython_only", ] def run_with_locale(catstr: str, *locales: str) -> Callable[..., Any]: def decorator(func: Callable[..., Any]...
import scrapy import json import re from locations.items import GeojsonPointItem DAYS = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] class HarristeeterSpider(scrapy.Spider): name = "harristeeter" allowed_domains = ["harristeeter.com"] start_urls = ( 'https://www.harristeeter.com/store/#/app/store-loca...
import os import json import time import sqlite3 import contextlib import webbrowser from pathlib import PurePosixPath, Path from tempfile import NamedTemporaryFile, TemporaryDirectory from urllib.request import pathname2url SQL_BACKSLASHED_CHARS = str.maketrans({ "\x00": "\\0", "\x08": "\\b", "\x09": "\\t"...
from twisted.test.proto_helpers import StringTransportWithDisconnection from hendrix.experience import hey_joe def test_websocket_mechanics(): """ Shows that we can put our protocol (hey_joe._WayDownSouth) and factory (hey_joe.WebSocketService) together, along with a transport, and properly open a websocket...
"""Nikola -- a modular, fast, simple, static website generator.""" import os import sys __version__ = '8.0.0.dev0' DEBUG = bool(os.getenv('NIKOLA_DEBUG')) if sys.version_info[0] == 2: raise Exception("Nikola does not support Python 2.") from .nikola import Nikola # NOQA from . import plugins # NOQA
__revision__ = "test/scons-time/run/config/scons.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Verify specifying an alternate SCons through a config file. """ import TestSCons_time test = TestSCons_time.TestSCons_time() test.write_sample_project('foo.tar.gz') my_scons_py = test.workpath('my_scons.py'...
from datetime import datetime, timedelta from app.dao.notifications_dao import dao_get_last_date_template_was_used from tests.app.db import create_ft_notification_status, create_notification def test_dao_get_last_date_template_was_used_returns_bst_date_from_stats_table( sample_template ): last_status_date =...
import numpy import chainer from chainer.backends import cuda from chainer.backends import intel64 from chainer import function_node import chainer.functions from chainer.functions.math import floor as _floor from chainer import utils from chainer.utils import type_check from chainer import variable def _convert_value_...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openunipay.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
__all__ = ['ku6_download', 'ku6_download_by_id'] from ..common import * import json import re def ku6_download_by_id(id, title = None, output_dir = '.', merge = True, info_only = False): data = json.loads(get_html('http://v.ku6.com/fetchVideo4Player/%s...html' % id))['data'] t = data['t'] f = data['f'] ...
import asyncio import os import sys import mido import mido.backends.rtmidi import pickle import hashlib from itertools import zip_longest from animator import MidiFighterAnimator class MidiServer(object): knobStateFilename = 'knobState' knobConfigFilename = 'knobConfig' def __init__(self, hostname, port): ...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'hellodjango.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
from __future__ import print_function import os import sys if not os.path.isfile("pynmrstar.py"): if not os.path.isfile("../pynmrstar.py"): raise ImportError("Could not locate pynmrstar.py library. Please copy to this directory.") sys.path.append("..") import bmrb if len(sys.argv) < 2: raise ValueEr...
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Paym...
import pytest from readthedocs.search.faceted_search import PageSearch @pytest.mark.django_db @pytest.mark.search class TestPageSearch: @pytest.mark.parametrize('case', ['upper', 'lower', 'title']) def test_search_exact_match(self, client, project, case): """Check quoted query match exact phrase with ca...
""" WSGI config for dummy_only 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.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTING...
"""Test descendant package tracking carve-out allowing one final transaction in an otherwise-full package as long as it has only one parent and is <= 10k in size. """ from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, assert_rai...
from Network import Network from Models import NonstationaryLogistic, alpha_unif from Experiment import RandomSubnetworks from numpy.random import normal, seed seed(137) N = 100 net = Network(N) alpha_unif(net, 0.5) data_model = NonstationaryLogistic() data_model.kappa = -1.0 covariates = ['x_%d' % i for i in range(1)]...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('NYRP', '0016_selector_indexes'), ] operations = [ migrations.AlterField( model_name='selector', name='indexes', field...
""" Author: C. Grima (cyril.grima@gmail.com) """
import numpy as np import time from scipy import sparse from petsc4py import PETSc from pigasus.gallery.poisson import poisson from igakit.cad_geometry import square as domain import sys import inspect filename = inspect.getfile(inspect.currentframe()) # script filename (usually with path) sys.stdout = open(filename.sp...
import cherrypy, unittest, os, shutil from finaLib import finaDisp as fd from fina import home from . import cptestcase as ctc def setUpModule(): cherrypy.tree.mount(home(), '/', "home.cfg") cherrypy.engine.start() setup_module = setUpModule def tearDownModule(): cherrypy.engine.exit() teardown_module = tearDownM...
""" Usage: jiver build-and-run [--skip-tests] <maven-module>... jiver core-checkout [--depth-1] <version> jiver core-checkout-url [--depth-1] <url> jiver create (project | plugin) jiver database (connect | backup | restore-latest) jiver diffmerge <directory-1> <directory-2> <file> jiv...
from os.path import basename from rauth import OAuth2Session, OAuth2Service from requests_toolbelt import MultipartEncoder class BitcasaException(Exception): @classmethod def check(cls, data): if 'error' in data and data['error']: error = data['error'] raise cls(error.get('messag...
""" Присваивание """ aList = [123, 'abc', 4.56, ['inner', 'list'], 7-9j] anotherList = [None, 'something to see here'] print aList print anotherList aListThatStartedEmpty = [] print aListThatStartedEmpty print list('foo')
import sys import os import numpy as np from condor_kmeans.condor import CondorKmeans if __name__ == '__main__': num_points = 10000 num_clusters = 5 num_dimensions = 2 cluster_colors = ['blue', 'orange', 'purple', 'goldenrod', 'pink'] clusters = np.random.random(size=(num_clusters, num_dimensions)) ...
from __future__ import print_function try: input = raw_input except: pass import fileinput import pyRBT import sys from collections import defaultdict class Alignment: def __init__(self,seqid,start1,start2,length): self.seqid = seqid self.start1,self.start2,self.length = start1,start2,length def __cmp__(x,y...
import re import sys from subprocess import Popen, PIPE class ARP(object): """ Finds the MAC Addresses using ARP NOTE: This finds mac addresses only within the subnet. It doesn't fetch mac addresses for routed network ips. """ MAC_RE = re.compile(r'(([a-f\d]{1,2}[:-]){5}[a-f\d]{1,2})') def __ini...
"""Cut down the number of HML forecasts stored Suspicion is that do to retrans, etc, there are lots of dups in the HML database. So this attempts to de-dup them. """ import sys import datetime from pyiem.util import get_dbconn, logger, utc LOG = logger() def workflow(ts): """Deduplicate this timestep""" pgconn...
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from datetime import datetime from time import mktime from collections import Counter class JuniorCollector(): def __init__(self...
"""Keychain.py Simple Keychain library for MacOSX Keychain.py is a simple class allowing access to keychain data and settings. Keychain.py can also setup new keychains as required. As the keychain is only available on MaxOSX the module will raise ImportError if import is attempted on anything other than Mac OSX Create...
from __future__ import print_function from __future__ import unicode_literals import unittest import mongoengine from bson import DBRef, ObjectId from pyramid import testing from pyramid.request import Request from mongoengine_relational.relationalmixin import set_difference, equals from tests_mongoengine_relational.ba...
from qstrader.execution.execution_handler import ( ExecutionHandler ) from qstrader.execution.execution_algo.market_order import ( MarketOrderExecutionAlgorithm ) from qstrader.portcon.pcm import ( PortfolioConstructionModel ) from qstrader.portcon.optimiser.fixed_weight import ( FixedWeightPortfolioOpt...
import random import physicalobject, resources class Asteroid(physicalobject.PhysicalObject): """An asteroid that divides a little before it dies""" def __init__(self, *args, **kwargs): super(Asteroid, self).__init__(resources.asteroid_image, *args, **kwargs) # Slowly rotate the asteroid as it m...
""" Molecular linker object """ import os import math import copy import numpy as np from moleidoscope.geo.quaternion import Quaternion from moleidoscope.mirror import Mirror from moleidoscope.hd import read_library from moleidoscope.output import save from moleidoscope.input import read_xyz from moleidoscope.geo.vecto...
import subprocess from os3.fs.entry import Entry from os3.core.list import init_tree, Os3List def all_childrens(process): yield process for child in process._children: for subchild in all_childrens(child): yield subchild def set_cache_tree(tree): tree = list(tree) process_by_pid = {p...
def k_fold_cross_validation(X, K, randomise = False): """ Generates K (training, validation) pairs from the items in X. Each pair is a partition of X, where validation is an iterable of length len(X)/K. So each training iterable is of length (K-1)*len(X)/K. If randomise is true, a copy of X is shuffled before part...
from django.shortcuts import render from datetime import datetime from django.http import HttpResponse from django.http import HttpResponseRedirect from trips.models import Post from trips.models import Article from trips.models import IDForm from trips.models import StateForm from trips.models import LogForm from trip...
"""Chat client. 聊天客户端。 Available functions: - question_pack: Package the question as the JSON format specified by the server. 将问题打包为服务器指定的json格式。 - config_pack: Package the config info as the JSON format specified by the server. 将配置信息打包为服务器指定的json格式。 - match:Match the answers from the semantic knowledge database. 从语义知识...
def near_hundred(n): if n <=100 and n >=90: return True elif n <=110 and n >=100: return True elif n <=200 and n >=190: return True elif n <=210 and n >=200: return True else: return False
import os import sys import numpy import scipy.io import gzip import cPickle import theano import cv2 def shared_dataset(data_xy, borrow=True, svm_flag = True): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(numpy.asarray(d...
from PIL import Image, ImageDraw, ImageFont from mockaron.generators import Generator class LogoLayout: pass class IconText(LogoLayout): """A layout for logo with an icon on the left and the text on the right. The generated image will contain: left margin + icon + space + text + right margin Usage: impo...
from sqlalchemy import Column, Integer, String, Text, Enum, Float, ForeignKey, ForeignKeyConstraint from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from sqlalchemy.dialects import mysql...
from decimal import Decimal import hashlib from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from . import NAME from django.views.decorators.csrf import csrf_exempt from default_set.models import * from default_set.tra...
from behave import then, when from django.urls import reverse from test_app.models import BehaveTestModel @when(u'I call get_url() without arguments') def without_args(context): context.result = context.get_url() @when(u'I call get_url("{url_path}") with an absolute path') def path_arg(context, url_path): conte...
"""Provide a GANGA interface for master worker computing with PyMW. """ __author__ = "Wayne San <waynesan@twgrid.org>" __date__ = "6 May 2010" import subprocess import os import time import sys import shutil import pickle import threading GANGA_TEMPLATE = """j = Job(name = 'PyMW Worker') j.backend = %(GANGA_BKN)s j.app...
"""A flask API for generating (and retrieving) player details! Usage: api.py run [--no-debug] [--port=<p>] [--host=<h>] api.py (-h | --help) Options: -h --help Show this screen --no-debug Don't add debug=True when running --port=<p> The port to use [default: 5000] --host...
""" Evrything Docs https://dashboard.evrythng.com/documentation/api/reactor """ from evrythng import assertions, utils reactor_bundle_field_specs = { 'datatypes': { 'bundle_bytes': 'not_implemented', }, 'readonly': ('id', 'createdAt', 'updatedAt'), 'writable': ('bundle_bytes',), 'required': ...
from __future__ import print_function import os from subprocess import call import xml.etree.ElementTree as etree from wand.image import Image from .symbol import VectorSymbol, Pattern __all__ = ['symbolsets', 'generate_symbolset', 'update_file'] here = os.path.dirname(__file__) symbolsets = ('day', 'dusk', 'dark') def...
""" Support for Homematic binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.homematic/ """ import logging from homeassistant.const import STATE_UNKNOWN from homeassistant.components.binary_sensor import BinarySensorDevice import...
import subprocess from io import StringIO from time import sleep import multiprocess as multiprocessing from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from BioSQL import BioSeqDatabase from BioSQL.BioSeq import DBSeqRecord from Bio import SeqIO, SeqFeature from RecBlast.Search import id_search from inspect...
from Resizer import Resizer class RendezvousHashing(Resizer): """Implement Highest Random Weight hashing method. Part of 'Functional Core' - methods of this class don't change any state or objects, all they do is take values and return values. """ def __init__(self, nodes): pass def get_...
from euler_funcs import timed import sympy as sp def coef(n,i): l = [n*i] l.extend([i]*(n-1)) l[i-1]+=1 l = l[1:] + [l[0]] return l def doit(n): lofl = [] for i in range(2,n+1): lofl.append(coef(n,i)) sol = sp.Matrix(lofl).rref() arr = sol[0][n-1::n] missing = n - sum(arr...
"""Checks for environment variables""" import os from preflyt.base import BaseChecker class EnvironmentChecker(BaseChecker): """Verify that an environment variable is present and, if so, it has a specific value.""" checker_name = "env" def __init__(self, name, value=None): """Initialize the checker ...
import uuid import time import logging import pytest import requests @pytest.yield_fixture def logger(handler): logger = logging.getLogger('test') logger.addHandler(handler) yield logger logger.removeHandler(handler) def log_warning(logger, message, args=None, fields=None): args = args if args else ...
from functools import wraps from elasticsearch.exceptions import NotFoundError from flask import abort def index_exists(es, index_name): if not es.indices.exists(index=index_name): raise Exception("Index does not exist") def needs_es(index_name=None): def inner_function(function=None): @wraps(fu...
import sys from . import px_terminal if sys.version_info.major >= 3: # For mypy PEP-484 static typing validation from . import px_process # NOQA from six import text_type # NOQA from typing import List # NOQA from typing import Tuple # NOQA from typing import Dict # NOQA from typing imp...
import logging from parsemypsa.storage import objects def compute_mileage(): mileage = 0 result = 0.0 for trip in objects.Trip.select(): trip.calculate_mileage() logging.debug("%f, %f, %f" % (trip.fuel_consumation, trip.distance, trip.mileage)) mileage = mileage + trip.mileage tr...
''' BUBBLE SORT ''' num = [int(input("digite o primeiro numero: ")),int(input("digite o segundo numero: ")),int(input("digite o terceiro numero: "))] def ordenar(lista): for x in range(len(lista)-1,0,-1): for i in range(x): if (lista[i] > lista[i+1]): aux = lista[i] ...
from test_framework.test_framework import VCoinTestFramework from test_framework.util import * try: import urllib.parse as urlparse except ImportError: import urlparse class AbandonConflictTest(VCoinTestFramework): def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self...
from textwrap import dedent from docxUtils.reports import DOCXReport from docxUtils.tables import TableMaker HUMAN_VIVO_FOOTNOTE = """+, positive –, negative +/–, equivocal (variable response in several experiments within an adequate study) * Significance is indicated using asterisks (+) or (–), positive/negative in a ...
from interpreter.heap import peek, declare def closure( oply, index, declaration, identifier, identifiers, value ): H = "H" + str( oply.len ) oply.heap[H] = [ declaration, value, index ] if identifiers == "nil" else [ declaration, identifiers, value, index ] oply.len = oply.len + 1 index = peek( oply ) ...
import email import os.path import six from django.test import TestCase from django_mailbox import models from django_mailbox.models import Mailbox, Message def get_email_as_text(name): with open( os.path.join( os.path.dirname(__file__), 'messages', name, ), ...
def create_django_choice_tuple_from_list(list_a): if list_a is None: return () tuples_list = [] for item in list_a: if isinstance(item, str): tuple_item_title = item.title() else: tuple_item_title = item tuple_item = (item, tuple_item_title) tu...
import sys import json import requests import pprint import unittest import string import random import os import json import time import datetime import base64 import uuid import argparse pp = pprint.PrettyPrinter(depth=6) parser = argparse.ArgumentParser() parser.add_argument('--quite', help='Just...
from modules.commands.helpers.textutil import get as get_pun HELP_TEXT = ["!pun", "Displays a random reviewed pun from your channel."] def call(salty_inst, c_msg, **kwargs): success, response = get_pun(salty_inst, c_msg, "pun", **kwargs) return success, response def test(salty_inst, c_msg, **kwargs): assert...
from . import main from flask import render_template @main.route('/') def index(): return render_template('index.html')
import time from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.sites.models import Site from django.contrib.a...
"""Sonos Music Services interface. This module provides the MusicService class and related functionality. """ from __future__ import absolute_import, unicode_literals import logging import requests from xmltodict import parse from .. import discovery from ..compat import parse_qs, quote_url, urlparse from ..exceptions ...
from ._utils import CreatureUtils from ._action import CreatureAction from copy import deepcopy class Creature(CreatureAction, CreatureUtils): """ Creature class handles the creatures and their actions and some interactions with the encounter. """ pass
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('excerptexport', '0061_auto_20210831_1502'), ] operations = [ migrations.AddField( model_name='export', name='estimated_pbf_size', field=models.FloatField(nul...
from django.contrib.auth.models import User def _useful_details(details): return { "username": details["player"]["steamid"], "first_name": details["player"]["personaname"], } def user_details(user, details, strategy, *args, **kwargs): """Update user details using data from provider.""" i...
import pylab as pyl import numpy as np import matplotlib.pyplot as pp import scipy as scp import scipy.ndimage as ni import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import rospy import hrl_lib.viz as hv import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu import pickle import unittest import ghm...
from backend.util.coords import Coords class SingleBlockInitPos(): def __init__(self, row_num=400, col_num=600): self.current_row = 100 self.current_col = 100 self.row_num = row_num self.col_num = col_num def __iter__(self): return self def __next__(self): if ...
""" :Author Patrik Valkovic :Created 19.08.2017 17:25 :Licence MIT Part of grammpy """ from unittest import TestCase, main from grammpy import * class A(Nonterminal): pass class B(Nonterminal): pass class C(Nonterminal): pass class Rules(Rule): rules = [ ([A], [B, C]), ([A], [EPS]), ([B], [0...
import numpy as np from numpy import * from rlscore.utilities import array_tools def accuracy_singletask(Y, P): assert Y.shape[0] == P.shape[0] vlen = float(Y.shape[0]) perf = sum(sign(multiply(Y, P)) + 1.) / (2 * vlen) return perf def accuracy_multitask(Y, P): Y = np.mat(Y) P = np.mat(P) vl...
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="treemap.pathbar.textfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
import pygame as pg import random import os from settings import * from sprites import * from os import path class Game: def __init__(self): # Initialize game window, etc pg.init() pg.mixer.init() self.screen = pg.display.set_mode((width, height)) pg.display.set_caption(title...