code stringlengths 1 199k |
|---|
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'My first Flask site'
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0') |
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("2000000... |
from .flaskext import FlaskJSONAPI
from .serializer import (JSONAPI, AttributeActions, RelationshipActions,
Permissions, attr_descriptor, relationship_descriptor,
permission_test) |
__title__ = 'asana'
__version__ = '0.10.3'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Asana, Inc.'
from .client import Client |
import datetime
from pyspark.sql import SparkSession
from pyspark.sql.functions import count, mean, stddev
import smtplib
def timestamp_hour(date, time):
"""Convert date and time to timestamp of the hour (truncate minutes)"""
dt = datetime.datetime.strptime(date + time, '%Y-%m-%d%H:%M')
return (datetime.dat... |
import logging
from cue_csgo.gui import start_app
from cue_csgo.helpers import setup_logging
def main():
try:
setup_logging(debug=False)
start_app()
except Exception:
logging.exception("")
if __name__ == '__main__':
main() |
from sys import argv
import time
from PIL import Image
import netLcd
usage = '%s ip_addr image_files...'
wait_time = 2;
if len(argv) < 3:
print(usage % argv[0])
exit(1)
nd = netLcd.NetLcd(argv[1])
size = (nd.width, nd.height)
for i in range(2,len(argv)):
file = argv[i]
im = Image.open(file)
im.thumb... |
collect_ignore = ['examples'] |
"""
Digraph class
"""
from pygraph.classes.exceptions import AdditionError
from pygraph.mixins.labeling import labeling
from pygraph.mixins.common import common
from pygraph.mixins.basegraph import basegraph
class digraph (basegraph, common, labeling):
"""
Digraph class.
Digraphs are built of nodes and dire... |
"""
This script reads in the given CMSIS device include file (eg stm32f405xx.h),
extracts relevant peripheral constants, and creates qstrs, mpz's and constants
for the stm module.
"""
from __future__ import print_function
import argparse
import re
import platform
if platform.python_version_tuple()[0] == '2':
def co... |
import scrapy
from recipe_scraper.items import RecipeItem
class TwopeasandtheirpodSpider(scrapy.Spider):
name = "twopeasandtheirpod"
start_urls = ['http://www.twopeasandtheirpod.com/category/recipes/main-dishes/']
# prepTime comes out in the following format: PT45M, or PT8H10M
# Need to parse this to "4... |
"""
Django settings for catastrophe_clock project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... |
import tweepy
import bitly_api
import sys, pickle, re, datetime, time
import urllib2
from urllib2 import urlopen, Request, HTTPError
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
CONSUMER_KEY = 'Your Consumer Key'
CONSUMER_SECRET = 'Your Consumer Secret'
ACCESS_KEY = 'Your Access Key'
ACCESS_SECRET = 'Your... |
import json
import os
import subprocess
import requests
from bs4 import BeautifulSoup as bs
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SAVE_PATH = os.path.join(os.path.expandvars('%APPDATALOCAL%'), 'ccleaner')
SAVE_FILE = 'ccleaner_install.exe'
LOCAL_VERSION = '5.05.5176'
chunk_size = 1024
headers = {'User-A... |
from nose.tools import assert_greater_equal, assert_is_instance, assert_equal
from asyncio import iscoroutinefunction, coroutine, async, get_event_loop
from asyncio.futures import Future
from routes import Mapper
from aiohttp.server import ServerHttpProtocol
from logbook import Logger
import inspect
from .request impor... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.core.urlresolvers import reverse_lazy
from .views import *
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^login/', auth_views.LoginView.as_view(template_name='core/login.html', redirect_authenticated_user=Tru... |
import numpy as np, tensorflow as tf
from glob import glob
from analysis import plot_deep_features, plot, smooth_ranges_2d, text
import os
import h5py
from pprint import pprint
from tqdm import tqdm
from IPython import display
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def make_frames(filepath... |
import _plotly_utils.basevalidators
class LValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="l", parent_name="layout.slider.pad", **kwargs):
super(LValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_typ... |
from ..rule_decorators import help_file_entry_rule
from ..linter import RuleError
from ..util import LinterError
import shlex
from unittest import mock
import re
_az_pattern = 'az\s*' + '(([^\"\'])*|' + '((\"[^\"]*\"\s*)|(\'[^\']*\'\s*))' + ')'
_CMD_SUB_1 = re.compile("\$\(\s*" + "(" + _az_pattern + ")" + "\)")
_CMD_SU... |
from __future__ import print_function, unicode_literals
import git
import xml.etree.ElementTree
import os.path
def get_repo_name(repo_dir):
"""
Takes a directory (which must be a git repo) and returns the repository name, derived from
remote.origin.url; <domain>/foo/bar.git => bar
:param repo_dir: path ... |
from pathlib import Path
from doitpy import docs
SAMPLE_PATH = Path(__file__).parent / 'sample'
class TestSpell(object):
def test_check_ok(self):
assert docs.check_no_output(str(SAMPLE_PATH / 'flake_fail.py'),
str(SAMPLE_PATH / 'dict.txt'))
def test_check_fail(self):
... |
from fabric.api import env, require, task, settings, run, sudo, roles, cd, prefix, put
from fabric.operations import prompt
from fabric.contrib.files import exists, sed, upload_template
from fabric.colors import *
from contextlib import contextmanager
import os
import calendar
import time
from time import gmtime, strft... |
from django import forms
from django.forms.util import flatatt
from django.utils.datastructures import MultiValueDict, MergeDict
from django.utils.encoding import force_unicode
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
class PercentageWidget(forms.TextInput):
def... |
from blessings import Terminal
from multiprocessing import Lock
DEFAULT_BAR_WIDTH = 60
class ProgressBar:
def __init__(self, name, total, terminal):
self.name = name
self.total = total
self.term = terminal
self.done = 0
self.errored = 0
self.started = 0
self.w... |
from all import *
occlusion = [(50,50),(50,70),(70,70),(70,50)]
level_lines = [40,70,85,100,115,130,160]
img_file = "img/lena_256.png"
original = misc.imread(img_file)
def test_paint_region():
img = np.copy(original)
intersection_points = 0
cmp_occlusion = complete_points(occlusion)
img_level,level_points = compute... |
import sys
import csv
import nltk
import string
import datetime
import numpy as np
import tensorflow as tf
from nltk.corpus import stopwords
from string import ascii_lowercase as letters
stopwords = stopwords.words('english')
class FNN(object):
'''a simple FNN model for sentiment claasification'''
def __init__(... |
import os
import math
import cv2
import glob
import numpy as np
import uuid
from fileutils import create_dir_check_exists, get_video_datetime
import constants
def calc_distance(x1, y1, x2, y2):
x_dist = (x2 - x1)
y_dist = (y2 - y1)
return math.sqrt(x_dist * x_dist + y_dist * y_dist)
def increment_dict_key_v... |
import urllib.parse
from pyotp import TOTP
import bna
SERIAL = "US120910711868"
SECRET = "HA4GCYLGMFRWKNBYGI4TCZJQHFSGGMLFMNSTSYZSMFQTINDEHAZTSOJYGNQTOZTG"
def test_token():
totp = TOTP(SECRET, digits=8)
assert totp.at(1347279358) == "93461643"
assert totp.at(1347279359) == "93461643"
assert totp.at(1347279360) == ... |
from setuptools import setup
setup(name='oink',
version='0.1.0',
description='A CLI budgeting tools for nerds.',
url='http://github.com/geekforbrains/oink',
author='Gavin Vickery',
author_email='gavin@geekforbrains.com',
entry_points = {
'console_scripts': ['oink=oink.cli:mai... |
import sys
import os
import RPi.GPIO as GPIO
import time
import pygame
DEBUG = False
RUNNING = True
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
pygame.init()
screen = pygame.display.set_mode([50,50])
ObjStep = 22
ObjDir = 27
SlideStep = 17
SlideDir = 4
LEDR = 24
LEDG = 18
LEDB = 23
StepPause = 0.005 #0.001
GPIO.setu... |
import pytest
pytestmark = pytest.mark.page('non_control_elements.html')
class TestOls(object):
def test_with_selectors_returns_the_matching_elements(self, browser):
assert list(browser.ols(class_name='chemistry')) == [browser.ol(class_name='chemistry')]
def test_returns_the_correct_number_of_ols(self, ... |
import os
import time
from django.conf import settings
from django.db import models
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from rest_framework.reverse import reverse
from osmaxx.conversion import coordinate_reference_system as crs, output_format, status
from osmaxx.... |
"""
Copyright (c) 2014 Guillaume Havard - BVS
"""
import sys
import os
import time
import serial
import signal
port = serial.Serial("/dev/ttyAMA0",
baudrate=115200,
timeout=0,
parity=serial.PARITY_NONE,
stopbits=serial.S... |
from remove_chars import remove_chars
def test_remove_chars1():
in_string, letters = 'how are you', 'abc'
expected = 'how re you'
actual = remove_chars(in_string, letters)
assert actual == expected
def test_remove_chars2():
in_string, letters = 'hello world', 'def'
expected = 'hllo worl'
act... |
import . |
from __future__ import unicode_literals
import frappe
import unittest
from frappe.utils import set_request
from frappe.website.render import render
class TestWebsiteRouteMeta(unittest.TestCase):
def test_meta_tag_generation(self):
blogs = frappe.get_all('Blog Post', fields=['name', 'route'],
filters={'published':... |
__date__= 'Apr 13, 2014 '
__author__= 'samuel'
def insertion_sort(A):
n = len(A)
if n == 1:
return A
for key,i in [(A[j], j-1) for j in xrange(1,n)]:
print '%s @[%s]' % (key, i+1),
while i>0 and A[i] > key:
A[i+1] = A[i]
i = i -1
A[i+1] = key
p... |
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 'Search'
db.create_table(u'ui_search', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=Tr... |
import optparse
import sys
import os
import shutil
import json
from os.path import join
import jsontemplate
slingshothomedir = join(os.path.expanduser('~'), '.slingshot')
def _readfile(filename):
f = open(filename, "r")
s = f.read()
f.close()
return s
class Generator:
"""Generator class
"""
def __init__(s... |
from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class BWAInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing BWA 0.7.10 on %s" % (node.alias))
node.ssh.execute('wget -c -P /opt/software/bwa http://sourcef... |
from __future__ import unicode_literals
from frappe.model.document import Document
from frappe.modules.export_file import export_to_files
from frappe.config import get_modules_from_all_apps_for_user
import frappe
from frappe import _
import json
class Dashboard(Document):
def on_update(self):
if self.is_default:
... |
import logging
import sys
loggingInstance = None
def getLogger(debug=False):
global loggingInstance
if loggingInstance is not None:
return loggingInstance
root = logging.getLogger()
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'%(asctime)s - ocarina - %(level... |
import logging
class ExecutionContext(object):
def __init__(self, host=None, port=None, ssl_key=None, ssl_cert=None,
ssl_cacerts=None, userid=None, passwd=None):
self.host = host
self.port = port
self.ssl_key = ssl_key
self.ssl_cert = ssl_cert
self.ssl_cacert... |
from .visualization_user_io import visualization_user_io
class visualization_user_execute(visualization_user_io):
pass; |
'''
created on 2018/9/1
@author:sunyihuan
'''
import tensorflow as tf
from sklearn.metrics import confusion_matrix, recall_score, accuracy_score
from transfer_learning.vgg_transfer import get_record_data
import numpy as np
from PIL import Image
import os
def valid_result_analysis(ckpt_path, data_path, error_show=False)... |
"""Write a function that can decode a string pattern like the following:
Examples:
pattern: ab2[xy]
decoded: abxyxy
pattern: abc2[xy3[rt]wv]xyz
decoded: abcxyrtrtrtwvxyrtrtrtwvxyz
pattern: ab2[xy]tv3[a2[e]]
decoded: abxyxytvaeeaeeaee"
pattern: ab10[x]
... |
from django.core.handlers.base import BaseHandler
from django.middleware.transaction import TransactionMiddleware
class DummyHandler(BaseHandler):
"""Required to process request and response middleware"""
def __call__(self, request):
self.load_middleware()
response = self.get_response(request)
... |
'''
:py:mod:`basecamp.py` - The Everest base class
----------------------------------------------
The :py:obj:`everest` engine. All :py:obj:`everest` models
inherit from :py:class:`Basecamp`.
'''
from __future__ import division, print_function, absolute_import, \
unicode_literals
from . import missions
from .utils ... |
from _pydevd_bundle.pydevd_constants import dict_iter_values, IS_PY24
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_import_class
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame
from _pydev_imps._pydev_saved_modules import threading
class ExceptionBreakpoint(object):
def ... |
from pyvcal.resource import Resource
class File(Resource):
"""A snapshot of a versioned file."""
def get_data(self):
"""Return a binary blob of the file contents"""
raise NotImplementedError
data = property(get_data) |
import json
from django import template
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.utils.safestring import mark_safe
from django.core.signing import Signer
from django.template import Template, Context
from django.template.loader import render_to_string
from members.m... |
import numpy as np
from qtpy.QtWidgets import QFileDialog, QApplication
from qtpy import QtCore
import os
import shutil
from ..fitting.fitting_functions import basic_fit, advanced_fit
from ..utilities.file_handler import FileHandler
class ExportFittingHandler(object):
table = []
x_axis = []
def __init__(sel... |
"""
users.py
A Flask Blueprint module for the user manager page.
"""
from flask import Blueprint, render_template, request, jsonify, g, abort
from werkzeug.exceptions import HTTPException
from meerkat_auth.user import User, InvalidCredentialException
from meerkat_auth.role import InvalidRoleException
from meerkat_auth.... |
from mysite import db
class Paint(db.Model):
__tablename__ = 'Paint'
id = db.Column(db.Integer, primary_key=True)
pid = db.Column(db.String(32), default='')
name = db.Column(db.String(32), default='')
paper = db.Column(db.String(32), default='')
length = db.Column(db.String(32), default='')
width = db... |
"""
The Starshot module analyses a starshot image made of radiation spokes, whether gantry, collimator, MLC or couch.
It is based on ideas from `Depuydt et al <http://iopscience.iop.org/0031-9155/57/10/2997>`_
and `Gonzalez et al <http://dx.doi.org/10.1118/1.1755491>`_.
Features:
* **Analyze scanned film images, single... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pagseguro', '0002_auto_20150506_0220'),
]
operations = [
migrations.AlterField(
model_name='checkout',
name='date',
field=models.DateTimeField(verbose_name='... |
import unittest
from weighted_edit_distance import WeightedEditDistance
class TestEditDistance(unittest.TestCase):
def test_neighbors_consistant(self):
# Check to make sure our key relationships are bidirectional
# because we are using this map to represent a bidirectional
# graph.
ed = WeightedEditDistance()
... |
from magictest import MagicTest as TestCase, suite
from codetalker import pgm
from codetalker.pgm.tokens import STRING, ID, NUMBER, WHITE, CCOMMENT, NEWLINE, EOF, StringToken
from codetalker.pgm.special import star, plus, _or
from codetalker.pgm.grammar import ParseError
class SYMBOL(StringToken):
items = list('[]=... |
import numpy as np
from PIL import Image
im = np.array(Image.open('data/src/lena_square.png').resize((256, 256)))
im_32 = im // 32 * 32
im_128 = im // 128 * 128
im_dec = np.concatenate((im, im_32, im_128), axis=1)
Image.fromarray(im_dec).save('data/dst/lena_numpy_dec_color.png') |
'''*****************************************************************************************************************
Raspberry Pi + Raspbian Weather Station
By Uladzislau Bayouski
https://www.linkedin.com/in/uladzislau-bayouski-a7474111b/
A Raspberry Pi based weather station that measures temperature, h... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
description = "Pyccuweather is a simple, efficient back-end to the Accuweather API. Presently, it allows you to " \
"interface with the API and download forecasts, which it then abstracts into files or passes on... |
""" Small script to run the bot that plays on webdiplomacy.net
You can stop the bot with keyboard interruption (Ctrl+C).
"""
import argparse
import logging
import os
import sys
import time
import traceback
from diplomacy.integration.webdiplomacy_net.api import API
from diplomacy.utils import exceptions
from tornado... |
from __future__ import absolute_import
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
def test_color_descriptor():
from ..colors import ColorChoiceDescriptor
class DummyStyle(object):
value = ColorChoiceDescriptor('value')
style = ... |
"""
Traversing a graph of Django models, using FK and M2M relationships as edges. A
model can also explicitly define a relationship via a static method that takes
in model instances and returns a QuerySet for fetching the related objects for
these instances.
"""
import types
from django.db import connections, router
fr... |
import re
class TheAuctionMill():
""" Module for the http://www.theauctionmill.com site """
def __init__(self, auction_helper):
self.base_url = "http://www.theauctionmill.com"
self.url = "http://www.theauctionmill.com/upcoming-auctions/"
self.AuctionHelper = auction_helper
self.r... |
import collections
import numpy as np
dataset = collections.namedtuple('dataset', 'inputs targets labels')
def targets_from_labels(labels, num_classes):
"""
Create a matrix of targets from the given labels. Input labels are
integers in {0,1,...,num_classes} representing class labels.
Targets is a <num_c... |
import datetime
import random
import flask
from sqlalchemy.orm.exc import NoResultFound
import zeeguu_core
from sqlalchemy import desc
from zeeguu_core.model.user import User
db = zeeguu_core.db
class Session(db.Model):
__table_args__ = {'mysql_collate': 'utf8_bin'}
id = db.Column(db.Integer, primary_key=True)
... |
from cmath import polar, rect, pi as π
from math import copysign, sqrt, sin
vector = complex
def axisPos(t : float, P : float, V : float, A : float) -> float:
''' Calculates position on one axis '''
return P + V*t + (1/2)*A*t**2
def position(t : float, P0 : vector, V0 : vector, A : vector) -> vector:
''' Calculates ... |
from juju_suspend.providers.base import Provider
class OpenstackProvider(Provider):
suspend_cmd = ". {1}; nova stop {0}"
resume_cmd = ". {1}; nova start {0}"
def __init__(self, environment):
Provider.__init__(self, environment)
if not self.environment.options.novarc:
raise Except... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
from .. import base
logger = logging.getLogger(__name__)
def process(conf, conn):
# Iterate over all hra publications
count = 0
for publication ... |
"""
manifest.py is a utility class to help determine version differences in sprinter apps.
example manifest sections look like:
[FEATURE]
version = {{ manifest_version }}
{{ configuration vars }}
The manifest can take a source and/or a target manifest
"""
from __future__ import unicode_literals
import logging
import os... |
import os
from setuptools import setup, find_packages
import serverscope_benchmark
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='serverscope_benchmark',
version=serverscope_benchmark.__version__,
author='ServerScope',
author_email='contact@serverscope.io',
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviews', '0009_employee_service_line'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='email',
... |
from __future__ import unicode_literals
from django.db import migrations, models
def create_initial_choices(apps, schema_editor):
OutreachMaterialType = apps.get_model('metadata', 'OutreachMaterialType')
OutreachMaterialType.objects.create(name='Flyer/Brochure')
OutreachMaterialType.objects.create(name='Gui... |
import requests
class API:
__token = ''
_host = 'http://www.hackerrank.com/x/api/v2/'
_endpoints = {
"tests": _host + "tests",
}
_default_headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
_payload = {
"access_token": __token
}
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('huntserver', '0027_auto_20181023_2303'),
]
operations = [
migrations.CreateModel(
name='Prepuzzle',
... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
TEMPALTE_DIRS = (
'/Users/fishb1jw/capstone_project/note_exchange/notes_app/templates'
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine... |
from thefuck import utils
from thefuck.utils import replace_argument
from thefuck.specific.git import git_support
@git_support
def match(command):
return (command.script.split()[1] == 'stash'
and 'usage:' in command.stderr)
stash_commands = (
'apply',
'branch',
'clear',
'drop',
'list... |
from common import *
def test_describe(ds_local):
ds = ds_local
ds.info() |
from view import Events, UI
from controller import Console
from model import BucketToolField |
from __future__ import division
import tweepy
import os
import requests
import re
import nltk
from nltk import word_tokenize
from nltk.corpus import stopwords
from sutime import SUTime
import json
from secrets import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
BAD_WORDS_URL='https://raw.githubuserc... |
import socket
import sys
import numpy as np
from numpy import linalg as npla
from bot_geometry.rigid_transform import RigidTransform, Pose
from bot_geometry.quaternion import Quaternion
from bot_externals.draw_utils import publish_pose_list, publish_sensor_frame, publish_cloud, \
publish_line_segments
def triggerPo... |
from __future__ import unicode_literals
from html5lib import getTreeWalker
from html5lib_truncation import truncate_html, TruncationFilter
result_a = (
'<p>Return a truncated copy of the string. The length is specified with '
'the first parameter which <tt class="docutils literal">\n'
'<span class=pre></spa... |
"""
Die Datenmodelle für die Wettbewerbsdatenbank
- Zentral ist Teilnahme von Personen an Veranstaltungen
- Veranstaltung kann Wettbewerbsrunde oder Seminar sein
- Parallel gibt es Beschreibungen von Wettbewerben, sinnvoll gruppiert
- Verknüpfungen zwischen Veranstaltungen sind indirekt über Kategorien
- alles, wa... |
from django.db import models
from django.core.urlresolvers import reverse
from bib.models import Book
from reversion import revisions as reversion
class TrackChanges(models.Model):
"""
Abstract base class with a creation and modification date and time
"""
created = models.DateTimeField(auto_now_add=True... |
import numpy as np
import audioread as ar
import math
import sys, time
wavName_hi = "../wav/02-Are You Real.wav"
wavName_cd = "../wav/02-Are You Real_CD.wav"
csvName_hi = "../result_hi.csv"
csvName_cd = "../result_cd.csv"
N = 20
def pcm2float(short_ndary):
float_ndary = np.array(short_ndary, dtype=np.float64)
r... |
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.contrib.auth import authenticate
from bookstore.python_app.py.DBController import *
from bookstore.python_app.py.Book import *
... |
from esockets.socket_server import *
with open(__path__[0] + '/version', 'r') as r:
__version__ = r.read() |
"""
Instead of using a joystick control:
- program your plant placement (servo angles)
- amount of water (pump power and time)
- Add to cron
Notes:
Keep towels close by.
"""
from time import sleep
import os
import pigpio
from robot import Robot
from pump import Pump
program = [
# angle_a,angle_2, PUMP POWER, PUMP T... |
import boto3
import unittest
from aws_ir_plugins import isolate_host
from moto import mock_ec2
class IsolateHostTest(unittest.TestCase):
@mock_ec2
def test_tag_host(self):
self.ec2 = boto3.client('ec2', region_name='us-west-2')
session = boto3.Session(region_name='us-west-2')
ec2_resourc... |
from yelp_fusion_api import *
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
print(search(bearer_token, "bars", "150.644", "-34.397")) |
from django.contrib.auth.models import User
from django.shortcuts import resolve_url as r
from django.test import TestCase
from ..models import Company
class CompanyViewTest(TestCase):
def setUp(self):
user = User.objects.create_user('user', 'email@domain.com', 'password')
Company.objects.create(**{... |
import os, sys, getopt, shutil
inputFileName = 'test.sl'
outputFileName = 'main.c'
architecture = 'testarch'
targetOS = 'mansos'
pathToOS = '../..'
verboseMode = False
testMode = False
def exitProgram(code):
if not testMode:
exit(code)
print ("Would exit from program with code " + str(code))
raise E... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def home(request):
if request.is_ajax():
return render(request, 'home.html')
return render(request, 'index.html')
def auth_view(request): #do i want this to also include a par... |
"""Exceptions used by hangups."""
class HangupsError(Exception):
"""An ambiguous error occurred."""
class NetworkError(HangupsError):
"""A network error occurred."""
class ConversationTypeError(HangupsError):
"""An action was performed on a conversation that doesn't support it.""" |
"""
Python implementation of Haversine formula
Copyright (C) <2009> Bartek Górny <bartek@gorny.edu.pl>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... |
import iperf3
client = iperf3.Client()
client.duration = 1
client.server_hostname = '127.0.0.1'
client.port = 5201
print('Connecting to {0}:{1}'.format(client.server_hostname, client.port))
result = client.run()
if result.error:
print(result.error)
else:
print('')
print('Test completed:')
print(' start... |
from rest_framework import viewsets
from game.models import Game
from game.serializers import GameSerializer
class GameViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing Game and editing
"""
serializer_class = GameSerializer
queryset = Game.objects.all() |
<<<<<<< HEAD
<<<<<<< HEAD
""" Python Character Mapping Codec mac_romanian generated from 'MAPPINGS/VENDORS/APPLE/ROMANIAN.TXT' with gencodec.py.
"""#"
import codecs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(sel... |
import os
import datetime
import sys
sys.path.append("..")
import puka
def get_queue_name():
return os.environ.get('RABBITMQ_QUEUE', 'default_queue')
def get_timestamp():
return datetime.datetime.utcnow().strftime("%H:%M:%S")
client = puka.Client("amqp://guest:guest@127.0.0.1:5672/")
promise = client.connect()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.