code stringlengths 1 199k |
|---|
from report_aeroo.ctt_objects import ctt_currency
class trl(ctt_currency):
def _init_currency(self):
self.language = u'tr_TR'
self.code = u'TRL'
self.fractions = 100
self.cur_singular = u' Lira'
# default plural form for currency
self.cur_plural = u' Lira'
sel... |
"""
Gandi driver for compute
"""
import sys
from datetime import datetime
from libcloud.common.gandi import BaseGandiDriver, GandiException,\
NetworkInterface, IPAddress, Disk
from libcloud.compute.base import StorageVolume
from libcloud.compute.types import NodeState, Provider
from libcloud.compute.base import Nod... |
from django.conf.urls.defaults import patterns # noqa
from django.conf.urls.defaults import url # noqa
from openstack_dashboard.dashboards.project.vpn import views
urlpatterns = patterns('openstack_dashboard.dashboards.project.vpn.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^addikepolic... |
import calendar
import time
from email.utils import formatdate, parsedate, parsedate_tz
from datetime import datetime, timedelta
TIME_FMT = "%a, %d %b %Y %H:%M:%S GMT"
def expire_after(delta, date=None):
date = date or datetime.utcnow()
return date + delta
def datetime_to_header(dt):
return formatdate(calen... |
"""Support for MySensors binary sensors."""
from homeassistant.components import mysensors
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES, DOMAIN, BinarySensorDevice)
from homeassistant.const import STATE_ON
SENSORS = {
'S_DOOR': 'door',
'S_MOTION': 'motion',
'S_SMOKE': 'smoke',
... |
"""Functions used by compiler.py to determine the parameters rendered
within INSERT and UPDATE statements.
"""
from .. import util
from .. import exc
from . import dml
from . import elements
import operator
REQUIRED = util.symbol('REQUIRED', """
Placeholder for the value within a :class:`.BindParameter`
which is requir... |
from gen import *
flow_var[0] = """
(declare-fun tau () Real)
(declare-fun x1 () Real)
(declare-fun x2 () Real)
(declare-fun x3 () Real)
"""
flow_dec[0] = """
(define-ode flow_1 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)... |
DOCUMENTATION = """
---
module: lineinfile
author:
- "Daniel Hokka Zakrissoni (@dhozac)"
- "Ahti Kitsik (@ahtik)"
extends_documentation_fragment:
- files
- validate
short_description: Ensure a particular line is in a file, or replace an
existing line using a back-referenced regular ex... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
author: 'Matt Martz (@sivel)'
short_description: 'Deploys a VMware virtual machine from an OVF or OVA... |
"""
.. module: security_monkey.watchers.security_group
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <pkelley@netflix.com> @monkeysecurity
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.constants import TROUBLE_REGIONS
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ["preview"],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_compute_ssl_policy_facts
description:
- Gather facts for ... |
import utils
import os
import shutil
import sys
def go( boost_root ):
OUTPUT = "src/third_party/boost"
if os.path.exists( OUTPUT ):
shutil.rmtree( OUTPUT )
cmd = [ "bcp" , "--scan" , "--boost=%s" % boost_root ]
src = utils.getAllSourceFiles()
cmd += src
cmd.append( OUTPUT )
if not os... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
clean_html,
determine_ext,
js_to_json,
)
class FKTVIE(InfoExtractor):
IE_NAME = 'fernsehkritik.tv'
_VALID_URL = r'http://(?:www\.)?fernsehkritik\.tv/folge-(?P<id>[0-9]+)(?:/.*)?'
_TEST = {
'ur... |
from __future__ import unicode_literals
from django.db import models
from imagekit.models.fields import ProcessedImageField
from imagekit.processors import ResizeToFill
from .utils import unique_filename
class DateTimeModel(models.Model):
class Meta:
abstract = True
modified = models.DateTimeField(auto_... |
from IECore import *
import sys
import unittest
class LensDistortOpTest(unittest.TestCase):
def testDistortOpWithStandardLensModel(self):
# The lens model and parameters to use.
o = CompoundObject()
o["lensModel"] = StringData( "StandardRadialLensModel" )
o["distortion"] = DoubleData( 0.2 )
o["anamorphicSque... |
import os
from migrate import exceptions as versioning_exceptions
from migrate.versioning import api as versioning_api
from migrate.versioning.repository import Repository
import sqlalchemy
from nova.db.sqlalchemy import api as db_session
from nova import exception
from nova.openstack.common.gettextutils import _
INIT_... |
"""Tests for slim.nets.alexnet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib.slim.nets import alexnet
slim = tf.contrib.slim
class AlexnetV2Test(tf.test.TestCase):
def testBuild(self):
batch_size = 5... |
"""Tests frame.inspect() """
import unittest
import sys
import os
from sparktkregtests.lib import sparktk_test
class FrameInspectTest(sparktk_test.SparkTKTestCase):
def setUp(self):
"""Build test frame"""
super(FrameInspectTest, self).setUp()
dataset = self.get_file("movie_user_5ratings.csv"... |
from __future__ import absolute_import
from celery import current_app
from celery.backends.base import BaseDictBackend
from celery.utils.timeutils import maybe_timedelta
from ..models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backend.
Using Django models to store task ... |
from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class PageViewTests(BasePageTests):
def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available onl... |
from __future__ import unicode_literals
import uuid
from django.forms import UUIDField, ValidationError
from django.test import SimpleTestCase
class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_1(self):
field = UUIDField()
value = field.clean('550e8400e29b41d4a716446655440000')
self.ass... |
self.description = "Backup file relocation"
lp1 = pmpkg("bash")
lp1.files = ["etc/profile*"]
lp1.backup = ["etc/profile"]
self.addpkg2db("local", lp1)
p1 = pmpkg("bash", "1.0-2")
self.addpkg(p1)
lp2 = pmpkg("filesystem")
self.addpkg2db("local", lp2)
p2 = pmpkg("filesystem", "1.0-2")
p2.files = ["etc/profile**"]
p2.back... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
"""Database migrations for resource-providers."""
from migrate import UniqueConstraint
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Float
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy impo... |
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 'Law.merged_into'
db.add_column('laws_law', 'merged_into', self.gf('django.db.models.fields.related.ForeignKey')(blank=T... |
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
from powerline.lint.selfcheck import havemarks
class WithPath(object):
def __init__(self, import_paths):
self.import_paths = import_paths
def __enter__(self):
self.oldpath = sys.path
sys.path = self.import_paths + sy... |
from pylab import figure,pcolor,scatter,contour,colorbar,show,subplot,plot,connect
from numpy import array,meshgrid,reshape,linspace,min,max
from numpy import concatenate,transpose,ravel
from modshogun import *
from modshogun import *
from modshogun import *
import util
util.set_title('KernelRidgeRegression')
width=20
... |
from tests.support import unittest2, inPy3k
try:
unicode
except NameError:
# Python 3
unicode = str
long = int
import inspect
from mock import Mock, MagicMock, _magics
class TestMockingMagicMethods(unittest2.TestCase):
def testDeletingMagicMethods(self):
mock = Mock()
self.assertFals... |
from helpers import unittest
import luigi
import namespace_test_helper # declares another Foo in namespace mynamespace
class Foo(luigi.Task):
pass
class FooSubclass(Foo):
pass
class TestNamespacing(unittest.TestCase):
def test_vanilla(self):
self.assertEqual(Foo.task_namespace, None)
self.a... |
from .provider_base import ExternalPaymentProvider
from tapiriik.database import db
from tapiriik.settings import MOTIVATO_PREMIUM_USERS_LIST_URL
import requests
class MotivatoExternalPaymentProvider(ExternalPaymentProvider):
ID = "motivato"
def RefreshPaymentStateForExternalIDs(self, external_ids):
from tapiriik.s... |
"""
Some utility functions to deal with mapping Amazon DynamoDB types to
Python types and vice-versa.
"""
import base64
from decimal import (Decimal, DecimalException, Context,
Clamped, Overflow, Inexact, Underflow, Rounded)
from exceptions import DynamoDBNumberError
DYNAMODB_CONTEXT = Context(
... |
class DB(object):
"""DB is a generic class for SQL Database"""
def __init__(self, table_prefix=''):
self.table_prefix = table_prefix
def stringify(self, val):
"""Get a unicode from a value"""
# If raw string, go in unicode
if isinstance(val, str):
val = val.decode... |
"""Utility classes to write to and read from non-blocking files and sockets.
Contents:
* `BaseIOStream`: Generic interface for reading and writing.
* `IOStream`: Implementation of BaseIOStream using non-blocking sockets.
* `SSLIOStream`: SSL-aware version of IOStream.
* `PipeIOStream`: Pipe-based IOStream implementatio... |
"""
This config file extends the test environment configuration
so that we can run the lettuce acceptance tests.
"""
import os
os.environ['EDXAPP_TEST_MONGO_HOST'] = os.environ.get('EDXAPP_TEST_MONGO_HOST', 'edx.devstack.mongo')
from .acceptance import *
LETTUCE_HOST = os.environ['BOK_CHOY_HOSTNAME']
SITE_NAME = '{}:{}... |
"""
You can run this example like this:
.. code:: console
$ rm -rf '/tmp/bar'
$ luigi --module examples.foo examples.Foo --workers 2 --local-scheduler
"""
from __future__ import print_function
import time
import luigi
class Foo(luigi.WrapperTask):
task_namespace = 'examples'
def run(... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: ios_static_route
version_added: "2.4"
author: "Ricardo Carrillo Cruz (@rcarrillocruz)"
short_description: Manage static IP routes on Cisco IOS network ... |
from twisted.trial import unittest
from twisted.python import lockfile
class LockingTestCase(unittest.TestCase):
def testBasics(self):
lockf = self.mktemp()
lock = lockfile.FilesystemLock(lockf)
self.failUnless(lock.lock())
self.failUnless(lock.clean)
lock.unlock()
se... |
"""
Meteorology visualisation examples
==================================
""" |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: katello
short_description: Manage Katello Resources
deprecat... |
"""
Tests for L{twisted.python.monkey}.
"""
from __future__ import division, absolute_import
from twisted.trial import unittest
from twisted.python.monkey import MonkeyPatcher
class TestObj:
def __init__(self):
self.foo = 'foo value'
self.bar = 'bar value'
self.baz = 'baz value'
class Monkey... |
from pyasn1.type import univ, char, tag
__all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime']
NoValue = univ.NoValue
noValue = univ.noValue
class ObjectDescriptor(char.GraphicString):
__doc__ = char.GraphicString.__doc__
#: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
tagSet... |
import argparse
import cPickle
import os
import mxnet as mx
from ..logger import logger
from ..config import config, default, generate_config
from ..dataset import *
def reeval(args):
# load imdb
imdb = eval(args.dataset)(args.image_set, args.root_path, args.dataset_path)
# load detection results
cache_... |
"""A simple utility for constructing filesystem-like trees from beets
libraries.
"""
from __future__ import division, absolute_import, print_function
from collections import namedtuple
from beets import util
Node = namedtuple('Node', ['files', 'dirs'])
def _insert(node, path, itemid):
"""Insert an item into a virtu... |
from bar import path |
from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_util ... |
self.description = "CleanMethod = KeepCurrent"
sp = pmpkg("dummy", "2.0-1")
self.addpkg2db("sync", sp)
sp = pmpkg("bar", "2.0-1")
self.addpkg2db("sync", sp)
sp = pmpkg("baz", "2.0-1")
self.addpkg2db("sync", sp)
lp = pmpkg("dummy", "1.0-1")
self.addpkg2db("local", lp)
lp = pmpkg("bar", "2.0-1")
self.addpkg2db("local", l... |
from sqlalchemy import Column
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Text
BASE_TABLE_NAME = 'instance_extra'
NEW_COLUMN_NAME = 'pci_requests'
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
for prefix in ('', 'shadow_'):
table = ... |
import numpy as np
import unittest2 as unittest
from nupic.frameworks.opf.metrics import getModule, MetricSpec, MetricMulti
class OPFMetricsTest(unittest.TestCase):
DELTA = 0.01
VERBOSITY = 0
def testRMSE(self):
rmse = getModule(MetricSpec("rmse", None, None,
{"verbosity" : OPFMetricsTest.VERBOSITY}))
gt ... |
"""This is used by run_tests.py to create cpu load on a machine"""
while True:
pass |
from sqlalchemy.dialects.mssql import base, pyodbc, adodbapi, \
pymssql, zxjdbc, mxodbc
base.dialect = pyodbc.dialect
from sqlalchemy.dialects.mssql.base import \
INTEGER, BIGINT, SMALLINT, TINYINT, VARCHAR, NVARCHAR, CHAR, \
NCHAR, TEXT, NTEXT, DECIMAL, NUMERIC, FLOAT, DATETIME,\
DATETIME2, DATETIMEOFF... |
from __future__ import with_statement
from time import sleep
from os.path import exists, join
from shutil import copy
from traceback import print_exc
from utils import chmod
IGNORE = (
"FreakshareNet", "SpeedManager", "ArchiveTo", "ShareCx", ('hooks', 'UnRar'),
'EasyShareCom', 'FlyshareCz'
)
CONF_VERSION = ... |
"""End-to-end benchmark for batch normalization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import time
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import constant_op
from ten... |
import optparse
import os
import re
import sys
import shutil
def DoCopy(path, target_path):
if os.path.isfile(path):
package = ''
package_re = re.compile(
'^package (?P<package>([a-zA-Z0-9_]+.)*[a-zA-Z0-9_]+);$')
for line in open(path).readlines():
match = package_re.match(line)
if mat... |
DOCUMENTATION = '''
---
module: rds
version_added: "1.3"
short_description: create, delete, or modify an Amazon rds instance
description:
- Creates, deletes, or modifies rds instances. When creating an instance it can be either a new instance or a read-only replica of an existing instance. This module has a depen... |
""" cdecl.py - parse c declarations
(c) 2002, 2003, 2004, 2005 Simon Burton <simon@arrowtheory.com>
Released under GNU LGPL license.
version 0.xx
"""
import string
class Node(list):
" A node in a parse tree "
def __init__(self,*items,**kw):
list.__init__( self, items )
self.lock1 = 0 # these two... |
"""
Lexing error finder
~~~~~~~~~~~~~~~~~~~
For the source files given on the command line, display
the text where Error tokens are being generated, along
with some context.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import ... |
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.name |
""" Tests for library reindex command """
import ddt
from django.core.management import call_command, CommandError
import mock
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from common.test.utils ... |
import logging
import unittest
from dogstream.cassandra import parse_cassandra
logger = logging.getLogger(__name__)
class TestCassandraDogstream(unittest.TestCase):
def testStart(self):
events = parse_cassandra(logger, " INFO [main] 2012-12-11 21:46:26,995 StorageService.java (line 687) Bootstrap/Replace/Mo... |
from ordereddict import OrderedDict
from qapi import *
import sys
import os
import getopt
import errno
def generate_visit_struct_body(field_prefix, members):
ret = ""
if len(field_prefix):
field_prefix = field_prefix + "."
for argname, argentry, optional, structured in parse_args(members):
i... |
"""
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeun... |
"""
Simple SSL client, using blocking I/O
"""
from OpenSSL import SSL
import sys, os, select, socket
def verify_cb(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
return ok
if len(sys.argv) < 3:
print 'Usage: python[2] client.py HOST PO... |
class A:
pass
class B(A):
def m(self, x):
"""
Parameters:
x (int): number
"""
return x |
import sys
import uos as os
tests = [
"basics", "micropython", "float", "import", "io",
" misc", "unicode", "extmod", "unix"
]
if sys.platform == 'win32':
MICROPYTHON = "micropython.exe"
else:
MICROPYTHON = "micropython"
def should_skip(test):
if test.startswith("native"):
return True
if... |
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=tester
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0 101
a=rtpmap:0 PCMU/8000
a=sendrecv
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:WnD7c1ksDGs+dIefCEo8omPg4uO8DYIinNGL5yxQ
a=crypto:... |
""" Test the change_enrollment command line script."""
import ddt
import unittest
from uuid import uuid4
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from enrollment.api import get_enrollment
from student.tests.factories import Use... |
"""engine.SCons.Variables.PackageVariable
This file defines the option type for SCons implementing 'package
activation'.
To be used whenever a 'package' may be enabled/disabled and the
package path may be specified.
Usage example:
Examples:
x11=no (disables X11 support)
x11=yes (will search for the pac... |
"""Defines an enum for classifying RPC methods by streaming semantics."""
import enum
@enum.unique
class Cardinality(enum.Enum):
"""Describes the streaming semantics of an RPC method."""
UNARY_UNARY = 'request-unary/response-unary'
UNARY_STREAM = 'request-unary/response-streaming'
STREAM_UNARY = 'request-stream... |
"""Tests for Sample Stats Ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.distributions.python.ops import sample_stats
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_op... |
class MyClass():
@classmethod
def foo_method(cls):
spam = "eggs" |
r"""
LLVM Enumerations
=================
This file defines enumerations from LLVM.
Each enumeration is exposed as a list of 2-tuples. These lists are consumed by
dedicated types elsewhere in the package. The enumerations are centrally
defined in this file so they are easier to locate and maintain.
"""
__all__ = [
'... |
from openerp.osv import fields, osv
class email_template_preview(osv.osv_memory):
_inherit = "email.template"
_name = "email_template.preview"
_description = "Email Template Preview"
def _get_records(self, cr, uid, context=None):
"""
Return Records of particular Email Template's Model
... |
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'PyTips'
copyright = u'2012, Hank Gay'
version = '0.1.0-alpha.1'
release = '0.1.0-alpha.1'
excl... |
from .src import *
def plugin_loaded():
distractionless.plugin_loaded(reload=False)
def plugin_unloaded():
distractionless.plugin_unloaded() |
"""
This version of julian is currently in development and is not considered stable.
""" |
import wx
class SocketFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: SocketFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.button_aquarium = wx.ToggleButton(self, wx.ID_ANY, "Aquarium")
self.button_kitche... |
import logging; logger = logging.getLogger("robots.introspection")
import threading
introspection = None
if False:
try:
import Pyro4
import Pyro4.errors
uri = "PYRONAME:robots.introspection" # uses name server
try:
introspection = Pyro4.Proxy(uri)
introspectio... |
from django.db import models
from django.utils.translation import ugettext as _
from common import models as common_models
from hosts import models as hosts_models
class Project(common_models.TimestampedModel):
name = models.CharField(_('Name'), max_length=254)
description = models.TextField(_('Name'), blank=Tr... |
import unittest
from click.testing import CliRunner
from make_dataset import main
class TestMain(unittest.TestCase):
def test_main_runs(self):
runner = CliRunner()
result = runner.invoke(main, ['.', '.'])
assert result.exit_code == 0 |
'''
Created on: 2015
Author: Mizael Martinez
'''
from pyfann import libfann
from login import Login
from escribirArchivo import EscribirArchivo
import inspect, sys, os
sys.path.append("../model")
from baseDatos import BaseDatos
class CtrlEntrenarRNANormalizado:
def __init__(self):
self.__coneccion=1
self.__tas... |
from threading import Thread
from flask_mail import Message
from flask import render_template, current_app
from . import mail
from .decorators import async
@async
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._ge... |
"""
Useful Utils
==============
"""
from setuptools import setup, find_packages
setup(
name='utilitybelt',
version='0.2.6',
author='Halfmoon Labs',
author_email='hello@halfmoonlabs.com',
description='Generally useful tools. A python utility belt.',
keywords=('dict dictionary scrub to_dict todict... |
import os
import socket
import subprocess
from apnsexceptions import *
from utils import *
class APNSConnectionContext(object):
certificate = None
def __init__(self, certificate = None):
self.certificate = certificate
def connect(self, host, port):
raise APNSNotImplementedMethod, "APNSConnec... |
import re
prefix = 'http://'
with open('top100_alexa.txt','r') as f:
newlines = []
for line in f.readlines():
found=re.sub(r'\d+', '', line)
line=found
newlines.append(line.replace(',', ''))
with open('urls.txt', 'w') as f:
for line in newlines:
#f.write('%s%s%s\n' % (prefix,... |
from flask import Flask
from flask_compress import Compress
from .. import db
app = Flask(__name__)
app.config.from_pyfile('../config.py')
from . import views
Compress(app)
@app.before_first_request
def initialize_database():
db.init_db() |
"""Specialized SipHash-2-4 implementations.
This implements SipHash-2-4 for 256-bit integers.
"""
def rotl64(n, b):
return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b
def siphash_round(v0, v1, v2, v3):
v0 = (v0 + v1) & ((1 << 64) - 1)
v1 = rotl64(v1, 13)
v1 ^= v0
v0 = rotl64(v0, 32)
v2 = (v... |
import os
import platform
import re
import chardet
import argparse
import logging
from subprocess import Popen, PIPE
parser = argparse.ArgumentParser(description='A script for condensing local repository')
parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true')
args = parser.parse_... |
import RPi.GPIO as GPIO
import subprocess
GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.IN)
GPIO.wait_for_edge(3, GPIO.BOTH)
subprocess.call(['shutdown', '-h', 'now'], shell=False) |
import os.path
import pygame.image
import time
import ConfigParser
from helpers import *
from modules import Module
class Animation(Module):
def __init__(self, screen, folder, interval = None, autoplay = True):
super(Animation, self).__init__(screen)
if folder[:-1] != '/':
folder = folder + '/'
self.folder = ... |
import argparse
def parentArgs():
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='''\
Suzanne's pipeline to identify somatic CNVs from single-cell whole-genome sequencing data
=======================================================================================... |
import sys
import os
import pkg_resources
VERSION = 0.5
script_path = os.path.dirname(sys.argv[0])
def resource_path(relative_path):
base_path = getattr(sys, '_MEIPASS', script_path)
full_path = os.path.join(base_path, relative_path)
if os.path.isfile(full_path):
return full_path
else:
r... |
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import operator
import os
import sys
OUT_CPP = "qt/bitcoinstrings.cpp"
EMPTY = ['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
... |
"""
WSGI config for django_mailing project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... |
import sys
import os
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.imgmath',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
pngmath_latex = "/usr/bin/latex"
pngmath_dvipng = "/usr/bin/dvipng"
source_suffix = '.rst'
master_doc = 'index'
project = u'Python 101'
copyright... |
'''
The MIT License (MIT)
Copyright (c) 2014 NTHUOJ team
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, pu... |
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 'Item'
db.create_table('books_item', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RandomPasswordGenerator.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... |
import os;
link = "http://media.blizzard.com/heroes/images/battlegrounds/maps/haunted-mines-v2/underground/6/"
column = 0;
rc_column = 0;
while (rc_column == 0):
row = 0;
rc_column = os.system('wget ' + link + str(column) + '/' + str(row) + '.jpg -O ' + str(1000 + column) + '-' + str(1000 + row) + '.jpg')
rc_row = r... |
import unittest
import graph
class TestGraph(unittest.TestCase):
'''
Unit test for graph.py
'''
def setUp(self):
'''
This method sets up the test graph data
'''
test_graph_data = {'1': [], '2': ['1'], '3': ['1', '4'], '4': [],
'5': ['2', '3'], '... |
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from routes.campapel.home import returnIndex
from tekton import router
from tekton.gae.middleware.redirect impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.