content string |
|---|
import json, time
import requests.packages.urllib3
from urllib import urlencode
import urllib2
# User identification data
_CLIENT_ID = "xxxxxxxxxxxxx" #client ID from http://dev.netatmo.com/dev/listapps
_CLIENT_SECRET = "xxxxxxxxxxxx" #client app secret
_USERNAME = "<EMAIL>" #netatmo username
_PA... |
from __future__ import print_function
import numpy as np
import argparse
import os
import sys
import signal
import time
import socket
from contextlib import closing
from six import string_types
import math
import paddle
import paddle.fluid as fluid
import paddle.fluid.profiler as profiler
import paddle.fluid.unique_na... |
from setuptools import setup
import os
import sys
import re
install_requires = []
if sys.version_info < (2, 7):
raise Exception("health-stats requires Python 2.y or higher.")
elif sys.version_info < (3, 0):
install_requires += ['future']
install_requires += [
'pretty',
'plotly',
'sqlalchemy',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/RiskAssessment) on 2016-06-23.
# 2016, SMART Health IT.
from . import domainresource
class RiskAssessment(domainresource.DomainResource):
""" Potential outcomes for a subject with likelihoo... |
"""
Pseudostate diagram items.
See also gaphor.UML.states package description.
"""
from gaphas.util import path_ellipse
from gaphor import UML
from gaphor.diagram.presentation import ElementPresentation
from gaphor.diagram.shapes import Box, EditableText, IconBox, Text, stroke
from gaphor.diagram.support import repr... |
import csv
import datetime
import io
import re
from django.db.models.fields.files import FieldFile
import pandas as pd
POSTGRES_KEYWORDS = [
'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc',
'asymmetric', 'authorization', 'binary', 'both', 'case', 'cast', 'check', 'collate', 'collation',
'... |
# Based from http://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
# We shouldn't need pypandoc on remote users's systems just becau... |
#!/usr/bin/env python
"""Read GenBank flat files.
Currently only reads sequence data and not annotations.
"""
from __future__ import absolute_import
from ..utils import *
from ..seq import *
names = ( 'genbank',)
extensions = ('gb','genbank', 'gbk')
def read(fin, alphabet=None):
"""Read and parse a f... |
"""Solvers for non-smooth optimization problems."""
from __future__ import absolute_import
__all__ = ()
from .proximal_operators import *
__all__ += proximal_operators.__all__
from .chambolle_pock import *
__all__ += chambolle_pock.__all__
from .douglas_rachford import *
__all__ += douglas_rachford.__all__
from .... |
#!/usr/bin/env python
# coding:utf-8
import platform
from tools_lib.host_info import TEST_BL_DB_IP, BL_SERVICE_NODE, BL_DB_IP
NODE = platform.node()
"""DB configurations."""
DB = {
'default': {
'host': TEST_BL_DB_IP,
'port': 3306,
'user': 'fengdev',
'password': 'qaz123',
'd... |
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version():
INIT = os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
from .models import *
from .forms import *
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.contrib.gis.geos import Point
def add_point(request):
if request.method == 'POST':
form = AddHou... |
"""
RefererMiddleware: populates Request referer field, based on the Response which
originated it.
"""
import warnings
from typing import Tuple
from urllib.parse import urlparse
from w3lib.url import safe_url_string
from scrapy import signals
from scrapy.exceptions import NotConfigured
from scrapy.http import Request... |
"""
"""
#end_pymotw_header
import asynchat
import logging
class EchoHandler(asynchat.async_chat):
"""Handles echoing messages from a single client.
"""
# Artificially reduce buffer sizes to illustrate
# sending and receiving partial messages.
ac_in_buffer_size = 64
ac_out_buffer_size = 64
... |
import string
import numpy as np
from pandas import DataFrame, MultiIndex, Series, concat, date_range, merge, merge_asof
from .pandas_vb_common import tm
try:
from pandas import merge_ordered
except ImportError:
from pandas import ordered_merge as merge_ordered
class Append:
def setup(self):
s... |
"""
conttest
--------
This task uses ``conttest`` to monitor a directory for changes and executes the specified
task everytime a change is made. The following configuration is supported::
config = {
'conttest': {
'task': 'registered_task',
'directory': './directory/to/monitor/'
... |
from rsf.proj import *
import fdmod
# ------------------------------------------------------------
# model parameters
def param():
par = {
'nx':3201, 'ox':10.025,'dx':0.025, 'lx':'Position', 'ux':'km',
'nz':1201, 'oz':0, 'dz':0.025, 'lz':'Depth', 'uz':'km',
'ft2km':0.3048
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
from oslo.config import cfg
from nova import context as nova_context
from nova import utils
from nova.openstack.common import log as logging
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class ManagerInitHostHook(object):
def __init__(self):
... |
import string
import random
import json
from collections import defaultdict
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from catmaid.fields import Double3D
from catmaid.models import Log, Neur... |
#!/usr/bin/env python3
"""
A script which reads Higgins Annotation Tool (HAT) XML annotation files <http://www.speech.kth.se/hat/>, extracts the individual "segment" elements contained therein and creates POS tags for the segment tokens using NLTK.
The counts of each unique token-tag pair are then printed to the stand... |
from pylearn2.utils import serial
import sys
_, model_path = sys.argv
model = serial.load(model_path)
from pylearn2.gui.patch_viewer import make_viewer
space = model.generator.get_output_space()
from pylearn2.config import yaml_parse
import numpy as np
dataset = yaml_parse.load(model.dataset_yaml_src)
dataset = datase... |
# coding: utf-8
"""
This module handles all things related to creating a new invoice, including
* keeping track of when they were issued
* making sure they have unique and correct invoice numbers
* keeping track who was the issuer of the invoice (changes form year to year)
* stroing full copy in the Invoice model to ... |
import sys
import os
import shlex
import neurom
from neurom.version import VERSION
# Mock out modules depending on 3rd party C libraries
from mock import Mock
class _Mock(Mock):
@classmethod
def __getattr__(cls, name):
return _Mock()
MOCK_MODULES = ['scipy', 'scipy.spatial', 'h5py', 'yaml', 'tqdm']
s... |
"""Spellcorrection module, for custom word sets.
Forked from https://github.com/phatpiglet/autocorrect and modified so it uses
a fixed set of words.
"""
from itertools import chain
ALPHABET = 'abcdefghijklmnopqrstuvwxyz\','
class SpellCorrection(object):
"""Corrects a word based on given set of words."""
... |
import uuid
from designateclient.tests import v2
class TestTSIGKeys(v2.APIV2TestCase, v2.CrudMixin):
RESOURCE = 'tsigkeys'
def new_ref(self, **kwargs):
ref = super(TestTSIGKeys, self).new_ref(**kwargs)
ref.setdefault("name", uuid.uuid4().hex)
ref.setdefault("algorithm", "hmac-sha256"... |
"""Deploy artifacts to S3."""
import logging
import os
import subprocess
from ..exceptions import S3ArtifactNotFound
from ..utils import get_details, get_properties
LOG = logging.getLogger(__name__)
class S3Deployment:
"""Handle uploading artifacts to S3 and S3 deployment strategies."""
def __init__(self, ... |
"""
Test cases for Neutron PLUMgrid Plug-in
"""
from mock import patch
from neutron.manager import NeutronManager
from neutron.tests.unit import test_db_plugin as test_plugin
class PLUMgridPluginV2TestCase(test_plugin.NeutronDbPluginV2TestCase):
_plugin_name = ('neutron.plugins.plumgrid.plumgrid_nos_plugin.'
... |
from __future__ import print_function
from bs4 import BeautifulSoup
import datetime
import spynner
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import sys
try:
import argparse
p = argparse.ArgumentParser(parents=... |
#!/usr/bin/python3
import sys
import os
import fnmatch
import rarfile
import zipfile
import binascii
import shutil
import argparse
# Go over the directory and gather the crcs of the files inside
def _gather_crcs(directory):
if not os.path.isdir(directory) or not os.path.exists(directory):
print("The ad d... |
from gaiatest import GaiaTestCase
from gaiatest.tests.clock import clock_object
import time
class TestClockCreateNewAlarm(GaiaTestCase):
def setUp(self):
GaiaTestCase.setUp(self)
# unlock the lockscreen if it's locked
self.lockscreen.unlock()
# launch the Clock app
self.... |
# -*- coding: utf-8 -*-
#
# © 2014 Ian Eure
#
"""Data I/O serial interface."""
import array
import logging
import serial
import sys
import time
from . import format
from yar.cksum import *
import yar.io as io
EOL = "\r"
# Error handling
ERRS = ((2**31, "Error:"),
(2**26, "Serial overrun error"),
... |
import os
from django.core.files.uploadedfile import SimpleUploadedFile
from survey.forms.upload_csv_file import UploadEAForm
from survey.models import Survey
from survey.tests.base_test import BaseTest
class UploadEAFormTest(BaseTest):
def setUp(self):
self.filename = 'test_uganda.csv'
self.fileda... |
"""Testcases for cssutils.css.CSSFontFaceRule"""
__version__ = '$Id$'
import xml.dom
import test_cssrule
import cssutils
class CSSFontFaceRuleTestCase(test_cssrule.CSSRuleTestCase):
def setUp(self):
super(CSSFontFaceRuleTestCase, self).setUp()
self.r = cssutils.css.CSSFontFaceRule()
... |
#
# -*- encoding: utf-8 -*-
#
import cookielib
import urllib
import config
import mechanize
import BeautifulSoup
import urlparse
import cgi
import os
import sys
import re
import datetime
import hashlib
import time
def unienc(s):
if type(s) == unicode:
return s.encode('utf-8')
else:
return s
... |
# vim: set fileencoding=utf-8 :
# vim: set et ts=4 sw=4:
'''
EventManger class
License: LGPLv2+
Author: Angelo Naselli <<EMAIL>>
@package manatools
'''
import manatools.event as event
class EventManager:
def __init__(self):
'''
EventManager manages 4 kind of YUI events:
widget, menu, timeout... |
#! /usr/bin/env python
"""
Author: inodb and limr
Loosely based on niknafs original
"""
import sys
import subprocess
import warnings
import re
from sufam.mutation import Mutation, MutationsAtSinglePosition
from collections import Counter
MPILEUP_DEFAULT_PARAMS = '--ignore-RG --min-MQ 1 --max-depth 250000 --max-idepth... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
output of struct of files and folders for these settings, see array position, config[x]
config[3] - (root backup folder)
/media/ext-hd/
configx[0] - (app name folder)
... |
def create_debug_port():
"""
N/A This functionality does not exist on Windows.
"""
pass
_win32_cpu_usage = None
def get_cpu_usage():
"""
N/A. Unfortunately, this implementation is way too slow
Probably should run it in a thread or something.
"""
return 0
global _win32_cpu_usa... |
from sympy import *
from IPython.display import display
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
x1, x2, x3 = symbols("x_1 x_2 x_3")
alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3")
R, L, ga, gv = symbols("R L g_a g_v")
init_printing()
#%%
a1 = pi / 2 + (L / 2 - alpha1)/R
x = (R + ga*cos(g... |
from __future__ import print_function
import random, time
from annoy import AnnoyIndex
try:
xrange
except NameError:
# Python 3 compat
xrange = range
n, f = 100000, 40
t = AnnoyIndex(f, 'angular')
for i in xrange(n):
v = []
for z in xrange(f):
v.append(random.gauss(0, 1))
t.add_item(i... |
"""
sentry.tsdb.inmemory
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from collections import Counter, defaultdict
import six
from django.utils import timezone
from sentry.tsdb... |
import webob
from fanstatic.config import convert_config
from fanstatic import (Injector, Delegator, Publisher, LibraryRegistry,
ConfigurationError)
import fanstatic
def Fanstatic(app,
publisher_signature=fanstatic.DEFAULT_SIGNATURE,
injector=None,
**c... |
# encoding: utf-8
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 'StaticPage.creation_date'
db.add_column('staticpages_staticpage', 'creation_date', self.gf... |
import unittest
from zope.testing import doctestunit
from zope.component import testing
from Testing import ZopeTestCase as ztc
from Products.Five import zcml
from Products.Five import fiveconfigure
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import PloneSite
ptc.setupPlo... |
from flask_restful import Resource, Api
from flask_restful_swagger import swagger
from flauthority import app
from flauthority import api, app, celery, auth
from ModelClasses import AnsibleCommandModel, AnsiblePlaybookModel, AnsibleExtraArgsModel
import celery_runner
class TaskOutput(Resource):
@swag... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals, absolute_import
import os
import sys
import logging
import argparse
from . import __version__
from .daemonrunner import DaemonRunner
from .watcher import watcher
try:
import configparser
except ImportError: # python 2 and... |
# generate a network diagram (tree)
# requires the PyGraphviz library
# draw graph linear order or not
linear = False
output = False
# import pygraphviz for tree structures
import pygraphviz as pg
# create empty graph
graph = pg.AGraph()
# add sets
graph.add_node('k', shape='square', color="#7979FF", style="filled"... |
# Django settings for secondhand project.
import os
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Ankur Sethi', '<EMAIL>'),
)
MANAGERS = ADMINS
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangop... |
import textwrap
class BlittedFigure(object):
def _on_draw(self, *args):
canvas = self.figure.canvas
self._background = canvas.copy_from_bbox(self.figure.bbox)
self._draw_animated()
def _draw_animated(self):
canvas = self.ax.figure.canvas
canvas.restore_region(self._ba... |
"""
Copyright 2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... |
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v7.errors',
marshal='google.ads.googleads.v7',
manifest={
'EnumErrorEnum',
},
)
class EnumErrorEnum(proto.Message):
r"""Container for enum describing possible enum errors. """
class EnumError(p... |
#!/usr/bin/env python
"""
The APIRUS API as an Abstract Base Class
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class APIRUS:
"""
ABC for the API for Regular,... |
######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
"""
dyld emulation
"""
import os
from framework import framework_info
from dylib import dylib_inf... |
"""The ATEN PE switch component."""
import logging
from atenpdu import AtenPE, AtenPEError
import voluptuous as vol
from homeassistant.components.switch import (
DEVICE_CLASS_OUTLET,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_USERNAME
from homeassistant.ex... |
"""Various utility functions and classes not specific to any single area."""
import argparse
import atexit
import cStringIO
import functools
import json
import logging
import logging.handlers
import optparse
import os
import re
import sys
import threading
import time
import utils
from utils import zip_package
# Pat... |
import os
import re
import gzip
import json
import time
import errno
import random
import urllib
import contextlib
from datetime import datetime
import idiokit
from idiokit.xmpp.jid import JID
from abusehelper.core import bot, events, taskfarm, utils
def _create_compress_path(path):
head, tail = os.path.split(p... |
class Colors:
reset = '\033[0m'
bold = '\033[01m'
disable = '\033[02m'
underline = '\033[04m'
reverse = '\033[07m'
strikethrough = '\033[09m'
invisible = '\033[08m'
fg_black = '\033[30m'
fg_red = '\033[31m'
fg_green = '\033[32m'
fg_orange = '\033[33m'
fg_blue = '\033[34m... |
import numbers
import os
import os.path
import traceback
import sys
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
from .source_enumerator import SourceEnumerator
from ert.util import installAbortSignals
from ert.util import Version
TESTDATA_ROOT = None
SHARE_ROOT = Non... |
import threading
from contextlib import contextmanager
from django.conf import settings
class SearchUpdateOptions(threading.local):
"""
Temporary search update options for the current thread.
Setting them:
with search_update_options(async=False):
notice.save()
Accessing them:
... |
import unittest
import webapp2
import webtest
from google.appengine.ext import testbed
from mock import patch
from gcp_census.model.model_creator import ModelCreator
from gcp_census.model.model_creator_handler import ModelCreatorHandler
class TestModelCreatorHandler(unittest.TestCase):
def setUp(self):
... |
import os
import sys
import logging
import openerp
import pickle
import xlrd
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SU... |
import TractorDispatcherUI
__import__( "IECore" ).loadConfig( "GAFFER_STARTUP_PATHS", {}, subdirectory = "GafferTractorUI" ) |
import json
import re
import gzip
import urllib2
import tempfile
#
# Subclass your inspector from this class below
#
class FeedbackInspector:
'''
Each inspector focuses on undrstanding a logfile and provides inspect, a method that parses the log
The purpose is to fill the object 'report' with info, warn a... |
from mock import patch
from django.test import TestCase
from ..serializer import ViewSerializer
class ViewSerializerTests(TestCase):
"""Test RepoSerializer methods"""
def setUp(self):
self.username = "delete_me_username"
self.repo_base = "delete_me_repo_base"
self.password = "delete... |
from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.gepetto import Viewer
rootJointType = 'freeflyer'
packageName = 'hpp-rbprm-corba'
meshPackageName = 'hpp-rbprm-corba'
urdfName = 'hrp2_trunk_flexible'
urdfNameRoms = ['hrp2_larm_rom','hrp2_rarm_rom','hrp2_lleg_rom','hrp2_rleg_rom']
urdfSuffix = ""
srdfSu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 19 14:29:15 2016
@author: agiovann
"""
from __future__ import print_function
from builtins import zip
from builtins import str
try:
if __IPYTHON__:
# this is used for debugging purposes only. allows to reload classes when changed
... |
from dpa.action import Action, ActionError, ActionAborted
from dpa.product.subscription import ProductSubscription
from dpa.shell.output import Output, Style
# -----------------------------------------------------------------------------
class SubscriptionEditAction(Action):
"""Edit an existing subscription."""
... |
#!/usr/bin/env python
import flask
from hashlib import sha512
from RedisObjects import RedisDict, RedisList
import redis
import pickle
NAME = 'RedisObjects_example'
app = flask.Flask(NAME)
app.debug = True
####
# Helper classes
####
class UserDoesNotExist(Exception):
pass
class RedisSession(object):
def __... |
#coding=utf-8
import sys
import facenet
import numpy as np
def sample_people(dataset, people_per_batch, images_per_person):
nrof_images = people_per_batch * images_per_person
# Sample classes from the dataset
nrof_classes = len(dataset)
class_indices = np.arange(nrof_classes)
np.random.shuffle(... |
from __future__ import print_function
import numpy as np
from scipy import special
import unittest
import sys
sys.path.append("..")
from op_test import OpTest
import paddle
import paddle.fluid as fluid
paddle.enable_static()
SEED = 2021
def np_gelu(x):
y = 0.5 * x * (1 + special.erf(x / np.sqrt(2)))
return ... |
"""This module defines decorators to ensure communications with the boards.
"""
__all__ = ["ensure_write_method",
"ensure_read_method",
"ensure_connect_method"
]
__author__ = 'antmil'
__docformat__ = 'restructuredtext'
try:
import eapi
from adp_exception import *
except ImportError, e:... |
"""
This customization makes it easier to deal with the bootstrapping
data returned by the ``iam create-virtual-mfa-device`` command.
You can choose to bootstrap via a QRCode or via a Base32String.
You specify your choice via the ``--bootstrap-method`` option
which should be either "QRCodePNG" or "Base32StringSeed". Y... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import time
import sys
import paddle.fluid as fluid
import math
__all__ = ["DPN", "DPN68", "DPN92", "DPN98", "DPN107", "DPN131"]
train_parameters = {
"input_size": [3, 224, 224... |
# -*- coding: utf-8 -*-
# file: login.py
import urllib
import urllib2
import sys
import ssl
import json
# 这段代码是用于解决中文报错的问题
reload(sys)
sys.setdefaultencoding("utf8")
ssl._create_default_https_context = ssl._create_unverified_context
class dataPost(object):
def __init__(self):
self.baseUrl = ''
de... |
# -*- coding: utf-8 -*-
"""
Display unread feeds in your favorite RSS aggregator.
For now, supported aggregators are:
* OwnCloud/NextCloud with News application
* Tiny Tiny RSS 1.6 or newer
You can also decide to check only for specific feeds or folders of feeds. To use this
feature, you have to first get the... |
from django.conf.urls import include, url
from rest_framework import routers
import rest_framework.authtoken.views as drf_views
from workflows.api import views
router = routers.DefaultRouter()
def trigger_error(request):
division_by_zero = 1 / 0
router.register(r'inputs', views.InputViewSet, base_name='input')
... |
import numpy as np
import math
import scipy.special as sp
from scipy.interpolate import lagrange
from numpy.polynomial.chebyshev import chebgauss
#import sys
from utilities import *
from interfaces import *
#from utilities.arclength import*
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
R ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Button(QtGui.QPushButton):
def mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.RightButton:
return
# write the relative cursor position to mime data
mimeData = QtCore.QMimeData()
... |
from openerp import models
class ResPartner(models.Model):
_inherit = 'res.partner'
def check_vat_es(self, vat):
"""
Verify Spanish VAT numbers.
"""
return True
def simple_vat_check(self,cr,uid,country_code,vat_number, context=None):
"""Main check method override"""
return True |
"""Test broken-object suppport
"""
import sys
import unittest
import persistent
import transaction
import os
if os.environ.get('USE_ZOPE_TESTING_DOCTEST'):
from zope.testing.doctest import DocTestSuite
else:
from doctest import DocTestSuite
from ZODB.tests.util import DB, checker
def test_integration():
r... |
import os
from unittest.mock import patch
from django.contrib.auth.models import User
from django.core.management import call_command
from django.test import TestCase
from experiments_manager.models import ChosenExperimentSteps, Experiment
from git_manager.models import GitRepository
from user_manager.models import W... |
"""
gridback/__init__.py
~~~~~~~~~~~~~~~~~~~~
Initialize Gridback server backend, which schedules API calls to a state's
energy-data provider.
:author: Sean Pianka
:e-mail: <EMAIL>
:github: @seanpianka
"""
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
from flask_sqlalchem... |
import pyaudio
import wave
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file.wav"
def pyaudio_record(RECORD_SECONDS):
audio = pyaudio.PyAudio()
# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
r... |
import os
import unittest
import tempfile
import testing_config
import app
from app.models.users import KBUser
class ThreatKBTestCase(unittest.TestCase):
def setUp(self):
app.app.config.from_object("testing_config")
self.app = app.app.test_client()
with app.app.app_context():
... |
import pygame
from pygame.locals import KEYUP, QUIT, MOUSEBUTTONUP, K_ESCAPE, K_RETURN, K_t
import maps.bar.scene as bar
import maps.test.scene as test
def run(screen, debug=False, **kwargs):
if debug:
print "game.menu.loop started"
font = pygame.font.Font('freesansbold.ttf', 20)
message = font.re... |
# -*- coding: utf-8 -*-
import numpy
import hashlib
import dijitso
import dolfin.cpp as cpp
_cpp_math_builtins = [
# <cmath> functions: from http://www.cplusplus.com/reference/cmath/
"cos", "sin", "tan", "acos", "asin", "atan", "atan2",
"cosh", "sinh", "tanh", "exp", "frexp", "ldexp", "log", "log10", "mod... |
# -*- coding: utf-8 -*-
"""
OnionShare | https://onionshare.org/
Copyright (C) 2015 Micah Lee <<EMAIL>>
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
(at your o... |
from django.contrib.auth.decorators import login_required,\
permission_required
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.db.models import Sum, Avg, Count
from django.conf import settings
from dialer_campaign.f... |
# -*- coding: utf-8 -*-
import re
from ..base.simple_downloader import SimpleDownloader
class EdiskCz(SimpleDownloader):
__name__ = "EdiskCz"
__type__ = "downloader"
__version__ = "0.28"
__status__ = "testing"
__pattern__ = (
r"http://(?:www\.)?edisk\.(cz|sk|eu)/(stahni|sk/stahni|en/down... |
import timeit
import unittest
class TestBasicFunctions(unittest.TestCase):
def test_add_feature_performance(self):
print timeit.timeit(
"rollout.add_feature(Feature('feature_for_all', groups=['ALL']))",
setup='from pyrollout import Rollout; from pyrollout.feature import Feature; ro... |
import time
import os.path
import hashlib
import uuid
from django.db import models
from django.conf import settings
from django.core.files.uploadedfile import UploadedFile
from django.utils import timezone
from .settings import EXPIRATION_DELTA, UPLOAD_PATH, STORAGE, ABSTRACT_MODEL
from .constants import CHUNKED_UPLO... |
from . import VCF
class TagSet(VCF):
''' This class is for a special subset of SNPs within a VCF, namely tSNPs.
It contains methods specific to tag SNPs and doing fun things with them
such as '''
def __init__(self,vcffile,force=False):
raise NotImplementedError()
super().__init_... |
from django.db import models
from django.db.models.expressions import Value
from django.db.models.functions import Cast
from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
from .models import Author
class CastTests(TestCase):
@classmethod
def setUpTestData(self):
Author.objects.cre... |
from netforce.model import Model, fields, get_model
class ProductLocation(Model):
_name = "product.location"
_string = "Product Location"
_fields = {
"product_id": fields.Many2One("product","Product",required=True,on_delete="cascade"),
"sequence": fields.Integer("Sequence",required=True),
... |
"""Provides functions for parsing and outputting Zulu time."""
import datetime
import pytz
from infra_libs.time_functions import timestamp
def parse_zulu_time(string):
"""Parses a Zulu time string, returning None if unparseable."""
# Ugh https://bugs.python.org/issue19475.
zulu_format = "%Y-%m-%dT%H:%M:%S"
... |
#!/usr/bin/python3
import sys
import os
SRC_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SRC_PATH+os.sep+'../common')
import netLog
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
#from PyQt5.QtTextToSpeech import QTextToSpeech
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
from bokeh.util.api import INTERNAL, PUBLIC ; INTERNAL, PUBLIC
from bokeh.util.testing import verify_api ; verify_api
#-----------------------------------------------------------------------------
# Imports
#---... |
"""
This is the maven module which manages jar files downloaded
from maven repository
"""
import os
import shutil
import subprocess
import time
import configparse
import console
def is_valid_id(id):
"""Check if id is valid. """
parts = id.split(':')
if len(parts) == 3:
group, artifact, version... |
# -*- coding: utf-8 -*-
'''
Module for gathering and managing bridging information
'''
from __future__ import absolute_import
import sys
import re
import salt.utils
__func_alias__ = {
'list_': 'list'
}
# Other BSD-like derivatives that use ifconfig may work too
SUPPORTED_BSD_LIKE = ['FreeBSD', 'NetBSD', 'OpenB... |
import math, pyperclip
def main():
myMessage = 'Cenoonommstmme oo snnio. s s c'
myKey = 8
plaintext = decryptMessage(myKey, myMessage)
# Print with a | (called "pipe" character) after it in case
# there are spaces at the end of the decrypted message.
print(plaintext + '|')
pyperclip.copy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.