code stringlengths 1 199k |
|---|
import os
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
LAYOUT_DIR = os.path.join(ROOT_PATH, 'layout')
CONTENT_DIR = os.path.join(ROOT_PATH, 'content')
MEDIA_DIR = os.path.join(ROOT_PATH, 'media')
DEPLOY_DIR = os.path.join(ROOT_PATH, 'deploy')
TMP_DIR = os.path.join(ROOT_PATH, 'deploy_tmp')
BACKUPS_DIR = os.pa... |
def f():
for i in []:
pass
else:
<caret> |
""" Unit test suite for daemon package.
"""
import scaffold
suite = scaffold.make_suite() |
import copy
import httplib2
class fake_httplib2(object):
def __init__(self, return_type=None, *args, **kwargs):
self.return_type = return_type
def request(self, uri, method="GET", body=None, headers=None,
redirections=5, connection_type=None):
if not self.return_type:
... |
"""
@author: Brendan Dolan-Gavitt
@license: GNU General Public License 2.0
@contact: bdolangavitt@wesleyan.edu
"""
import volatility.obj as obj
import volatility.win32.rawreg as rawreg
import volatility.win32.hive as hive
from Crypto.Hash import MD5, MD4
from Crypto.Cipher import ARC4, DES
from struct i... |
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
import threading
import logging
logger = logging.getLogger(__name__)
class SendLayer(YowInterfaceLayer):
#This message is go... |
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql("""update
`tabTimesheet` as ts,
(
select min(from_time)as from_time, max(to_time) as to_time, parent from `tabTimesheet Detail` group by parent
) as tsd
set ts.status = 'Submitted', ts.start_date = tsd.from_time, ts.end_date ... |
import os
import warnings
from collections import Counter, OrderedDict
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango110Warnin... |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function normalizes the encoding names before
doing the lookup, so the mapping will have to map normalized
encoding names to module names.
Conten... |
class A:
pass
class B:
pass |
"""
Dateish Plugin for Pelican
==========================
This plugin adds the ability to treat arbitrary metadata fields as datetime
objects.
"""
from pelican import signals
from pelican.utils import get_date
def dateish(generator):
if 'DATEISH_PROPERTIES' not in generator.settings:
return
for article ... |
from pyb import SPI
for bus in (-1, 0, 1, 2, 3, "X", "Y", "Z"):
try:
SPI(bus)
print("SPI", bus)
except ValueError:
print("ValueError", bus)
spi = SPI(1)
print(spi)
spi = SPI(1, SPI.MASTER)
spi = SPI(1, SPI.MASTER, baudrate=500000)
spi = SPI(1, SPI.MASTER, 500000, polarity=1, phase=0, bit... |
import sys, os
extensions = ['sphinx.ext.pngmath']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'ns-3'
copyright = u'2011, ns-3 project'
version = 'ns-3-dev'
release = 'ns-3-dev'
exclude_patterns = []
pygments_style = 'sphinx'
html_theme = 'ns3_html_theme'
html_theme_path = ['.... |
"""Django Unit Test framework."""
from django.test.client import Client, RequestFactory
from django.test.testcases import (
LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase,
skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature,
)
from django.test.utils import (
ignore_warnings, modi... |
import bench
def func(a, b, c):
pass
def test(num):
for i in iter(range(num)):
func(i, i, i)
bench.run(test) |
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models, IntegrityError
class Migration(DataMigration):
def forwards(self, orm):
"""Map all Finance Admins to Sales Admins."""
finance_admins = orm['student.courseaccessrole'].objects.filter(role='finance... |
import unittest
class TestHashing(object):
"""Used as a mixin for TestCase"""
# Check for a valid __hash__ implementation
def test_hash(self):
for obj_1, obj_2 in self.eq_pairs:
try:
if not hash(obj_1) == hash(obj_2):
self.fail("%r and %r do not hash e... |
KEY_LENGTH = 16
SREG2AX = { # from http://www.axschema.org/types/#sreg
'nickname': 'http://axschema.org/namePerson/friendly',
'email': 'http://axschema.org/contact/email',
'fullname': 'http://axschema.org/namePerson',
'dob': 'http://axschema.org/birthDate',
'gender': 'http://axschema.org/person/... |
from node import NodeVisitor, ValueNode, ListNode, BinaryExpressionNode
from parser import atoms, precedence
atom_names = {v:"@%s" % k for (k,v) in atoms.iteritems()}
named_escapes = set(["\a", "\b", "\f", "\n", "\r", "\t", "\v"])
def escape(string, extras=""):
rv = ""
for c in string:
if c in named_esc... |
import curses
import math
import os
import traceback
import threading
import time
import random
overflow = False # set to True to enable growth past final stage (softcorrupts plant file)
class CursedMenu(object):
#TODO: name your plant
'''A class which abstracts the horrors of building a curses-based menu syste... |
from __future__ import print_function
from cfn_pyplates import functions
import respawn
import sys
def standardize_refs(d):
"""
Recursively transform all ref's and get_att's in dictionary to CloudFormation references.
"""
for k, v in d.iteritems():
if isinstance(v, dict):
standardize... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: panos_ipsec_ipv4_proxyid
short_description: Configures IPv4 Pro... |
import os
option = input("Build options: win32, win64, osx, linux, linux64, enter your option: \n")
buildpath = "";
if(option == "win64"):
option = "-buildWindows64Player";
buildpath = "WIN_Build\\KaziJump.exe";
os.popen("\"C:\\Program Files\\Unity 5.6.0b3\\Editor\\Unity.exe\" -batchmode " + option + "builds\\" + bui... |
"""
Just to check
"""
def add(a, b):
"""
>>> add(2, 2)
4
>>> add(2, -2)
0
"""
return a + b
if __name__ == "__main__":
a = 5
b = 6
print(f"The sum of {a} + {b} is {add(a, b)}") |
""" Program version information.
"""
import sys
DEBUGGING = False
PROGRAM_NAME = 'astviewer'
PROGRAM_VERSION = '1.1.2'
PYTHON_VERSION = "%d.%d.%d" % (sys.version_info[0:3]) |
from helpers import cache
@cache
def powers(n):
result = set()
for a in range(2, n+1):
for b in range(2, n+1):
result.add(pow(a, b))
return result
n = 100
print len(powers(n)) |
from sqlalchemy.orm.exc import NoResultFound
import io
import sys
sys.path.append("models/")
from ModelBase import SessionFactory
from Twitter_User import Twitter_User
from sqlalchemy import or_
import logging
class setTargetUsers(object):
def parseparams(self, argv):
pc = 0
while(pc < len(argv)):
... |
"""
Local Authorities downloader class
"""
import logging
import os
import re
import requests
from ..caches.s3_cache import S3Cache
from ..caches.filesystem_cache import FilesystemCache
from ..caches.multi_level_caching_strategy import MultiLevelCachingStrategy
from ..downloaders.download_manager import DownloadManager... |
"""
Library of common CRC configurations
:note: POLY is the polynome of CRC and specifies which bits
should be xored together.
:note: WIDTH - specifies the width of CRC state/value
:note: REFIN - If it is True the bits in each byte are reversed before processing.
:note: REFOUT If it is set to FALSE, the
final v... |
import pytest
from flask_postmark import Postmark
BODY = "<html><body><strong>Hello</strong> dear Postmark user.</body></html>"
SUBJECT = "Postmark test"
RECEIVER = "receiver@example.com"
SENDER = "sender@example.com"
DATA = {"From": SENDER, "To": RECEIVER, "Subject": SUBJECT, "HtmlBody": BODY}
def test_token(test_clie... |
from django.conf.urls import patterns, url
from bento.views import connexion, deconnexion, inscription, Recettes, ajoutrecette, modifier, VoirRecette, commenter, \
supprimer, voter
urlpatterns = patterns('',
url(r'^$', Recettes.as_view(), name='index'),
url(r'^index$', ... |
"""
Django settings for impulse project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
BASE_... |
import autograd.numpy as np
from util import memoize, WeightsParser
from rdkit_utils import smiles_to_fps
def batch_normalize(activations):
mbmean = np.mean(activations, axis=0, keepdims=True)
return (activations - mbmean) / (np.std(activations, axis=0, keepdims=True) + 1)
def relu(X):
"Rectified linear act... |
class person():
hp = 3
atk = 1
class goblin():
hp = 2
atk = 1
class dragon():
hp = 10
atk = 3 |
"""melodi 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-based... |
from src.CommentReflow import GreatestCommonPrefix
class TestBasic:
gcp = GreatestCommonPrefix()
def test_pine_match(self):
actual = self.gcp.parse(['pineapple',
'pine tree'])
assert 'pine' == actual
def test_pine_miss(self):
actual = self.gcp.parse([' pin... |
import time
class Timer:
def __init__(self, name, interval = 's'):
if not name.replace(' ', '').isalnum():
raise ValueError('Device names must only contain letters, numbers and spaces')
self.start_time()
self.name = name
if interval == 'ms':
self.interval = .001
if interval == 's':... |
from itertools import count
# if i % 20 == 0:
# if i % 19 == 0:
# if i % 18 == 0:
# if i % 17 == 0:
# if i % 16 == 0:
# if i % 15 == 0:
# if i % 14 == 0:
# if i % 13 == 0:
# if i % 12 == 0:
# if i % 11 == 0:
# if i % 10 == 0:
# if i % 9 == 0:... |
from mathml.termbuilder import tree_converters, InfixTermBuilder
__all__ = [ 'SqlTermBuilder' ]
class SqlTermBuilder(InfixTermBuilder):
_NAME_MAP = {
'e' : 'exp(1.0)',
'pi' : 'pi()',
'true' : 'TRUE',
'false' : 'FALSE'
}
def _handle_const_bool(self, operator, opera... |
"""
A fake pool that only serves one getwork, meant for local testing
"""
import gevent.pywsgi
import os, logging, json
def handle_getwork():
response = {"id":1,"error":None,"result":{"midstate":"5fa3febd7c47f69762101eb58f7e07f86414f6cddab264ea29e979e93a681af3","target":"ffffffffffffffffffffffffffffffffffffffffffff... |
from .binary import BinaryCommand, BinaryDevice, BinaryReply, BinarySerial
from .exceptions import TimeoutError, UnexpectedReplyError |
import os
import sys
import sqlite3
import csv
import json
import argparse
try:
import win32crypt
except:
pass
def args_parser():
parser = argparse.ArgumentParser(
description="Retrieve Google Chrome Passwords")
parser.add_argument("-o", "--output", choices=['csv', 'json'],
... |
import argparse
import string
def dec_to_bin(dec, verbose=False):
rest = dec % 2
if int(dec) != 0:
if verbose == True:
print "%s \t:\t 2 = %s \t-- Rest: %s" % (dec,int(dec/2),rest)
verbose = True
binary = str(dec_to_bin(int(dec/2),verbose)) + str(rest)
return bina... |
import argparse
import logging
import os
import sys
import time
import ceilometerclient.exc
from ceilometerclient.v2 import client as ceilometer_client
import cinderclient.exceptions
from cinderclient.v1 import client as cinder_client
import glanceclient.exc
from glanceclient.v1 import client as glance_client
from heat... |
from typing import List, Dict, Optional, Any
import aiohttp
import json
import jinja2
from irisett import (
log
)
async def send_slack_notification(url: str, attachments: List[Dict]):
data = {
'attachments': attachments
}
try:
async with aiohttp.ClientSession() as session:
as... |
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from Crawler.utils import run_crawler
logger = get_task_logger(__name__)
__author__ = 'nolram'
@periodic_task(
run_every=(crontab(minute='*/15')),
name="crawling_news_rss",
ignore_result=T... |
raise NotImplementedError("command is not yet implemented in Skulpt") |
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 field 'Event.last_update'
db.add_column('multilingual_events_event', 'last_update',
self.gf('django.db.m... |
import numpy as np
def robotBoschikt(robot, pos):
"""
Inverse kinematic task for robot Bosch.
:param robot: Robot Bosch instance.
:param pos: Coordinates of robot position in world coordinates.
:return: Coordinates of robot position in joint coordinates (degrees).
"""
pos = np.array(pos).ast... |
import atexit
import logging
import os
import platform
import subprocess
from enum import Enum, unique
from tempfile import mkdtemp
import re
import shutil
from typing import List, Union, Dict, Set
from uuid import uuid4
from useintest.modules.irods.models import IrodsResource, IrodsUser, Version
@unique
class AccessLe... |
from fc_2014_10_06 import multiply
def test_numbers_3_4():
assert multiply(3,4) == 12 |
from PyQt4 import uic
from PyQt4 import QtGui, QtCore
import pyqtgraph as pg
import os
import numpy as np
from ipbec.clt.imtools import getROISlice
curr_dir = os.path.dirname(os.path.abspath(__file__))
ui_file = os.path.join(curr_dir, "sterngerlach.ui")
Ui_PluginDialog, QDialog = uic.loadUiType(ui_file)
class PluginDia... |
import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="y", parent_name="contour.colorbar", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type... |
import smtplib
import config
from email.mime.text import MIMEText
from time import sleep
SLEEP_TIME = config.SLEEP_TIME
VALID_MESSAGE_HEADERS = ["To", "From", "Subject", "Cc"]
VALID_MESSAGE_FIELDS = VALID_MESSAGE_HEADERS + ["Bcc", "Body"]
def validateFields(fields):
'''Require that all fields used are legitimate.
... |
from __future__ import unicode_literals
from pybooru import Pybooru
client = Pybooru('Konachan', username='your-username', password='your-password')
client.comments_create(post_id=id, comment_body='Comment content') |
import sequencing_np as snp
import tensorflow as tf
from sequencing import MODE, TIME_MAJOR
from sequencing.encoders.rnn_encoder import StackBidirectionalRNNEncoder
from sequencing_np import np, DTYPE
def stack_bidir_rnn_encoder(rnn_cell, name=None):
time_steps = 4
hidden_units = 32
batch_size = 6
num_l... |
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
__import__('pkg_resources').declare_namespace(__name__) |
from django.contrib.auth.models import AnonymousUser
from .auth import ApiToken
class BettyApiKeyMiddleware(object):
def process_request(self, request):
if "HTTP_X_BETTY_API_KEY" in request.META:
api_key = request.META["HTTP_X_BETTY_API_KEY"]
try:
token = ApiToken.obj... |
from typing import Dict, List, Optional, Tuple, Union
import tensorflow as tf
from odin.bay.vi.autoencoder.beta_vae import BetaVAE
from odin.bay.vi.losses import disentangled_inferred_prior_loss
from odin.utils import as_tuple
class DIPVAE(BetaVAE):
""" Implementation of disentangled infered prior VAE
Parameters
... |
import sys, os
sys.path.insert(0, "..")
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'srcgen'
copyright = u'2013, Tomer Filiba'
from srcgen.version import version_string
version = version_string
release = version_string... |
def get_stop_loss_price(price, stop, relative_stop=False):
"""Returns the stop loss price. The actual stop loss price is
calculated from the piven stop. The stop can be set in abosult
(default) or in relative values to the price.
Please note that the stop must be positive for BUY orders and
negative... |
print "Content-Type: text/plain"
print ""
print "<script src='//connect.facebook.net/en_US/sdk.js'></script>" |
from mock import Mock, MagicMock
import unittest2 as unittest
from contextlib import contextmanager
from monocle.callback import defer
from helpers import mock_db, listen_for, mock_worker
def _account_for_test(config=None, db=None):
from tinymail.account import Account
if config is None:
config = {
... |
import binaryninja as bn
import os
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_debug_info")
print = print
if __name__ != "__main__":
print = bn.log_error
def pretty_print_add_data_variable(
debug_info: bn.debuginfo.DebugInfo, address: int, t: bn.types.Type, name: str = None
) -> None:
... |
"""
Created on Thu Jul 16 14:26:07 2015
@author: ibackus
"""
import os
import numpy as np
import scipy.interpolate as interp
interp1d = interp.interp1d
import pynbody as pb
SimArray = pb.array.SimArray
from diskpy.utils import strip_units, match_units
def _loadcoeffs(fname):
"""
Loads hermite polynomial coeffic... |
import sys
from os.path import basename
from osgeo import ogr; ogr.UseExceptions() # pylint: disable=multiple-statements
from osgeo import osr; ogr.UseExceptions() # pylint: disable=multiple-statements
from osgeo import gdal; gdal.UseExceptions() # pylint: disable=multiple-statements
from img import ImageFileReader
fro... |
"""Support for loading picture from Neato."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from pybotvac.exceptions import NeatoRobotException
from pybotvac.robot import Robot
from urllib3.response import HTTPResponse
from homeassistant.components.camera import... |
"""
Build helper functions for Labtronyx
"""
__author__ = 'kkennedy'
VER_MAJOR = 1
VER_MINOR = 0
VER_PATCH = 0
RELEASE = False
REL_TYPE = 'dev' # Development Release
import os, time
rootPath = os.path.dirname(os.path.realpath(os.path.join(__file__, os.curdir))) # Resolves symbolic links
def generate_ver(filename='la... |
import scarlett
from scarlett.constants import *
class ScarlettBasics(object):
def __init__(self, brain, **kwargs):
self.brain = brain |
"""Unit test for KNX 2 and 4 byte float objects."""
import math
import struct
from unittest.mock import patch
import pytest
from xknx.dpt import (
DPT2ByteFloat,
DPT4ByteFloat,
DPTElectricCurrent,
DPTElectricPotential,
DPTEnthalpy,
DPTFrequency,
DPTHumidity,
DPTLux,
DPTPartsPerMillio... |
import logging
import definitions
class EvaluateError(Exception):
def __init__(self, eIdent, eArgCount, argCount):
self.ident = eIdent
self.eArgCount = eArgCount
self.argCount = argCount
def __str__(self):
msg = 'too less arguments for ' + str(self.ident) + ' -- '
msg += ... |
"""
Simpler example printing the list of chats you have.
"""
from pytg.sender import Sender
__author__ = 'luckydonald'
def main():
x = Sender("127.0.0.1", 4458)
result = x.dialog_list()
print("Got: %s" % str(result))
if __name__ == '__main__':
main() |
import json
import logging
import re
logger = logging.getLogger(__name__)
class RtmEventHandler(object):
def __init__(self, slack_clients, msg_writer):
self.clients = slack_clients
self.msg_writer = msg_writer
self.stand_up = self.get_standup_channel_id()
def get_standup_channel_id(self)... |
from swiftype import swiftype
import os
import time
import unittest2 as unittest
from six.moves.urllib_parse import urlparse, parse_qs
import vcr
from mock import Mock
class TestClientFunctions(unittest.TestCase):
def setUp(self):
try:
api_key = os.environ['API_KEY']
except:
... |
"""
MIT License
Copyright (c) 2017 Maxim Krivich
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, publish, d... |
def factR(n):
'''
n is an int > 0
return n!
'''
if n == 1:
return n
else:
return n * factR(n - 1) |
import cv2_product_test.find
import unittest
import os
import cv2
import numpy as np
DATA_DIR = os.path.dirname(os.path.abspath(__file__))
IMG1 = cv2.imread(os.path.join(DATA_DIR, 'icons.png'))
TGT1 = cv2.imread(os.path.join(DATA_DIR, 'icons_region.png'))
EXP1 = [[172, 62], [270, 62], [270, 163], [172, 163]]
IMG2 = cv... |
"""Advent of Code 2015, Day 10: Elves Look, Elves Say"""
import pytest
puzzle_input = '1113122113'
def parse_number_string(number_string):
char, *text = str(number_string) # str just in case
count = 1
output = ''
for new_char in text:
if new_char == char:
count += 1
else:
... |
from Util.position import Position
from Util.role import Role
from ai.Algorithm.Graph.Graph import Graph
from ai.STA.Strategy.strategy import Strategy
from ai.STA.Tactic.go_to_random_pose_in_zone import GoToRandomPosition
class PathfinderBenchmark(Strategy):
def __init__(self, p_game_state):
super().__init_... |
import sys
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, classification_report
if len(sys.argv) != 2:
print("Enter the model option.")
exit()
if sys.argv[1] == "--hunpos":
check = 0;
elif sys.argv[1] == "--crf++":
check = 1
else:
print "Enter correct option."
exit()
dir_path... |
import flask
status = flask.Blueprint('status', __name__)
@status.route('/status/healthcheck')
def healthcheck() -> str:
return '' |
"""context processors
"""
from django.contrib.sites.models import Site
from django.utils.functional import SimpleLazyObject
def site(request):
"""get site object
"""
return {
'site': SimpleLazyObject(
lambda: 'http://%s' % Site.objects.get_current_site().domain
),
} |
import subprocess
from subprocess import Popen,PIPE
import os
import ConfigParser
import csv
import sys
import shlex
import re
import unicodedata
import time
import shutil
from distutils.dir_util import copy_tree
import zipfile
interval=240
delugePath=''
megatoolsPath=''
zip7Path=""
thisdir=False#os.getcwd()
mstart='ma... |
from lxml import etree
import re
import os
import sys
import time
from hadoop.hadoop.node import *
from hadoop.hadoop.nameservice import *
from hadoop.hadoop.hadoopinfo import *
home = os.environ['HOME']
def addProperty(root, name, value):
property = etree.XML('''<property><name>''' + name + '''</name><value>''' + ... |
import ldap
import copy
import constants # Local module
def mergeDicts(toDict, fromDict):
#Copy items from 'fromDict' to 'toDict'
if not (isinstance(fromDict, dict) and isinstance(toDict,dict)):
return None
for key in fromDict:
keyCopy = copy.copy(key)
valueCopy = copy.copy(fromDict[key])
toDict[k... |
import pandas as pd
import matchup
import xlsxwriter
import xlautofit
import xlrd
import sys
import time
import collections
import os
week_timer = time.time()
week_number = 'wc_matrix'
matchups = collections.OrderedDict()
matchups['Matchups'] = [('NE', 'DEN'),
('NE', 'PIT'),
... |
import random
import string
from six import string_types
from six import text_type
from six import PY3 as python_3
def parse_args(instance, method, ignore_py3=False):
def parser(func):
if ignore_py3 and python_3:
return func
def wrapper(*args, **kwargs):
new_args = []
... |
from finch import Finch
from time import sleep
from random import randint
tweety = Finch()
accList = []
left, right = tweety.obstacle()
tweety.wheels(.46, .5)
while 1:
x,y,z,tap,shake = tweety.acceleration()
acc = [x, y, z]
accList.append(acc)
# print ("X : ", x)
# print ("Y : ", y)
# print ("Z ... |
from settings.common import *
DATABASES = {
'default': SECRETS_DICT['DATABASES']['LIVE']
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'static'),
) |
from __future__ import absolute_import
import weakref
from warnings import warn
from fontTools.misc.py23 import basestring
from fontTools.misc.arrayTools import unionRect
from defcon.objects.base import BaseObject
from defcon.objects.contour import Contour
from defcon.objects.point import Point
from defcon.objects.comp... |
import os
import unittest
import pocketcasts
USERNAME = os.environ.get('POCKETCAST_USER')
PASSWORD = os.environ.get('POCKETCAST_PASSWORD')
class PocketcastTest(unittest.TestCase):
pocket = pocketcasts.Pocketcasts(USERNAME, PASSWORD)
def test_invalid_method(self):
self.assertRaises(Exception, self.pocket... |
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F40... |
attendees = ['Alison', 'Carolyn', 'Hannah']
for person in attendees: #for "name of variable that we're going to use as we go through this list" in "this list"
print person
#person = 'Alison', print person
#person = 'Carolyn', print person
for cow in range(5):
print cow
print '\n\n\n\n\n'
days_of_week = ... |
import Shadow
from matplotlib import pylab as plt
import numpy
ymin = -100.0
ymax = 100.0
ypoints = 101
beam = in_object_1._beam
tkt = Shadow.ShadowTools.ray_prop(beam,nolost=1,ymin=ymin,ymax=ymax,ypoints=ypoints,xbins=61,zbins=61)
f1 = plt.figure(1)
plt.plot(tkt["y"],2.35*tkt["x_sd"],label="x (tangential)")
plt.plot(t... |
import pytari2600.memory.cartridge as cartridge
import unittest
import pkg_resources
class TestCartridge(unittest.TestCase):
def test_cartridge(self):
cart = cartridge.GenericCartridge(pkg_resources.resource_filename(__name__, 'dummy_rom.bin'), 4, 0x1000, 0xFF9, 0x0)
# Write should do nothing
... |
"""
Make sure to check out the TwiML overview and tutorial
"""
import xml.etree.ElementTree as ET
class TwimlException(Exception):
pass
class Verb(object):
"""Twilio basic verb object.
"""
GET = "GET"
POST = "POST"
nestables = None
def __init__(self, **kwargs):
self.name = self.__cla... |
"""
.. module:: __main__
:platform: linux
:synopsis: Special main entry point.
.. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com>
.. modulecreated:: 6/28/15
"""
import sys
from planet_alignment.app.app_factory import AppFactory
from planet_alignment.cmd.cmd_parser import CommandParser
def main(argv=None):
... |
"""Single slice vgg with normalised scale.
"""
import functools
import lasagne as nn
import numpy as np
import theano
import theano.tensor as T
import data_loader
import deep_learning_layers
import image_transform
import layers
import preprocess
import postprocess
import objectives
import theano_printer
import updates
... |
from CIM14.IEC61970.Core.IdentifiedObject import IdentifiedObject
class Cashier(IdentifiedObject):
"""The operator of the point of sale for the duration of CashierShift. Cashier is under the exclusive management control of Vendor.
"""
def __init__(self, CashierShifts=None, electronicAddress=None, Vendor=Non... |
from sqlalchemy_inventory_definition import session, OperatingSystem
for os in session.query(OperatingSystem):
print (os) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.