code
stringlengths
1
199k
import logging from django.conf import settings from github2.client import Github from vcs_support.base import BaseContributionBackend import base64 import os import urllib import urllib2 log = logging.getLogger(__name__) GITHUB_URLS = ('git://github.com', 'https://github.com', 'http://github.com') GITHUB_TOKEN = getat...
''' Compare Turbustat's Delta-variance to the original IDL code. ''' from turbustat.statistics import DeltaVariance from turbustat.simulator import make_extended import astropy.io.fits as fits from astropy.table import Table import matplotlib.pyplot as plt import astropy.units as u import seaborn as sb font_scale = 1.2...
from statsy.helpers import get_correct_value_field class ValueDescriptor(object): def get_field_name(self, value_type): return '_'.join([value_type, 'value']) def __init__(self, value_types): self.value_types = value_types def __get__(self, obj, objtype): for value_type in self.value...
import os DEBUG = True ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { "default": { "ENGINE": "tenant_schemas.postgresql_backend", # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. "NAME": "tenant_tutorial", # Or path to database file if using...
"""The client and server for a basic ping-pong style heartbeat. """ import errno import os import socket from threading import Thread import zmq from IPython.utils.localinterfaces import localhost class Heartbeat(Thread): "A simple ping-pong style heartbeat that runs in a thread." def __init__(self, context, ad...
from ConvertFile import main, find_zombie_processes import demistomock as demisto from CommonServerPython import entryTypes import logging import pytest import glob import os import subprocess RETURN_ERROR_TARGET = 'ConvertFile.return_error' @pytest.fixture(autouse=True) def set_logging(caplog): """set logging to D...
from behave import when, then from test_app.models import BehaveTestModel @when(u'I save the object') def save_object(context): BehaveTestModel.objects.create(name='Behave Works', number=123) @then(u'I should only have one object') def should_have_only_one_object(context): assert 1 == BehaveTestModel.objects.co...
import urllib import urllib2 data = urllib.urlencode({'color': '#ff00ff'}) req = urllib2.Request('https://api.cilamp.se/v1/testsystem', data) urllib2.urlopen(req).read()
import smtplib from decimal import Decimal from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group as DjangoGroup, GroupManager as _GroupManager, Permission, PermissionsMixin, ) from ...
import struct, math from data import * from actions import * from filters import SWFFilterFactory class SWFStream(object): """ SWF File stream """ FLOAT16_EXPONENT_BASE = 15 def __init__(self, file): """ Initialize with a file object """ self.f = file self._bits_pending = 0 ...
import http.server import socketserver import socket def set_proc_name(newname): """Change the process name using libc.so.6""" from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary('libc.so.6') buff = create_string_buffer(len(newname) + 1) buff.value = newname.encode("ascii") ...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/component/armor/shared_armor_segment_ris_acklay.iff" result.attribute_template_id = -1 result.stfName("craft_armor_ingredients_n","armor_segment_ris_acklay") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS ...
from cachetools import LRUCache, TTLCache from dogpile.cache import register_backend from dogpile.cache.api import CacheBackend, NO_VALUE from dorthy.security import crypto def sha2_mangle_key(key): return crypto.secure_hash(key, crypto.SecureHashAlgorithms.SHA2) class LRULocalBackend(CacheBackend): def __init_...
import pytz import logging import datetime from pytz import timezone import simplejson as json from tastypie.api import Api from django.conf import settings from django.test import TestCase from monlog.log.views import save_label from datetime import timedelta, datetime from monlog.log.models import LogMessage,Label fr...
from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_murra_hue.iff" result.attribute_template_id = 9 result.stfName("monster_name","murra") #### BEGIN MODIFICATIONS #### result.setStringAttribute("radial_filename", "radials/player_pet.py") result.options_mask...
from collections import namedtuple import logging import action from action import actions from clock import bg from clock import utils logger = logging.getLogger(__name__) Alarm = namedtuple('Alarm', 'id name days hour minute next_run, action, param') Alarm.__new__.__defaults__ = (None, None, None, None, None, None, N...
import numpy as np import sys __all__ = [ "xperm", "rndperm","mcperm" ] def _mcperm(mtx, eps = 1e-3, ntry=None, seed=None): sz = len(mtx[0]) idx = np.asarray(xrange(sz),int) prm = 0 prm2 = 0 pstride = 100*sz i=0 if not seed is None: np.random.seed(seed) while True: np.ran...
from rest_framework.response import Response from rest_framework.decorators import api_view from biohub.core.routes import register_api, url from .models import TestModel register_api(r'^my_plugin/', [ url( r'^$', api_view(['GET'])(lambda r: Response(list(TestModel.objects.all()))), name='in...
from __future__ import unicode_literals import pytest from mock import Mock from ..vocab import Vocab from ..tokens import Doc, Span, Token from ..tokens.underscore import Underscore def test_create_doc_underscore(): doc = Mock() doc.doc = doc uscore = Underscore(Underscore.doc_extensions, doc) assert u...
import os from allauth.socialaccount import providers from allauth.socialaccount.models import SocialApp from django.contrib.sites.models import Site from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Automatically create default SocialApp for each provider' def handle(self,...
import struct import dns.exception import dns.rdata import dns.tokenizer class CAA(dns.rdata.Rdata): """CAA (Certification Authority Authorization) record @ivar flags: the flags @type flags: int @ivar tag: the tag @type tag: string @ivar value: the value @type value: string @see: RFC 684...
from myhdl import * def mm_cnt(clock, reset, out): @always_seq(clock.posedge, reset=reset) def rtl(): if out <= 30: out.next = out + 1 else: out.next = out - 1 return rtl clock = Signal(bool(0)) reset = ResetSignal(0, active=0, async=True) out = Signal(intbv(0, min=0,...
""" ============================================== groups - Group Management for the Pushover API ============================================== This module defines functions and classes used for handling groups on the Pushover servers. Users can be added, removed, activated, or deactivated from a group. Information ...
import BoostBuild t = BoostBuild.Tester(use_test_config=False) t.write("a.cpp", "int main() {}\n") t.write("jamroot.jam", "import standalone ;") t.write("standalone.jam", """\ import alias ; import project ; project.initialize $(__name__) ; project standalone ; local pwd = [ PWD ] ; alias x : $(pwd)/../a.cpp ; alias ru...
from __future__ import print_function, absolute_import import time from collections import OrderedDict import torch from .evaluation_metrics import cmc, mean_ap from .feature_extraction import extract_cnn_feature from .utils.meters import AverageMeter def extract_features(model, data_loader, print_freq=1, metric=None):...
from __future__ import unicode_literals from functools import update_wrapper from django.contrib import admin from django.contrib import messages from django.core.exceptions import PermissionDenied from django.shortcuts import render from django.utils.encoding import force_text from django.utils.translation import uget...
"""Provides the %bucket{} function for path formatting. """ from __future__ import (division, absolute_import, print_function, unicode_literals) from datetime import datetime import re import string from itertools import tee, izip from beets import plugins, ui class BucketError(Exception): p...
from .lin_op import LinOp import numpy as np from ..utils.cuda_codegen import indent, sub2ind, ind2sub class subsample(LinOp): """Samples every steps[i] pixel along axis i, starting with pixel 0. """ def __init__(self, arg, steps): self.steps = self.format_shape(steps) self.orig_shape...
class Solution: # @param {ListNode[]} lists # @return {ListNode} def mergeKLists(self, lists): n = len(lists) if n == 0 : return None if n == 1: return lists[0] mid = n/2 l = self.mergeKLists(lists[:mid]) r = self.mergeKLists(lists[mid:...
import os import sys import urlparse from kombu import Exchange, Queue sys.path.append('.') redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/") if not redis_url.endswith("/"): redis_url += "/" BROKER_URL = redis_url + "1" # REDIS_CELERY_TASKS_DATABASE_NUMBER = 1 CELERY_RESULT_BACKEND = redis_url + "...
from __future__ import absolute_import import os from .utils import mkdir_p def write_jobfile(cmd, jobname, pbspath, scratchpath, nodes=1, ppn=1, gpus=0, mem=4, ndays=1, queue=''): """ Create a job file. Parameters ---------- cmd : str Command to execute. jobname : st...
import random, string import redis import ledis from redis_import import copy, scan, set_ttl rds = redis.Redis() lds = ledis.Ledis(port=6380) def random_word(words, length): return ''.join(random.choice(words) for i in range(length)) def get_words(): word_file = "/usr/share/dict/words" words = open(word_fil...
from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # 66 0F 3A 14 /r ib # PEXTRB reg/m8, xmm2, imm8 Buffer = bytes.fromhex('660f3a142011') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opc...
__all__ = ["HierarchicalStatusAttr"] import string, types from pyasm.common import * from pyasm.search import SObjectAttr from .pipeline import Pipeline from .status_attr import * class HierarchicalStatusAttr(SObjectAttr): '''A more complex attribute that uses any number of pipelines''' def __init__(self, name,...
import Cellule import Actions import MainMenuBar import MainToolBar import View2D import GraphEditor import Console import CommandLine from PyQt4 import Qt mainWinSIP = Cellule.toSIP( Cellule.appli.mainWin, Qt.QMainWindow ) Actions.createMainWindowActions( mainWinSIP ) mainMenuBar = MainMenuBar.Widget( mainWinSIP ) mai...
# Copyright (c) 20131 Torrent-TV.RU import xbmc import xbmcaddon import xbmcgui import sys import socket import os import threading import subprocess import random import json import urllib import copy import time import defines from adswnd import AdsForm DEFAULT_TIMEOUT = 122 def LogToXBMC(text, type = 1): ttext ...
import argparse import time import gettext from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from fabtotum.utils.translation import _, setLanguage from fabtotum.fabui.config import ConfigService from fabtotum.fabui.gpusher import GCodePusher from fabtotum.fabui.constants i...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pbspy', '0006_auto_20160501_1728'), ] operations = [ migrations.AddField( model_name='player', name='ingame_stack', f...
from contextlib import contextmanager import os from PyQt5.QtCore import ( QAbstractListModel, QModelIndex, Qt, pyqtSignal, ) from PyQt5.QtGui import QCursor, QIcon from PyQt5.QtWidgets import ( QFileDialog, QGroupBox, QMenu, ) from plover import _ from plover.config import DictionaryConfig ...
aliases = [ "number_of_households = building.number_of_agents(household)", "number_of_non_home_based_jobs = building.aggregate(job.home_based_status==0)", "number_of_home_based_jobs = building.aggregate(job.home_based_status==1)", "vacant_residential_units = clip_to_zero(building.residen...
import os import sys sys.plugins_path = [] from umit.pm.core.i18n import _ from umit.pm.core.const import PM_DEVELOPMENT, PM_PLUGINS_TEMP_DIR from umit.pm.core.atoms import generate_traceback from umit.pm.core.logger import log from umit.pm.gui.plugins.atoms import Version, DepDict from umit.pm.gui.plugins.core import ...
""" Family Lines, a Graphviz-based plugin for Gramps. """ from functools import partial import html import logging LOG = logging.getLogger(".FamilyLines") from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.lib import EventRoleType, EventType, Person, PlaceType, Date fr...
subS = '' print "s = " + s for x in range(len(s)-1): tmpS = s[x] for y in range(x+1, len(s)): if tmpS[-1] <= s[y]: tmpS = tmpS + s[y] else: break if len(tmpS) > len(subS): subS = tmpS print "Longest substring in alphabetical order is: " + subS
''' Scroll View =========== .. versionadded:: 1.0.4 The :class:`ScrollView` widget provides a scrollable/pannable viewport that is clipped at the scrollview's bounding box. Scrolling Behavior ------------------ The ScrollView accepts only one child and applies a viewport/window to it according to the :attr:`scroll_x` a...
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 ...
default_app_config = 'community.apps.CommunityConfig'
import json import bottle import data.store api = bottle.Bottle(__name__) collections = {} @api.route("/collections") def get_collections(): """Returns a list of collections.""" global collections return collections @api.route("/collections/<name>") def get_collection(name): global collections retur...
from string import digits, punctuation from string import ascii_lowercase as lowercase from string import ascii_uppercase as uppercase from String.Transform import TranslatorFactory class Finished( Exception ): pass setQuoteChars = frozenset( '"\'' ) # '"' + "'" setAsciiAlpha = frozenset( lowercase + uppercase ) ...
""" /*************************************************************************** Common Plugins settings NextGIS ------------------- begin : 2014-10-31 git sha : $Format:%H$ copyright : (C) 2014 by NextGIS email ...
""" Do some data-work 烦的时候写写注释 By H.YC """ from __future__ import print_function import cPickle import sys import os import numpy as np import sklearn from sklearn import linear_model, datasets, metrics from sklearn.cross_validation import train_test_split from sklearn.neural_network import BernoulliRBM from sklearn.pi...
import os.path import re import time from spacewalk.common import rhnCache from spacewalk.common.rhnConfig import CFG from spacewalk.server import rhnSQL import domain CACHE_PREFIX = "/var/cache/rhn/" class ChannelMapper: """ Data Mapper for Channels to the RHN db. """ def __init__(self, pkg_mapper, erratum_map...
""" This page is in the table of contents. ==Overview== ===Introduction=== Skeinforge is a GPL tool chain to forge a gcode skein for a model. The tool chain starts with carve, which carves the model into layers, then the layers are modified by other tools in turn like fill, comb, tower, raft, stretch, hop, wipe, fillet...
import os import sys import urllib import urllib2 import re import shutil import zipfile import time import xbmc import xbmcgui import xbmcaddon import xbmcplugin import plugintools import time from datetime import datetime addonName = xbmcaddon.Addon().getAddonInfo("name") addonVersion = xbmcaddon.Add...
import os from inprocess.demo.utilities import indicator_to_XML_writer from inprocess.travis.opus_core.indicator_framework.representations.indicator import Indicator indicators = { 'zone_population':Indicator( dataset_name = 'zone', attribute = 'urbansim.zone.population'), 'gridcell_population':Indi...
import common.utils if common.utils.python_major_version() < 3: import Tkinter as tkinter else: import tkinter import common.i18n as i18n from common.utils import hsv import math ProgW = 50 ProgH = 20 Period = 10 PeriodInc = 2 Delay = 100 class ProgressBar(tkinter.Frame): def __init__(self, root, onstop, *arg...
from __future__ import print_function from numpy import * from random import uniform import IMP from IMP.isd import Scale, HybridMonteCarlo import IMP.test vel_keys_xyz = [IMP.FloatKey("vx"), IMP.FloatKey("vy"), IMP.FloatKey("vz")] vel_key_nuisance = IMP.FloatKey("vel") kB = 1.381 * 6.02214 / 4184.0 class TestHybridMon...
from django.db import connection class GenerateViewsetQuery(object): def generate_query_sql(self, request): qset = self.get_queryset() # apply filters # get sql for the query that should be run for backend in list(self.filter_backends): qset = backend().filter_queryset(re...
from __future__ import absolute_import, unicode_literals from django.utils.translation import ugettext as _ def get_title(article): """Utility function to format the title of an article...""" return truncate_title(article.title) def truncate_title(title): """Truncate a title (of an article, file, image etc)...
cfg_filename = '/path/to/the/sframe/config.xml' sys_uncerts = { # 'name' : {'item name': 'item value', ...}, 'jec_up' : {'jecsmear_direction':'up'}, 'jec_down' : {'jecsmear_direction':'down'}, 'jer_up' : {'jersmear_direction':'up'}, 'jer_down' : {'jersmear_direction':'down'},...
"""Test runner for all Ansible tests.""" from __future__ import absolute_import, print_function import errno import os import sys from lib.util import ( ApplicationError, display, raw_command, ) from lib.delegation import ( delegate, ) from lib.executor import ( command_posix_integration, comman...
from hachoir_py3.core.tools import (humanDatetime, humanDuration, timestampUNIX, timestampMac32, timestampUUID60, timestampWin64, durationWin64, durationMillisWin64) from hachoir_py3.field import Bits, FieldSet from datetime import datetime class G...
from __future__ import absolute_import import numpy, pycbc from pycbc.types import real_same_precision_as from pycbc.weave import inline from pycbc import WEAVE_FLAGS if pycbc.HAVE_OMP: omp_libs = ['gomp'] omp_flags = ['-fopenmp'] else: omp_libs = [] omp_flags = [] def chisq_accum_bin_numpy(chisq, q): ...
""" classes/utils for Kerberos principal name validation/manipulation """ import re import six from ipapython.ipautil import escape_seq, unescape_seq if six.PY3: unicode = str REALM_SPLIT_RE = re.compile(r'(?<!\\)@') COMPONENT_SPLIT_RE = re.compile(r'(?<!\\)/') def parse_princ_name_and_realm(principal, realm=None):...
'''FakeTransport implements dummy interface for Transport.''' from transport import Transport class FakeTransport(Transport): def __init__(self, device, *args, **kwargs): super(FakeTransport, self).__init__(device, *args, **kwargs) def _open(self): pass def _close(self): pass def...
from module.plugins.Account import Account from module.common.json_layer import json_loads class RapidgatorNet(Account): __name__ = "RapidgatorNet" __type__ = "account" __version__ = "0.09" __description__ = """Rapidgator.net account plugin""" __license__ = "GPLv3" __authors__ = [(...
class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: host: description: - Specifies the DNS host name or address for connecting to the remote device over the specified transport. The value of host is used as the destination address fo...
from builtins import filter import re import six import datetime import pytz import requests from jinja2 import Template from bugwarrior.config import asbool, aslist, die from bugwarrior.services import IssueService, Issue import logging log = logging.getLogger(__name__) class PagureIssue(Issue): TITLE = 'paguretit...
import re import sys import urlparse import urllib2 import urllib from core import config from core import logger from core import scrapertools from core.item import Item __channel__ = "streamtime" __category__ = "F" __type__ = "generic" __title__ = "streamtime" __language__ = "IT" host = "http://streamtime.altervista....
import sys import SCons import CmdLineOpts, SConsOpts, StaticHelp, TestUtil def Configure(args, env): env.Replace(AvidaUtils_path = __path__) # Load platform-specific configuration and default options. env.Tool('PlatformTool', toolpath = __path__) # Load custom options file: if user specified the customOptions ...
import server import logging from suds import WebFault from util import update_template import copy import json log = logging.getLogger(__name__) class AttributeTest(server.SoapServerTest): """ Test for attribute-based functionality """ def test_get_network_attrs(self): net = self.create_net...
import os import subprocess from ipaplatform.paths import paths import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_plugins.integration import tasks CLIENT_KEYTAB = paths.KRB5_KEYTAB class TestForcedClientReenrollment(IntegrationTest): """ Forced client re-enrollment ...
""" Image recognition and overlap matching. """ __revision__ = "$Rev: 2006 $" __date__ = "$Date: 2007-08-20 06:02:52 +0530 (Mon, 20 Aug 2007) $" __author__ = "$Author: johann $"
""" This module contains: * the class Section, which acts as a data structure for section attributes. """ import copy import re import rose class Section(object): """This class stores the data and metadata of an input section. The section is ignored if any ignored_reason keys exist, and contains errors if ...
''' Solving initial value problem using 4th order Runge-Kutta method. Sine function is calculated using its derivative, cosine. ''' import math def rk4(x, y, yprime, dx = 0.01): # x, y , derivative, stepsize k1 = dx * yprime(x) k2 = dx * yprime(x + dx/2.0) k3 = dx * yprime(x + dx/2.0) k4 = dx * yprime(x + dx) re...
test = { 'name': 'Question 9', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> import pandas as pd >>> d = pd.read_csv('q09.csv') >>> len(d) 10 >>> np.all(d.sum() == [1544, 1440, 1268]) True""", 'hidden': Fa...
import time import numpy as np from scipy.sparse import isspmatrix_csc, coo_matrix import cyipopt class DataHelper: """ SciPy sparse matrix slicing is slow, as stated here: https://stackoverflow.com/questions/42127046/fast-slicing-and-multiplication-of-scipy-sparse-csr-matrix Profiling confi...
import sys sys.path = [".."] + sys.path import CppHeaderParser testScript = "" testCaseClasses = [] def main(): #init testScript with boiler plate code global testScript global testCaseClasses testScript = """\ import unittest from test import test_support import sys sys.path = [".."] + sys.path import ...
from django.contrib import admin from notification.models import Notification class NotificationAdmin(admin.ModelAdmin): pass admin.site.register(Notification, NotificationAdmin)
import xbmcgui import urllib.request, urllib.parse, urllib.error import time start = time.time() class customdownload(urllib.request.FancyURLopener): version = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' def silent_download(url, dest): cu...
import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config from core import unpackerjs def test_video_exists( page_url ): logger.info("[streamcloud.py] test_video_exists(page_url='%s')" % page_url) data = scrapertools.cache_page( url = page_url ) ...
from openerp import models, api from datetime import datetime class StockTransferDetails(models.TransientModel): _inherit = 'stock.transfer_details' @api.one def do_detailed_transfer(self): result = super(StockTransferDetails, self).do_detailed_transfer() self.picking_id._catch_operations() ...
""" Bookmarks module. """ from __future__ import absolute_import from collections import namedtuple DEFAULT_FIELDS = [ 'id', 'course_id', 'usage_id', 'block_type', 'created', ] OPTIONAL_FIELDS = [ 'display_name', 'path', ] PathItem = namedtuple('PathItem', ['usage_key', 'display_name'])
from openerp import fields, models class ResCompany(models.Model): _inherit = 'res.company' invoice_unpaid_margin = fields.Integer( string="Maturity Margin", help="Days after due date to set an invoice as unpaid")
from rest_framework import serializers from taiga.base.serializers import (Serializer, TagsField, NeighborsSerializerMixin, PgArrayField, ModelSerializer) from taiga.mdrender.service import render as mdrender from taiga.projects.validators import ProjectExistsValidator from taiga.projects.notifications.validato...
import json from django.contrib.contenttypes.models import ContentType from django.core.files.base import ContentFile from django.test import TestCase from django_date_extensions.fields import ApproximateDate from pombola.core import models from pombola.core.popolo import get_popolo_data from pombola.images.models impo...
""" This module provides a central location for defining default behavior. Throughout the package, these defaults take effect only when the user does not otherwise specify a value. """ try: # Python 3.2 adds html.escape() and deprecates cgi.escape(). from html import escape except ImportError: from cgi impo...
""" Unit tests for preview.py """ import unittest import preview import pyparsing class LatexRenderedTest(unittest.TestCase): """ Test the initializing code for LatexRendered. Specifically that it stores the correct data and handles parens well. """ def test_simple(self): """ Test th...
import os import os.path import subprocess import stat import sys import faust convert_cmd = faust.config.get("facsimile", "convert") tile_dir = "/".join((faust.config.get("facsimile", "dir"), "ptif")) facs_dir = "/".join((faust.config.get("facsimile", "dir"), "tif")) for root, dirs, files in os.walk(facs_dir): for f ...
from django.dispatch import receiver from .signals import order_creator_finished from shoop.notify import Event, Variable from shoop.notify.typology import Model, Email, Language, Phone class OrderReceived(Event): identifier = "order_received" order = Variable("Order", type=Model("shoop.Order")) customer_em...
import logging import superdesk from superdesk.resource import Resource from superdesk.services import BaseService from apps.auth.errors import CredentialsAuthError from superdesk import get_resource_service logger = logging.getLogger(__name__) class ChangePasswordResource(Resource): schema = { 'username': ...
from superdesk.resource import Resource, text_with_keyword CONTACTS_PRIVILEDGE = "contacts" VIEW_CONTACTS = "view_contacts" class ContactsResource(Resource): """Resource class for contact items A contact can either be for an individual or for an organisation """ schema = { # flag to mark the con...
import os Import ('plugin_base') Import ('env') PLUGIN_NAME = 'hello' plugin_env = plugin_base.Clone() plugin_sources = Split( """ %(PLUGIN_NAME)s_datasource.cpp %(PLUGIN_NAME)s_featureset.cpp """ % locals() ) libraries = [ '' ] # eg 'libfoo' libraries.append('boost_system%s' % env['BOOST_APPEND']) libr...
""" ================ NoCmodel basic models for testing ================ This package includes: * Module basic_channel * Module basic_ipcore * Module basic_protocol * Module basic_router * Module intercon_model * Module basic_noc_codegen """ from basic_channel import * from basic_ipcore import * from basic_protocol impo...
import spack.container.writers as writers def test_manifest(minimal_configuration): writer = writers.create(minimal_configuration) manifest_str = writer.manifest for line in manifest_str.split('\n'): assert 'echo' in line def test_build_and_run_images(minimal_configuration): writer = writers.cre...
from gofer.messaging.consumer import Consumer from gofer.messaging import Producer, Reader, Exchange, Queue N = 10 class Address(object): def __init__(self, address): self.address = address self.parts = address.split('/') @property def exchange(self): if len(self.parts) > 1: ...
from __future__ import print_function, division, absolute_import from msmbuilder.utils import KDTree import numpy as np X1 = 0.3 * np.random.RandomState(0).randn(500, 10) X2 = 0.3 * np.random.RandomState(1).randn(1000, 10) + 10 def test_kdtree_k1(): kdtree = KDTree([X1, X2]) dists, inds = kdtree.query([ ...
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTe...
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTe...
""" Utility functions """ from IPython.display import HTML def inline_map(m): """From http://nbviewer.ipython.org/gist/rsignell-usgs/ bea6c0fe00a7d6e3249c.""" m._build_map() srcdoc = m.HTML.replace('"', '&quot;') embed = HTML('<iframe srcdoc="{srcdoc}" ' 'style="width: 100%; height:...
from collections import OrderedDict from typing import Dict, Type from .base import CloudRedisTransport from .grpc import CloudRedisGrpcTransport from .grpc_asyncio import CloudRedisGrpcAsyncIOTransport _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = Cloud...