code
stringlengths
1
199k
try: theme = settings.get_theme() except: print "ERROR: File now needs to be run in the web2py environment in order to pick up which theme to build" exit() import os import sys import shutil SCRIPTPATH = os.path.join(request.folder, "static", "scripts", "tools") os.chdir(SCRIPTPATH) sys.path.append("./") im...
""" Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7 remaining blanks to place it in. Repeat until you've filled all 8 blanks. You wi...
definition = { "where": "?subj a foaf:Organization .", "fields": { "name": { "where": "?subj rdfs:label ?obj ." } } }
import sys import re re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$') def valid_email(s): return not (re_valid_email.search(s) == None) N = int(raw_input().strip()) A = [] for i in range(N): A += [ str(raw_input().strip()) ] A.sort() V = filter(valid_email, A) print V
import argparse from nltk.corpus import brown import requests import arrow import json parser = argparse.ArgumentParser() parser.add_argument('host') args = parser.parse_args() def create_new_novel(): url = 'http://{host}/api/novel'.format(host=args.host) response = requests.post(url, json={'title': 'Test Novel...
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.forms import models from djanban.apps.hourly_rates.models import HourlyRate from django import forms class HourlyRateForm(models.ModelForm): class Meta: model = HourlyRate fields = ["name", "start_...
""" The daemon that calls auto_copy.py uppon optical disc insertion """ import signal import sys import time sys.path.append('/usr/local/bin') import auto_copy SIGNAL_RECEIVED = False def run_daemon(config): """ Run the damon config: configParser object """ signal.signal(signal.SIGUSR1, signal_handl...
import json import os import unittest from monty.json import MontyDecoder from pymatgen.apps.battery.conversion_battery import ConversionElectrode from pymatgen.apps.battery.insertion_battery import InsertionElectrode from pymatgen.apps.battery.plotter import VoltageProfilePlotter from pymatgen.core.composition import ...
from abc import ABCMeta, abstractmethod class AbstractAuthenticator(metaclass=ABCMeta): def __init__(self): """ Every authenticator has to have a name :param name: """ super().__init__() @abstractmethod def authorise_transaction(self, customer): """ De...
from django.conf.urls import url, include urlpatterns = [ url(r'^postcode-lookup/', include('django_postcode_lookup.urls')), ]
import sys [_, ms, _, ns] = list(sys.stdin) ms = set(int(m) for m in ms.split(' ')) ns = set(int(n) for n in ns.split(' ')) print(sep='\n', *sorted(ms.difference(ns).union(ns.difference(ms))))
import os import numpy as np class Dataset(object): """ This class represents a dataset and consists of a list of SongData along with some metadata about the dataset """ def __init__(self, songs_data=None): if songs_data is None: self.songs_data = [] else: self.so...
import gevent import time def doit(i): print "do it:%s" % (i) gevent.sleep(2) print "done:%s" %(i) t2 = time.time() threads = {} for i in range(5): t = gevent.spawn(doit, i) threads[i] = t #print dir(t) gevent.sleep(1) print threads print threads[3].dead threads[3].kill() print threads[3].dead d...
import sys import os import time import numpy import cv2 import cv2.cv as cv from PIL import Image sys.path.insert(0, os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))))) from picture.util import define from picture.util.system import POINT from picture.util.log import LOG as L THRESHOLD = 0....
def output_gpx(points, output_filename): """ Output a GPX file with latitude and longitude from the points DataFrame. """ from xml.dom.minidom import getDOMImplementation def append_trkpt(pt, trkseg, doc): trkpt = doc.createElement('trkpt') trkpt.setAttribute('lat', '%.8f' % (pt['lat...
import json import urllib import time import datetime def CalculateDistance(Origin = False,Destination = False, Method = "driving",TimeUnits = "Minutes",DistUnits = "Miles"): #this is the start of a distnace matrix url base = "https://maps.googleapis.com/maps/api/distancematrix/json?" #Converts the variables to the ...
from datetime import date NTESTS = 1 PREV_DAYS = 10 PERCENT_UP = 0.01 PERCENT_DOWN = 0.01 PERIOD = 'Hourly' # [5-min, 15-min, 30-min, Hourly, 2-hour, 6-hour, 12-hour, Daily, Weekly] MARKET = 'bitstampUSD' YEAR_START = 2011 MONTH_START = 9 DAY_START = 13 DATE_START = date(YEAR_START, MONTH_START, DAY_START) DATE_END = d...
from rest_framework import test, status from waldur_core.structure.models import CustomerRole, ProjectRole from waldur_core.structure.tests import factories as structure_factories from . import factories class ServiceProjectLinkPermissionTest(test.APITransactionTestCase): def setUp(self): self.users = { ...
from email.mime.text import MIMEText from jinja2 import Environment, FileSystemLoader from datetime import datetime as dt import os import six import smtplib SECRET_SANTA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') j2env = Environment(loader=FileSystemLoad...
""" Collect the elasticsearch stats for the local node * urlib2 """ import urllib2 import re try: import json json # workaround for pyflakes issue #13 except ImportError: import simplejson as json import diamond.collector RE_LOGSTASH_INDEX = re.compile('^(.*)-\d\d\d\d\.\d\d\.\d\d$') class ElasticSearchCol...
class VecEnv(object): """ An abstract asynchronous, vectorized environment. """ def __init__(self, num_envs, observation_space, action_space): self.num_envs = num_envs self.observation_space = observation_space self.action_space = action_space def reset(self): """ ...
EGA2RGB = [ (0x00, 0x00, 0x00), (0x00, 0x00, 0xAA), (0x00, 0xAA, 0x00), (0x00, 0xAA, 0xAA), (0xAA, 0x00, 0x00), (0xAA, 0x00, 0xAA), (0xAA, 0x55, 0x00), (0xAA, 0xAA, 0xAA), (0x55, 0x55, 0x55), (0x55, 0x55, 0xFF), (0x55, 0xFF, 0x55), (0x55, 0xFF, 0xFF), (0xFF, 0x55, 0x5...
from django.apps import AppConfig class BallerShotCallerConfig(AppConfig): name = 'baller_shot_caller'
import json from util import d import os __home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/" BASE_SERVER_CONFIG = d({ "id":"server_config", "display": "server_config", "preconfig": False, "presets":[], "params": [{ "id": "externa...
""" Created on Mon Sep 29 21:25:13 2014 @author: 27182_000 """ import sys ans = 1 for n in range(999,1,-1): for m in range(999,1,-1): num = n*m if str(num) == str(num)[::-1] and num > ans: ans = num print ans
from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Page content') def custom(request): return render(request, 'custom.html', {})
from __future__ import unicode_literals from django.db import models, migrations from django.utils.timezone import utc import datetime class Migration(migrations.Migration): dependencies = [ ('content', '0009_auto_20150829_1417'), ] operations = [ migrations.CreateModel( name='Me...
''' Manage Ruby gem packages. (see https://rubygems.org/ ) ''' from pyinfra.api import operation from pyinfra.facts.gem import GemPackages from .util.packaging import ensure_packages @operation def packages(packages=None, present=True, latest=False, state=None, host=None): ''' Add/remove/update gem packages. ...
import sys, os sys.path.insert(0, os.path.abspath('../')) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.doctest'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'partpy' copyright = u'2013, Taylor "Nekroze" Lawson' version = '1.2' release = '1.2.4' exclud...
import pytest from clustaar.authorize.conditions import TrueCondition @pytest.fixture def condition(): return TrueCondition() class TestCall(object): def test_returns_true(self, condition): assert condition({})
from ulnoiot import * from ulnoiot.shield.onboardled import blue blue.high() # make sure it's off (it's reversed) button("b1", d6, pullup=False, threshold=2) run(5)
from __future__ import absolute_import from . import common from .. import rw from ..glossary import DEFAULT_TIMEOUT from .base import BaseMessage class CancelMessage(BaseMessage): __slots__ = BaseMessage.__slots__ + ( 'ttl', 'tracing', 'why', ) def __init__(self, ttl=DEFAULT_TIMEOUT...
import pygame import os from color import * from pygame.locals import * class Score(pygame.sprite.Sprite): def __init__(self, score, player, width, height): super(pygame.sprite.Sprite).__init__(Score) self.score = int(score) self.color = None self.player = player self.bossHei...
from __future__ import unicode_literals from django.db import models from django.utils.timezone import now, timedelta Q = models.Q class LogisticJob(models.Model): LOCK_FOR = ( (60*15, '15 minutes'), (60*30, '30 minutes'), (60*45, '45 minutes'), (60*60, '1 hour'), (60*60*3, '...
"""Parse ISI journal abbreviations website.""" try: from html.parser import HTMLParser except ImportError: from HTMLParser import HTMLParser class ISIJournalParser(HTMLParser): """Parser for ISI Web of Knowledge journal abbreviation pages. **Note:** Due to the ISI pages containing malformed html...
import glob import os import pandas as pd class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[index+...
""" Running the template pre-processor standalone. Input: Templated Antimony model (stdin) Output: Expanded Antimony model (stdout) """ import fileinput import os import sys directory = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(directory, "TemplateSB") sys.path.append(path) from template_p...
from bottle import route, default_app app = default_app() data = { "id": 78874, "seriesName": "Firefly", "aliases": [ "Serenity" ], "banner": "graphical/78874-g3.jpg", "seriesId": "7097", "status": "Ended", "firstAired": "2002-09-20", "network": "FOX (US)", "networkId": "",...
import RPi.GPIO as GPIO from common.adafruit.Adafruit_MCP230xx.Adafruit_MCP230xx import Adafruit_MCP230XX class Relay(object): _mcp23017_chip = {} # Conceivably, we could have up to 8 of these as there are a possibility of 8 MCP chips on a bus. def __init__(self, mcp_pin, i2c_address=0x27): """ ...
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from flask_sockets import Sockets app = Flask(__name__, static_folder="../static/dist", template_folder="../static") if os.environ.get('PRODUCTION'): app.config.from_object('config.ProductionConfig') el...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job_board', '0004_jobpost_is_from_recruiting_agency'), ] operations = [ migrations.AlterField( model_name='jobpost', name='location', field=models.CharField(...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import tree from subprocess import call X = pd.read_csv('Datasets/agaricus-lepiota.data', names=['label', 'cap-shape', 'cap-surface', 'cap-color', 'bruises', ...
import os from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() class DBConnector(): ''' where every row is the details one employee was paid for an entire month. ''' @classmethod def get_session...
import sys import urllib.parse import urllib.request def main(): search = sys.argv[1] url = 'http://rarbg.to/torrents.php?order=seeders&by=DESC&search=' url = url + search print(url) req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) resp = urllib.request.urlopen(req) ...
""" Module containing classes for HTTP client/server interactions """ try: from urllib.error import HTTPError, URLError from urllib.parse import urlencode except ImportError: from urllib2 import HTTPError, URLError from urllib import urlencode import socket from pyowm.exceptions import api_call_error, u...
import unittest import itertools class TestWorld(object): def __init__(self, **kw): self.__dict__.update(kw) self.components = self self.entities = set() self.new_entity_id = itertools.count().__next__ self.new_entity_id() # skip id 0 for comp in list(kw.values()): comp.world = self class TestComponent(...
from django.db import models from django.contrib.sites.models import Site class Link(models.Model): url = models.URLField(max_length=512) site = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True) request_times = models.PositiveIntegerField(default=0) updated = models.DateTimeField(auto_now=Tr...
class InvalidValueState(ValueError): pass
import numpy as np import sys import scipy from scipy import stats data_file = sys.argv[1] data = np.loadtxt(data_file) slope, intercept, r_value, p_value, std_err = stats.linregress(data[499:2499,0], data[499:2499,1]) nf = open('linear_reg.dat', 'w') nf.write("Linear Regression for data between %5d ps (frame: 499) and...
import sys import os import urllib.request import path_utils def download_url(source_url, target_path): if os.path.exists(target_path): return False, "Target path [%s] already exists" % target_path contents = None try: with urllib.request.urlopen(source_url) as f: contents = f.re...
import os import numpy as np from plantcv.plantcv.threshold import binary as binary_threshold from plantcv.plantcv import params from plantcv.plantcv import fatal_error from plantcv.plantcv._debug import _debug import pandas as pd from plotnine import ggplot, aes, geom_line, labels, scale_color_manual def _hist_gray(gr...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('basicviz', '0002_auto_20160717_1939'), ] operations = [ migrations.AlterField( model_name='document', name='name', fi...
"""This module contains the classes underlying SoCo's caching system.""" from __future__ import unicode_literals import threading from time import time from . import config from .compat import dumps class _BaseCache(object): """An abstract base class for the cache.""" # pylint: disable=no-self-use, unused-argum...
from logika import IGRALEC_R, IGRALEC_Y, PRAZNO, NEODLOCENO, NI_KONEC, MAKSIMALNO_STEVILO_POTEZ, nasprotnik from five_logika import Five_logika from powerup_logika import Powerup_logika, POWER_STOLPEC, POWER_ZETON, POWER_2X_NW, POWER_2X_W from pop10_logika import Pop10_logika from pop_logika import Pop_logika import ra...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path as osp import numpy as np from easydict import EasyDict as edict __C = edict() cfg = __C __C.TRAIN = edict() __C.TRAIN.LEARNING_RATE = 0.001 __C.TRAIN.MOMENTUM = 0.9 __C.TRAIN.WEIGHT_DEC...
__VERSION__="ete2-2.2rev1056" from PyQt4 import QtCore, QtGui class Ui_OpenNewick(object): def setupUi(self, OpenNewick): OpenNewick.setObjectName("OpenNewick") OpenNewick.resize(569, 353) self.comboBox = QtGui.QComboBox(OpenNewick) self.comboBox.setGeometry(QtCore.QRect(460, 300, 81...
from collections import Counter from os.path import splitext import matplotlib.pyplot as plt from arcapix.fs.gpfs import ListProcessingRule, ManagementPolicy def type_sizes(file_list): c = Counter() for f in file_list: c.update({splitext(f.name): f.filesize}) return c p = ManagementPolicy() r = p.ru...
import timeit def insertion_sort(nums): """Insertion Sort.""" for index in range(1, len(nums)): val = nums[index] left_index = index - 1 while left_index >= 0 and nums[left_index] > val: nums[left_index + 1] = nums[left_index] left_index -= 1 nums[left_ind...
from django.db import models class Citizen(models.Model): """ The insurance users. """ name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # Contact information email = models.EmailField() phone = models.CharField(max_length=50) # Citizen documents ...
import datetime import typing from . import helpers from .tl import types, custom Phone = str Username = str PeerID = int Entity = typing.Union[types.User, types.Chat, types.Channel] FullEntity = typing.Union[types.UserFull, types.messages.ChatFull, types.ChatFull, types.ChannelFull] EntityLike = typing.Union[ Phon...
__author__ = 'yfauser' from tests.config import * from nsxramlclient.client import NsxClient import time client_session = NsxClient(nsxraml_file, nsxmanager, nsx_username, nsx_password, debug=True) def test_segment_pools(): ### Test Segment ID Pool Operations # Get all configured Segment Pools get_segment_r...
import numpy as np import jarvis.helpers.helpers as helpers from data_cleaner import DataCleaner def get_data(csv=None, sep='|'): dataset = create_dataset(csv, sep) inputs = DataCleaner().clean(dataset[:, 0:1]) outputs = format_targets(dataset[:, 1]) train_data, test_data = inputs[::2], inputs[1::2] train_targets,...
from jaspyx.visitor import BaseVisitor class Return(BaseVisitor): def visit_Return(self, node): self.indent() if node.value is not None: self.output('return ') self.visit(node.value) else: self.output('return') self.finish()
import os import os.path from raiden.constants import RAIDEN_DB_VERSION def database_from_privatekey(base_dir, app_number): """ Format a database path based on the private key and app number. """ dbpath = os.path.join(base_dir, f"app{app_number}", f"v{RAIDEN_DB_VERSION}_log.db") os.makedirs(os.path.dirname(...
from django.apps import AppConfig class ProxyConfig(AppConfig): name = 'geoq.proxy' verbose_name = 'GeoQ Proxy'
from __future__ import absolute_import from __future__ import division from __future__ import print_function import fnmatch import os import re import sys from setuptools import find_packages, setup, Command from setuptools.command.install import install as InstallCommandBase from setuptools.dist import Distribution _V...
''' Created on Jun 16, 2014 @author: lwoydziak ''' import pexpect import sys from dynamic_machine.cli_commands import assertResultNotEquals, Command class SshCli(object): LOGGED_IN = 0 def __init__(self, host, loginUser, debug = False, trace = False, log=None, port=22, pexpectObject=None): self.pexpect ...
import argparse import logging import json import os from bootstrap import bootstrap from library import execute_command, tempdir LOGGER_BASENAME = '''_CI.test''' LOGGER = logging.getLogger(LOGGER_BASENAME) LOGGER.addHandler(logging.NullHandler()) def get_arguments(): parser = argparse.ArgumentParser(description='A...
from gramfuzz.fields import * import names TOP_CAT = "postal" class PDef(Def): cat = "postal_def" class PRef(Ref): cat = "postal_def" EOL = "\n" Def("postal_address", PRef("name-part"), PRef("street-address"), PRef("zip-part"), cat="postal") PDef("name-part", Ref("name", cat=names.TOP_CAT), EOL ) PDef("...
"""Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os import re import sys TIMES...
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework_swagger.views import get_swagger_view from . import views, views_api router = DefaultRouter() router.register(r'election', views_api.ElectionInterface) router.register(r'district', views_api.DistrictInterface)...
''' Created on Jan 15, 2014 @author: Jose Borreguero ''' from setuptools import setup setup( name = 'dsfinterp', packages = ['dsfinterp','dsfinterp/test' ], version = '0.1', description = 'Cubic Spline Interpolation of Dynamics Structure Factors', long_description = open('README.md').read(), author = 'Jose ...
from django.core.mail import EmailMultiAlternatives from django.template import Context, Template from django.template.loader import get_template from helpers import ClientRouter, MailAssetsHelper, strip_accents class UserMail: """ This class is responsible for firing emails for Users and Nonprofits """ ...
""" flask.ext.babelex ~~~~~~~~~~~~~~~~~ Implements i18n/l10n support for Flask applications based on Babel. :copyright: (c) 2013 by Serge S. Koval, Armin Ronacher and contributors. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import os if os.environ.get('LC...
try: from tornado.websocket import WebSocketHandler import tornado.ioloop tornadoAvailable = True except ImportError: class WebSocketHandler(object): pass tornadoAvailable = False from json import loads as fromJS, dumps as toJS from threading import Thread from Log import console import Settings from utils import ...
""" For detailed documentation and examples, see the README. """ import networkx, matplotlib.pyplot, scipy import numpy as np import os import pyximport if os.name == 'nt': if 'CPATH' in os.environ: os.environ['CPATH'] = os.environ['CPATH'] + np.get_include() else: os.environ['CPATH'] = np.get_i...
""" make_loaddata.py Convert ken_all.csv to loaddata """ import argparse import csv def merge_separated_line(args): """ yields line yields a line. if two (or more) lines has same postalcode, merge them. """ def is_dup(line, buff): """ lines is duplicated or not """ # same pos...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0003_auto_20171221_0336'), ] operations = [ migrations.AlterField( model_name='dailyproductivitylog', name='source', ...
import aaf import os from optparse import OptionParser parser = OptionParser() (options, args) = parser.parse_args() if not args: parser.error("not enough argements") path = args[0] name, ext = os.path.splitext(path) f = aaf.open(path, 'r') f.save(name + ".xml") f.close()
""" telemetry full tests. """ import platform import sys from unittest import mock import pytest import wandb def test_telemetry_finish(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): run = wandb.init() run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) ...
' 检查扩展名是否合法 ' __author__ = 'Ellery' from app import app import datetime, random from PIL import Image import os def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config.get('ALLOWED_EXTENSIONS') def unique_name(): now_time = datetime.datetime.now().strftime("%...
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 import...
""" Test the Multinet Class. """ import multinet as mn import networkx as nx class TestMultinet(object): def test_build_multinet(self): """ Test building Multinet objects. """ mg = mn.Multinet() assert mg.is_directed() == False mg.add_edge(0, 1, 'L1') mg.add_e...
import hashlib import unittest from test import test_support from test.test_support import _4G, precisionbigmemtest def hexstr(s): import string h = string.hexdigits r = '' for c in s: i = ord(c) r = r + h[(i >> 4) & 0xF] + h[i & 0xF] return r class HashLibTestCase(unittest.TestCase)...
from .sub_resource import SubResource class VirtualNetworkPeering(SubResource): """Peerings in a virtual network resource. :param id: Resource ID. :type id: str :param allow_virtual_network_access: Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virt...
import sys sys.path.append('../browser_interface/browser') class BrowserFactory(object): def create(self, type, *args, **kwargs): return getattr(__import__(type), type)(*args, **kwargs)
import sqlite3 VERBOSE = 0 CTABLE_DOMAIN = ''' CREATE TABLE IF NOT EXISTS Domains( did INTEGER PRIMARY KEY AUTOINCREMENT, domain VARCHAR(64) UNIQUE, indegree INTEGER, outdegree INTEGER )''' CTABLE_WEBSITE = ''' CREATE TABLE IF NOT EXISTS Websites( wid INTEGER PRIMARY KEY AUTOINCREMENT, did INTEGER, url VARCHAR(2...
import re from crossword import * class Crossword2(Crossword): def __init__(self): self.grid = OpenGrid() self.connected = {} self.used_words = [] def copy(self): copied = Crossword2() copied.grid = self.grid.copy() copied.connected = self.connected.copy() ...
import math class Point: def __init__(self, x, y): self.x = x self.y = y def rssToEstimatedDistance(rss): freq = 2462 # freq of WiFi channel 6 origDBm = -20 # estimate this value loss = abs(origDBm - rss) dist = 10 ** ( ( loss + 27.55 - 20 * math.log10(freq) ) /...
import pytest from swimlane.exceptions import ValidationError def test_getattr_fallback(mock_record): """Verify cursor __getattr__ falls back to AttributeError for unknown cursor + list methods""" with pytest.raises(AttributeError): getattr(mock_record['Text List'], 'unknown_method') def test_set_valida...
callback_functions = ["collision_enter", "collision_stay", "collision_exit"] length_area_world = 75 raise_exception = False from game import * from gameobject import * from contracts import * from configuration import * from component import * from loader import * from physics import * from scene import * from timeutil...
from functools import reduce mask1 = mask2 = polyred = None def setGF2(degree, irPoly): """Define parameters of binary finite field GF(2^m)/g(x) - degree: extension degree of binary field - irPoly: coefficients of irreducible polynomial g(x) """ def i2P(sInt): """Convert an integer int...
from __future__ import unicode_literals import unittest import os import sys from flake8.api import legacy as engine if sys.version_info[0] == 3: unicode = str if sys.version_info[:2] == (2, 6): # Monkeypatch to make tests work on 2.6 def assert_less(first, second, msg=None): assert first > second ...
import pyak import yikbot import time yLocation = pyak.Location("42.270340", "-83.742224") yb = yikbot.YikBot("yikBot", yLocation) print "DEBUG: Registered yikBot with handle %s and id %s" % (yb.handle, yb.id) print "DEBUG: Going to sleep, new yakkers must wait ~90 seconds before they can act" time.sleep(90) print "DEB...
import prosper.datareader.exceptions import prosper.datareader._version
""" Visualization module. """ import numpy as np from matplotlib import animation import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset from pca import create_handles impor...
__author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" import time from datetime import datetime, timedelta def timeit(method): def timed(*args...
from app.app_and_db import app from flask import Blueprint, jsonify, render_template import datetime import random import requests dashboard = Blueprint('dashboard', __name__) cumtd_endpoint = 'https://developer.cumtd.com/api/{0}/{1}/{2}' cumtd_endpoint = cumtd_endpoint.format('v2.2', 'json', 'GetDeparturesByStop') wun...
from __future__ import print_function import sys sys.path.append('..') # help python find cyton.py relative to scripts folder from openbci import cyton as bci import logging import time def printData(sample): # os.system('clear') print("----------------") print("%f" % (sample.id)) print(sample.channel_...
__author__ = 'mengpeng' import os from unittest import TestCase from pycrawler.scraper import DefaultScraper from pycrawler.handler import Handler from pycrawler.utils.tools import gethash from test_scraper import SpiderTest class TestTempHandler(TestCase): def test_setargs(self): h = Handler.get('TempHandl...