content string |
|---|
#!/usr/bin/python
import os,os.path,sys,pdfkit,requests,re
import getpass
import pynotify
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
#IMPORTANT--Make sure your gmail settings' access to 'less-secure ap... |
# objectHashHolder is a timer-driven thread. One objectHashHolder thread is used
# by each sendDataThread. The sendDataThread uses it whenever it needs to
# advertise an object to peers in an inv message, or advertise a peer to other
# peers in an addr message. Instead of sending them out immediately, it must
# wait a ... |
from org.slf4j import LoggerFactory
from wherehows.common import Constant
from com.ziclix.python.sql import zxJDBC
import sys
class LdapTransform:
_tables = {"ldap_user": {
"columns": "app_id, is_active, user_id, urn, full_name, display_name, title, employee_number, manager_urn, email, department_id, department... |
"""
webuser_config.py - magic constants for webuser module.
"""
# Used by merge_usera_into_userb, contains the list of which SQL tables refer
# to the external key id_user, and what column contains this information.
CFG_WEBUSER_USER_TABLES = (
## The next tables are disabled because they are often too big
## a... |
config = {
"interfaces": {
"google.devtools.cloudtrace.v1.TraceService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
"ini... |
from __future__ import absolute_import, division, print_function
from future.builtins import range
import re
import warnings
import numpy as np
from skbio.util import cardinal_to_ordinal
_whitespace_regex = re.compile(r'\s')
_newline_regex = re.compile(r'\n')
def _decode_qual_to_phred(qual_str, variant=None, phre... |
"""The tests for the mFi switch platform."""
import unittest.mock as mock
import pytest
import homeassistant.components.mfi.switch as mfi
import homeassistant.components.switch as switch_component
from homeassistant.setup import async_setup_component
PLATFORM = mfi
COMPONENT = switch_component
THING = "switch"
GOOD_... |
'''
Created on 28 Jul 2014
@author: Levi Wright
'''
import os
if os.getcwd()[-4:] == "data":
os.chdir("..")
running = True
imported = False
import data
import pygame
import time
class level():
pixelsToGrid = 10
fillGaps = True
originLatLong = ([52, 56, 23.44],[0,4,10.75])
origi... |
from binascii import unhexlify
from ipv8.keyvault.crypto import ECCrypto
from tribler_core.modules.bootstrap import Bootstrap
from tribler_core.tests.tools.base_test import MockObject
from tribler_core.tests.tools.test_as_server import TestAsServer
from tribler_core.utilities.utilities import succeed
class FakeDHT(... |
import dns.exception
import dns.rdata
import dns.tokenizer
class NSAP(dns.rdata.Rdata):
"""NSAP record.
@ivar address: a NASP
@type address: string
@see: RFC 1706"""
__slots__ = ['address']
def __init__(self, rdclass, rdtype, address):
super(NSAP, self).__init__(rdclass, rdtype)
... |
#!/usr/bin/env python
import os
import re
import sys
import pickle
import time
import traceback
import yahoo.search
from yahoo.search.web import WebSearch
APP_ID = 'P5ihFKzV34G69QolFfb3nN7p0rSsYfC9tPGq.IUS.NLWEeJ14SG9Lei0rwFtgwL8cDBrA6Egdw--'
QUERY_MODIFIERS = '-site:txdns.net -site:sitedossier.com -mx -site:dataopedi... |
from behave import given, when, then
from hamcrest.core import assert_that
from hamcrest.core.core.isequal import equal_to
from hamcrest.library.number.ordering_comparison import greater_than, less_than
from hamcrest.library.text.stringcontains import contains_string
from pages.base import Base
from pages.rate_checker... |
import win32ras
stateStrings = {
win32ras.RASCS_OpenPort : "OpenPort",
win32ras.RASCS_PortOpened : "PortOpened",
win32ras.RASCS_ConnectDevice : "ConnectDevice",
win32ras.RASCS_DeviceConnected : "DeviceConnected",
win32ras.RASCS_AllDevicesConnected : "AllDevicesConnected",
win32ras.RASCS_Authentica... |
import account_check_batch_printing
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
t... |
"""Various classes representing distributed values for PS."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import weakref
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import distribution_strategy_... |
import sys
import glob
# Compute the summary information from the files created by
# excheck.py. Run in the build directory where you used the
# excheck.py plugin.
class Function:
def __init__(self, name):
self.name = name
self.location = None
self.callers = []
self.can_throw = Fa... |
import os
import sys
import logging
import logging.handlers
from Singleton import Singleton
class attrdict(dict):
""" Dictionary with attribute like access """
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
class Logging_Manager(Singlet... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# David Art <<EMAIL>>
# Program Arcade Games With Python And Pygame - Build a Platformer
# http://programarcadegames.com
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
WIDTH, HEIGHT = 640, 480
... |
class TestConfigLib(object):
def setup(self):
self.config_path = 'tests/fixture/fqdnblocklist.conf'
def test_current_behavior(self):
from configlib import getConfig
res = getConfig('mongohost', 'defaultvalue', self.config_path)
assert res == 'mongodb'
def test_option_parser... |
import sys
sys.path.append("../if/gen-py")
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
host = "localhost"
port = 9290
from hadoop.api import Jobtracker
from hadoop.api.ttypes import *
#print dir(ThriftTaskPhase)
#exit()
socket = TSocket.T... |
import math
import numpy
def normalise(a):
'''
Normalises a vector
Accepts: a numpy vector
Returns: a numpy vector pointing in the same direction with magnitude 1
'''
a_norm = numpy.linalg.norm(a)
return numpy.array([float(each)/a_norm for each in a])
def rotation_axis_angle(axis, angle)... |
"""
The workflow Project module handles creating Jenkins workflow projects.
You may specify ``workflow`` in the ``project-type`` attribute of
the :ref:`Job` definition.
For now only inline scripts are supported.
Requires the Jenkins :jenkins-wiki:`Workflow Plugin <Workflow+Plugin>`.
In order to use it for job-templat... |
# -*- coding: utf-8 -*-
"""
Simple incremental latex lexer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import codecs
import collections
import re
class Token(collections.namedtuple("Token", "name text")):
"""Stores information about a matched token."""
__slots__ = () # efficiency
def __new__(cls, name=Non... |
import datetime
import functools
import logging
from luigi import six
from luigi import task
from luigi import parameter
from luigi.deprecate_kwarg import deprecate_kwarg # NOQA: removing this breaks code
if six.PY3:
xrange = range
logger = logging.getLogger('luigi-interface')
def common_params(task_instance... |
from openerp.osv import fields
from openerp.osv.orm import TransientModel
class attach_mail_manually(TransientModel):
_name = 'fetchmail.attach.mail.manually'
_columns = {
'folder_id': fields.many2one('fetchmail.server.folder', 'Folder',
readonly=True),
'mail_ids': fie... |
from setuptools import Command
from setuptools.archive_util import unpack_archive
from distutils import log, dir_util
import os, shutil, pkg_resources
class install_egg_info(Command):
"""Install an .egg-info directory for the package"""
description = "Install an .egg-info directory for the package"
user_... |
#!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... |
from golem.interface.command import group, CommandHelper, Argument, command, CommandResult
@group(name="envs", help="Manage environments")
class Environments(object):
name = Argument('name', help="Environment name")
table_headers = ['name', 'supported', 'active', 'performance', 'description']
sort = Ar... |
"""Implementation of platform-specific functionality.
For each function or class described in `tornado.platform.interface`,
the appropriate platform-specific implementation exists in this module.
Most code that needs access to this functionality should do e.g.::
from tornado.platform.auto import set_close_exec
""... |
from numbers import Integral
from .base import TestBase
from ..object import ObjectFile
from ..object import Relocation
from ..object import Section
from ..object import Symbol
class TestObjectFile(TestBase):
def get_object_file(self):
source = self.get_test_binary()
return ObjectFile(filename=sou... |
import sys, unittest, re, os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'src'))
from tempfile import mkdtemp
from shutil import rmtree
from Exscript import Host
from Exscript.FileLogger import FileLogger
from LoggerTest import LoggerTest, FakeJob
class FakeError(Exception):
pass
... |
# 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 'Profile.dashboard_date'
db.add_column('profile_profile', 'dashboard_date', self.gf('django... |
"""
PRE-PROCESSORS
=============================================================================
Preprocessors work on source text before we start doing anything too
complicated.
"""
import re
import markdown
HTML_PLACEHOLDER_PREFIX = markdown.STX+"wzxhzdk:"
HTML_PLACEHOLDER = HTML_PLACEHOLDER_PREFIX + "%d" + markd... |
"""
===================================================================
Decision Tree Regression
===================================================================
A 1D regression with decision tree.
The :ref:`decision trees <tree>` is
used to fit a sine curve with addition noisy observation. As a result, it
learns ... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import copy
import json
import sys
from ansible.compat.tests import unittest
from ansible.module_utils import basic
from units.mock.procenv import swap_stdin_and_argv, swap_stdout
empty_invocation = {u'module_args': {}}
class TestAnsibleModul... |
"""Type-based dispatch for TensorFlow ops.
"Operation dispatchers" can be used to override the behavior for TensorFlow ops
when they are called with otherwise unsupported argument types. In particular,
when an operation is called with arguments that would cause it to raise a
TypeError, it falls back on its registered... |
from gnuradio import gr
from gnuradio import blocks
from gnuradio import digital
from gnuradio import filter
from gnuradio.filter import firdes
from scipy import signal
import math
import bruninga
class fsk_demod(gr.hier_block2):
"""
Tidied up version of the demodulator found in examples/aprs-rx.grc
samp_... |
"""
@author: Bowen
"""
from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, render_to_response
from django.template import RequestContext, loader
from django.core.mail import send_mail
from... |
from django.conf import settings
from django.core.urlresolvers import reverse
from geonode.geoserver.helpers import ogc_server_settings
def geoserver_urls(request):
"""Global values to pass to templates"""
defaults = dict(
GEOSERVER_BASE_URL=ogc_server_settings.public_url,
UPLOADER_URL=reverse... |
"""
Simple class that stores security context information in the web request.
Projects should subclass this class if they wish to enhance the request
context or provide additional information in their specific WSGI pipeline.
"""
import itertools
import uuid
def generate_request_id():
return 'req-' + str(uuid.uu... |
from jc_types import Scope
class VMWriter:
arithmeticOperations = ["add", "sub", "and", "or", "not", "neg", "eq", "gt", "lt"]
scopeTable = { Scope.STATIC : "static",
Scope.FIELD : "dunno?",
Scope.ARG : "argument",
Scope.VAR : "local" }
def __init__... |
from content_index import indexer, cntIndex
from subprocess import Popen, PIPE
import StringIO
import odt2txt
import sys, zipfile, xml.dom.minidom
import logging
_logger = logging.getLogger(__name__)
def _to_unicode(s):
try:
return s.decode('utf-8')
except UnicodeError:
try:
return ... |
from multiprocessing import Pool
"""
A generator function for chopping up a given list into chunks of
length n.
"""
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def MapReduce(Map, Reduce, text):
l = min(len(text),8)
# Fragment the string data into 8 chunks
partitioned_text = list(chunks... |
# coding=utf-8
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
import json
from app.content.models import City,ShoppingAddress
f... |
# $Id$
import inc_sip as sip
import inc_sdp as sdp
pjsua = "--null-audio --id=sip:CLIENT --registrar sip:127.0.0.1:$PORT " + \
"--realm=python --user=username --password=password " + \
"--auto-update-nat=0"
req1 = sip.RecvfromTransaction("Initial request", 401,
include=["REGISTER sip"],
exclude=["Authoriza... |
from openerp.osv import osv, fields
from itertools import groupby
def grouplines(self, ordered_lines, sortkey):
"""Return lines from a specified invoice or sale order grouped by category"""
grouped_lines = []
for key, valuesiter in groupby(ordered_lines, sortkey):
group = {}
group['categor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('uploads', '0001_initial'),
migrat... |
import datetime
import config.general
project_github_username='veltzer'
project_name='demos-linux'
project_website='https://{project_github_username}.github.io/{project_name}'.format(**locals())
project_website_source='https://github.com/{project_github_username}/{project_name}'.format(**locals())
project_website_git=... |
# -*- coding: utf-8 -*-
'''
Covenant Add-on
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 option) any later version.
This prog... |
from odoo import api, models, fields, _
class AccountMove(models.Model):
_inherit = 'account.move'
edi_show_abandon_cancel_button = fields.Boolean(
compute='_compute_edi_show_abandon_cancel_button')
edi_error_message = fields.Html(compute='_compute_edi_error_message')
edi_blocking_level = fie... |
"""Converter construction support.
This module contains a base class for all converters, as well as supporting
structures. These structures are referred to as contexts.
The class hierarchy is as follows:
<your converter>
[extends] converter.Base
[extends] transformer.Base
[extends] gast... |
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas.v3 import reset_server_state
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
from nova.compute import vm_states
from nova import exc... |
/**
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Shrey Malhotra
*
* 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 witho... |
from datetime import datetime
from typing import List, Dict, Union, Any
from ..BaseModel import BaseModel
from .ClusterPrinterStatus import ClusterPrinterStatus
from .ClusterPrintJobStatus import ClusterPrintJobStatus
# Model that represents the status of the cluster for the cloud
class CloudClusterStatus(BaseModel)... |
from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp
FLAGS = gflags.FLAGS
gflags.DEFINE_string('data', 'data/steel_mill/steel_mill_slab.txt',
'path to data file')
gflags.DEFINE_integer('time_limit', 20000, 'global time limit')
#----------------helper for ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
"""
Management command to remove enrollments and any related models created as
a side effect of enrolling students.
Intented for use in integration sandbox environments
"""
import logging
from textwrap import dedent
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
... |
import os
import sys
import tempfile
import operator
import functools
import itertools
import re
import contextlib
import pickle
import textwrap
from setuptools.extern import six
from setuptools.extern.six.moves import builtins, map
import pkg_resources
if sys.platform.startswith('java'):
import org.python.modul... |
ACTIVATE_SCRIPT = """# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
PATH="$_OLD_VIRTUAL_PATH"
export PATH
unset _OLD_VIRTUAL_PATH
fi
# This shoul... |
"""
Internationalization support.
"""
import re
import warnings
from contextlib import ContextDecorator
from decimal import ROUND_UP, Decimal
from django.utils.autoreload import autoreload_started, file_changed
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import lazy
__al... |
from gnuradio import gr
from gnuradio import blocks
from gnuradio import filter
class ssb_demod( gr.hier_block2 ):
def __init__( self, if_rate, af_rate ):
gr.hier_block2.__init__(self, "ssb_demod",
gr.io_signature(1,1,gr.sizeof_gr_complex),
gr... |
import time
from openerp.osv import osv
from openerp.report import report_sxw
class account_inverted_analytic_balance(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_inverted_analytic_balance, self).__init__(cr, uid, name, context=context)
self.localcontext.update( ... |
from mock import patch
from StringIO import StringIO
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import encode_multipart, BOUNDARY, MULTIPART_CONTENT
from rest_framework.reverse import reverse as rest_framework_reverse
from pypln.web.core.models imp... |
from __future__ import absolute_import
import base64
import hashlib
import imp
import os
import re
import shlex
import traceback
import urlparse
from ansible import errors
from ansible import utils
from ansible.callbacks import vvv, vvvv, verbose
from ansible.runner.shell_plugins import powershell
try:
from winrm... |
from __future__ import with_statement
import os.path
import sys
from warnings import warn
import java.lang.reflect.Array
__all__ = ['add_history', 'clear_history', 'get_begidx', 'get_completer',
'get_completer_delims', 'get_current_history_length',
'get_endidx', 'get_history_item', 'get_history_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import special
from scipy import stats
from tensorflow.contrib.distributions.python.ops import gamma as gamma_lib
from tensorflow.python.client import session
from tensorflow.pyth... |
from __future__ import absolute_import, division, print_function
from invenio_records.models import RecordMetadata
from inspirehep.modules.migrator.models import InspireProdRecords
def test_all_records_were_loaded(app):
records = [record.json for record in RecordMetadata.query.all()]
expected = 42
resu... |
# -*- encoding: utf-8 -*-
import unittest2
from openerp.tests.common import TransactionCase
from .. import models
ID_FIELD = {'id': 'id', 'name': 'id', 'string': "External ID", 'required': False, 'fields': []}
def make_field(name='value', string='unknown', required=False, fields=[]):
return [
ID_FIELD,
... |
import json
from httpretty import HTTPretty
from social.exceptions import AuthFailed
from social.tests.backends.oauth import OAuth2Test
class GithubOAuth2Test(OAuth2Test):
backend_path = 'social.backends.github.GithubOAuth2'
user_data_url = 'https://api.github.com/user'
expected_username = 'foobar'
... |
# coding=utf-8
import datetime
import re
from xml.sax.saxutils import quoteattr
from markupsafe import Markup, escape_silent
from ._compat import to_unicode, iteritems
class FakeMultiDict(dict):
"""Adds a fake `getlist` method to a regular dict; or acts as a proxy to
Webob's MultiDict `getall` method.
"... |
from __future__ import division, unicode_literals
from six.moves import zip
import itertools
import numpy as np
import math
from . import coord_utils_cython as cuc
"""
Utilities for manipulating coordinates or list of coordinates, under periodic
boundary conditions or otherwise. Many of these are heavily vectorized i... |
#!/opt/local/bin/python3.4
# Loads some common capacitor and resistor values and then exhaustively searches the space of possible combinations to find a good combination.
import re,sys,math,blist
from blist import sortedset
def convertToValue(x) :
y = x.strip()
if y.endswith("pF") :
return float(y.replace... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Functionality for resolving ASCII printable strings within
the debuggee's address space.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import string
import gdb
... |
import ncbi_toolkit
class blaster(object):
def __init__(self, query, **kw):
# program type must be passed to the constructor to ensure correct
# default settings for all other options
program = kw.pop('Program', ncbi_toolkit.EProgram.eBlastn)
self.query = query
self.blast_... |
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from commander.deploy import hostgroups, task
import commander_settings as settings
_src_dir = lambda *p: os.path.join(settings.SRC_DIR, *p)
VIRTUALENV = os.path.join(os.path.dirname(settings.SRC_DIR), 'venv')
@task
def create_virtu... |
from django import template
from django.core.cache import cache
from django.template import Node, TemplateSyntaxError, Variable
from django.template import resolve_variable
register = template.Library()
class CacheNode(Node):
def __init__(self, nodelist, expire_time, key):
self.nodelist = nodelist
... |
"""
homeassistant.components.thermostat.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform that offers a fake thermostat.
"""
from homeassistant.components.thermostat import ThermostatDevice
from homeassistant.const import TEMP_CELCIUS, TEMP_FAHRENHEIT
def setup_platform(hass, config, add_devices, discovery... |
"""Tests for plotting utilities."""
import warnings
import tempfile
import shutil
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nose
import nose.tools as nt
from nose.tools import assert_equal, raises
import numpy.testing as npt
import pandas.util.testing as pdt
from distutils.version ... |
import copy
import os
from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QUrl
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QWidget, QAbstractItemView, QMenu, QWidgetAction, QLabel
from mdt.gui.maps_visualizer.actions import SetDimension, SetSliceIndex, SetVolumeIndex, SetColormap, SetRotate, \
... |
import sys
import numpy as np
if sys.version > '3':
xrange = range
basestring = str
from pyspark import SparkContext, since
from pyspark.mllib.common import callMLlibFunc, inherit_doc
from pyspark.mllib.linalg import Vectors, SparseVector, _convert_to_vector
from pyspark.sql import DataFrame
class MLUtils(o... |
"""Test cases for XLA devices."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.o... |
from __future__ import with_statement
from cms.api import create_page, add_plugin
from cms.models.pluginmodel import CMSPlugin
from cms.plugins.text.models import Text
from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PLUGIN_ADD,
URL_CMS_PLUGIN_EDIT, URL_CMS_PLUGIN_REMOVE)
from django.conf import settings... |
"""Tests of grpc.beta._connectivity_channel."""
import unittest
from grpc.beta import interfaces
class ConnectivityStatesTest(unittest.TestCase):
def testBetaConnectivityStates(self):
self.assertIsNotNone(interfaces.ChannelConnectivity.IDLE)
self.assertIsNotNone(interfaces.ChannelConnectivity.CONNECTING)... |
import os
import sys
from django.db.backends import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'mysql'
def runshell(self):
settings_dict = self.connection.settings_dict
args = [self.executable_name]
db = settings_dict['OPTIONS'].get('db', settings_d... |
from default import Test, db
from nose.tools import assert_raises
from factories import UserFactory
from pybossa.repositories import UserRepository
from pybossa.exc import WrongObjectError, DBIntegrityError
class TestUserRepository(Test):
def setUp(self):
super(TestUserRepository, self).setUp()
... |
from .charsetgroupprober import CharSetGroupProber
from .sbcharsetprober import SingleByteCharSetProber
from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel,
Latin5CyrillicModel, MacCyrillicModel,
Ibm866Model, Ibm855Model)
from .langgreekmodel ... |
"Thread-safe in-memory cache backend."
import time
from contextlib import contextmanager
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.utils.synch import RWLock
try:
from django.utils.six.moves import cPickle as pickle
except ImportError:
import pickle
# Global in-memor... |
#!/usr/bin/env python
"""
# OpenWRT download directory cleanup utility.
# Delete all but the very last version of the program tarballs.
#
# Copyright (c) 2010 Michael Buesch <<EMAIL>>
"""
import sys
import os
import re
import getopt
# Commandline options
opt_dryrun = False
def parseVer_1234(match, filepath):
progn... |
import sys
from optparse import make_option
from django.core.management import get_commands, load_command_class
from django.utils.translation import activate as activate_language
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
try:
from haystack.management.comman... |
#!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_cg_stc_eng_stc
@file marine-integrations/mi/dataset/parser/test/test_cg_stc_eng_stc.py
@author Mike Nicoletti
@brief Test code for a Cg_stc_eng_stc data parser
"""
import os
import re
import ntplib
from nose.plugins.attrib import attr
from mi.core.except... |
from __future__ import print_function
import argparse
import os, sys
import random
import pexpect
import subprocess
import time
import types
DEFAULT_TIMEOUT = 5
class Strategy(object):
def __init__(self, func=None):
if func != None:
if sys.version_info < (3,):
self.__class__.ex... |
from zope.interface import implements
from twisted.python.components import backwardsCompatImplements
from twisted.trial.itrial import IReporter
from twisted.plugin import IPlugin
class _Reporter(object):
implements(IPlugin, IReporter)
def __init__(self, name, module, description, longOpt, shortOpt, klass):
... |
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.db import connection
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.manager import Manager
f... |
from webob import exc
from nova.api.openstack.compute.plugins.v3 import agents
from nova import context
from nova import db
from nova.db.sqlalchemy import models
from nova import exception
from nova import test
fake_agents_list = [{'hypervisor': 'kvm', 'os': 'win',
'architecture': 'x86',
... |
"""
This extension makes it easy to edit documentation on github.
It adds links associated with each docstring that go to the
corresponding view source page on Github. From there, the user can
push the "Edit" button, edit the docstring, and submit a pull request.
It has the following configuration options (to be set... |
from __future__ import absolute_import, division, print_function
import os
from os import path
import glob
import shutil
import tempfile
from dynd import nd, ndt
from .. import array
def load_json_file_array(root, array_name):
# Load the datashape
dsfile = root + '.datashape'
if not path.isfile(dsfile)... |
from django.conf import settings
try:
from PIL import Image
dir(Image) # Placate PyFlakes
except ImportError:
import Image
AVATAR_DEFAULT_SIZE = getattr(settings, 'AVATAR_DEFAULT_SIZE', 80)
AUTO_GENERATE_AVATAR_SIZES = getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (AVATAR_DEFAULT_SIZE,))
AVATAR_RESIZE_M... |
#!/usr/bin/env python
#----------------------------------------------------------
# odoo cli
#
# To install your odoo development environement type:
#
# wget -O- https://raw.githubusercontent.com/odoo/odoo/8.0/odoo.py | python
#
# The setup_* subcommands used to boostrap odoo are defined here inline and may
# only depe... |
"""An object to represent warc records, using the abstract record in
record.py"""
import re
import hashlib
from hanzo.warctools.record import ArchiveRecord, ArchiveParser
from hanzo.warctools.archive_detect import register_record_type
import uuid
bad_lines = 5 # when to give up looking for the version stamp
@Archiv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.