code stringlengths 1 199k |
|---|
from random import shuffle
from res import types
from src import ai
from src import coordinate
from src import historynode
from src import interface
from settings import (DISPLAYEVALUATION,
SEARCHPLY,
STANDARD,
USERPLAYSFOX)
def aPlayerHasWon(game):
... |
"""
Mock SMBUS
"""
class SMBus(object):
"""
SMBus
http://blog.bitify.co.uk/2013/11/interfacing-raspberry-pi-and-mpu-6050.html
"""
def __init__(self, V=1):
"""
"""
self.version=V
def write_byte_data(self, address, reg, value):
"""
write_byte... |
import sqlalchemy as sa
from auto.models.base import Base, WithOrigin
class BaseSteering:
id = sa.Column(sa.Integer, autoincrement=True)
complectation_id = sa.Column(sa.Integer, nullable=False)
amplifier_id = sa.Column(sa.Integer, nullable=True)
spread_diameter = sa.Column(sa.Integer, nullable=True) # ... |
import os
from .model import PageModel
__VERSION__ = "0.0.20" |
template = 'R=2 \cdot %.0f +%.0f=%.0f~\\text{Ом}'%(h_11,R_eg,R) |
import os
import threading
import time
import datetime
import configparser
from subprocess import check_output
from os import system
class ConfigReader:
def __init__(self):
self.config = configparser.ConfigParser()
self.config['Misc'] = {'Delay in seconds': '10', 'Number of dropped packets': '5'}
... |
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
SCOPES = "https://www.googleapis.com/auth/spreadsheet... |
import numpy as np
def LCSBackTrack(v, w):
s = np.zeros((len(v)+1,len(w)+1))
backtrack = np.zeros((len(v)+1,len(w)+1))
for i in range(1, len(v)+1):
for j in range(1, len(w)+1):
if v[i-1] == w[j-1]:
s[i][j] = max(s[i-1][j], s[i][j-1], s[i-1][j-1]+1)
else:
... |
from pygsl import _numobj as numx
from pygsl import wavelet, errors
import pylab
def transform(data):
w = wavelet.daubechies(4)
# If no workspace is given, the wrapper will allocate one itself for the
# transform. I am not sure how much of an performance impact that is.
result = w.transform_forward(data... |
from .date_files import DateFiles |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Gradient(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattergeo.marker"
_path_str = "scattergeo.marker.gradient"
_valid_props = {"color", "colorsr... |
import json
import unittest
import httpretty
from pkgparse.registry.rubygems import RubygemsRegistry
from tests import utils
class RubygemsRegistryUnitTestCase(unittest.TestCase):
@httpretty.activate
def test_fetch_rubygems_pkg_details(self):
"""
Test that given a valid Rubygems package name, it... |
"""
Copyright 2006-2008 SpringSource (http://springsource.com), All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Un... |
import os
from tinytag import TinyTag
print("Valid responses:\nY: Rename\nS: Skip album\nN: Do nothing\n")
continuing = False
for (path, directories, files) in os.walk("/home/daboross/Music"):
if continuing:
print("\n")
continuing = False
split = path.rsplit("/", 2)
if len(split) < 3:
co... |
from setuptools import setup
from pkgstack import __title__
from pkgstack import __version__
setup(
name=__title__,
version=__version__,
description='Simple python package management tool based on pip',
url='https://github.com/ownport/pkgstack',
author='ownport',
author_email='ownport@gmail.com'... |
import os
import re
class DocsWriter:
"""Utility class used to write the HTML files used on the documentation"""
def __init__(self, filename, type_to_path_function):
"""Initializes the writer to the specified output file,
creating the parent directories when used if required.
'type... |
class Solution:
def prisonAfterNDays(self, cells, N):
self.cells = cells
key = ''.join(map(str, cells))
d, l = {}, []
def next_key():
new_cells = [0]*8
for i in range(1,7):
new_cells[i] = 1-(self.cells[i-1]+self.cells[i+1])%2
self.c... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalogue', '0005_submitted_created_... |
from nose.tools import *
from ..stegatonic.stegatonic import StegaTonic
from ..stegatonic.stegatonicCrypto import StegaTonicCrypto
def test_encryption_decryption():
crypto = StegaTonicCrypto()
test_string = "Testing encryption and decryption"
test_password = "test this"
encrypted = crypto.encrypt(test_stri... |
'''Gets clients using a filter that only returns clients that have registered within a certain time'''
__author__ = 'Jim Olsen <jim.olsen@tanium.com>'
__version__ = '2.1.6'
pytan_loc = '~/gh/pytan'
import os
import sys
sys.dont_write_bytecode = True
sys.path.append(os.path.join(os.path.expanduser(pytan_loc), 'lib'))
my... |
from __future__ import division
import nltk, re, pprint
from nltk.corpus import brown
raw = "I do not like green eggs and ham, I do not like the Sam I am!"
tokens = nltk.word_tokenize(raw)
default_tagger = nltk.DefaultTagger('NN')
print default_tagger.tag(tokens)
print "###"
patterns = [
(r'.*ing$', 'VBG'), # geru... |
"""
This is the age_model.py module, to invert isochronal layers along a radar profile.
"""
import os
import time
import sys
import random
import math as m
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LogNorm, Normalize
from matplotli... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('unach_photo_server', '0006_photorepository_is_blob'),
]
operations = [
migrations.AlterField(
model_name='photorepository',
name=... |
import argparse
from itertools import combinations
from multiprocessing import Process, Pool
import cv2
import numpy as np
import learning
import transformation
from Card import Card
from image_processing import auto_canny
def find_cards_in_image(im):
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
edges = auto_canny... |
"""
Created on 20 Nov 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import re
class RealtimeClient(object):
"""
classdocs
"""
__HOST = "realtime.opensensors.io" # hard-coded URL
# -----------------------------------------------------------------------------------------... |
import argparse
import time
import os
from train_agent import train_agent
parser = argparse.ArgumentParser(description="Main script for running the model")
parser.add_argument('--scoring-function', action='store', dest='scoring_function',
choices=['activity_model', 'tanimoto', 'no_sulphur'],
... |
import os
import shutil
import ioutil
CUSTOM_INIs = ['development.ini','test.ini']
RUNROOT_NUKE_EXCEPTIONS = [r'(development|test)\.ini$', r'\.ini\.unedited$']
def filter_build_phase(item):
if item.endswith('.bzr/'):
return False
fname = os.path.basename(item)
keep = not (fname.endswith('.pyc') or
... |
from .UniqueTreeContainer import UniqueTreeContainer
class UniqueTreeTuple(UniqueTreeContainer):
"""
A tuple-like node in a "unique" tree.
"""
### INITIALIZER ###
def __init__(self, children=None, name=None):
super().__init__(name=name)
self._children = []
self._mutate(slice(... |
import json
import itertools as it
from collections import defaultdict
import textwrap
from itertools import chain
COURSE_LIST_FILENAME = 'course_list.json'
REVERSE_KDAM_FILENAME = 'reverse_kdam.json'
REVERSE_ADJACENT_FILENAME = 'reverse_adjacent.json'
def read_json_to_dict(filename=COURSE_LIST_FILENAME):
with open... |
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
fr... |
from src import app
from flask_jsontools import jsonapi
from flask import render_template, request
from google.appengine.api import mail
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
return render_template('index.html')
@app.route('/contact/email', methods=['POST'])
@jsonapi
def... |
import asyncio
import logging
import os
from binascii import hexlify
from lbry.testcase import CommandTestCase
from lbry.blob_exchange.downloader import BlobDownloader
class FileCommands(CommandTestCase):
VERBOSITY = logging.WARN
async def test_file_management(self):
await self.stream_create('foo', '0.0... |
'''
Created on 2017/12/27.
@author: chk01
'''
from utils import *
eyebr, eye, nose, lip, chinA, chinB, chinC, chinD, chinE = load_feature_matrix()
ChinData = {"A": chinA, "B": chinB, "C": chinC, "D": chinD, "E": chinE}
CartoonPoint = load_cartoon_center()
Glasses = [164, 75]
def organ_struct(landmark72):
# reb,reye... |
"""Notification channels to which to propagate alert messages."""
from verta._internal_utils import documentation
from ._notification_channel import (
_NotificationChannel,
SlackNotificationChannel,
)
documentation.reassign_module(
[SlackNotificationChannel],
module_name=__name__,
) |
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
NEVER = 'n'
CONNECTION_ERROR = 'c'
TIMEOUT = 't'
CONNECTION_ERROR_AND_TIMEOUT = 'ct'
DEFAULT = CONNECTION_ERROR
DEFAULT_RETRY_LIMIT = 4 |
import logging
from genmod.vcf_tools import (add_metadata)
logger = logging.getLogger(__name__)
def add_regions(header):
"""Add region annotations to header"""
logger.info("Adding 'Annotation' to vcf header")
add_metadata(
header,
'info',
'Annotation',
annotation_number='.',
... |
import pytest
from testing import norm
from testing.assertions import assert_svstat
from testing.assertions import wait_for
from testing.subprocess import assert_command
pytestmark = pytest.mark.usefixtures('in_example_dir')
@pytest.fixture
def service_name():
yield 'unreliable'
def it_fails_twice_but_doesnt_restar... |
"""
runSim.py
28 May 2012
Glenn Hickey, hickey (a) soe ucsc edu
Dent Earl, dearl (a) soe ucsc edu
"""
import argparse
import cPickle
import os
import sys
import copy
import random
import math
from collections import defaultdict
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.backends.backen... |
from msrest.pipeline import ClientRawResponse
from .. import models
class HttpSuccess(object):
"""HttpSuccess operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model des... |
from __future__ import unicode_literals
from django.db import migrations, models
def set_null_values(apps, schema_editor):
Course = apps.get_model("studygroups", "Course")
Course.objects.filter(total_ratings__isnull=True).update(total_ratings=0)
Course.objects.filter(total_reviewers__isnull=True).update(to... |
from __future__ import print_function, absolute_import, unicode_literals
def tzlc(dt, tz, truncate_to_sec=True):
if dt is None:
return None
if truncate_to_sec:
dt = dt.replace(microsecond=0)
return tz.localize(dt) |
"""
__graph_IN1.py___________________________________________________________
Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION
_________________________________________________________________________
"""
import tkFont
from graphEntity import *
from GraphicalForm import *
from ATOM3C... |
"""
Generalized N-Point Crossover.
For even values of N, perform N point crossover
(select N/2 points each in the two genomes, and alternate)
For odd values of N, perform symmetric N+1 point crossover
(select N/2 points for both genomes)
N-Point introduction (my notation):
| genome 1: A-----B-----C-----D----... |
from Acquisition import aq_inner
from five import grok
import calendar
from DateTime import DateTime
from plone.directives import dexterity, form
from Products.CMFPlone.PloneBatch import Batch
from Products.CMFCore.utils import getToolByName
try:
from plone.app.discussion.interfaces import IConversation
USE_PAD... |
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseForbidden
from django.shortcuts im... |
import re
string = '''Love, Kenneth, kenneth+challenge@teamtreehouse.com, 555-555-5555, @kennethlove
Chalkley, Andrew, andrew@teamtreehouse.co.uk, 555-555-5556, @chalkers
McFarland, Dave, dave.mcfarland@teamtreehouse.com, 555-555-5557, @davemcfarland
Kesten, Joy, joy@teamtreehouse.com, 555-555-5558, @joykesten'''
conta... |
"""
Setup script for the optinum package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="optinum",
version="0.1a",
description=(
"This project provides the user with an analysis regarding "
"the results obtained by a couple of ... |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import settings
import utils
from collections import Counter
from sklearn.model_selection import StratifiedShuffleSplit
class DataGenerator:
def __init__(self, settings, dataloader):
self.settings = set... |
from nameko.extensions import DependencyProvider
class Config(DependencyProvider):
def get_dependency(self, worker_ctx):
return self.container.config.copy() |
def print2(*args):
print "1: %s\n2: %s" % args
def print2again(arg1, arg2):
print "%s and %s" % (arg1, arg2)
def print1(arg1):
print "%s is sized %d" % (arg1, len(arg1))
def print0():
print "no no no, nothing passed"
print2('python', 'pro')
print2again('python', 'pro')
print1('python')
print0() |
def get_batch_idx(N, batch_size):
num_batches = (N + batch_size - 1) / batch_size
for i in range(num_batches):
start, end = i * batch_size, (i + 1) * batch_size
idx = slice(start, end)
yield idx
if __name__ == '__main__':
import numpy as np
X = np.random.random((14, 4))
print... |
"""Support for interface with a Ziggo Mediabox XL."""
from __future__ import annotations
import logging
import socket
import voluptuous as vol
from ziggo_mediabox_xl import ZiggoMediaboxXL
from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.con... |
from django.conf.urls import url # url(regex, template, name=<name>)
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.BlogPostListView.as_view(), name='blog_home'),
url(r'^newblogpost/$', views.new_blog_post, name='new_blog_post')
] |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Monster'
db.create_table('dnd_monster', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=T... |
from distutils.core import setup, Extension
DESCRIPTION = """
p53scan (http://www.ncmls.nl/bioinfo/p53scan/) is an algorithm to
locate p53 binding sites in DNA sequences. It is described in:
Smeenk L, van Heeringen SJ, Koeppel M, Driel MA, Bartels SJ,
Akkers RC, Denissov S, Stunnenberg HG, Lohrum M. Characterization
o... |
'''
This script will validate a DataModel against an collection of
input files. It will verify they are able to be parsed correctly.
'''
import os, sys, time, glob
sys.path.append("c:/peach")
print """
]] Peach Validate Multiple Files
]] Copyright (c) Michael Eddington
"""
if len(sys.argv) < 3:
print """
This program... |
'''
sum of numbers which are in the even positions
'''
N = int(raw_input())
x = map(int, raw_input().split())
total = 0
for i in xrange(1, N+1):
if i%2==0:
total += x[i]
print total |
'''
Queue manager script for SCDA mask optimization programs
4-20-2016
AUTHOR
Neil Zimmerman
Space Telescope Science Institute
USAGE
Execute directly from the command line, specifying the name of the design
survey file (extension .pkl) as an argument. For example:
$ ./scda_queuefill.py april_survey01_15bw_ntz_2016-04-2... |
from lablog.interfaces import Interface
import humongolus.field as field
from xml.etree import ElementTree as ET
from datetime import datetime
from datetime import timedelta
from lablog import messages
import requests
import logging
class RTTP(Interface):
exchange = messages.Exchanges.energy
measurement_key = "... |
import itertools
import argparse
import sys
parser = argparse.ArgumentParser(description='Generate an (n)fecta sheet for betting on the order of multiple outcomes.')
parser.add_argument('-o', '--file', dest='file', default='trifecta.html')
parser.add_argument('-r', '--racers', dest='racers', help='How many elements to ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('falkor', '0006_auto_20161102_0455'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'permissions': (('ca... |
from pearce.emulator import NashvilleHot
from GPy.kern import *
import numpy as np
from os import path
training_file = '/home/users/swmclau2/scratch/xi_gg_fastpm/PearceXiggFastPM.hdf5'
em_method = 'gp'
fixed_params = {'z': 0.5503876}
hyperparams = {'kernel': (Matern32(input_dim=8, ARD=True) + RBF(input_dim=8, ARD=True)... |
__author__ = 'dmitrij'
from django.conf.urls import patterns, include, url
urlpatterns = patterns('places.views',
# Examples:
# url(r'^$', 'jmd.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'home'... |
from benchmark import Benchmark
import libtree
def _get_node_by_title(transaction, title):
nodes = transaction.get_nodes_by_property_value("title", title)
return nodes.pop() if nodes else None
def change_parent_worst_case(transaction):
node = _get_node_by_title(transaction, "0x0")
new_parent = _get_node... |
import binascii
import hashlib
import asyncio
import websockets
import random
import secrets
H = 'sha256'
N = "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02... |
from datetime import date
import unittest
from meetup import meetup, MeetupDayException
class MeetupTest(unittest.TestCase):
def test_monteenth_of_may_2013(self):
self.assertEqual(meetup(2013, 5, "teenth", "Monday"), date(2013, 5, 13))
def test_monteenth_of_august_2013(self):
self.assertEqual(me... |
"""
Remove distortion of camera lens and project to the real world coordinates.
(C) 2016-2019 1024jp
"""
import io
import os
import unittest
import sys
import numpy as np
from modules import argsparser
from modules.datafile import Data
from modules.undistortion import Undistorter
from modules.projection import Projecto... |
import numpy as np
l_1d = [0, 1, 2]
arr_1d = np.array(l_1d)
print(arr_1d)
print(arr_1d.dtype)
arr_1d_f = np.array(l_1d, dtype=float)
print(arr_1d_f)
print(arr_1d_f.dtype)
l_2d = [[0, 1, 2], [3, 4, 5]]
arr_2d = np.array(l_2d)
print(arr_2d)
l_2d_error = [[0, 1, 2], [3, 4]]
arr_2d_error = np.array(l_2d_error)
print(arr_2d... |
import json
import codecs
class ScrapyDeepinBbsPipeline(object):
def __init__(self):
self.file = codecs.open('deepin_bbs.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item
... |
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
""" czy tu nie brakuje:
if request.user.is_superuser:
return True
"""
if request.method == "DELETE":
return False
... |
import gdsfactory as gf
def test_route_error2():
"""Ensures that an impossible route raises value Error"""
c = gf.Component("pads_route_from_steps")
pt = c << gf.components.pad_array(orientation=270, columns=3)
pb = c << gf.components.pad_array(orientation=90, columns=3)
pt.move((100, 200))
rout... |
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
return (num-1)%9+1 if num else 0 |
class Loki:
@staticmethod
def printf(x):
print(x)
@staticmethod
def plus(*args):
return reduce((lambda x, y : x + y), args)
@staticmethod
def minus(*args):
return reduce((lambda x, y : x - y), args)
@staticmethod
def div(*args):
return reduce((lambda x, y ... |
__author__ = "Miracle Wong"
class Fibonacci(object):
"""返回一个Fibonacci数列"""
def __init__(self):
self.fList = [0,1] #设置初始数列
self.main()
def main(self):
listLen = raw_input('请输入Fibonacci数列的长度(3-50):')
self.checkLen(listLen)
while len(self.fList) < int(listLen):
... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from paw.models import Page, IconFolder, PageTextLink, PageIconDisplay, EntryPoint
from django.views.decorators.cache import cache_page
def _getPageDict(page):
iconFolders = IconFolder.objects.all()
leftText = ... |
import os
import ycm_core
flags = [
'-x',
'c++',
'-DETL_VECTORIZE_FULL',
'-DNDEBUG',
'-ICatch/include',
'-Ietl/include/',
'-Ietl/lib/include',
'-Iinclude',
'-Imnist/include/',
'-Inice_svm/include',
'-Wall',
'-Wdocumentation',
'-Werror',
'-Wextra',
'-Winit-self... |
""" --- Day 7: Some Assembly Required ---
This year, Santa brought little Bobby Tables
a set of wires and bitwise logic gates!
Unfortunately, little Bobby is a little under the recommended age range,
and he needs help assembling the circuit.
Each wire has an identifier (some lowercase letters)
and can carry a 16-bit si... |
'''
Created on Feb 23, 2012
@author: sstrau
1) download and install py2exe from http://sourceforge.net/projects/py2exe
2) run python setup.py py2exe
'''
import sys
from glob import glob
"""
image_files = []
for files in os.listdir('gfx/'):
f1 = 'gfx/' + files
if os.path.isfile(f1):
f2 = 'images', [f1]
... |
from panda3d.bullet import BulletWorld, BulletDebugNode
from pandac.PandaModules import Vec3
from direct.task.Task import Task
class PhysicsMgr():
def __init__(self, _game, _gravity=(0, 0, -9)):
self.game = _game
self.physicsWorld = BulletWorld()
self.physicsWorld.setGravity(Vec3(_gravity))
def s... |
"""
WSGI config for birding_ear 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", "birding_ear.settings")
from django.co... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20170628_1545'),
]
operations = [
migrations.AddField(
model_name='event',
name='kicker',
field=m... |
import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="colorsrc",
parent_name="choroplethmapbox.marker.line",
**kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plo... |
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print " [x] Received %r" % body
channel.basic_consume(callback,
queue='hello',
... |
import logging
import re
import string
from operator import methodcaller
from string import Template
from cpp_generator import CppGenerator
from cpp_generator_templates import CppGeneratorTemplates as CppTemplates
from generator import Generator, ucfirst
from models import EnumType, ObjectType, PrimitiveType, AliasedTy... |
from abjad.tools.pitchtools.NamedInterval import NamedInterval
from abjad.tools.scoretools.StaffGroup import StaffGroup
from abjad.tools.tonalanalysistools.ScaleDegree import ScaleDegree
from abjad.tools.topleveltools.iterate import iterate
from counterpoint import constants
from counterpoint.composition_environment im... |
import unittest
from nose.plugins.attrib import attr
import numpy
import theano
from theano import tensor, function
class TestKeepDims(unittest.TestCase):
def makeKeepDims_local(self, x, y, axis):
if axis is None:
newaxis = list(range(x.ndim))
elif isinstance(axis, int):
if a... |
import os
import sys
import subprocess
from scrape import __scrape_from_web__
def repeatOnError(*exceptions):
def checking(function):
def checked(*args, **kwargs):
while True:
try:
result = function(*args, **kwargs)
except exceptions as problem:
print "There was a problem... |
import bpy
from bpy.types import Panel
import mmd_tools.core.model as mmd_model
class _PanelBase(object):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = 'object'
class MMDModelObjectPanel(_PanelBase, Panel):
bl_idname = 'OBJECT_PT_mmd_tools_root_object'
bl_label = 'MMD Model Inf... |
"""
Copyright (c) 2010-2011 Tyler Kennedy <tk@tkte.ch>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publ... |
import cabbagerc as rc
import psycopg2
from psycopg2 import sql
from sql.cabbagebase import CabbageBase
from datetime import datetime, timedelta
class FlagFramework:
''' Functions for managing simple flags in the SQL database
Note that flags are not unique -- that is, it is possible to have
multiple flags wit... |
from backend import create_app
app = create_app("development") |
"""These tests only test the aspects of the `fseq.SeqReader` that does not
involve running the the encoding as that behaviour is a complex behaviour
involving all aspects of `fseq` those tests are performed by `test_fseq`.
Those are:
SeqReader.run()
for res in SeqReader
...
SeqReader.clearResults()
... |
"""
Django settings for thatforum project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
from django... |
import lacuna.bc
import lacuna.building
class embassy(lacuna.building.MyBuilding):
path = 'embassy'
def __init__( self, client, body_id:int = 0, building_id:int = 0 ):
super().__init__( client, body_id, building_id )
@lacuna.building.MyBuilding.call_returning_meth
def create_alliance( self, alli... |
import numpy as np
from mle import var, Normal
x = var('x', observed=True, vector=True)
y = var('y', observed=True, vector=True)
a = var('a')
b = var('b')
sigma = var('sigma')
model = Normal(y, a * x + b, sigma)
xs = np.linspace(0, 2, 20)
ys = 0.5 * xs + 0.3 + np.random.normal(0, 0.1, 20)
result = model.fit({'x': xs, '... |
from setuptools import find_packages
from setuptools import setup
tests_require = [
'pytest-cov',
'pytest-flakes',
'pytest-pep8',
'pytest', # Installed first if last item
]
setup(
name='libsse',
version='0.1.0',
url='https://github.com/infotim/python-libsse',
author='Timofey Stolbov',
... |
import pymongo
from pymongo import MongoClient
URI = "mongodb://admin:chalupacity@ds041651.mongolab.com:41651/rufound"
client = MongoClient(URI)
db = client.rufound
collection = db.namelist
def dbInsert(name, email, url):
collection.insert({"name" : name, "email" : email, "url": url})
while True:
x = raw_input("Type ... |
"""
Custom transformers for scikit-learn.
These are helpful for constructing pipelines.
"""
from typing import Dict
from typing import FrozenSet
from typing import Iterable
from typing import Optional
from typing import Set
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.exceptions import NotFitt... |
import tweepy
import requests
class PostTwitter:
def __init__(self,consumer_key,consumer_secret,access_token,access_token_secret):
self.access_token = access_token
self.access_token_secret = access_token_secret
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
... |
from pytest import fixture
from inapppy.asyncio import AppStoreValidator
@fixture
def appstore_validator() -> AppStoreValidator:
return AppStoreValidator()
@fixture
def appstore_validator_sandbox() -> AppStoreValidator:
return AppStoreValidator(sandbox=True)
@fixture
def appstore_validator_auto_retry_on_sandbox... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.