content stringlengths 4 20k |
|---|
"""Tests for finish_volume_migration."""
from cinder import context
from cinder import db
from cinder import objects
from cinder import test
from cinder.tests.unit import utils as testutils
class FinishVolumeMigrationTestCase(test.TestCase):
"""Test cases for finish_volume_migration."""
def test_finish_vol... |
from fractions import Fraction
import sys
# rational approximation of a unit circle using farey sequence and a
# Chromogeometry - ish paramterization of unit pts on circle. requires
# numpy, matplotlib
layer = [Fraction(0,1),Fraction(1,1)]
newlayer = []
depth=4
for i in range(1,depth):
for i in range(len(layer)-1)... |
#! /usr/bin/python
import sqlite3
import json
conn = sqlite3.connect('/var/www/html/codeprojects/lights/lights.db')
#print sys.argv[1]
curs = conn.cursor()
def solution(grid):
# json to list of strings
grid = json.loads(grid)
# list of strings to list of lists
grid = [list(x) for x in grid]
figur... |
"""Functions used to download problems from www.goproblems.com"""
import requests
import json
import random
import time
from path import path
from lxml import etree
def parse_problem(html):
"""Parse the given HTML for problem components.
:param str html: the HTML contents of the problem's page
:returns: ... |
from __future__ import unicode_literals
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.operations import SymmOp, MagSymmOp
from pymatgen.electronic_structure.core import Magmom
import numpy as np
class SymmOpTestCase(PymatgenTest):
def setUp(self):
self.op = SymmOp.from_axis_angle_and... |
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_serialization import jsonutils
from neutron.common import constants
from neutron.common import exceptions
from neutron.common import utils
from neutron import context as neutron_context
from neutron.extensions import l3
fro... |
# -*- coding: UTF-8 -*-
#! python3
"""
Usage from the repo root folder:
```python
# for whole test
python -m unittest tests.test_enums
# for specific
python -m unittest tests.test_enums.TestEnums
```
"""
# #############################################################################
# ###... |
import random
import numpy
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from Layers.DenoisingAutoEncoder import DenoisingAutoEncoder
from Phonology.get_phonology_vectors import get_phoneme_vectors
class PhonAutoEncoder(object):
def __init__(self, vocabulary... |
"""Development settings and globals."""
from base import * # NOQA
# DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
# END DEBUG CONFIGURATION
# EMAIL CONFIGURATION
# ... |
from random import random
from bokeh.layouts import row
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import figure, output_file, show
output_file("callback.html")
x = [random() for x in range(500)]
y = [random() for y in range(500)]
s1 = ColumnDataSource(data=dict(x=x, y=y))
p1 = figure(p... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# v = u + 1/2 * a * t^2
#
# The animation pattern is based on the animation tutorial found here:
# http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
#
class Bounce:
# This class is just a... |
# -*- coding: utf-8 -*-
"""\
This is a python port of "Goose" orignialy licensed to Gravity.com
under one or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.
Python port was written by Xavier Grangier for Recrutae
Gravity.co... |
#!/usr/bin/env python3
import os
from mpi4py import MPI
from stable_baselines.common import set_global_seeds
from stable_baselines import bench, logger, PPO1
from stable_baselines.common.atari_wrappers import make_atari, wrap_deepmind
from stable_baselines.common.cmd_util import atari_arg_parser
from stable_baselines... |
from __future__ import absolute_import
import octoprint.util
FiltrackerPrinterStatusDict = {
'PrinterConnected' : {
'Connected' : 'Connected'
},
'PrinterDisconnected' : {
'Disconnected' : 'Disconnected'
},
'PrinterError' : {
'Error' : 'Error'
},
'PrinterUnknown' : {
'Unknown' : 'Unknown'
}
}
FiltrackerP... |
from tempest.api.compute import base
from tempest import test
class InstanceActionsV3Test(base.BaseV3ComputeTest):
@classmethod
def resource_setup(cls):
super(InstanceActionsV3Test, cls).resource_setup()
cls.client = cls.servers_client
resp, server = cls.create_test_server(wait_until=... |
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) == 0:
return
n = len(board)
m = len(board[0])
vis = [[0 for i in range(len(b... |
#!/usr/bin/env python3
"""This script plots two gradually mixed spectra. It can be used
to visualize the spectra changes over the course of a chemical reaction,
e.g. a photoreaction."""
import argparse
import sys
import matplotlib as mpl
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import... |
"""
Stores the data fetched in the cache.
Parse the HTTP header if asked.
"""
import re
import shutil
import struct
import cacheAddress
class CacheData():
"""
Retrieve data at the given address
Can save it to a separate file for export
"""
HTTP_HEADER = 0
UNKNOWN = 1
def __init__(self, ... |
import os
import pango
import gobject, gtk
from hal_widgets import _HalWidgetBase
import linuxcnc
from hal_glib import GStat
from hal_actions import _EMC_ActionBase, ensure_mode
# path to TCL for external programs eg. halshow
try:
TCLPATH = os.environ['LINUXCNC_TCL_DIR']
except:
pass
class EMC_MDIHistory(gtk... |
import os
from lib.cuckoo.common.abstracts import Processing
from lib.cuckoo.common.objects import File
from lib.cuckoo.common.utils import convert_to_printable
class Dropped(Processing):
"""Dropped files analysis."""
def run(self):
"""Run analysis.
@return: list of dropped files with related... |
LIST_TYPE_TAGS = [
'A1',
'A2',
'A3',
'A4',
'AU',
'KW',
]
TAG_KEY_MAPPING = {
'TY': "type_of_reference",
'A1': "first_authors", #ListType
'A2': "secondary_authors", #ListType
'A3': "tertiary_authors", #ListType
'A4': "subsidiary_authors", #ListType
'AB': "abstract",
'... |
# -*- coding: utf-8 -*-
from chunsabot.database import Database
from datetime import datetime, timedelta
import time
from multiprocessing.pool import ThreadPool
from multiprocessing import Lock
class TimeNoti:
@staticmethod
def print_time(room_id):
hour = datetime.now().hour()
amorpm = u"오후" i... |
__author__ = 'Tom Schaul, <EMAIL>'
from pybrain.optimization.optimizer import BlackBoxOptimizer
from scipy import exp
from random import random
class HillClimber(BlackBoxOptimizer):
""" The simplest kind of stochastic search: hill-climbing in the fitness landscape. """
evaluatorIsNoisy = ... |
'''
Generate html file of results
'''
import os
import sys
import pickle
import gzip
from string import Template
import numpy as np
import pandas as pd
sys.path.append('./aneic-core/src')
from aneic import mfm
from aneic import mutual
# Template string for HTML for page
doc_tpl = Template('''\
<!DOCTYPE html PUBLIC "... |
import dbus
import dbus.glib
import dbus.service
import os
import urllib
import webbrowser
from gi.repository import Gio
import gobject
import githubutils
config_tool = "gnome-shell-search-github-repositories-config"
# Convenience shorthand for declaring dbus interface methods.
# s.b.n. -> search_bus_name
search_b... |
from django.conf import settings
from casexml.apps.case.models import CommCareCase
from corehq.apps.hqcase.management.commands.ptop_fast_reindexer import PtopReindexer
from corehq.pillows.reportcase import ReportCasePillow
class Command(PtopReindexer):
help = "Fast reindex of case elastic index by using the case... |
import logging
import re
from scrapers.npr_api import NPRAPIScraper
from util.analytics import GoogleAnalytics
from util.models import Story
from util.slack import SlackTools
from plugins.base import CarebotPlugin
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
npr_api_scrape... |
"""
Ce module comporte l'objet Battle, qui décrit un combat, et les
différentes exceptions qui peuvent se produire durant celui-ci.
"""
import random
import inventory
class Battle(object):
"""Represente un Battle"""
def __init__(self, team1, team2):
"""
Initialise un Battle avec `team1` et `... |
from pprint import pformat
import xbmc, xbmcaddon
import socket
import os
import re
import datetime
import time
from lib.PytzBox import PytzBox
# Script constants
__addon__ = xbmcaddon.Addon()
__addon_id__ = "script.service.fritzbox"
#__version__ = "1"
class FritzCallmonitor():
__pytzbox = None... |
# -*- coding: utf8 -*-
import random
try:
import urllib.parse as urllib
except ImportError:
import urllib
from openload import OpenLoad
from mybs import MyHtmlParser, SelStr
from comm import DWM, match1, echo, start
class VMUS(DWM): # http://vmus.co/
handle_list = ['vmus\.online']
login_url = 'h... |
import logging
import copy
# Get the configuration for the classifier
import emission.analysis.config as eac
import emission.storage.timeseries.abstract_timeseries as esta
import emission.storage.decorations.analysis_timeseries_queries as esda
import emission.storage.decorations.trip_queries as esdt
import emission.s... |
"""Guess which db package to use to open a db file."""
import os
if os.sep==".":
endsep = "/"
else:
endsep = "."
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but ca... |
__author__ = 'yanikafarrugia'
import sys
import logging
import lattly_service.converter
logger = logging.getLogger('lattly')
class MidPointFinder:
def compute_weighted_average(cartesian_point, weights, total_weight):
try:
weighted_average = [0.0] * 3
for point in cartesian_point:
weighted_x = weighte... |
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import timezone
from .models import Course, Step
class CourseModelTests(TestCase):
def test_course_creation(self):
course = Course.objects.create(
title="Python Regular Expressions",
de... |
import csv
import cStringIO
from io import BytesIO
from datetime import datetime, timedelta
import logging
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
... |
# EJ (Mercy) Emelike
# May 23, 2016
# Homework 1
yob = input("What year were you born?")
age = 2016 - int(yob)
#do not allow year of birth to be in the future
if age < 0:
print("Impossible! Try a year in the PAST. One more time.")
yob = input("What year were you born?")
#if year of birth is not in the future
... |
# Time: O(4^n)
# Space: O(n)
#
# Given a string that contains only digits 0-9
# and a target value, return all possibilities
# to add operators +, -, or * between the digits
# so they evaluate to the target value.
#
# Examples:
# "123", 6 -> ["1+2+3", "1*2*3"]
# "232", 8 -> ["2*3+2", "2+3*2"]
# "00", 0 -> ["0+0", ... |
# coding=utf-8
import unittest
"""558. Quad Tree Intersection
https://leetcode.com/problems/quad-tree-intersection/description/
A quadtree is a tree data in which each internal node has exactly four
children: `topLeft`, `topRight`, `bottomLeft` and `bottomRight`. Quad trees
are often used to partition a two-dimension... |
#!/usr/bin/python
from __future__ import print_function
from itertools import *
import math
import os, sys, subprocess, signal
def signal_handler(signal, frame):
sys.exit(0)
#data is like (value, row, col)
class CONSTRAINT:
def __init__(self, N, path):
self.N = N
self.psols = []
check... |
import wx
from service.fit import Fit
import gui.mainFrame
from gui import globalEvents as GE
from gui.fitCommands.calc.fitSetCharge import FitSetChargeCommand
from gui.fitCommands.calc.fitReplaceModule import FitReplaceModuleCommand
from gui.fitCommands.calc.fitRemoveCargo import FitRemoveCargoCommand
from .calc.fitA... |
# -*- coding: utf-8 -*-
import argparse
from argparse import RawTextHelpFormatter
from py6Nimmt import __version__
def build_parser():
""" Parser args """
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter,
description='6 Nimmt! cardgame')
parser.... |
"""Test utility functions shared by several tests."""
import logging
import os
import unittest
from w3testrunner.browsers.manager import browsers_manager
from w3testrunner.browsers.browser import BrowserInfo, BrowserException
log = logging.getLogger(__name__)
class WTRTestCase(unittest.TestCase):
def assertTest... |
"""Module for tracing and analysing network activity of a running VM.
Tshark is required by both the acquisition and analysis Hooks.
https://www.wireshark.org
"""
import os
from see import Hook
from .utils import launch_process, collect_process_output, create_folder
TSHARK = 'tshark'
class NetworkTracerHook(Ho... |
import threading
import os
import pexpect
import time
from mainbot.commands import Command
class cca(Command):
arguments = ["str"]
permissionLevel = 0
permitExtraArgs = True
manArgCheck = False
defaultArgs = []
callName = "cca"
def __init__(self, bot):
#requirement check
... |
from __future__ import with_statement
import os.path
import sys
# Try importing Python 2 modules using new names
try:
import ConfigParser as configparser
import urllib2
from urllib import urlencode
# On error import Python 3 modules
except ImportError:
import configparser
import urllib.request as... |
#!/usr/bin/env python
import urllib,cgi
def pp(x):
print x;
# def getObjects():
# return ['a','b','c','d','e']
# def getBags():
# return [{"name":'a',"selected":True},
# {"name":'a',"selected":False},
# {"name":'a',"selected":False},
# {"name":'a',"selected":False}
# ... |
__author__ = 'Renato'
VK_LBUTTON = 0x01 # Left mouse button
VK_RBUTTON = 0x02 # Right mouse button
VK_CANCEL = 0x03 # Control-break processing
VK_MBUTTON = 0x04 # Middle mouse button (three-button mouse)
VK_XBUTTON1 = 0x05 # X1 mouse button
VK_XBUTTON2 = 0x06 # X2 mouse button
# 0x07 Undefined
VK_BACK = 0x08 # BA... |
"""Rewarder class implementation."""
import copy
import random
import dm_env
import numpy as np
import ot
from sklearn import preprocessing
class PWILRewarder(object):
"""Rewarder class to compute PWIL rewards."""
def __init__(self,
demonstrations,
subsampling,
env_... |
#!/usr/bin/env python
#
# GoPiGo Example for using the Grove Ultrasonic Ranger (http://www.dexterindustries.com/shop/ultrasonic-sensor/)
#
# The GoPiGo is a robotics platform for the Raspberry Pi. You can learn more about GoPiGo here: www.dexterindustries.com/GoPiGo/
#
# Have a question about this example? Ask on th... |
#
# The Python Imaging Library
# $Id$
#
# this demo script illustrates pasting into an already displayed
# photoimage. note that the current version of Tk updates the whole
# image everytime we paste, so to get decent performance, we split
# the image into a set of tiles.
#
from Tkinter import *
from PIL import Image... |
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler,\
FileDeletedEvent, FileCreatedEvent, FileModifiedEvent
import time
import logging
import os.path
from typing import Union, List, Callable, Iterable
## Watches the filesytem for changes and executes any registered callbacks... |
class PaycheckReceipt:
def __init__(self,*args,**kwargs):
self.year = int(args[0])
self.month = int(args[1])
self.pay = args[2]
self.vacation_subsidy = args[3]
self.christmas_subsidy = args[4]
self.irs = args[5]
self.irs_on_vacation_subsidy = args[6]
s... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Alumno'
db.create_table(u'alumnos_alumno', (
... |
#!/usr/bin/env python
# -*- coding: iso-8859-2 -*-
import copy
import pygtk
pygtk.require('2.0')
import gobject
import gtk
# Application logic classes
class Matrix:
def __init__(self, x, y):
self.x = x
self.y = y
self.data = [[]] * x
for x_i in range(x):
self.data[x_i... |
"""Base Entity for all TelldusLiveEntities."""
from datetime import datetime
import logging
from homeassistant.const import ATTR_BATTERY_LEVEL, DEVICE_DEFAULT_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Enti... |
import urllib, time
from twisted.web import html
from twisted.web.util import Redirect
from buildbot.status.web.build import BuildsResource, StatusResourceBuild
from buildbot.status.web.base import HtmlResource, make_row, make_stop_form, \
css_classes, make_name_user_passwd_form
from step import JhStepsResource... |
import socket
from twisted.internet import defer
from feat.test.integration import common
from feat.agents.base import agent, descriptor, replay, resource
from feat.database import document
from feat.agents.common import host
from feat.common.text_helper import format_block
from feat.common import first
from feat.ag... |
""" Interface for the numerous operations and processes
An **operation** takes one summary of data as input and produces a
second one as output with a set of *processes*.
Each **process** can be considered as
an atomic task that can be executed independently from all other processes
of the operation.
Standard Specif... |
from pikos.recorders.text_stream_recorder import TextStreamRecorder
class TextFileRecorder(TextStreamRecorder):
""" The TextStreamRecorder that creates the file for the records.
Private
-------
_stream : TextIOBase
A text stream what supports the TextIOBase interface. The Recorder
wil... |
### import ####################################################################
import collections
import numpy as np
import attune
import yaqc
import pycmds.project.classes as pc
import pycmds.project.project_globals as g
from hardware.opas.opas import Driver as BaseDriver
from hardware.opas.opas import GUI as Bas... |
#!/usr/bin/python
"""Check to see if a driver is functioning properly, else exit with a non-zero
exit code"""
import sys
from optparse import OptionParser
import urllib2
import time
#set json keywords
(true,false,null) = (True, False, None)
parser = OptionParser()
parser.add_option("-s", "--source", dest="source", h... |
#!/usr/bin/env python
"""
lttree_postprocess.py
This is a stand-alone python script which checks the files created by
lttree.py to insure that the standard instance-variables ($variables)
have all been defined. This script performs a task which is very similar
to the task performed by lttree_check... |
import ctypes
import gc
import json
import os
import sys
import threading
def child(pipe_name):
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
objlist = [id(o) for o in gc.garbage]
del gc.garbage[:]
fdwrite = os.open(pipe_name, os.O_WRONLY)
os.write(fdwrite, json.dumps(objlist))
os.close(fdwr... |
import time
import unittest
from king_phisher import testing
from king_phisher import utilities
from king_phisher.server import aaa
from king_phisher.server.database import manager as db_manager
from king_phisher.server.database import models as db_models
class ServerAuthenticationTests(testing.KingPhisherTestCase):
... |
import json
from base64 import b64encode
from urllib.parse import urlparse
import html2text
from dojo.models import Finding, Endpoint
from django.utils.encoding import force_str
__author__ = "Jay Paz"
class ArachniJSONParser(object):
def __init__(self, json_output, test):
self.target = None
sel... |
"""
Use this class to fork off a thread to recieve event callbacks from the bitbake
server and queue them for the UI to process. This process must be used to avoid
client/server deadlocks.
"""
import socket, threading, pickle
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
class BBUIEven... |
import os
import winreg
import admin
if not admin.isUserAdmin():
admin.runAsAdmin()
print(os.popen('ipconfig /all').read())
googleDns = '8.8.4.4 8.8.8.8'
openDns = '208.67.222.222 208.67.220.220'
level3Dns = '209.244.0.3 209.244.0.4'
comodoSecureDNS = '8.26.56.26 8.20.247.20'
nortonSafeDns = '199.85.126.10 1... |
import adagio.common.ml as ml
import adagio.common.eval as eval
import adagio.core.instructionSet as instructionSet
import adagio.common.pz as pz
import collections
import numpy as np
import matplotlib.pyplot as plt
from random import shuffle
from progressbar import *
from sklearn import svm
from sklearn.grid_search i... |
# """Test the singularity container
# Custom test for singularity container: not used here
# """
# import os
# import time
# import json
# import utils
# import pytest
# from GangaCore.Core.GangaRepository.container_controllers import get_database_config
# from GangaCore.Utility.Config import getConfig
# from GangaCor... |
"""Utility functions grab bag."""
def decode_content(response, content):
"""Decode content to a proper string."""
content_type = response.get('content-type',
'application/binary').lower()
if ';' in content_type:
content_type, charset = (attr.strip() for attr in
... |
import os
import subprocess
import tempfile
import mx
import mx_fetchjdk
from jdk_distribution_parser import JdkDistribution
from mx import VC
from mx_bisect import BuildSteps
import shutil
class BuildStepsGraalVMStrategy(BuildSteps):
_mx_path = mx._mx_path
_jdk_home = None
_tmp_dir = None
def __init... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import urllib
from ...unittest import TestCase
from oauthlib.oauth2.draft25 import AuthorizationServer
from oauthlib.oauth2.draft25.exceptions import (InvalidClientIdentifier,
MissingRedirectURI, InvalidRedirectURI)
class Authorizat... |
# -*- encoding:utf-8 -*-
from datetime import datetime
# from matplotlib.patches import Polygon
# from matplotlib.ticker import MaxNLocator
# import pylab
# import matplotlib.pyplot as plt
# import numpy as np
import os
import urllib
import simplejson as json
ROOT_URL = "http://112.124.1.3:8004"
CATEGORY_URL = "api... |
from spack import *
class Phylip(Package):
"""PHYLIP (the PHYLogeny Inference Package) is a package of programs for
inferring phylogenies (evolutionary trees)."""
homepage = "http://evolution.genetics.washington.edu/phylip/"
url = "http://evolution.gs.washington.edu/phylip/download/phylip-3.6... |
"""
Contains all Web related functionality such as cookies and session management,
and Tornado's handler helpers.
"""
import base64
import functools
import time
from bson import ObjectId
import logging
from tornado.web import RequestHandler, asynchronous, HTTPError, urlparse, \
urllib
from to... |
from pd import *
ctimeseed() ## Set a random number seed using system time
timer() ## Start a generic timer
## Set up a simple system containing a short peptide
## and a simple forcefield contianing electrostatics
## and vdw forces
ffps = FFParamSet("amber03aa.ff")
sim = System(ffps)
mol = NewProt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""googleSpeechAPI
Usage:
googleSpeechAPI.py APIKEY FILE
Process FILE and optionally apply correction to either left-hand side or
right-hand side.
Arguments:
APIKEY API Key for Google Speech
FILE File containing links
Options:
-h --help Show... |
# Random forest algorithm
# Starter code borrowed from https://github.com/chandarb/Python-Regression-Tree-Forest
import decision_tree as dt
import numpy as np
class Forest(object):
def __init__(self, trees):
self.trees = trees
def classify(self, obs):
"""Returns the predicted value given the parameters."""
p... |
import theano
from theano import tensor as T
import keras.backend as K
def in_top_k(predictions, targets, k):
'''Says whether the `targets` are in the top `k` `predictions`
# Arguments
predictions: A tensor of shape batch_size x classess and type float32.
targets: A tensor of shape batch_size a... |
"""
L2TP (Layer 2 Tunneling Protocol) for VPNs.
[RFC 2661]
"""
import struct
from scapy.packet import Packet, bind_layers, bind_bottom_up
from scapy.fields import BitEnumField, ConditionalField, FlagsField, \
PadField, ShortField
from scapy.layers.inet import UDP
from scapy.layers.ppp import PPP
class L2TP(Pac... |
# -*- coding: utf-8 -*-
"""
Production Configurations
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis for cache
- Use sentry for error logging
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
fro... |
# coding: utf-8
from __future__ import absolute_import
# This module contains abstractions for the input stream. You don't have to
# looks further, there are no pretty code.
#
# We define two classes here.
#
# Mark(source, line, column)
# It's just a record and its only use is producing nice error messages.
# Parse... |
from AutoVocal.maryclient_http import maryclient
from xml.etree import ElementTree as ET
import mido
import mido.messages
import requests
from AutoVocal.syllable import Syllable
import math
import numpy as np
VOWELS = "A{6QE@3IO29&U}VY=~"
def generate_song():
client = maryclient()
client.set_audio("WAVE_FILE... |
from . import mockito
from twisted.internet.defer import Deferred
from twisted.python.failure import Failure
from twisted.web.http_headers import Headers
from launchkey_twisted.twisted_api import NoneBodyProducer, JSONResponseBodyParser
from .api_test_base import TwistedAPITestBase
class TwistedAPIPingTest(TwistedAPI... |
import hashlib
import json
import uuid
from keystoneclient.contrib.ec2 import utils as ec2_utils
from keystone import exception
from keystone.tests import test_v3
class CredentialBaseTestCase(test_v3.RestfulTestCase):
def _create_dict_blob_credential(self):
blob = {"access": uuid.uuid4().hex,
... |
# -*- coding: utf8 -*-
"""
"""
__author__ = "Jérôme Samson"
__copyright__ = "Copyright 2014, Mikros Image"
import os
import sys
import csv
import time
import datetime
from optparse import OptionParser
import numpy as np
import pygal
from pygal.style import *
try:
import simplejson as json
except ImportEr... |
import dask
import pytest
import ray
from ray.util.dask import ray_dask_get, RayDaskCallback
@dask.delayed
def add(x, y):
return x + y
def test_callback_active():
"""Test that callbacks are active within context"""
assert not RayDaskCallback.ray_active
with RayDaskCallback():
assert RayDas... |
import cherrypy
import cherrypy.lib.auth_basic
import os.path
from sickbeard import logger
from sickbeard.webserve import WebInterface
def initWebServer(options = {}):
options.setdefault('port', 8081)
options.setdefault('host', '0.0.0.0')
options.setdefault('log_dir', Non... |
import aiohttp
import json
from faf.api.client.client_base import BaseApiClient
class AioHttpClient(BaseApiClient):
def make_session(self):
return aiohttp.ClientSession()
async def get(self, url, **kwargs):
"""
Retrieve and deserialize the objects at the given url
:param url:... |
CODE = """\
import zipfile
file = zipfile.ZipFile("library.zip", "r")
names = []
for name in file.namelist():
if name.startswith("timelinelib/plugin/plugins"):
name = name.rsplit("/", 1)[1]
if name.endswith(".pyc") and not name.startswith("__")... |
from firecares.celery import app
from django.db import connections
from django.db.utils import ConnectionDoesNotExist
from firecares.firestation.models import create_quartile_views
from firecares.firestation.models import FireDepartment, create_quartile_views
from firecares.firestation.models import NFIRSStatistic as n... |
'''Library of utilities called by the aurora client binary
'''
from __future__ import print_function
import functools
import math
import re
import sys
from pystachio import Empty
from apache.aurora.client import binding_helper
from apache.aurora.client.base import deprecation_warning, die
from apache.aurora.config ... |
/**
* The MIT License (MIT)
*
* Copyright (c) 2017 BossuytWannes
*
* 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
... |
from oslo.config import cfg
from ceilometer import nova_client
from ceilometer import plugin
OPTS = [
cfg.BoolOpt('workload_partitioning',
default=False,
help='Enable work-load partitioning, allowing multiple '
'compute agents to be run simultaneously.')
]
cfg.... |
# -*- coding: utf-8 -*-
"""
DBSCAN: Density-Based Spatial Clustering of Applications with Noise
"""
#
# License: BSD 3 clause
import numpy as np
from ..base import BaseEstimator, ClusterMixin
from ..metrics import pairwise_distances
from ..utils import check_random_state
from ..neighbors import NearestNeighbors
de... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.core.paginator import Paginator, EmptyPage, InvalidPage
def paginated(req, query_set, per_page=None, default_page=1, prefix="", wrapper=None):
if per_page is None:
from ..conf import settings
per_page = settings.PAGINATOR_OBJECTS_PER... |
from PyQt4 import QtCore, QtGui, Qt
from PyQt4.QtGui import QProgressDialog
from PyQt4.QtCore import QProcess, QString
import bitstring
from bitstring import BitStream, ConstBitStream
from tempfile import TemporaryFile
import csv
import logging
import os
import re
import shutil
import tempfile
import common
import e... |
import lit
import lit.formats
import os
import pipes
import re
import shutil
import subprocess
def _supportsVerify(config):
"""
Determine whether clang-verify is supported by the given configuration.
This is done by checking whether the %{cxx} substitution in that
configuration supports certain compil... |
'''
Created on Jan 20, 2016
@author: kashefy
'''
from nose.tools import assert_equal, assert_true, assert_false, \
assert_is_not_none, assert_is_instance, assert_greater, assert_list_equal, \
assert_is_not
import os
import tempfile
import shutil
from google.protobuf import text_format
from caffe.proto.caffe_pb... |
"""
Base utilities to build API operation managers and objects on top of.
"""
########################################################################
#
# THIS MODULE IS DEPRECATED
#
# Please refer to
# https://etherpad.openstack.org/p/kilo-oslo-library-proposals for
# the discussion leading to this deprecation.
#
# W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.