content stringlengths 4 20k |
|---|
"""Script for testing ganeti.impexpd"""
import os
import sys
import re
import unittest
import socket
from ganeti import constants
from ganeti import objects
from ganeti import compat
from ganeti import utils
from ganeti import errors
from ganeti import impexpd
import testutils
class CmdBuilderConfig(objects.Config... |
#!/usr/bin/env python
import org
import odslib
import time
import wodson_pb2
from google.protobuf import json_format
from google.protobuf import timestamp_pb2
def content_type_binary():
return 'application/x-wodson-protobuf'
def content_type_json():
return 'application/x-wodson-protobuf-json'
def o2p_ag... |
from __future__ import unicode_literals
import frappe, sys
import erpnext
import frappe.utils
from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts, projects, fixed_asset
from erpnext.demo.user import education as edu
from erpnext.demo.setup import education, manufacture, setup_data, health... |
{
"name" : "Pexego - Account Admin Tools",
"version" : "1.0",
"author" : "Pexego",
"website" : "http://www.pexego.es",
"category" : "Enterprise Specific Modules",
"description": """Account Tools for Administrators
Import tools:
- Import accounts from CSV files. This may... |
import os
import sys
import tempfile
import mock
import json
from libcloud.storage.drivers.backblaze_b2 import BackblazeB2StorageDriver
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import b
from libcloud.utils.files import exhaust_iterator
from libcloud.test import unittest
from libcloud.test import... |
import os
import re
from django.core.management.base import BaseCommand
from poetry.apps.corpus.models import Poem, Markup, MarkupVersion
from poetry.settings import BASE_DIR
class Command(BaseCommand):
def handle(self, *args, **options):
poems = Poem.objects.all()
directory = os.path.join(BASE_D... |
# -*- coding: utf-8 -*-
"""
equip.analysis.dfg
~~~~~~~~~~~~~~~~~~~
Builds a dataflow graph.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
from .graph import DiGraph, Edge, Node, Walker, EdgeVisitor
from ..bytecode.decl import MethodDeclaration
... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... |
import tensorflow as tf
import numpy as np
import os
from utils import debug_print
from scipy.misc import imread, imresize
NUM_CLASSES = 37
def _conv2d(input_data, k_h, k_w, c_o, s_h, s_w, name, relu=True, padding="SAME"):
c_i = input_data.get_shape()[-1].value
convolve = lambda i, k: tf.nn.conv2d(i, k, [1,... |
# -*- coding: utf-8 -*-
"""Tests for Apple System Log (ASL) files."""
import unittest
from dtformats import asl
from tests import test_lib
class AppleSystemLogFileTest(test_lib.BaseTestCase):
"""Apple System Log (.asl) file tests."""
# pylint: disable=protected-access
def testFormatIntegerAsFlags(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:author: Josh Moore, josh at glencoesoftware.com
OMERO Grid node controller
This is a python wrapper around icegridnode.
Copyright 2008, 2016 Glencoe Software, Inc. All Rights Reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
from omero.cl... |
from PySide import QtCore, QtGui
import os
import models
import dialogs
import osutil
import widgets
import dal
import dal.query
class Sink4(QtCore.QObject):
def __init__(self, parent = None):
super(Sink4, self).__init__(parent)
self.form = parent
def add_new_modifier(self):
... |
# tests for things that are not implemented, or have non-compliant behaviour
try:
import array
import ustruct
except ImportError:
print("SKIP")
raise SystemExit
# when super can't find self
try:
exec('def f(): super()')
except SyntaxError:
print('SyntaxError')
# store to exception attribute i... |
from unittest.mock import patch
import pytest
from szurubooru import api, db, errors, model
from szurubooru.func import snapshots, tag_categories, tags
def _update_category_name(category, name):
category.name = name
@pytest.fixture(autouse=True)
def inject_config(config_injector):
config_injector(
... |
from io import StringIO
import pytest
from doit.cmd_resetdep import ResetDep
from doit.dependency import TimestampChecker, get_md5, get_file_md5
from doit.exceptions import InvalidCommand
from doit.task import Task
from tests.conftest import tasks_sample, CmdFactory, get_abspath
class TestCmdResetDep(object):
... |
#!/usr/bin/env python
''' Example of a mass lookup using the AddressToDistrictService
Be sure to set GMAPS_API_KEY and PATH_TO_CDFILES appropriately:
GMAPS_API_KEY: Google Maps key (http://www.google.com/apis/maps/signup.html)
PATH_TO_CDFILES: copy of cd99 (http://www.census.gov/geo/www/cob/cd110.html)
'''
... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Sta... |
import numpy as np
from ...utils import verbose
from ._utils import _fetch_one, _data_path, _on_missing, AGE_SLEEP_RECORDS
from ._utils import _check_subjects
data_path = _data_path # expose _data_path(..) as data_path(..)
BASE_URL = 'https://physionet.org/physiobank/database/sleep-edfx/sleep-cassette/' # noqa: E5... |
from som.interp_type import is_ast_interpreter
from som.vmobjects.abstract_object import AbstractObject
class _AbstractPrimitive(AbstractObject):
_immutable_fields_ = ["_is_empty", "_signature", "_holder"]
def __init__(self, signature_string, universe, is_empty=False):
AbstractObject.__init__(self)
... |
import unittest
import os
from test.aiml_tests.client import TestClient
from programy.config import BrainFileConfiguration
class LearnTestClient(TestClient):
def __init__(self):
TestClient.__init__(self, debug=True)
def load_configuration(self, arguments):
super(LearnTestClient, self).load_co... |
"""
Game-level constructs
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import math
from collections import OrderedDict
from collections import namedtuple
import pygame
from pygame import locals as consts
from pong.geometry import Corners
from pong.g... |
import json
import uuid
from oauth.oauth import (
OAuthToken, OAuthRequest, OAuthConsumer, OAuthSignatureMethod_HMAC_SHA1)
from twisted.python import log
from twisted.web import resource, client, server
class Callback(resource.Resource):
"""
Handles a callback requests from Twitter's OAuth endpoint.
... |
import argparse
import collections
import json
import logging
import os
import sys
import zipfile
_BASE_CHART = {
'format_version': '0.1',
'benchmark_name': 'apk_size',
'benchmark_description': 'APK size information.',
'trace_rerun_options': [],
'charts': {}
}
# TODO(rnephew): Add support for spl... |
import pytest
from unittest import mock
from tornado import testing
from tests.server.api.v1.utils import ServerTestCase
from waterbutler.server.utils import CORsMixin
class MockHandler(CORsMixin):
request = None
headers = {}
def set_header(self, key, value):
self.headers[key] = value
class M... |
from numpy import tanh, fabs, mean, ones,loadtxt,fromfile
import sys
import math
from PIL import Image
from matplotlib.pyplot import hist, title, subplot
import matplotlib.pyplot as plot
def sigmoid(xx):
return .5 * (1 + tanh(xx / 2.))
def from_file(path):
return loadtxt(path,delimiter=',')
def hist_mat... |
from ADSOrcid.models import AuthorInfo, ChangeLog
from copy import deepcopy
from .exceptions import IgnorableException
"""
Tools for enhancing our knowledge about orcid ids (authors).
"""
def build_short_forms(orig_name):
orig_name = cleanup_name(orig_name)
if ',' not in orig_name:
ret... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "default-src 'self' ab... |
import os,sys,random
import networkx as nx
import pylab as plt
import math
graph_combinations = [(0,3),(0,4),(1,3),(1,4),(2,5),(0,5),(1,5),(2,3),(2,4)]
graph_combinations_self = [(0,0),(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8)]
def getMetricString(metric,g1,g2):
return metric+"\n"+str(g1.graph['title'][4:])... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'network'}
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import get_capabilities, nxos_argument_spec
from ansible.m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Helper script for making sure that the configuration of the logger works. Called by test-logger.sh
Checks the output from logger_test_messages.py for formatting. First arg is level: simple, raw, or rich
"""
import codecs
import sys
import re
LEVEL = ['raw', 'simple', '... |
import _plotly_utils.basevalidators
class CarpetValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="carpet", parent_name="", **kwargs):
super(CarpetValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from config import USER_AVATAR_DIRECTORY
from hashlib import md5
from util import connect_db, dump_response_and_exit, forbidden
from MySQLdb import Error
import Cookie
import cgi
import os
import sys
if 'HTTP_COOKIE' not in os.environ:
forbidden()
cookie_string = os.env... |
#Test the difference on a 2d array
from numpy import *
from scipy import sparse, linalg
from ABCSolver.mathlink import timer
from ABCSolver.difflounge import finitedifference, linesparse, boundary
from ABCSolver.difflounge.finitedifference import *
from ABCSolver.difflounge.boundary import *
from ABCSolver.diffloung... |
from boto.dynamodb2.items import Item
class Context(object):
def __init__(self):
self.__batch_data = {}
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return False
# Flush anything that's left.
if s... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import imp
import pytest
import zipfile
from collections import namedtuple
from functools import partial
from io import BytesIO, StringIO
import ansible.errors
from ansible.executor.module_common import recursive_finder
from ans... |
import sqlalchemy as sa
from common import databases as db
class Session(db.CustBase):
__tablename__ = 'session'
id = sa.Column(sa.Integer, primary_key=True)
visitor_id = sa.Column(sa.String(36), index=True)
session_id = sa.Column(sa.Integer, index=True)
page_view_count = sa.Column(sa.Integer)
... |
import json
import logging
import pickle
import random
import string
import sys
import redis
__all__ = [
'Client',
'Server',
'RemoteException',
'TimeoutException'
]
if sys.version_info < (3,):
range = xrange
def random_string(size=8, chars=string.ascii_uppercase + string.digits):
"""Ref: ht... |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from compat import url
from organizations import views
urlpatterns = [
# Organization URLs
url(r'^$', view=login_required(views.OrganizationList.as_view()),
name="organization_list"),
url(r'^switch/$', view=views.s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bottle
import inspect
import beaker
from beaker import middleware
class BeakerPlugin(object):
name = 'beaker'
def __init__(self, keyword='beaker'):
"""
:param keyword: Keyword used to inject beaker in a route
"""
self.keywor... |
import unittest2
import time
import datetime
import random
import logging
from consts.event_type import EventType
from helpers.event_helper import EventHelper, REGIONAL_EVENTS_LABEL, CHAMPIONSHIP_EVENTS_LABEL,\
WEEKLESS_EVENTS_LABEL, OFFSEASON_EVENTS_LABEL, PRESEASON_EVENTS_LABEL
from models.event import Event
c... |
import os
import numpy as np
from .generate_dm_testing_files import dm3_data_types
from nose.tools import assert_equal
from hyperspy.io import load
my_path = os.path.dirname(__file__)
# When running the loading test the data of the files that passes it are
# stored in the following dict.
# TODO: fixtures should be ... |
"""
Implement a manager for ebtables rules.
NOTE: The ebtables manager contains a lot of duplicated or very similar code
from the iptables manager. An option would have been to refactor the
iptables manager so that ebtables and iptables manager can share common
code. However, the iptables manager was... |
# -*- coding: utf-8 -*-
__author__ = 'Taras Lyapun'
__email__ = '<EMAIL>'
__version__ = '0.1.3'
import os
import subprocess
import tempfile
from io import open
from webassets.filter import Filter
from webassets.exceptions import FilterError
class BabelFilter(Filter):
"""Turn ES6+ code into ES5 friendly code us... |
__author__ = 'Michel Llorens'
__email__ = "<EMAIL>"
from gfx import *
import codecs
import time
class Screen:
def __init__(self):
self.read_ascii_art("resources/ascii_images/full.txt")
self.width = 44
self.height = 30
self.xPos = 0
self.yPos = 0
self.window = Ventan... |
from xml.dom.minidom import parse
import matplotlib.pyplot as plt
def getCorner(xmlParse, cornerName):
corner = xmlParse.getElementsByTagName(cornerName)[0]
cornerCoord = []
cornerCoord.append(float(corner.getAttribute('x')))
cornerCoord.append(float(corner.getAttribute('y')))
return cornerCoord
... |
"""Miscellaneous functions for dealing with sequences."""
import sys
# Add path to Bio
sys.path.append('../..')
from __future__ import print_function
import re
from math import pi, sin, cos
from Bio.Seq import Seq, MutableSeq
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Data import IUPACData
__... |
from prometheus_client import start_http_server, Gauge, Counter
from subprocess import call, Popen, PIPE, STDOUT
import random
import datetime
import time
import sys
import json
import os
import signal
# cd to the scripts location
os.chdir(os.path.dirname(sys.argv[0]))
# globals
ELASTIC_URL = 'http://localhost:9200'
... |
# -*- coding: utf-8 -*-
"""
BibTeX Test
~~~~~~~~~~~
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import textwrap
import unittest
from pygments.lexers import BibTeXLexer, BSTLexer
from pygments.token import Token
class BibTeXTest(unit... |
import pytest
from six.moves import reload_module
from mpi4py import MPI
from spectralDNS import config, get_solver, solve
from TG import initialize, regression_test
comm = MPI.COMM_WORLD
if comm.Get_size() >= 4:
params = ('NS/uniform/slab', 'VV/uniform/slab',
'NS/nonuniform/slab', 'VV/nonuniform/sl... |
#!/usr/bin/env python
########################################
#Globale Karte fuer tests
# from Rabea Amther
########################################
# http://gfesuite.noaa.gov/developer/netCDFPythonInterface.html
import math
import numpy as np
import pylab as pl
import Scientific.IO.NetCDF as IO
import matplotlib as ... |
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in divide_ii_2i"""
def testScaBasicBehavior(self):
####################################################################... |
__author__ = "Andrea Rizzo, Matteo Bruni"
__copyright__ = "Copyright 2014, Dining Engineers"
__license__ = "GPLv2"
import cv2
import numpy as np
import utils
from const import *
def compute_background_running_average(frame, average, alpha, holes_frame):
"""
Calculate background using running average techniq... |
from __future__ import with_statement
import logging
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config... |
#!/usr/bin/env python
__author__ = "Devin Kelly"
import json
import unittest
from note import Note_Server
class Note_Server_Test(unittest.TestCase):
def setUp(self):
self.note_server = Note_Server('noteTest')
note_1 = {"note": "note 1",
"tags": ["t1", "t2"]}
note_2 = ... |
################################################################################
### Copyright © 2012-2013 BlackDragonHunt
###
### This file is part of the Super Duper Script Editor.
###
### The Super Duper Script Editor is free software: you can redistribute it
### and/or modify it under the terms of the GNU Genera... |
import sys
import traceback
from callbacks import Compress, Decompress
from org.apache.nifi.processor import Processor
from org.apache.nifi.processor import Relationship
from org.apache.nifi.components import PropertyDescriptor
class CompressFlowFile(Processor) :
__rel_success = Relationship.Builder().description(... |
# -*- coding: utf-8 -*-
from module.plugins.internal.misc import json
from module.plugins.internal.MultiHoster import MultiHoster
class MyfastfileCom(MultiHoster):
__name__ = "MyfastfileCom"
__type__ = "hoster"
__version__ = "0.14"
__status__ = "testing"
__pattern__ = r'http://\d{1,3}\.\d{1,3}\... |
"""
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 program is distributed in the hope that it will be useful,
but WITHOUT ... |
from muranoclient.common import base
class Session(base.Resource):
def __repr__(self):
return '<Session %s>' % self._info
def data(self, **kwargs):
return self.manager.data(self, **kwargs)
class SessionManager(base.Manager):
resource_class = Session
def get(self, environment_id, se... |
# University of Montreal (2012)
# RNN-RBM deep learning tutorial
# More information at http://deeplearning.net/tutorial/rnnrbm.html
from __future__ import print_function
import glob
import os
from constants import *
import sys
import numpy
try:
import pylab
except ImportError:
print ("pylab isn't available... |
from __future__ import print_function, division, unicode_literals
import argparse
from lpdec.cli import code, browse
def script():
import locale
locale.resetlocale()
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--database', metavar='DB', help='database connection string')
parser.a... |
"""'Platform" support for a Python virtualenv."""
import os
import sys
import SCons.Util
virtualenv_enabled_by_default = False
def _enable_virtualenv_default():
return SCons.Util.get_os_env_bool('SCONS_ENABLE_VIRTUALENV', virtualenv_enabled_by_default)
def _ignore_virtualenv_default():
return SCons.Util.... |
import sys
import dbus
import dbus.service
import dbus.mainloop.glib
import logging
import signal
import time
import gobject
busaddress1='tcp:host=192.168.1.181,port=1234'
busaddress2='tcp:host=192.168.1.180,port=1234'
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus1 = dbus.bus.BusConnection(busaddress1)
bu... |
"""
Python wrapper for Dynamic Topic Models (DTM) and the Document Influence Model (DIM) [1].
This module allows for DTM and DIM model estimation from a training corpus.
Example:
>>> model = gensim.models.wrappers.DtmModel('dtm-win64.exe', my_corpus, my_timeslices, num_topics=20, id2word=dictionary)
.. [1] https:/... |
""" Python 'utf-16' Codec
Written by Marc-Andre Lemburg (<EMAIL>).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs, sys
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is ... |
from django.forms import (
CharField, HiddenInput, PasswordInput, Textarea, TextInput,
ValidationError,
)
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_charfield_1(self):
f = CharField()
... |
from multiprocessing import cpu_count, Pool
import matplotlib.pyplot as plt
import numpy as np
import requests
from wfdb.io.annotation import rdann
from wfdb.io.download import get_record_list
from wfdb.io.record import rdsamp
class Comparitor(object):
"""
The class to implement and hold comparisons between... |
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestManager, TestInstance
from test_framework.mininode import *
from test_framework.blocktools import *
import logging
import copy
import time
import numbers
from test_framework.key im... |
####################################################################
# Second step in the order process: Capture the billing method and shipping type
#####################################################################
from django import http
from django.conf import settings
from django.shortcuts import render_to_res... |
"""Utilities used by insteon component."""
import asyncio
import logging
from pyinsteon import devices
from pyinsteon.address import Address
from pyinsteon.constants import ALDBStatus
from pyinsteon.events import OFF_EVENT, OFF_FAST_EVENT, ON_EVENT, ON_FAST_EVENT
from pyinsteon.managers.link_manager import (
async... |
# Smoke-tests a x-pack release candidate
#
# 1. Downloads the zip file from the staging URL
# 3. Installs x-pack plugin
# 4. Starts one node for zip package and checks:
# -- if x-pack plugin is loaded
# -- checks xpack info page, if response returns correct version and feature set info
#
# USAGE:
#
# python3 -B .... |
#!/usr/bin/env python
# Built-in
import os
import argparse
# Common
import numpy as np
# tofu_west
from WEST_PFC_BumperInner_Notes import make_Poly as InBump
#from tofu_west.VesStruct.Inputs.WEST_Struct_VDE_Notes import make_Poly as VDE
from WEST_PFC_Ripple_Notes import make_Poly as Ripple
from WEST_PFC_DivLowGC_Not... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : create_lookup_value
Description : Create new lookup values
Date : 02/January/2016
copyright : (C) 2015 by UN-Habitat and implementing partners.
... |
# -*- coding: cp936 -*-
from coinkit.keypair import BitcoinKeypair
import threading
class vb4(BitcoinKeypair):
# _pubkeyhash_version_byte=10
def __init__(self,pubkey_byte):
BitcoinKeypair._pubkeyhash_version_byte = pubkey_byte
BitcoinKeypair.__init__(self)
class finder(threading.Thread):
... |
# -*- coding: utf-8 -*-
"""Package tests."""
#
# (C) Pywikibot team, 2007-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id$'
import os
import sys
import warnings
__all__ = ('requests', '_cache_dir', 'TestRequest',
'patch_request', 'unpa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Program Information
#
__author__ = "Florian Breit"
__contact__ = "Florian Breit <<EMAIL>>"
__copyright__ = "(c) 2012-2015 Florian Breit"
__license__ = "GNU General Public License, Version 3"
__date__ = "16 Dec 2015"
__version__ = "2.0.0"
__title__ = "IPAtype"
#
# IPA ... |
"""
Predictions widget
"""
from collections import OrderedDict, namedtuple
import numpy
from PyQt4 import QtCore, QtGui
import Orange
from Orange.base import Model
from Orange.data import ContinuousVariable, DiscreteVariable
from Orange.widgets import widget, gui
from Orange.widgets.settings import Setting
# Inpu... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 14:54:21 2014
@author: jmmauricio-s
"""
def part(part_title):
'''
Generates a part in RestructuredText
Parameters
----------
part_title : string
Name of the part.
Returns
-------
rst_str : string ... |
from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
from flask_rest_jsonapi.exceptions import ObjectNotFound
from sqlalchemy.orm.exc import NoResultFound
from commandment.mdm.schema import CommandSchema
from commandment.models import db, Command, Device
class CommandsList(ResourceList):... |
from random import randint
def get_comp(design, num):
try:
c = [x for x in design.complist if x.num == num][0]
except:
c = Component(design)
c.num = num
return c
class Component:
def __init__(self, design):
design.complist.append(self)
self.design = design
self.name = ""
self.num = 0
self.pins_in ... |
import types
import simplejson
from decimal import *
import datetime
json_parse = lambda s: simplejson.loads(s.decode("utf-8"))
class DateTimeAwareJSONEncoder(simplejson.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time types
"""
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT =... |
"""
Tests for database migrations. This test case reads the configuration
file test_migrations.conf for database connection settings
to use in the tests. For each connection found in the config file,
the test case runs a series of test cases to ensure that migrations work
properly both upgrading and downgrading, and th... |
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.views import defaults as default_views
from chronoju... |
#!/usr/bin/env python
# coding:utf-8
"""
Copyright (c) 2016-2017 LandGrey (https://github.com/LandGrey/pydictor)
License: GNU GENERAL PUBLIC LICENSE Version 3
"""
from __future__ import unicode_literals
import os
import time
import string
from lib.fun.fun import cool
from collections import Counter
from lib.fun.decora... |
from tempest.api.network import base
from tempest.common.utils.data_utils import rand_name
from tempest.test import attr
class LoadBalancerJSON(base.BaseNetworkTest):
_interface = 'json'
"""
Tests the following operations in the Neutron API using the REST client for
Neutron:
create vIP, and ... |
# setup.py, config file for distutils
#
# To install this package, execute
#
# python setup.py install
#
# in this directory. To upload the latest version to the python
# repository run
#
# python setup.py sdist --formats gztar,zip upload
#
# The initial version of this file was provided by
# Andrew MacIntyre <<EM... |
"""
This module contains definitions useful for the testing of template
resource extraction.
"""
import collections
import logging
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger("test_resources")
# TestInput is a data structure representing the data to be used as input for
# tests. Its fi... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
import gitlab
HAS_GITLAB_PACKAGE = True
except:
HAS_GITLAB_PACKAGE = False
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.basic import... |
from openstack import resource
# NOTE: The VPN service is unmaintained, need to consider remove it
class VPNService(resource.Resource):
resource_key = 'vpnservice'
resources_key = 'vpnservices'
base_path = '/vpn/vpnservices'
# capabilities
allow_create = True
allow_fetch = True
allow_com... |
import unittest
import os
rnase_pir = os.path.join(unittest_data_dir, "rnase.pir")
poly_ala_frag = os.path.join(unittest_data_dir, "crashes_on_cootaneering-v2.pdb")
class CootaneerTestFunctions(unittest.TestCase):
def test01_0(self):
"""Assignment of new PIR sequence overwrites old assignment"""
... |
from io import BytesIO
import logging
import os
import re
import struct
import sys
from .compat import sysconfig, detect_encoding, ZipFile
from .resources import finder
from .util import (FileOperator, get_export_entry, convert_path,
get_executable, in_venv)
logger = logging.getLogger(__name__)
_D... |
"""
Python implementation of ga.php.
Snatched from (based on, yep!) https://github.com/b1tr0t/Google-Analytics-for-Mobile--python-
Thank you very much, man!
Let me know if you will be in Prague, b1tr0t, I will set a beer,
Eugene
"""
import re
try:
from hashlib import md5
except:
from md5 import md5
from random ... |
"""
Plotting functions for control system responses. Pairs best with the output
from control_sim.
Requres matplotlib
"""
import matplotlib.pyplot as plt
def plot_regsf(t, u, x, name=None, plot_now=True):
""" Plot the response of a full state feedback regulator.
Args:
t: Time vector
u: Ar... |
import discord
import logging
import os
from .config import Config
from .handler import Handler
logging.basicConfig(level=logging.INFO) # Enables logging
version = '1.4.2'
class Evanthe(discord.Client):
def __init__(self):
super().__init__()
botVersion = version
self.conf... |
"""
Footnotes Extension for Python-Markdown
=======================================
Adds footnote handling to Python-Markdown.
See <https://pythonhosted.org/Markdown/extensions/footnotes.html>
for documentation.
Copyright The Python Markdown Project
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)... |
"""Demonstration of the move_connected keyword for Rules
"""
from pysb import *
Model()
Monomer('A', ['b'])
Monomer('B', ['a'])
# One main 3d compartment and two 2d membranes inside it
Parameter('Vmain', 1)
Parameter('Vx', 1)
Parameter('Vy', 1)
Compartment('Main', None, 3, Vmain)
Compartment('X', Main, 2, Vx)
Compa... |
## 1. Take a number of with four digits (N)
## 2. Sort digits small to big (ASC)
## 3. Sort digits big to small (DESC)
## 4. Result - DESC - ASC
## 5. If Result = N exit and record number of iterations
def sortAsc(n):
""" Sort the input number by characters from small to big"""
a = str(n)
b = sorted... |
#!/usr/bin/env python
import os.path
from setuptools import setup, find_packages
def auto_version_setup(**kwargs):
pkg_name = kwargs["packages"][0]
# Populate the "version" argument from the "VERSION" file.
pkg_path = os.path.join(os.path.dirname(__file__), pkg_name)
with open(os.path.join(pkg_path, ... |
import numpy as np
from cvxopt import matrix, solvers
import cdd
import shapely.geometry as geom
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # flake8: noqa
from scipy.linalg import block_diag
def cross_m(vec):
return np.array([[0, -vec.item(2), vec.item(1)],
[vec.item... |
"""Set of tests for the placeholder checking"""
from unittest import TestCase
from nose.tools import raises
import yql
class PublicTest(TestCase):
@raises(ValueError)
def test_empty_args_raises_valueerror(self):
y = yql.Public()
query = "SELECT * from foo where dog=@dog"
params = {}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.