code
stringlengths
1
199k
import sys if sys.version_info[0] < 3: from exceptions import NotImplementedError, ValueError, IOError if(sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] < 5)): print("Please consider upgrading your interpreter\nThis script needs at least python >= 2.5") sys.exit(1) impor...
import datetime import logging import requests from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) def _transform_result(response): columns = ({'name': 'Time::x', 'type': TYPE_DATETIME}, {'name': 'value::y', 'type': TYPE_FLOAT}, {'...
from django import VERSION as DJANGO_VERSION if DJANGO_VERSION[0:2] < (1, 4): from django.conf.urls.defaults import include, patterns, url else: from django.conf.urls import include, patterns, url from django.views import generic from django_comments_xtd import views, models, django_comments_urls from django_co...
import logging from collections import namedtuple from io import IOBase from itertools import chain, islice from threading import Thread from streamlink.buffers import RingBuffer from streamlink.packages.flashmedia import FLVError from streamlink.packages.flashmedia.tag import ( AACAudioData, AAC_PACKET_TYPE_SEQUEN...
''' Created on Nov 23, 2011 @author: Mirna Lerotic, 2nd Look Consulting http://www.2ndlookconsulting.com/ Copyright (c) 2013, Stefan Vogt, Argonne National Laboratory All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following condit...
"""JIRA utils used internally.""" from __future__ import unicode_literals import threading from jira.resilientsession import raise_on_error class CaseInsensitiveDict(dict): """A case-insensitive ``dict``-like object. Implements all methods and operations of ``collections.MutableMapping`` as well as dict's `...
""" MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_...
"""Production settings and globals.""" from base import * ALLOWED_HOSTS = [ 'devncode.it', 'euoserver.devncode.it', 'localhost', '127.0.0.1', ] MEDIA_ROOT = normpath(join(SITE_ROOT, '../media')) MEDIA_URL = '/media/' STATIC_ROOT = normpath(join(SITE_ROOT, '../assets')) STATIC_URL = '/static/' EMAIL_BACK...
from migen.fhdl.std import * from migen.flow.plumbing import Buffer from migen.actorlib.fifo import SyncFIFO, AsyncFIFO from migen.flow.network import DataFlowGraph, CompositeActor from ezusbfifo import SimUSBActor, AsyncUSBActor from mimisc.actors.plumbing import Relax class Echo(Module): def __init__(self, usb_ac...
""" @package mi.dataset.parser.test @file marine-integrations/mi/dataset/parser/test/test_flort_dj_cspp.py @author Jeremy Amundson @brief Test code for a flort_dj_cspp data parser """ import os from nose.plugins.attrib import attr from mi.core.log import get_logger from mi.dataset.test.test_parser import ParserUnitTest...
import unittest import textform class TestStringMethods(unittest.TestCase): def test_basic(self): r = textform.format('hello world', []) self.assertEqual(r, 'hello world') r = textform.format('', []) self.assertEqual(r, '') def test_wrong_number_of_values(self): with self...
import memcache from . import HandlerBase from uuid import uuid4 class Handler(HandlerBase): def __init__(self, host='127.0.0.1', port=11211): self.db = memcache.Client(['%s:%s' % (host, port)], debug=0) def set(self, sid, data, ttl=0): if self.db.set(sid, data, ttl): return sid ...
"""This is a module providing FSM actions for Install Operations plugins.""" def a_error(plugin_ctx, ctx): """Display the error message.""" message = ctx.ctrl.after.strip().splitlines()[-1] plugin_ctx.error(message) return False
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} INSTALLED_APPS = ("honeypot",) SECRET_KEY = "honeyisfrombees" MIDDLEWARE_CLASSES = () TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPT...
from __future__ import absolute_import from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_permission_codename import logging logger = logging.getLogger(__name__) try: from django.utils.timezone import now except ImportError: from datetime import datetime...
from distutils.core import setup, Extension ctc = Extension('constant_time_compare', sources=['src/constant_time_compare.c'], language='c') setup(name='constant_time_compare', version='1.3', description='This package includes a secure constant time comparison function written in C', au...
""" Base module variables """ from __future__ import unicode_literals __version__ = 'dev' __author__ = 'The CRN developers' __copyright__ = 'Copyright 2016, Center for Reproducible Neuroscience, Stanford University' __credits__ = ['Craig Moodie', 'Ross Blair', 'Oscar Esteban', 'Chris Gorgolewski', 'Shoshana Berleant', ...
from fractions import Fraction as Fract import sys def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] depth = 20 for m in range(-depth,depth): for n in range(-depth,depth): if redq(0,0,m,n)=...
airports_red = list() j = 0 for lineB in open("airports.dat","r",encoding="utf-8-sig"): letalisca = lineB.split(",") # Podatke iz vrstice zapišemo v seznam stringov for line0B in open("routes.dat","r",encoding="utf-8-sig"): poti = line0B.split(",") if len(letalisca) == 12 and len(poti) == 9: # p...
from moderation.tests.utils.testsettingsmanager import SettingsTestCase from moderation.tests.utils import setup_moderation, teardown_moderation from moderation.tests.apps.test_app2.models import Book class AutoDiscoverAcceptanceTestCase(SettingsTestCase): ''' As a developer I want to have a way auto discover a...
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("MLPClassifier" , "BreastCancer" , "oracle")
from rest_framework import status, views, response, generics from oscar.core.loading import get_model from oscarapi.permissions import IsOwner from oscarapi.views.utils import BasketPermissionMixin from oscarapi.loading import get_api_classes from oscarapi.signals import oscarapi_post_checkout Order = get_model('order'...
import json from binascii import b2a_hex try: from django.utils.six.moves import cPickle as pickle except ImportError: import pickle import unittest from unittest import skipUnless from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.geometry.test_data import TestDataMixin from django.utils.six....
import numpy as np import itertools from copy import deepcopy from .variables import create_variable from ..errors import InvalidConfigError, InvalidVariableNameError class Design_space(object): """ Class to handle the input domain of the function. The format of a input domain, possibly with restrictions: ...
import numpy as np from . import settings def wrap_180(values): values_new = values % 360. values_new[values_new > 180.] -= 360 return values_new def find_coordinate_range(transform, extent, coord_types): ''' Find the range of coordinates to use for ticks/grids Parameters ---------- pix2...
from collections import Counter from dt import datetime from datetime import date import enumerations import pytz import re flags = re.IGNORECASE|re.MULTILINE|re.UNICODE global tzinfo tzinfo = pytz.UTC month_to_number = enumerations.month_to_number def num(text): if text: if text.isdigit(): retu...
from sympycore.arithmetic.evalf import * from sympycore.arithmetic.evalf import mpmath, compile_mpmath from sympycore.calculus import Symbol, I, Number, Exp, Sin, Cos, E, pi import math import cmath def test_evalf(): expr1 = Number(1)/3 expr2 = Sin(E)**2 + Cos(E)**2 - 1 expr3 = Exp(I) - Cos(1) - I*Sin(1) ...
from pcaspy.cas import gdd import time while True: gddValue = gdd() gddValue.put(range(1000000)) v = gddValue.get() gddCtrl = gdd.createDD(34) # gddAppType_dbr_ctrl_double gddCtrl[1].put('eV') gddCtrl[2].put(0) gddCtrl[3].put(1) gddCtrl[4].put(0) gddCtrl[5].put(1) gddCtrl[6].put(...
import datetime from dateutil import tz def current_update(): """ Return a datetime object representing the current Canadian Weather Office forecast update """ # The data is updated 5:00 UTC and 17:00 UTC every day. We need # to see which update to get. hour = 5 date = datetime.datetime.now(...
'''active knives''' from threading import local from collections import deque from contextlib import contextmanager from stuf.utils import clsname from knife._compat import loads, optimize class _ActiveMixin(local): '''active knife mixin''' def __init__(self, *things, **kw): ''' Initialize :mod:...
from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin as DjangoPermissionRequiredMixin from django.contrib.auth.models import Permission from django.core.exceptions import PermissionDenied from django.shortcuts impor...
""" Vanilla RNN @author Graham Taylor """ import numpy as np import theano import theano.tensor as T from sklearn.base import BaseEstimator import logging import time import os import datetime import pickle as pickle import math import matplotlib.pyplot as plt plt.ion() mode = theano.Mode(linker='cvm') class RNN(object...
from distutils.core import setup import os import translatable setup( name = 'django-translatable', packages = ['translatable',], version = translatable.__version__, description = "Django app providing simple translatable models system", long_description = open(os.path.join(os.path.dirname(__file__)...
""" Export all open fonts as UFO Iterate through all open fonts, and export UFOs. Note: This script will look for a UFO named <vbf_name_without_extension>.ufo. If it can't find this UFO, it will make a new one. If it can find the UFO, it will only export: glyphs feature data font.lib alignment zones (if t...
"""Module containing the list default command.""" from command import Command class List(Command): """Command 'list'. This command should be used as a container to list informations such as sthe different bundles, routes and so on. """ name = "list" brief = "list specific informations" descr...
from __future__ import print_function from ploy.common import BaseInstance, BaseMaster, StartupScriptMixin from ploy.config import HooksMassager from ploy.config import StartupScriptMassager import logging log = logging.getLogger('ploy.dummy_plugin') class MockSock(object): def close(self): log.info('sock.c...
""" ============ rdflib.store ============ ``Context-aware``: An RDF store capable of storing statements within contexts is considered context-aware. Essentially, such a store is able to partition the RDF model it represents into individual, named, and addressable sub-graphs. Relevant Notation3 reference regarding form...
''' anaconda upload CONDA_PACKAGE_1.bz2 * [Uploading a Conda Package](http://docs.anaconda.org/using.html#Uploading) * [Uploading a PyPI Package](http://docs.anaconda.org/using.html#UploadingPypiPackages) ''' from __future__ import unicode_literals import argparse from glob import glob import logging import os ...
from celery.task import task from django.db import transaction from tardis.tardis_portal.staging import stage_file from tardis.tardis_portal.models import Dataset_File try: from tardis.tardis_portal.filters import FilterInitMiddleware FilterInitMiddleware() except Exception: pass try: from tardis.tardis...
from os.path import join, basename, abspath, relpath import pytest from pinner.api import check_requirement, find_requirements from pinner.exceptions import * def test_requirement_needs_version(): with pytest.raises(UnpinnedDependency): check_requirement('Django') with pytest.raises(NotStrictSpec): ...
from __future__ import print_function import sys sys.path.append('..') from os import mkdir from os.path import basename, exists, join as joinpath from sasmodels.core import load_model_info try: from typing import Optional, BinaryIO, List, Dict except ImportError: pass else: from sasmodels.modelinfo import ...
import re import os import sys import yaml NUM_TO_KEEP = 5 PACKAGE_DEFS = {} FOUND_PACKAGES = {} if __name__ == '__main__': with open('freight-clean.yml', 'r') as f: yml = yaml.load(f) NUM_TO_KEEP = yml.get('settings', {}).get('num-to-keep', 5) PACKAGE_DEFS = {} for name, pkgSettings...
from troposphere import (ecs, Ref, Join) import yaml, os class Compose2TaskDefinition(object): def __init__(self, compose_file, name_image_map): self.compose_file = compose_file self.container_definitions = {} f = open(self.compose_file) data_map = yaml.safe_load(f) f.close()...
import re _DAYS_IN_MONTH = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) _INTERPOLATION = re.compile('\${(\w*)}') def is_leap_year(year): """Return whether the given year is a leap year.""" if year % 4: return False if year % 400 == 0: return True return year % 100 != 0 def get_number...
from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('diagnosticos', '0003_auto_20150407_2123'), ] operations = [ migrations.AlterField( model_name='diagnosticos', nam...
''' RSS feeds for blog posts @copyright: Copyright 2012 Faraz Masood Khan, mk.faraz@gmail.com @author: Faraz Masood Khan ''' from foo.blog.models import Post from django.conf import settings from django.contrib.sites.models import Site from django.utils.feedgenerator import Rss201rev2Feed from django.contrib.syndicatio...
import numpy as np import scipy.linalg as lg import matplotlib.pyplot as plt from parametrix.monte_carlo.estimators import MC_Simulations_MSE from parametrix.bayesian_linear_model.signal_models import M_Bayesian_L from parametrix.bayesian_linear_model.estimators import E_Bayesian_L from parametrix.bayesian_linear_model...
""" Tests for dit.profiles.entropy_triangle. Known examples taken from http://arxiv.org/abs/1409.4708 . """ from __future__ import division import pytest from dit import Distribution from dit.profiles import EntropyTriangle, EntropyTriangle2 ex1 = Distribution(['000', '001', '010', '011', '100', '101', '110', '111'], [...
from __future__ import absolute_import from six.moves.urllib.parse import urlencode from datetime import timedelta from django.core.urlresolvers import reverse from django.utils import timezone from sentry.models import EventUser, GroupTagValue, OrganizationMemberTeam from sentry.testutils import APITestCase class Orga...
from __future__ import print_function, division, absolute_import from marvin.tests.api.conftest import ApiPage import pytest @pytest.mark.parametrize('page', [('api', 'mangaid2plateifu')], ids=['mangaid2plateifu'], indirect=True) class TestGeneralMangaid2Plateifu(object): @pytest.mark.parametrize('reqtype', [('get'...
def extractTaffyTranslations(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [ ('CCM', 'Close Combat Mage', 'translated'), ('CC', 'Cheating Cra...
""" negotiated.py Created by Thomas Mangin on 2012-07-19. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ from exabgp.bgp.message.open.asn import ASN from exabgp.bgp.message.open.asn import AS_TRANS from exabgp.bgp.message.open.holdtime import HoldTime from exabgp.bgp.message.open.capability import Capab...
import math import torch import torch.nn.functional as F from fairseq import metrics, modules, utils from fairseq.criterions import FairseqCriterion, register_criterion @register_criterion('masked_lm') class MaskedLmLoss(FairseqCriterion): """ Implementation for the loss used in masked language model (MLM) trai...
import datetime import unittest from django.conf import settings from django.core import management from django.core.management.color import no_style from django.db import backend, connection, DEFAULT_DB_ALIAS from django.db.backends.signals import connection_created from django.test import TestCase from regressiontest...
import unittest import numpy as np import scipy.sparse as sp from multimodal.lib.array_utils import normalize_features from multimodal.evaluation import (evaluate_label_reco, evaluate_NN_label, chose_examples) class TestLabelEvaluation(unittest.TestC...
import roslib; roslib.load_manifest('hanse_navigation') import rospy import smach import smach_ros import math import numpy import collections import actionlib import tf from tf.transformations import euler_from_quaternion from hanse_navigation.msg import NavigateAction, NavigateFeedback, NavigateResult from hanse_navi...
import random from CellModeller.Regulation.ModuleRegulator import ModuleRegulator from CellModeller.Biophysics.BacterialModels.CLBacterium import CLBacterium from CellModeller.GUI import Renderers import numpy import math max_cells = 400000 cell_colors = numpy.random.uniform(0,1,(9,3)) def setup(sim): # Set biophys...
""" Make base line result averages from the output of the get_results command """ import sys import re print "Making baseline averages with data from:" for line in sys.stdin: searchObj = re.search(r'jid\(', line, re.M | re.I) if searchObj: # Do some substitution work here, see comments above #in...
from __future__ import division, print_function from collections import defaultdict from vod.entropy import kullback_leiber_divergence import numpy as np import plac import sys def load_text_file(features_fpath, classes, use): #TODO: stemming and category names abbrv num_classes = len(set(classes)) count_cl...
import unittest from paws.conf import Config, env class ConfTest(unittest.TestCase): def test_attr(self): class Config(Conf): FOO : int = 0 self.assertEqual(Config.FOO, 0)
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.Table import Row from PLC.Auth import Auth from PLC.Namespace import hostname_to_hrn from PLC.Peers import Peers from PLC.Sites import Sites from PLC.Nodes import Node, Nodes from PLC.TagTypes import TagTypes from...
from django import template from django.utils.encoding import iri_to_uri register = template.Library() class PrefixNode(template.Node): def __repr__(self): return "<PrefixNode for %r>" % self.name def __init__(self, varname=None, name=None): if name is None: raise template.TemplateSy...
def pal(value): return str(value) == str(value)[::-1] p = 1 for i in xrange(999, 99, -1): for j in xrange(999, 99, -1): n = i * j if n > p and pal(n): p = n print p
from __future__ import print_function from BinPy import * class FlipFlop: """ Super Class for all FlipFlops """ def __init__(self, enable, clk, a, b): self.a = a self.b = b self.clk = clk self.clkoldval = 1 self.enable = enable def Enable(self): self.e...
from django import forms from django.utils.safestring import mark_safe import datetime import re from django.forms.widgets import Widget, Select from django.utils.dates import MONTHS class DatePicker(forms.TextInput): def render(self, name, value=None, attrs=None): input = self.renderTimeField(name, value) ...
from flask.ext.wtf import Form from wtforms import StringField from wtforms.validators import DataRequired class SettingsForm(Form): filename = StringField('filename', validators=[DataRequired()])
from django.contrib import admin from tidings.models import Watch, WatchFilter class FilterInline(admin.TabularInline): model = WatchFilter class WatchAdmin(admin.ModelAdmin): list_filter = ['content_type', 'event_type'] raw_id_fields = ['user'] inlines = [FilterInline] class WatchFilterAdmin(admin.Mode...
import warnings from sympy import (plot_implicit, cos, Symbol, symbols, Eq, sin, re, And, Or, exp, I, tan, pi) from sympy.plotting.plot import unset_show from tempfile import NamedTemporaryFile, mkdtemp from sympy.utilities.pytest import skip, warns from sympy.external import import_module from sympy...
from django.http import HttpResponse from django.views.generic import View import json import redis import requests redis_instance = redis.StrictRedis() class GetJson(View): """ Returns next departures per stop, only for currently active lines. """ def get(self, request, *args, **kwargs): data = redis_i...
from cudatree import RandomForestClassifier, load_data, timer from cudatree import util from hybridforest import RandomForestClassifier as hybridForest import numpy as np import math debug = False verbose = False bootstrap = False n_estimators = 100 def benchmark_cuda(dataset, bfs_threshold = None): x_train, y_train ...
""" Flaskr ~~~~~~ A microblog example application written as Flask tutorial with Flask and sqlite3. :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from sqlite3 import dbapi2 as sqlite3 from flask import Flask, request, session, g, redirect, url_for, abor...
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 'Rule.rule' db.add_column('poll_rule', 'rule', self.gf('django.db.models.fields.IntegerField')(max...
import shlex class Player(object): def __init__(self, location): self.location = location self.location.here.append(self) self.playing = True def get_input(self): return raw_input(">") def process_input(self, input): parts = shlex.split(input) if len(parts) ==...
from django.conf.urls import patterns from django.conf.urls import url from . import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='resu...
from django.apps import apps from rest_framework import viewsets from rest_framework.serializers import ModelSerializer def get_model_class(class_name): app_name, model_name = class_name.split('.') return apps.get_model(app_name, model_name) class GenericViewSet(viewsets.ModelViewSet): """ API endpoint ...
import cv2 import numpy as np def draw_circles(image, circles, color=(0,255,0), thickness=1, center_color=(0,0,255), center_thickness=2): if circles is None: return for circle in np.uint16(np.around(circles))[0,:]: center = tuple(circle[:2]) radius = circle[2] cv2.circle(image, center, radius, color...
""" Core protocol implementation """ import os import socket import sys import threading import time import weakref from hashlib import md5, sha1 import paramiko from paramiko import util from paramiko.auth_handler import AuthHandler from paramiko.channel import Channel from paramiko.common import xffffffff, cMSG_CHANN...
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('CHANGELOG.rst') as f: changelog = f.read() setup( name='devpi-builder', use_scm_version=True, packages=find_packages(exclude=['tests']), author='Matthias Bach', author_email='matthias.bach@...
import math from typing import Tuple import torch from torch import Tensor from torchvision.transforms import functional as F class RandomMixup(torch.nn.Module): """Randomly apply Mixup to the provided batch and targets. The class implements the data augmentations as described in the paper `"mixup: Beyond E...
import tests.periodicities.period_test as per per.buildModel((5 , 'BH' , 100));
from django.db import models from django.db.models import Q from django.utils.encoding import force_text, python_2_unicode_compatible from cms.models import CMSPlugin, Placeholder @python_2_unicode_compatible class AliasPluginModel(CMSPlugin): cmsplugin_ptr = models.OneToOneField(CMSPlugin, related_name='cms_aliasp...
import tuplespace ts = tuplespace.TupleSpace() print ts.set('event:1', 'some event') print ts.set('event:2', 'some event') while True: print ts.take('event*')
from datetime import datetime, timedelta from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from registration.managers import RegistrationManager from registration.user import User class RegistrationProfile(models.Model): """A simple profile which stores an activation ...
import unittest from pyasm.x86asm import assembler, CDECL, STDCALL, PYTHON from pyasm.x86cpToMemory import CpToMemory class test_python_funcs(unittest.TestCase): def test_simple_function(self): a = assembler() a.ADStr("hello_world", "Hello world!\n\0") a.AP("test_print", PYTHON) a.Ad...
from tornado import gen from tornadowebapi import exceptions from tornadowebapi.resource import Resource from tornadowebapi.resource_handler import ResourceHandler from tornadowebapi.traitlets import Unicode from remoteappmanager.webapi.decorators import authenticated class Container(Resource): """Represents a cont...
import Queue import threading import time import traceback from logger import Logger from task import ExecutableTask, Task class ThreadPool(object): def __init__(self): self._init_core_worker() def _init_core_worker(self): self.core_worker = CoreWorker() self.core_worker.setDaemon(True) ...
import datetime import unittest from types import GeneratorType from phoxpy import exceptions from phoxpy import xml from phoxpy import xmlcodec class XMLDecodeTestCase(unittest.TestCase): def test_decode_fallback(self): self.assertRaises(ValueError, xml.decode, '<foooooo/>') def test_decode_untyped(sel...
import os import sys try: from setuptools import setup # hush pyflakes setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( name='requests-aws', version='0.1.8', author='Paul Tax', aut...
from __future__ import unicode_literals from shop.models.defaults.order import Order # nopyflakes - materialize the default models from shop.models.defaults.order_item import OrderItem # nopyflakes - materialize the default models from shop.models.defaults.order_shipping import OrderShipping # nopyflakes - materiali...
"""Utilities to work with blueprints.""" from __future__ import print_function import os from chromite.lib import brick_lib from chromite.lib import workspace_lib BRICKS_FIELD = 'bricks' BSP_FIELD = 'bsp' _IMPLICIT_PACKAGES = ( 'virtual/target-os', 'virtual/target-os-dev', 'virtual/target-os-test', ) class ...
import os import tempfile from nose.tools import eq_, raises from helper import TestCase from appvalidator.zip import ZipPackage RESOURCES_PATH = os.path.join(os.path.dirname(__file__), 'resources') def get_path(fn): return os.path.join(RESOURCES_PATH, fn) class TestZipManager(TestCase): def setUp(self): ...
from django.db import models from django.core.exceptions import ValidationError import cyder from cyder.cydns.domain.models import Domain from cyder.cydns.models import CydnsRecord from cyder.cydns.validation import validate_name from cyder.cydns.mixins import ObjectUrlMixin from cyder.cydns.validation import validate_...
from __future__ import absolute_import, print_function import logging from time import time from urllib import urlencode from uuid import uuid4 from sentry.auth import Provider, AuthView from sentry.auth.exceptions import IdentityNotValid from sentry.http import safe_urlopen, safe_urlread from sentry.utils import json ...
""" =========================== Reading an inverse operator =========================== The inverse operator's source space is shown in 3D. """ import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator from mne.viz import set_3d_view print(__doc__) data_path = sample.data_path() subj...
""" Not stable therefore removed in the Beta. Might come back later. """ import time import socket import logging import gc class Portrange(object): def __init__(self): pass @staticmethod def get_kind(): """ return sensor kind """ return "mpportrange" @staticmetho...
import datetime import json import random import string import unicodedata import urllib import dns.resolver import config from aws import awsutils from db_utils import db def to_json(inst, cls, bonusProps=[]): """ Jsonify the sql alchemy query result. Inspired from http://stackoverflow.com/a/9746249 "...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBui...
""" Django dummy settings for docs project. """ import os import sys sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.path.join(os.getcwd(), os.pardir)) SITE_ID = 666 DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {"default": { "NAME": ":memory:", "ENGINE": "django.db.backends.sqlite3", }} INSTALLED_APPS ...
from fabric.api import * def ssh_config(host): from os.path import expanduser from paramiko.config import SSHConfig def hostinfo(host, config): hive = config.lookup(host) if 'hostname' in hive: host = hive['hostname'] if 'user' in hive: host = '%s@%s' % (hive[...
from __future__ import unicode_literals, print_function, division from django.db import models from editor_md.models import EditorMdField class Blog(models.Model): title = models.CharField(max_length=100, verbose_name="标题", blank=True) content = EditorMdField(imagepath="editor_md_image/", verbose_name="文章内容", b...