code
stringlengths
1
199k
import re import json from config.config import REPLY_PER_PAGE from exception import BadRequest, Unauthorized from helper.model_control import get_board, get_article, delete_article, \ edit_article, create_article from helper.permission import can_write, is_anybody, is_author, \ is_author_or_admin from helper.r...
"""Gathers all tests in the /tests/ subdirectory and runs them.""" import os import unittest from tests.test_utils import import_utils import_utils.prepare_lldb_import_or_exit() import happy_debugging import lldb def main(): # Add the custom print function to SBCommandReturnObject. lldb.SBCommandReturnObject.Printl...
import os from SCons.Script import * import SCons.Subst import tempfile import os def generate(env, **kw): env.Append(ENV = {'PATH' : os.environ['PATH']}) env.Tool('gcc') env.Tool('g++') env.Tool('gnulink') env.Tool('ar') env.Tool('as') env['PROGSUFFIX'] = ".elf" # used programs env['CC'] = "avr-gcc" env['CXX...
from todo import app from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine(app.config["DATABASE"], convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('multichoice', '0002_auto_20161203_0357'), ] operations = [ migrations.AlterField( model_name='mcquestion', name='point_value', ...
import os import sys import unittest import shutil sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import configgen.controllersConfig as controllersConfig shutil.copyfile(os.path.abspath(os.path.join(os.path.dirname(__file__), "resources/es_input.cfg.origin")), \ ...
__author__ = 'hhstore' ''' 功能: 解决文件读写的编码问题 依赖: codecs模块 说明: 1. 通过codecs模块,解决文件读写的编码问题. 2. 如下是标准写法. 3. 对文件读,作了类型判断. 4. 文件写,简单判断. ''' import codecs import os class BetterIO(object): def __init__(self): self.data = None def read(self, infile): if os.path.isfile(infile): # 有效的文件 ...
import re import unittest from csvkit.grep import FilteringCSVReader from csvkit.exceptions import ColumnIdentifierError class TestGrep(unittest.TestCase): def setUp(self): self.tab1 = [ ['id', 'name', 'i_work_here'], [u'1', u'Chicago Reader', u'first'], [u'2', u'Chicago ...
from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_zeelius_kraymunder.iff" result.attribute_template_id = 9 result.stfName("npc_name","human_base_male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def Luggage(): mala = [] take = input("O que você deseja levar na sua viagem?") mala.append(take) return mala x = Luggage() print(x)
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/furniture/cheap/shared_chest_s01.iff" result.attribute_template_id = 6 result.stfName("frn_n","frn_chest") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
import math def ncdf(mu, sigma, x): return (1+math.erf((x - mu)/sigma/math.sqrt(2)))/2 if __name__ == '__main__': mu,sigma = map(float, input().split()) x1 = float(input()) x2 = float(input()) print(round(100*(1-ncdf(mu, sigma, x1)), 2)) print(round(100*(1-ncdf(mu, sigma, x2)), 2)) print(rou...
from customers.views import TenantView, TenantViewRandomForm, TenantViewFileUploadCreate from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('', TenantView.as_view(), name="index"), path('sample-random/', TenantViewRandomForm.as_view()...
from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'^$', 'frontend.views.api_index'), url(r'^(?P<api_name>[a-z]+)$', 'frontend.views.api_view'), )
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from enum import Enum import base64 import hashlib import logging import re from dnf.i18n import _ import dnf.rpm.transaction import dnf.exceptions logger = logging.getLogger("dnf") RR_TYPE_OPENPGPKEY = ...
"""Define API endpoints for managing and searching buildroot overrides.""" import math from datetime import datetime from cornice import Service from cornice.validators import colander_body_validator, colander_querystring_validator from pyramid.exceptions import HTTPNotFound from sqlalchemy import func, distinct from s...
""" mxTextTools - A tools package for fast text processing. Copyright (c) 2000, Marc-Andre Lemburg; mailto:mal@lemburg.com Copyright (c) 2000-2001, eGenix.com Software GmbH; mailto:info@egenix.com See the documentation for further information on copyrights, or contact the author. All Rights Reserved. ""...
""" higwidgets/higentries.py entries related classes """ import gtk HIGTextEntry = gtk.Entry class HIGPasswordEntry(HIGTextEntry): """ An entry that masks its text """ def __init__(self): HIGTextEntry.__init__(self) self.set_visibility(False)
""" A simple (dumb) simulator to check the hub score calculation. """ from __future__ import print_function import sys import numpy as np from msmbuilder import msm_analysis steps = 10**6 # sample steps triples = [ (0, 1, 2), # (waypoint, source, sink) to test (0, 1, 3), (0, 1, 4) ] N = 11 T...
from enigma import * from datetime import datetime from Components.config import config def addMinutesToTime(entry, minutes): ret = entry + (minutes * 60) if ret >= 86400: ret -= 86400 return ret def getMinuteFromTime(entry): return int(entry % 3600 / 60) def getHourFromTime(entry): return int(entry / 3600) clas...
import re, os from autotest.client.shared import error from virttest import libvirt_vm, virsh def run_virsh_restore(test, params, env): """ Test command: virsh restore. Restore a domain from a saved state in a file 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. ...
import base64 import os import mimetypes from tastypie.fields import FileField from django.core.files.uploadedfile import SimpleUploadedFile class Base64FileField(FileField): """ https://gist.github.com/klipstein/709890 A django-tastypie field for handling file-uploads through raw post data. It uses bas...
from flask import Flask from celery import Celery app = Flask(__name__) app.config.from_object('zimbalaka.default_settings') celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) import zimbalaka.views
import threading import requests import shutil import os import time import gzip import datetime import xbmc import xbmcplugin import xbmcgui import xbmcaddon import xbmcvfs import sys from lib.common_variables import * from lib import xmltvmerger,listmerger if not xbmcvfs.exists(os.path.join(datapath,'download_folder'...
""" EasyBuild support for building and installing Bowtie, implemented as an easyblock @author: Cedric Laczny (Uni.Lu) @author: Fotis Georgatos (Uni.Lu) @author: Kenneth Hoste (Ghent University) @author: Jens Timmerman (Ghent University) """ from distutils.version import LooseVersion import glob import os import shutil ...
""" Raft is a script to create a reusable raft, elevate the nozzle and set the temperature. The default 'Activate Raft' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called. The raft script sets the temperature. If the "Activate Raft, Elevate Nozzle...
""" ============================================================================== Copyright (C) 2012 Hewlett-Packard Development Company, L.P. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software ...
import pickle def main(): filepath = 'test.pkl' try: favorite_color = {'lion': 'yellow', 'kitty': 'red'} with open(filepath, 'wb') as fd: pickle.dump(favorite_color, fd) except FileNotFoundError as ex: print('File not found, {}: {}.'.format(filepath, ex)) try: with open(filepath, 'rb') as fd: loaded =...
""" These are the elementary tests from OpenERPScenario: <http:///launchpad.net/~camptocamp/oerpscenario/> The aim here is to make the same feature tests in OpenERPScenario run in trytond_scenari on Tryton. YMMV! UNFINISHED """ import proteus from behave import * from .support.stepfuns import vAssertContentTable @step...
def square(x): ''' x: int or float. ''' result = x*x return result def fourthPower(x): ''' x: int or float. ''' result = (square(x))*(square(x)) return result
from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import ThreadingMixIn class ThreadingServer(ThreadingMixIn, HTTPServer): pass serveraddr = ('', 8765) srvr = ThreadingServer(serveraddr, SimpleHTTPRequestHandler) srvr.serve_forever()
from django.apps import AppConfig class CsPollsConfig(AppConfig): name = 'cs_polls'
import signal import sys from pprint import pprint import networkx as nx from PySide2.QtWidgets import QGraphicsView, QApplication from QNetworkxGraph.QNetworkxGraph import QNetworkxWidget, QNetworkxController from parseSMDSL import SMDSLparsing if __name__ == '__main__': app = QApplication(sys.argv) signal.sig...
from django.contrib.auth import get_user_model from django.contrib.auth import login from django.contrib.auth.models import Group from guardian.shortcuts import assign_perm, remove_perm, \ get_groups_with_perms, get_users_with_perms ADMIN_PERMISSIONS = [ 'view_resourcebase', 'download_resourcebase', 'ch...
import pytest from django.core.management import call_command from django.core.management.base import CommandError from pootle_store.constants import TRANSLATED from pootle_store.models import Unit @pytest.mark.cmd def test_test_checks_noargs(): """No args should fail wanting either --unit or --source.""" with ...
from ecl.grid import EclGrid from ecl.util.test import TestAreaContext from tests import EclTest class FKTest(EclTest): def test_cell_containment(self): grid_location = "local/ECLIPSE/faarikaal/faarikaal%d.EGRID" well_location = "local/ECLIPSE/faarikaal/faarikaal%d.txt" for i in range(1, 8):...
import re from django.utils.safestring import mark_safe from pootle.core.browser import get_table_headings from pootle.core.decorators import persistent_property from pootle.core.views.panels import TablePanel from pootle.i18n.dates import timesince class ChildrenPanel(TablePanel): panel_name = "children" _tabl...
""" formatting.py Contains functions for formatting and working with strings. The licensing for this module isn't solid, because I started working on this module before I had a proper system for tracking code licences. If your code is in this file and you have any queries, contact me by email at <lukeroge@gmail.com>! M...
import os.path import sickbeard from sickbeard import logger from sickbeard import encodingKludge as ek from sickbeard import processTV class PostProcesser(): def run(self): if not sickbeard.PROCESS_AUTOMATICALLY: return if not ek.ek(os.path.isdir, sickbeard.TV_DOWNLOAD_DIR): ...
from cwrap import BaseCEnum class FieldTypeEnum(BaseCEnum): TYPE_NAME = "field_type_enum" ECLIPSE_RESTART = None ECLIPSE_PARAMETER = None GENERAL = None UNKNOWN_FIELD_TYPE = None FieldTypeEnum.addEnum('ECLIPSE_RESTART', 1) FieldTypeEnum.addEnum('ECLIPSE_PARAMETER', 2) FieldTypeEnu...
import math from decorators import cached_property from rootpy.vector import LorentzVector, Vector3 from rootpy.extern.hep import pdg from rootpy import asrootpy from . import log; log = log[__name__] from .utils import dR, et2pt from .units import GeV from .hadhad.filters import IDNONE """ This module contains "mixin"...
from __future__ import unicode_literals import frappe import unittest from frappe.utils import nowdate, add_days test_dependencies = ["Shift Type"] class TestShiftAssignment(unittest.TestCase): def setUp(self): frappe.db.sql("delete from `tabShift Assignment`") def test_make_shift_assignment(self): shift_assignme...
"""Read a multiple sequence alignment in STOCKHOLM format. This file format is used by PFAM and HMMER. At present, all annotation information is ignored. See: - http://www.cgb.ki.se/cgb/groups/sonnhammer/Stockholm.html - HMMER manual """ import re from weblogoMod.corebio.utils import * from weblogoMod.corebio.s...
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...
import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for datas...
def substr(s, start, length=-1): if length < 0: length = len(s)-start return s[start:start + length] def sprintf(fmt, *args): return fmt % args def print_r(array): if not isinstance(array, dict): array = dict([(k, k) for k in array]) for k, v in array.items(): print "[%s] => ...
"""unipath.py - A two-class approach to file/directory operations in Python. Full usage, documentation, changelog, and history are at http://sluggo.scrapping.cc/python/unipath/ (c) 2007 by Mike Orr (and others listed in "History" section of doc page). Permission is granted to redistribute, modify, and include in commer...
import pyb led = pyb.LED(4) brightness = 0 fade_amount = 5 while True: led.intensity(brightness) brightness += fade_amount pyb.delay(30) if brightness > 255 or brightness < 0: fade_amount *= -1
from pyfaf.bugtrackers import bugzilla __all__ = ["RhelBugzilla"] class RhelBugzilla(bugzilla.Bugzilla): name = "rhel-bugzilla" def list_bugs(self, *args, **kwargs): abrt_specific = dict( status_whiteboard="abrt_hash", status_whiteboard_type="allwordssubstr", product=...
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
"""Classes to easily implement Qt-friendly computational tasks running in external threads or processes, with a simple API. """ import time import traceback import inspect import logging from Queue import Queue as tQueue from Queue import Empty from threading import Thread from multiprocessing import Process, Queue as ...
"""Very simple browser for testing purposes.""" import sys import argparse from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication try: from PyQt5.QtWebKitWidgets import QWebView except ImportError: QWebView = None try: from PyQt5.QtWebEngineWidgets import QWebEngineView except ImportError: ...
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from resigner.server import signed_req_required @signed_req_required @csrf_exempt def my_test_api_view(request): is_post = (request.method == 'POST') req = request.POST if is_post else request.GET test_data = req.get("...
import sys, os, glob import numpy as np import scipy import scipy.stats import argparse import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter parser = argparse.ArgumentParser() parser.add_argument('--dir', default=None, help='Directory with input data...
scalapack = False compiler = 'gcc' extra_compile_args += [ '-O3', '-funroll-all-loops', '-fPIC', ] libraries = ['gfortran'] mpi_prefix = '/softs/openmpi-gnu/' blas_lib_path = '/home/tjiang/softs/acml-4.0.1/gfortran64/lib/' lapack_lib_path = blas_lib_path library_dirs = [mpi_prefix + 'lib'] include_dirs ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: bigip_virtual_server short_description: Manage LTM virtual ser...
def barutil_function(x): return "barutil says: " + x
try: import json except ImportError: try: import simplejson as json except ImportError: from django.utils import simplejson as json from urllib import urlencode from urllib2 import urlopen from geopy.geocoders.base import Geocoder from geopy.util import logger, decode_page, join_filter from ...
import copy import glob import os import re import shlex import shutil import subprocess import sys from collections.abc import Iterable, Sequence from copy import deepcopy from itertools import combinations, tee from pathlib import Path, WindowsPath, PosixPath from shlex import quote from typing import Union, Dict, An...
""" Utilities that dont fit in other modules """ from log import log def num_args(f): """Returns the number of arguments received by the given function""" import inspect return len(inspect.getargspec(f).args) def smooth(_l, n=1): """Smooths the values in a list n times. You probably should be using hous...
"""Copyright (c) 2012 Sergio Gabriel Teves All rights reserved. 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 ...
import espressopp from espressopp import Int3D from espressopp import Real3D num_chains = 5 mon_per_chain = 100 L = 20 box = (L, L, L) bondlen = 0.97 rc = 1.5 skin = 2.5 dt = 0.00001 sigma = 1. temperature = 1. phi = 0. system ...
triangle = [list(map(int, line.split())) for line in open('triangle.txt').readlines()] max_sums = [] for i, line in enumerate(triangle): if i == 0: max_sums.append([line[0]]) else: max_sums.append([]) for j, value in enumerate(line): if j == 0: max_sums[-1].ap...
"""This module contain classes and methods with geometrical operations. The operations are done in the 2-D space It works with 2-D shapes represented by arrays. Thus, the calculations are based on matrix operations and linear algebra. """ import numpy as np class Triangle(object): """Class for dealing with geometri...
"""Test mdn.scrape.""" from __future__ import unicode_literals from json import dumps from mdn.models import FeaturePage from mdn.scrape import ( narrow_parse_error, scrape_page, scrape_feature_page, PageExtractor, PageVisitor, ScrapedViewFeature) from mdn.kumascript import kumascript_grammar from webplatformco...
import os import sys import logging from distutils import ccompiler from distutils.sysconfig import customize_compiler from pipes import quote from subprocess import Popen, PIPE pjoin = os.path.join if sys.version_info[0] >= 3: u = lambda x: x else: u = lambda x: x.decode('utf8', 'replace') def customize_mingw(...
from __future__ import division from __future__ import unicode_literals from activedata_etl.transforms import EtlHeadGenerator, get_test_result_content from activedata_etl.transforms.pulse_block_to_es import scrub_pulse_record, transform_buildbot from activedata_etl.transforms.unittest_logs_to_sink import process_unitt...
import calendar from datetime import date from django.core.management.base import BaseCommand from treeherder.intermittents_commenter.commenter import Commenter class Command(BaseCommand): """Management command to manually initiate intermittent failures commenter default is daily and non-test mode, use flags fo...
from collections import Counter def get_product_ids_and_quantities(basket): q_counter = Counter() for line in basket.get_lines(): if not line.product: continue q_counter[line.product.id] += line.quantity return dict(q_counter.most_common())
from datetime import datetime import uuid from sqlalchemy.orm import reconstructor, relationship, backref from sqlalchemy.schema import Column, ForeignKey, Table from sqlalchemy.types import Integer, Unicode, Boolean, DateTime from sqlalchemy import BigInteger from sqlalchemy.sql.expression import false, or_ from sqlal...
test_records = [ [{"doctype":"Campaign", "campaign_name":"_Test Campaign"}], [{"doctype":"Campaign", "campaign_name":"_Test Campaign 1"}], ]
import json from django.test import TestCase from django.urls import reverse from base.models.enums.education_group_categories import TRAINING, MINI_TRAINING, GROUP from base.tests.factories.certificate_aim import CertificateAimFactory from base.tests.factories.education_group_type import EducationGroupTypeFactory, Min...
{ 'name': 'Sentry', 'summary': 'Report Odoo errors to Sentry', 'version': '11.0.1.1.0', 'category': 'Extra Tools', 'website': 'https://odoo-community.org/', 'author': 'Mohammed Barsi,' 'Versada,' 'Nicolas JEUDY,' 'Odoo Community Association (OCA)', '...
import psutil, time onedayago = time.time() - 24 * 60 * 60 def kill_old(): for p in psutil.process_iter(): if p.create_time < onedayago: continue if len(p.username) != 8 or p.username == "whoopsie": continue print "Killing", p p.terminate() def monitor(interval): """R...
from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict): '''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Counter...
""" Views related to the video upload feature """ import urllib from boto import s3 import csv from uuid import uuid4 from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseNotFound from django.utils.translation import ugettext as _, ...
import etcd import importlib import os import pkgutil import six import socket import sys import threading import time import collectd import utils as tendrl_glusterfs_utils class PluginMount(type): def __init__(cls, name, bases, attrs): if not hasattr(cls, 'plugins'): cls.plugins = [] e...
import os, re, sys, time if os.system('mcompositor-test-init.py'): sys.exit(1) fd = os.popen('windowstack m') s = fd.read(5000) win_re = re.compile('^0x[0-9a-f]+') home_win = 0 for l in s.splitlines(): if re.search(' DESKTOP viewable ', l.strip()): home_win = win_re.match(l.strip()).group() if home_win == 0: ...
from vismach import * import hal import math import sys c = hal.component("scaragui") c.newpin("joint0", hal.HAL_FLOAT, hal.HAL_IN) c.newpin("joint1", hal.HAL_FLOAT, hal.HAL_IN) c.newpin("joint2", hal.HAL_FLOAT, hal.HAL_IN) c.newpin("joint3", hal.HAL_FLOAT, hal.HAL_IN) c.ready() d1 = 490.0 d2 = 340.0 d3 = 50.0 d4 =...
from __future__ import print_function import requests import sys import fedmsg from fedmsg.commands import BaseCommand class ReplayCommand(BaseCommand): """ Replay a message from the datagrepper history on your local bus. Example:: $ fedmsg-dg-replay --msg-id 2014-8909e1e9-2a46-4e53-9a0e-f5415a9bedcf ...
from __future__ import division, print_function, absolute_import from numpy import * def parLocator(keyWord,b,n,iDoNot,verbose): keyWord=keyWord.lower() iFocus=-1 icol = -1 for i in range(1, n): lineString=str(b[i]).lower() try: icol=lineString.index(':') except Value...
import os import shutil import numpy as np import nose from nose.plugins.skip import SkipTest import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.compat import subprocess from matplotlib.testing.compare import compare_images, ImageComparisonFailure from matplotlib.testing.decorators import _image_d...
import unittest from nose.tools import * # noqa; PEP8 asserts from webtest_plus import TestApp as WebtestApp # py.test tries to collect `TestApp` import mock from future.moves.urllib.parse import urlparse, urljoin, quote from rest_framework import status as http_status from flask import Flask from werkzeug.wrappers i...
import unittest from conary.lib import enum class EnumTest(unittest.TestCase): def testEnum(self): theEnum = enum.EnumeratedType("testenum", "foo", "bar") assert(theEnum.foo == "testenum-foo") assert(theEnum.values() == [ "testenum-foo", "testenum-bar" ]) self.assertRaises(AttributeE...
from __future__ import absolute_import from django.contrib.auth.models import UserManager from django.utils.timezone import now as timezone_now from zerver.models import UserProfile, Recipient, Subscription, Realm, Stream import base64 import ujson import os import string from six.moves import range from typing import ...
''' @author: yyk ''' import re import linux import bash class IpAddress(object): ''' Help to save and compare IP Address. ''' def __init__(self, ip): self.ip_list = ip.split('.', 3) self.ips = [] for item in self.ip_list: if not item.isdigit(): raise E...
"""Helpers to deal with Cast devices.""" from typing import Optional, Tuple import attr from pychromecast.const import CAST_MANUFACTURERS from .const import DEFAULT_PORT @attr.s(slots=True, frozen=True) class ChromecastInfo: """Class to hold all data about a chromecast for creating connections. This also has th...
from oslo.config import cfg from quantum.plugins.linuxbridge.common import config from quantum.tests import base class ConfigurationTest(base.BaseTestCase): def test_defaults(self): self.assertEqual(2, cfg.CONF.AGENT.polling_interval) self.assertEqual('sudo', ...
import random import unittest from robot.output.loggerhelper import LEVELS from robot.reporting.jsmodelbuilders import JsBuildingContext from robot.utils.asserts import assert_equals class TestStringContext(unittest.TestCase): def test_add_empty_string(self): self._verify([''], [0], []) def test_add_str...
from beritest_tools import BaseBERITestCase from nose.plugins.attrib import attr class test_cp2_clwu_unpriv(BaseBERITestCase): @attr('capabilities') def test_cp2_clwu_64aligned(self): '''Test a 64-bit aligned word load via an unprivileged capability''' self.assertRegisterEqual(self.MIPS.a0, 0x00...
""" bursts.py should work as import bursts [list of bursts] = bursts.bursts(docs2date, date2countC=backgroundcounts, resolution='week', doc2relevance={}, burstdetector='kleinberg', normalise=True, bg_smooth=True) where doc2date: is a dictionary from document id to a datetime (or date) object doc2relevance: is ...
import contextlib from taskflow import exceptions as exc from taskflow.openstack.common import uuidutils from taskflow.persistence import logbook from taskflow.utils import misc class PersistenceTestMixin(object): def _get_connection(self): raise NotImplementedError() def test_logbook_save_retrieve(self...
import logging import os import shutil import tempfile import time import traceback from collections import OrderedDict from pathlib import Path from google.protobuf.message import DecodeError import apache_beam as beam from apache_beam import coders from apache_beam.portability.api.beam_interactive_api_pb2 import Test...
""" Description: Export a Siconos mechanics-IO HDF5 file to raw data .dat file """ from siconos.io.vview import VView, VRawDataExportOptions from siconos.io.mechanics_hdf5 import MechanicsHdf5 if __name__=='__main__': # Parse command-line opts = VRawDataExportOptions() opts.parse() ## Options and config...
import re import mock import requests from oslo.serialization import jsonutils from six.moves import zip_longest from nailgun.test import base from nailgun.orchestrator import tasks_templates from nailgun.settings import settings class TestMakeTask(base.BaseTestCase): def test_make_ubuntu_sources_task(self): ...
from django.conf.urls import patterns # noqa from django.conf.urls import url # noqa from openstack_dashboard.dashboards.identity.domains import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^create$', views.CreateDomainView.as_view(), name='create'), url(r'^(...
import os from types import NoneType from xmlrpclib import DateTime import mock from nose.tools import * from webtest_plus import TestApp from tests.base import OsfTestCase from tests.factories import (UserFactory, ProjectFactory, NodeFactory, AuthFactory, PointerFactory, DashboardFactory, FolderFactory, Registrati...
from gym.spaces import Box, Dict, Discrete, Tuple, MultiDiscrete import numpy as np import unittest import ray from ray.rllib.agents.registry import get_agent_class from ray.rllib.examples.env.random_env import RandomEnv from ray.rllib.models.tf.fcnet import FullyConnectedNetwork as FCNetV2 from ray.rllib.models.tf.vis...
import argparse import io import os import sys from gen_splits import N_TASKS, ITEMS_PER_TASK def check_output(mr_out_dir): names = [_ for _ in os.listdir(mr_out_dir) if not _.startswith("_")] if len(names) != N_TASKS: raise RuntimeError("found %d output files (expected: %d)" % ...
from sahara import exceptions as ex from sahara.i18n import _ from sahara.service import api import sahara.service.validations.base as b NODE_GROUP_TEMPLATE_SCHEMA = { "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 50, ...