code
stringlengths
1
199k
"""A variational ansatz based on a linear swap network Trotter step.""" from typing import Iterable, Optional, Sequence, Tuple, cast import numpy import sympy import cirq from openfermioncirq import swap_network from openfermioncirq.variational.ansatz import VariationalAnsatz from openfermioncirq.variational.letter_wit...
import os import json import logging from functools import wraps import six from six.moves import urllib from st2client.utils import httpclient LOG = logging.getLogger(__name__) def add_auth_token_to_kwargs_from_env(func): @wraps(func) def decorate(*args, **kwargs): if not kwargs.get('token') and os.env...
import os from configurations import values from django.conf import global_settings class DjangoSettings(object): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = values.SecretValue() DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contr...
import sys, os, math import time import numpy as np from pandas.io.parsers import read_csv from sklearn.decomposition import PCA from sklearn.cross_validation import StratifiedShuffleSplit from sklearn import metrics import sklearn.svm as svm from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import...
"""Test for LatestBlessedModelStrategy.""" import tensorflow as tf from tfx import types from tfx.components.model_validator import constants as model_validator from tfx.dsl.input_resolution.strategies import latest_blessed_model_strategy from tfx.orchestration import metadata from tfx.types import standard_artifacts f...
"""One-time script for extracting all the cat and dog images from CIFAR-10.""" import cPickle import numpy as np from PIL import Image TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)] TEST_FILE = 'test_batch' CAT_INPUT_LABEL = 3 DOG_INPUT_LABEL = 5 CAT_OUTPUT_LABEL = 1 DOG_OUTPUT_LABEL = 0 de...
from copy import deepcopy from datetime import datetime from datetime import timezone from email.utils import mktime_tz from email.utils import parsedate_tz from io import BytesIO from itertools import chain from mimetypes import guess_type from typing import Callable from typing import Iterable from typing import List...
import logging import six from taskflow import exceptions from taskflow.utils import misc from taskflow.utils import reflection LOG = logging.getLogger(__name__) def _save_as_to_mapping(save_as): """Convert save_as to mapping name => index. Result should follow storage convention for mappings. """ # TOD...
import collections from nova import exception from nova import test from nova.virt.vmwareapi import fake from nova.virt.vmwareapi import vm_util class fake_session(object): def __init__(self, ret=None): self.ret = ret def _call_method(self, *args): return self.ret class VMwareVMUtilTestCase(test...
import pytest import requests from platformio import exception, util def test_platformio_cli(): result = util.exec_command(["pio", "--help"]) assert result["returncode"] == 0 assert "Usage: pio [OPTIONS] COMMAND [ARGS]..." in result["out"] def test_ping_internet_ips(): for host in util.PING_REMOTE_HOSTS...
../common/cgi_runtests.py
from PIL import Image import os.path,os import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Version import Versionned from lipyc...
__author__ = 'Keiran' from model.contact import Contact import pytest def test_contact_compare(app, orm): with pytest.allure.step('Given a sorted contact list from DB'): contacts_from_db = orm.get_contact_list() sorted_contacts_from_db = list(sorted(contacts_from_db, key=Contact.id_or_max)) with...
import os import time import json import pprint from util import hook def readConfig(): ### Read config json and parse it confJson = None with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile: confJson = confFile.read() return json.loads(confJson) inputs = {} #store time (unixtim...
import os import threading from huxley.consts import TestRunModes from huxley.errors import TestError from huxley.images import images_identical, image_diff from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys SCREENSHOT_LOCK = threading.RLock() class TestStep(object): def __i...
import netaddr import random import six from tempest.api.network import base from tempest.common.utils import data_utils from tempest import config from tempest.lib import exceptions as lib_exc from tempest import test CONF = config.CONF class NetworksTestDHCPv6(base.BaseNetworkTest): _ip_version = 6 """ Test D...
""" WSGI config for server_proj project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION...
import testlib import logging import splunklib.client as client class Tests(testlib.SDKTestCase): def setUp(self): self.service = client.connect(**self.opts.kwargs) self.storage_passwords = self.service.storage_passwords def tearDown(self): # Delete all passwords created by SDK tests ...
import time import unittest import mock from openhtf import plugs from openhtf.core import base_plugs from openhtf.core import monitors from six.moves import queue class EmptyPlug(base_plugs.BasePlug): pass class TestMonitors(unittest.TestCase): def setUp(self): super(TestMonitors, self).setUp() self.test_s...
import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_support_dir = os.path.join(sdk_dir, 'android') sys.path.extend([sdk_dir, support...
""" Asciimatics is a package to help people create full-screen text UIs (from interactive forms to ASCII animations) on any platform. It is licensed under the Apache Software Foundation License 2.0. """ __author__ = 'Peter Brittain' try: from .version import version except ImportError: # Someone is running str...
""" Helpers related to maintaining a registry of classes """ class Registry(dict): """ A registry class, used for registering services, drivers, etc. This is not the registry itself. The registry itself is in forklift.services, forklift.drivers, etc. """ def __call__(self, name): """ ...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re from xml.dom.minidom import parse from pants.backend.codegen.targets.jaxb_library import JaxbLibrary from pants.backend.codegen.tasks.code_gen impor...
def test_delite_group(app): app.session.login( username="admin", password="secret") app.group.delete_first_group() app.session.logout() if __name__ == '__main__': pytest.main('test_del_group.py')
import getpass import json import getopt from genericpath import isfile from os.path import sep from pingdumb.main_module import url_type def read_config(): f_path = "." + sep + "pingdumb.json" if not isfile(f_path): f = open(f_path, 'w') conf = { "url": "jellyms.kr", "sm...
"""Cache util functions for ReSDKTables.""" import os import pickle import sys from shutil import rmtree from typing import Any from resdk.__about__ import __version__ def _default_cache_dir() -> str: """Return default cache directory specific for the current OS. Code originally from Orange3.misc.environ. "...
import sys import threading import time io_lock = threading.Lock() blocker = threading.Lock() def block(i): t = threading.current_thread() with io_lock: print('{} with ident {} going to sleep'.format( t.name, t.ident)) if i: blocker.acquire() # acquired but never released ...
import nose.tools as ns import os from os.path import join from tempfile import gettempdir from relshell.record import Record from relshell.recorddef import RecordDef from relshell.batch import Batch from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.ostream.localfile import LocalFile TEST_FILE ...
import imp import os import sys PYCART_DIR = ''.join(['python-', '.'.join(map(str, sys.version_info[:2]))]) try: zvirtenv = os.path.join(os.environ['OPENSHIFT_HOMEDIR'], PYCART_DIR, 'virtenv', 'bin', 'activate_this.py') execfile(zvirtenv, dict(__file__ = zvirtenv) ) except IOError: p...
import json import os from os.path import isfile from os.path import join import re from oslo_config import cfg from oslo_log import log as logging from oslo_utils import encodeutils import sqlalchemy from sqlalchemy import and_ from sqlalchemy.schema import MetaData from sqlalchemy.sql import select from glance.common...
""" Google Analytics template tags and filters. """ from __future__ import absolute_import import re from django.template import Library, Node, TemplateSyntaxError from templatetags.utils import is_internal_ip, disable_html, get_required_setting SCOPE_VISITOR = 1 SCOPE_SESSION = 2 SCOPE_PAGE = 3 PROPERTY_ID_RE = re.com...
import glob import cv2 import cv_bridge import rospy from sensor_msgs.msg import Image from std_msgs.msg import Int32, Float32 import rospkg import sys class Animation: def __init__(self, directory): self.fnames = [fname for fname in glob.glob("%s/*" % directory)] self.fnames.sort() self.ima...
import asyncio import sys import traceback import pytest from pykka import Future, Timeout, get_all def run_async(coroutine): loop = asyncio.get_event_loop() f = asyncio.ensure_future(coroutine, loop=loop) return loop.run_until_complete(f) def test_base_future_get_is_not_implemented(): future = Future()...
""" Visualizers that wrap the model selection libraries of Scikit-Learn """ from .learning_curve import LearningCurve, learning_curve from .validation_curve import ValidationCurve, validation_curve from .cross_validation import CVScores, cv_scores from .importances import FeatureImportances, feature_importances from .r...
"""Copyright 2008 Orbitz WorldWide Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
""" Install flocker on a remote node. """ import posixpath from textwrap import dedent from urlparse import urljoin, urlparse from effect import Func, Effect import yaml from zope.interface import implementer from characteristic import attributes from pyrsistent import PRecord, field from ._libcloud import INode from ....
import webob from nova.api.openstack.compute.plugins.v3 import admin_password from nova.compute import api as compute_api from nova import exception from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes def fake_get(self, context, id): return {'uuid': id} def f...
'''------------------------------------------------------------------------- Copyright IBM Corp. 2015, 2015 All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/l...
from quantum.openstack.common import cfg meta_plugin_opts = [ cfg.StrOpt('plugin_list', default='', help=_("List of plugins to load")), cfg.StrOpt('l3_plugin_list', default='', help=_("List of L3 plugins to load")), cfg.StrOpt('default_flavor', default='', help=_...
""" KubeVirt API This is KubeVirt API an add-on for Kubernetes. OpenAPI spec version: 1.0.0 Contact: kubevirt-dev@googlegroups.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubevirt from kub...
""" title : __main__.py description : entry point for core sira component usage : python sira [OPTIONS] -h Display this usage message -d [input_directory] Specify the directory with the required config and model files ...
import unittest import mock from mopidy_playbackdefaults import PlaybackDefaultsFrontend class PlaybackDefaultsFrontendTest(unittest.TestCase): def test_no_settings(self): config = {'playbackdefaults': {'default_random': '', 'default_repeat': '', 'default_consume': '', 'default_single': ''}} core = ...
from __future__ import print_function import unittest import numpy as np from op_test import OpTest import paddle.fluid.core as core class TestFakeQuantizeOp(OpTest): def setUp(self): self.op_type = "fake_quantize_abs_max" self.attrs = {'bit_length': 8} self.inputs = {'X': np.random.random((...
from google.appengine.ext import db from google.appengine.api import memcache import webapp2 import math, logging from datetime import datetime, timedelta from ffe import markup from ffe.ffe_time import mark_cet, utc_from_cet, minutes_from_string, string_from_minutes from TASeries impor...
from threaded_ssh import ThreadedClients from ServerConfig import Aim from ServerConfig import TellStore from ServerConfig import General from ServerConfig import Storage from ServerConfig import Kudu def hostToIp(host): return General.infinibandIp[host] def semicolonReduce(x, y): return x + ';' + y def startAi...
import argparse import os import sys from ekko.manifest import structure as manifest_structure from six.moves import range from stevedore import driver def parse_args(): parser = argparse.ArgumentParser(description='Backup Block Device') parser.add_argument('--backupsize', required=True, type=int, ...
from __future__ import absolute_import from __future__ import unicode_literals import glob import imp import inspect import os import sys from mb.config.config import get_default_config_file from mb.lib import logger from mb.lib import process _log = logger.get_logger('[Ioc]') from mb import build_context # BuildContex...
"""Runs the main function in detokenize.py.""" from pw_tokenizer import detokenize detokenize.main()
from unittest import mock from senlin.common import consts from senlin.engine.actions import base as ab from senlin.engine.actions import cluster_action as ca from senlin.engine import cluster as cm from senlin.engine import dispatcher from senlin.objects import action as ao from senlin.objects import dependency as dob...
''' @author: sheng @license: ''' SPELL=u'xiàjùxū' CN=u'下巨虚' NAME=u'xiajuxu441' CHANNEL='stomach' CHANNEL_FULLNAME='StomachChannelofFoot-Yangming' SEQ='ST39' if __name__ == '__main__': pass
from oslo_serialization import jsonutils import webob from nova.compute import flavors from nova import test from nova.tests.unit.api.openstack import fakes FAKE_FLAVORS = { 'flavor 1': { "flavorid": '1', "name": 'flavor 1', "memory_mb": '256', "root_gb": '10', "swap": '5', ...
"""Location formatter.""" from aquilon.aqdb.model import Location, Rack, Building, Room from aquilon.worker.formats.formatters import ObjectFormatter class LocationFormatter(ObjectFormatter): def format_raw(self, location, indent="", embedded=True, indirect_attrs=True): details = [indent ...
from telnetlib import Telnet class James: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['password...
import sys, os, subprocess, re def config_vcs_tag(infile, outfile, fallback, source_dir, replace_string, regex_selector, cmd): try: output = subprocess.check_output(cmd, cwd=source_dir) new_string = re.search(regex_selector, output.decode()).group(1).strip() except Exception: new_string ...
import subprocess import threading import common import os import time import shutil from shutil import copyfile import sys import testobj import client import config import signal import envelope import system_metrics_gather from logger import LOG lctx = None cfg = config.CFG("DaytonaHost", lctx) cfg.readCFG("config.i...
import time def ToString (List): # Coverts List to String return ''.join(List) def Setup (): def Wait (): reading_file=open('DataStore.txt', 'r') lines=reading_file.readlines() #print lines GoodLine = lines[len(lines) - 1] #GoodLine is the last line of the file! if len(lines) > len(oldLinesGood)...
from unittest import TestCase from chess import get_potential_moves class ChessTestCase(TestCase): def setup(self): pass def teardown(self): pass def test_knight(self): response = get_potential_moves('knight', 'd2') response = [each.strip() for each in response.split(',')] ...
"""Classes supporting creation and use of content using XBlocks. Dependencies: 1. XBlock (https://github.com/edx/XBlock) 2. App Engine XBlock runtime (https://github.com/google/appengine_xblock_runtime) The appropriate versions of both of these libraries must be installed the the lib/ folder. See READM...
import poplib import email import time class MailHelper: def __init__(self, app): self.app = app def get_mail(self, username, password, subject): for i in range (5): pop = poplib.POP3(self.app.config['james']['host']) pop.user(username) pop.pass_(password) ...
from .main import main, zdkb
__author__ = "João Magalhães <joamag@hive.pt>" """ The author(s) of the module """ __version__ = "1.0.0" """ The version of the module """ __revision__ = "$LastChangedRevision$" """ The revision number of the module """ __date__ = "$LastChangedDate$" """ The last change date of the module """ __copyright__ = "Copyright...
__author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 28, 2018' """ 9-3. Users: Make a class called User . Create two attributes called first_name and last_name, and then create several other attributes that are typically ...
from givabit.backend.errors import AlreadyExistsException from givabit.backend.user import User from givabit.backend.user_repository import UserRepository from givabit.webapp.base_page import BasePage from givabit.webapp.url import Url class SignupPage(BasePage): def __init__(self, request, response, user_repositor...
""" KubeVirt API This is KubeVirt API an add-on for Kubernetes. OpenAPI spec version: 1.0.0 Contact: kubevirt-dev@googlegroups.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubevirt from kub...
import os, sys sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path from flTile.amConfig import CreateAMConfig def run(): tileConfig = CreateAMConfig() #hostname = gethostname() #machineDesc = tileConfig.getMachineDescByHostname(hostname) ...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('passive_data_kit', '0068_remove_deviceissue_platform_version'), ] operations = [ migrations.AlterField( model_name='deviceissue', name='state', field=models....
import collections import six from gbpservice.nfp.core import log as nfp_logging LOG = nfp_logging.getLogger(__name__) deque = collections.deque class SequencerEmpty(Exception): pass class SequencerBusy(Exception): pass """Sequences the events. """ class EventSequencer(object): class Sequencer(object): ...
import logging import os from django.contrib.auth.models import User from django.core import management from django.core.management.base import NoArgsCommand from django.utils.translation import ugettext as _ from hadoop import cluster from hadoop.fs.hadoopfs import Hdfs from liboozie.conf import REMOTE_DEPLOYMENT_DIR ...
LOGIN_EMAIL = 'your@email.here' LOGIN_PASSWORD = 'your_password_here' SUB_DOMAIN = 'www' DOMAIN = 'your-domain.here'
import unittest from rx import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable from rx.disposables import Disposable, SerialDisposable on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subsc...
from __future__ import print_function from collections import Counter from operator import itemgetter import os _path = os.path.abspath(os.path.dirname(__file__)) SOURCE = os.path.join(_path, 'poems_for_wordcount.txt') DESTINATION = os.path.join(_path, 'poem_words_out.txt') def sort_word_counts(word_dict): # first ...
from rethinkengine.fields import * import unittest2 as unittest class PrimaryKeyFieldTestCase(unittest.TestCase): def test_default(self): f = ObjectIdField() self.assertEqual(f._default, None) with self.assertRaises(TypeError): ObjectIdField(default='') def test_required(self...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'SurveyQuestion.statistic' db.delete_column(u'survey_surveyquestion', 'statistic_id...
"""Process that loads the datastore""" __author__ = 'Michael Meisinger, Thomas Lennan' """ Possible Features - load objects into different datastores - load from a directory of YML files in ion-definitions - load from a ZIP of YMLs - load an additional directory (not under GIT control) - change timestamp for resources ...
from __future__ import print_function import time import pyupm_grove as grove import pyupm_i2clcd as lcd import pyupm_th02 as th02 import pyupm_guvas12d as upmUV import pyupm_grovemoisture as upmMoisture from phant import Phant import requests from iot_utils import * __author__ = 'KT Kirk' myLcd = lcd.Jhd1313m1(0, 0x3E...
"""This module contains the parser/generators (or coders/encoders if you prefer) for the classes/datatypes that are used in iCalendar: 4.2 Defined property parameters are: ALTREP, CN, CUTYPE, DELEGATED-FROM, DELEGATED-TO, DIR, ENCODING, FMTTYPE, FBTYPE, LANGUAGE, MEMBER, PARTSTAT, RANGE, RELATED, RELTYPE, ROL...
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('webapp', url(r'^/?$', 'views.home', name='home'), url(r'^auth_redirect$', 'views.auth_redirect', name='auth_redirect'), url(r'^nights$', 'views.night_index', name='night_index'), url(r'^song$', 'views.song_index', name='song_ind...
from morphforgecontrib.simulation.synapse_templates.exponential_form.expsyn.core import PostSynapticMech_ExpSyn_Base as ExpSynTemplateType from morphforgecontrib.simulation.synapse_templates.exponential_form.exp2syn.core import PostSynapticMech_Exp2Syn_Base as Exp2SynTemplateType from morphforgecontrib.simulation.synap...
''' This script reads data from various sources to process and store in MongoDB. ''' import pyexcel import logging import models from transform_date import * from accent_remover import * logging.basicConfig(filename='logs/scieloci.info.txt', level=logging.INFO) logger = logging.getLogger(__name__) def scieloci(filename...
import datetime import os import os.path import subprocess from collections import defaultdict from django.conf import settings as dsettings from django.core import exceptions from django.core.cache import cache from django.db import connection from django.db import models from django.db import transaction from django....
import os from flask import Flask from flask_sslify import SSLify from .model import db from .auth import oauth from .ui import ui_bp from .api import api_bp app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY', os.urandom(24)) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABAS...
import os import sys PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(PROJECT_DIR) sys.path.append(os.path.abspath(PROJECT_DIR + '/../')) sys.path.append(os.path.abspath(PROJECT_DIR + '/../realestate/')) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject....
from download_music import run_midi_load
""" Module `lino_xl.lib.properties` ------------------------------- Imagine that we are doing a study about alimentary habits. We observe a defined series of properties on the people who participate in our study. Here are the properties that we are going to observe:: >>> weight = properties.INT.create_property(name='...
from os.path import join from tempfile import mkdtemp import unittest from shutil import rmtree import pandas as pd from feagen.data_wrappers.pandas_hdf import get_shape_from_pandas_hdf_storer class Test(unittest.TestCase): def setUp(self): self.test_output_dir = mkdtemp(prefix="feagen_test_output_") ...
import mongoengine as db class BaseObject(db.Document): meta = {'allow_inheritance': True} name = db.StringField(required=True) tags = db.ListField(db.StringField()) revision = db.IntField(default=1)
import sys import time from entrypoint2 import entrypoint import pyscreenshot from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper from pyscreenshot.util import run_mod_as_subproc ...
""" pygments.lexers._postgres_builtins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Self-updating data files for PostgreSQL lexer. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ KEYWORDS = ( 'ABORT', 'ABSOLUTE', 'ACCESS', 'ACTION'...
from flask import request from apps.core.flask.login_manager import osr_login_required from apps.configs.sys_config import METHOD_WARNING from apps.core.blueprint import api from apps.core.flask.permission import permission_required from apps.core.flask.response import response_format from apps.modules.category.process...
"""Leetcode 796. Rotate String Easy URL: https://leetcode.com/problems/rotate-string/ We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and onl...
"""Tests for Pattern Chain objects""" from morph import ( pattern, patternchain ) from morph.pattern import ( LiteralPattern, NumericCounterPattern, ) from morph.patternchain import ( generateFullReplaceChain, PatternChain, FilePatternChain, ) from morph.errors import ( PatternModeError ...
import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices( ('OK', 'OK'), ) class...
from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode class ArchPcode_dsPIC33E_LE_24_default(ArchPcode): name = 'dsPIC33E:LE:24:default' pcode_arch = 'dsPIC33E:LE:24:default' description = 'dsPIC33E' bits = 24 ip_offset = 0x2e sp_offset = 0x1e bp_offset = s...
import math def get_direction(src, target): diff = map(lambda a, b: a - b, target, src) mag = math.sqrt(sum(map(lambda a: a ** 2, diff))) if mag == 0: return [0, 0] return map(lambda a: a / mag, diff) def distance(pos1, pos2): return math.sqrt(sum(map(lambda a: a ** 2, map(lambda a, b: a - b...
def extractNotsogoodtranslatorWordpressCom(item): ''' Parser for 'notsogoodtranslator.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'transl...
import httpbenchmark from unuk.benchmarks.base import runtests
from datetime import datetime, timedelta import csv from cStringIO import StringIO from django.test import TestCase from django.contrib.auth.models import User from django.test import Client from django.http import HttpRequest, QueryDict, response from mock import patch, Mock from .models import Variable, Session, Visi...
from flask_login import AnonymousUserMixin from .interface import BUIhandler, BUIuser, BUIloader from ...utils import __ import ssl try: from ldap3 import ( Server, Connection, Tls, ALL, RESTARTABLE, AUTO_BIND_TLS_BEFORE_BIND, AUTO_BIND_NONE, SIMPLE, ...
from cms.exceptions import NoPermissionsException from cms.models import Page, PagePermission, GlobalPagePermission from cms.plugin_pool import plugin_pool from cms.utils import get_cms_setting from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Group f...
from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from rest_framework_nested.routers import NestedSimpleRouter from olympia.bandwagon.views import CollectionViewSet, CollectionAddonViewSet from . import views accounts = SimpleRouter() accounts.register(r'account', views.AccountVi...