content
stringlengths
4
20k
import ir import StringIO instr_types = ['assertfail', 'binop', 'binopip', 'call', 'compare', 'const', 'copy', 'excmatch', 'foriter', 'function', 'getattr', 'getexc', 'getitem', 'getiter', 'getlocalsdict', 'getslice', 'global', 'import', 'jumpif', 'jumpifnot', 'listappend', 'makeclass', 'makefunction', 'makelist', ...
from shinken_test import * class GoodArbiter(ArbiterLink): # To lie about satellites def ping(self): print "Dummy OK for", self.get_name() self.set_alive() def have_conf(self, i): return True def do_not_run(self): pass class GoodScheduler(SchedulerLink): # To li...
"""BlueNet: and out of the blue network to experiment with shake-shake.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections # Dependency imports import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from ...
#!/usr/bin/env python ''' sphinx_pipe.py - this file is part of S3QL (http://s3ql.googlecode.com) Implements a Sphinx extension that provides a `pipeinclude` directive to include the output of a program. Copyright (C) 2008-2011 Nikolaus Rath <<EMAIL>> This program can be distributed under the terms of the GNU GPLv3...
#!/usr/bin/env python from os.path import join, dirname import sys import os import glob def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('dsolve',parent_package,top_path) con...
import errno import os import shelve import time import sys import appdirs from plexapi.server import PlexServer import requests TVST_CLIENT_ID = 'DksvfcwLfe6tk7-K-bAf' TVST_CLIENT_SECRET = 'BLAtFZJqah5lqrQZSlLLDHGpff5rJw2xa_iDyR9N' _dirs = appdirs.AppDirs('plex-tvst-sync') try: os.makedirs(_dirs.user_cache_dir...
#!/usr/bin/env python # coding: utf-8 from __future__ import unicode_literals import shutil # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from test.helper import FakeYDL from ananse_dl.cache import Cache def _is_empty...
from lixian_query import ExactQuery from lixian_query import SearchQuery from lixian_query import query from lixian_query import bt_query import lixian_hash_bt import lixian_url import lixian_encoding import re ################################################## # queries #############################################...
''' This module defines the classes wrapping the SEXP FSM structures. In particular: - :class:`SexpFsm` which wraps the basic SEXP fsm - :class:`BoolSexpFsm` which wraps a boolean SEXP fsm ''' from pynusmv_lower_interface.nusmv.fsm.sexp import sexp as _sexp from pynusmv.fsm import SymbTable f...
from .kernel import _future_wait, new_task, sleep from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor __all__ = [ 'run_in_executor', 'run_blocking', 'run_cpu_bound', 'set_blocking_executor', 'set_cpu_executor' ] _MAX_BLOCKING_THREADS = 16 _default_blocking_executor = None _default_cpu_executor = N...
import logging from openerp import models, fields, api from datetime import date from ..boleto.document import Boleto from ..boleto.document import BoletoException _logger = logging.getLogger(__name__) class AccountMoveLine(models.Model): _inherit = 'account.move.line' date_payment_created = fields.Date( ...
#!/usr/bin/env python # coding:utf-8 u"""The first lib.""" import json import codecs import re import libformatconv as lfc def _compile_regexp(keywords): u"""Function compiles regexp and adds it to the dictionary""" for group_name, group_def in keywords.iteritems(): for keyword_name, reg_exp_def_list ...
# -*- coding: utf-8 -*- import csv import json import sys def produce_key(*args): """ Produce key. Returns: str: key """ key = "" for arg in args: if arg == "": break key += arg + "." if key.endswith('.'): key = key[:-1] return key def ma...
from federatedml.param.base_param import BaseParam class SecureAddExampleParam(BaseParam): def __init__(self, seed=None, partition=1, data_num=1000): self.seed = seed self.partition = partition self.data_num = data_num def check(self): if self.seed is not None and type(self.se...
from artdmx import ArtNet, ArtDMX from scapy.all import * from itertools import chain from time import sleep from random import randrange class Effect: """Special effect superclass""" def __init__(self, kind): self.kind = kind class Dimmer(Effect): """Make a light fade slowely to the targets""" ...
import os import numpy as np from astropy.coordinates import SkyCoord import astropy.units as u from .... import optics, source from ..hrma_py import Aperture, HRMA from .. import HETG parfile = os.path.join(os.path.dirname(optics.__file__), 'hrma.par') marx = optics.MarxMirror(parfile) aperpy = Aperture() mirrpy = HR...
#! /usr/bin/env python import oursql import sqlite3 import virustotal from os import (environ) from sys import (argv) import time class VirusTotalDB: _conn = None _skb = oursql.connect( host='localhost', user='root', db='app_db', port=3306) _vt = None ...
import unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] self.slot = self.pkcs11.getSlotL...
from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from ..person import RegExpName from ._memberbase import father_base ...
from constant import * from lang import __, getDefaultLanguage from pprint import pprint from utils import * import Queue as Q import apt import apt_pkg import errno import glib import hashlib import optparse import os.path import subprocess import sys import textwrap import threading as td import time import urllib im...
import urllib,urllib2,re,sys,httplib #import xbmcplugin,xbmcgui,xbmcaddon,urlresolver import cookielib,os,string,cookielib,StringIO import os,time,base64,logging from datetime import datetime from utils import * try: import json except ImportError: import simplejson as json #testing in shell #TEST 1 # pyth...
""" Handles all requests relating to volumes + cinder. """ import copy import sys from cinderclient import exceptions as cinder_exception from cinderclient import service_catalog from cinderclient.v1 import client as cinder_client from oslo.config import cfg from nova import exception from nova.openstack.common.gett...
""" Utilities shared by the different formats. """ import warnings from fractions import Fraction from astropy.utils.misc import did_you_mean from ..utils import maybe_simple_fraction def get_grouped_by_powers(bases, powers): """ Groups the powers and bases in the given `~astropy.units.CompositeUnit` i...
"""A simpler way to read configuration files. dotconfig provides a very simple way to read options from a config file. It is currently read-only. Example: --- data.config --- [network] port: 8080 --- eof --- --- example.py --- config = dotconfig.Config("data.config") config.network.po...
""" https://leetcode.com/problems/find-smallest-letter-greater-than-target/ https://leetcode.com/submissions/detail/131676021/ """ class Solution: def nextGreatestLetter(self, letters, target): """ :type letters: List[str] :type target: str :rtype: str """ dic = 'a...
# -*- coding: utf8 -*- """ .. module:: lesscpy.lessc.color :synopsis: Lesscpy Color functions Copyright (c) See LICENSE for details. .. moduleauthor:: Johann T. Mariusson <<EMAIL>> """ import operator import colorsys import re import six from . import utility from lesscpy.lib import colors class Color(...
from vdsm.utils import getHostUUID from vdsm.tool import expose import sys @expose("vdsm-id") def getUUID(): """ Printing host uuid """ hostUUID = getHostUUID(False) if hostUUID is None: raise RuntimeError('Cannot retrieve host UUID') sys.stdout.write(hostUUID) return 0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: tests.mc .. moduleauthor:: Hendrix Demers <<EMAIL>> Tests for package :py:mod:`pysemeels.mc`. """ ############################################################################### # Copyright 2017 Hendrix Demers # # Licensed under the Apache Lice...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Sat 27 DEC 2014 02:07:37 PM PST Builds HDF5 file with features from FCS data """ __author__ = "David Ng, MD" __copyright__ = "Copyright 2014" __license__ = "GPL v3" __version__ = "1.0" __maintainer__ = "Daniel Herman" __email__ = "<EMAIL>" __status__ = "Pro...
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui from PyQt4.Qt import * from regmasc_ui import Ui_RegistroMascota from control_db import SQL_Requests db = SQL_Requests() class RegistroMascota(QDialog): def __init__(self): QDialog.__init__(self) self.ui_registro = Ui_RegistroMascota() self.ui_registro.se...
import os, os.path from lyntin import net, utils, engine, constants, config, exported, event from lyntin.modules import modutils """ This module holds commands that are derived from Tintin, but don't involve a manager. Tintin commands that involve a manager (alias and unalias, action and unaction, variable and unvari...
"""Test suite for the pylinac.io module.""" import unittest import os import os.path as osp from pylinac.core.io import TemporaryZipDirectory, get_url, URLError, is_dicom, SNCProfiler from pylinac.core.profile import SingleProfile from tests_basic.utils import get_file_from_cloud_test_repo class TestIO(unittest.Test...
# -*- coding: utf-8 -*- """ Invoker that uses a single core or CPU respectively. """ # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # First Party from metaopt.concurrent.invoker.invoker import Invoker from metaopt.core.call.call import call from metaop...
__all__ = ['SimpleDoc'] class SimpleDoc(object): """ class generating xml/html documents using context managers doc, tag, text = SimpleDoc().tagtext() with tag('html'): with tag('body', id = 'hello'): with tag('h1'): text('Hello world!') print(doc.getvalu...
import logging import six from stevedore import extension from neutronclient.common import exceptions logger = logging.getLogger(__name__) _discovered_plugins = {} def _load_entry_point(ep_name, name=None): """Try to load the entry point ep_name that matches name.""" for ep in extension.ExtensionManager...
#!/usr/bin/python # -*- coding: utf-8 -*- from timer_decorator import timer from rons_tutorial_formatting import * class MyRange(object): def __init__(self, start, end): self.start = start self.end = end self.cur = self.start - 1 def __iter__(self): return self def next(s...
import os import urlparse import urllib2 import gobject from kupfer.objects import TextSource, TextLeaf, FileLeaf, UrlLeaf from kupfer.obj.objects import OpenUrl from kupfer import utils __kupfer_name__ = u"Free-text Queries" __kupfer_sources__ = () __kupfer_text_sources__ = ("BasicTextSource", "PathTextSource", "UR...
# -*- coding: utf-8 -*- # Tomado del example B46 del SOLVIA Verification Manual import xc_base import geom import xc from model import predefined_spaces from solution import predefined_solutions from materials import typical_materials import math __author__= "Luis C. Pérez Tato (LCPT)" __copyright__= "Copyright 2014,...
from time import time from os import path from boxbranding import getBoxType, getBrandOEM from enigma import eServiceCenter, eServiceReference, eTimer, pNavigation, getBestPlayableServiceReference, iPlayableService from Components.ParentalControl import parentalControl from Components.config import config from Co...
import pytest import requests_mock import datetime from dateutil.tz import tzutc from iotile.cloud.cloud import IOTileCloud from iotile.cloud.config import link_cloud from iotile.core.dev.config import ConfigManager from iotile.core.dev.registry import ComponentRegistry from iotile.core.exceptions import ArgumentError,...
from mock import patch from .. import address from ...tests import TestGCP @patch('cloudify_gcp.gcp.ServiceAccountCredentials.from_json_keyfile_dict') @patch('cloudify_gcp.gcp.build') class TestAddress(TestGCP): def setUp(self): super(TestAddress, self).setUp() self.ctxmock.node.properties['gcp...
from settings import * def writeRV(data): rv = ''' item(FEAT_ROADVEHS, rv_{{ id }}, {{ id }}) { property { {% if name %}name: {{ name }};{% endif %} {% if refittable_cargo_classes %}refittable_cargo_classes: {{ refittable_cargo_classes }};{% endif %} {% if default_cargo_type %}default_cargo_type: {{ default_ca...
import json from django.http import HttpResponseForbidden from django.shortcuts import redirect from django.template.loader import render_to_string from django.utils.translation import get_language import requests import xmltodict from .. import RedirectNeeded, PaymentError from ..core import BasicProvider class So...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # order is important here (for now) import gtk # string taken from pango examples directory and converted from utf8 # to python unicode string escapes hellos = '''This is Pango (Παν語) This is a list of ways to say hello in various languages. Its purpose is to illustrat...
import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import api from horizon import exceptions from horizon import forms from horizon import messages LOG = logging.getLogger(__name__) class UpdateInstance(forms.SelfHandlingForm): tena...
# -*- coding: utf-8 -*- 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): # Adding field 'UserProfile.verified' db.add_column(u'chat_userprofile', ...
import FWCore.ParameterSet.Config as cms from PhysicsTools.PatAlgos.tools.tauTools import * ## Should work for both standard and high pt taus def applyTauParameters(process): # Include tau reconstruction sequence. process.load("RecoTauTag.Configuration.RecoPFTauTag_cff") switchToPFTauHPS(process) pro...
#import pprint class Graph: def __init__(self, data): self.data = data self.idx = {} # create a node index for n in self.nodes(): # nid = n.node_id() self.idx[nid]=n.pos def node(self, i): # based on offset if i < len(self.data): ...
from PyQt5.QtCore import QLineF, QPointF from guide import Guide class GuideLine(Guide): def __init__(self, line_or_point, follows=None): super(GuideLine, self).__init__(follows) if isinstance(line_or_point, QLineF): self.line = line_or_point elif follows is not None: ...
import os.path import unittest from subprocess import check_output import pysam from crumbs.utils.test_utils import TEST_DATA_DIR from crumbs.utils.bin_utils import BIN_DIR from crumbs.bam.statistics import (count_reads, ReferenceStats, ReadStats, CoverageCounter, _flag_to_binary, ...
'''Trains a Bidirectional LSTM on the IMDB sentiment classification task. Output after 4 epochs on CPU: ~0.8146 Time per epoch on CPU (Core i7): ~150s. ''' from __future__ import print_function import numpy as np from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import De...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import re import ast try: from setuptools import setup except ImportError: from distutils.core import setup def extract_version(): with open('zhihu/__init__.py', 'rb') as f_version: ast_tree = re.s...
from __future__ import absolute_import import os from txaio import make_logger try: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler except ImportError: HAS_FS_WATCHER = False else: HAS_FS_WATCHER = True __all__ = ('FilesystemWatcher', 'HAS_FS_WATCHER') if ...
""" This module handles input data downloaded from the registration system. """ import os.path import re from matholymp.fileutil import file_extension __all__ = ['file_url_to_local', 'lang_to_filename'] _type_to_entity_type = {'flag': 'country', 'photo': 'person', 'co...
from django.test import LiveServerTestCase from django.core.urlresolvers import reverse from core.models import Host, Plugin, Data_Source as Source from core.tests.utils import storage_enabled, set_storage from multiviews.models import View, Skeleton from multiviews.tests.utils import create_view, create_event class...
import os import stat import subprocess import shutil from StringIO import StringIO from zipfile import ZipFile from urllib import urlopen PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS_FILE = os.path.join(PROJECT_DIR, "requirements.txt") TARGET_DIR = os.path.join(PROJECT_DIR, "libs") APPENGI...
"""Density functional perturbation theory (DFPT) package. DFPT ==== In DFPT the first-order variation in the density due to a static perturbation in the external potential is calculated self-consistently from a set of coupled equations for: 1. the variation of the effective potential, 2. variation of the wav...
''' Argument parsing code for various submodules. This is consolidated here, rather than in each entry point itself, to allow them to all accept the same (or at least a subset of the same) arguments without repeating the description of them everywhere. ''' import argparse, os, sys import constants, version class Tool(...
from django import http from django.conf import settings COORS_ALLOWED_ORIGINS = "*" COORS_ALLOWED_METHODS = ["POST", "GET", "OPTIONS", "PUT", "DELETE", "PATCH", "HEAD"] COORS_ALLOWED_HEADERS = ["content-type", "x-requested-with", "authorization", "accept-encoding", "...
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.contrib.sites.models import get_current_site class Community(models.Model): name = models.CharField(max_length=25, verbo...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource f...
import logging import time from vtdb import dbexceptions from vtdb import vtdb_logger INITIAL_DELAY_MS = 5 NUM_RETRIES = 3 MAX_DELAY_MS = 100 BACKOFF_MULTIPLIER = 2 def log_exception(exc, keyspace=None, tablet_type=None): """This method logs the exception. Args: exc: exception raised by calling code ke...
# -*- coding: utf-8 -*- """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...
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.1' install_requires = [ # List your project dependencies here. # For more detail...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} try: from capacity import KiB, Capacity HAS_CAPACITY = True except ImportError: ...
import json from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic import FormView, View from tsuru_dashboard.apps.views import AppMixin import requests from tsuru_autoscale.wizard import client as wclient from tsuru_autoscale.n...
#!/usr/bin/python # # An isogram (also known as a "nonpattern word") is a logological term # for a word or phrase without a repeating letter. It is also used by # some to mean a word or phrase in which each letter appears the same # number of times, not necessarily just # once. (http://en.wikipedia.org/wiki/Isogram) # ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('experiments', '0001_initial'), ] operations = [ migrations.CreateModel( name=...
import gobject from lastfm import LastFM class LastFMTrackInfo(object): __slots__ = ['title', 'album', 'artist'] def __eq__(self, other): if self.__class__ != other.__class__: return False return self.title == other.title and self.album == other.album and \ self.artist == other.artist def __ne__(self, o...
"""Mailman LMTP runner (server). Most mail servers can be configured to deliver local messages via 'LMTP'[1]. This module is actually an LMTP server rather than a standard runner. The LMTP runner opens a local TCP port and waits for the mail server to connect to it. The messages it receives over LMTP are very minima...
from rest_framework import serializers from waldur_core.core.serializers import Base64Field from . import models, utils class Saml2LoginSerializer(serializers.Serializer): idp = serializers.CharField() def clean_idp(self, value): if utils.is_valid_idp(value): return value else: ...
#!/usr/bin/env python import logging import socket import unittest import urllib2 import re from vtproto import topodata_pb2 import environment import tablet import utils # range '' - 80 shard_0_master = tablet.Tablet() shard_0_replica = tablet.Tablet() shard_0_spare = tablet.Tablet() # range 80 - '' shard_1_master...
import urllib from django import http try: from django.utils import simplejson as json except ImportError: import json from model import AutocompleteModel class AutocompleteRestModel(AutocompleteModel): widget_js_attributes = {'bootstrap': 'rest_model'} @property def model(self): retu...
from __future__ import absolute_import, unicode_literals from django.test import TestCase from localflavor.us.forms import (USZipCodeField, USPhoneNumberField, USStateField, USStateSelect, USSocialSecurityNumberField) from .forms import USPlaceForm ...
import sfsimodels as sm import json import numpy as np def test_save_and_load_2d_system(): vs = 250.0 sl = sm.Soil() unit_mass = 1700.0 sl.g_mod = vs ** 2 * unit_mass sl.poissons_ratio = 0.0 # sl.cohesion = sl.g_mod / 1000 sl.cohesion = 30.0e3 sl.id = 1 sl.phi = 0.0 sl.unit_d...
""" Pure Python implementation of a Back-Propagation Neural Network using the hyperbolic tangent as the sigmoid squashing function. Original Author: Neil Schemenauer <<EMAIL>> Modified Author: James Howard <<EMAIL>> Modified to work for function regression and added option to use matplotlib to display regression netw...
# coding=utf-8 from datetime import date from django.shortcuts import render from django.views import generic from django.core.exceptions import ValidationError from django.contrib import messages from django.shortcuts import redirect from django.contrib.auth.decorators import user_passes_test from django.utils.decora...
import os import readline # https://github.com/ContinuumIO/anaconda-issues/issues/152 from unittest.mock import MagicMock from unittest.mock import Mock import numpy from pandas import DataFrame from pandas import Series from sklearn.pipeline import Pipeline import pytest pytest.importorskip("rpy2") from rpy2.robj...
from html2text import HTML2Text from html2safehtml import HTML2SafeHTML def html2text(s, ignore_tags=(), indent_width=4, page_width=80): ignore_tags = [t.lower() for t in ignore_tags] parser = HTML2Text(ignore_tags, indent_width, page_width) parser.feed(s) parser.close() parser.generate() retur...
import numpy as np import dubiotools as dbt class OnehotSeqMutator: """An iterator for making pointwise mutations for a 4xn onehot numpy array representing nucleic acid sequence. Useful for passing mutation variants to deep neural networks for making mutation maps as described in Alipanahi 2015 ...
# This file is part of eddylicious # (c) Timofey Mukha # The code is released under the GNU GPL Version 3 licence. # See LICENCE.txt and the Legal section in the User Guide for more information import eddylicious from eddylicious.writers.ofnative_writers import * import numpy as np from os import path def test_point...
""" contentful.array ~~~~~~~~~~~~~~~~ This module implements the Array class. API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/introduction/collection-resources-and-pagination :copyright: (c) 2017 by Contentful GmbH. :license: MIT, see LICENSE for more details. """ class ...
'''Compare the RDM configurations saves with rdm_snapshot.py''' __author__ = '<EMAIL> (Simon Newton)' import getopt import logging import os import pickle import sys import tempfile import textwrap import webbrowser from ola.UID import UID class Error(Exception): """Base exception class.""" class LoadException(E...
from abc import ABCMeta, abstractmethod from enum import Enum from pyspatial.uom import UnitOfMeasure class AxisType(Enum): GEOCENTRIC_X = 'Geocentric X' GEOCENTRIC_Y = 'Geocentric Y' GEOCENTRIC_Z = 'Geocentric Z' GEOCENTRIC_RADIUS = 'Geocentric radius' GEODETIC_LONGITUDE = 'Geodetic longitude'...
""" Acceptance tests for Studio related to the asset index page. """ from flaky import flaky from ...pages.studio.asset_index import AssetIndexPage from .base_studio_test import StudioCourseTest from ...fixtures.base import StudioApiLoginError from ..helpers import skip_if_browser class AssetIndexTest(StudioCourse...
from .helpers import * class TestClientWebhooks(ClientTestCase): def setUp(self): ClientTestCase.setUp(self) self.webhook_data = { "id": 222, "resource": { "id": 111, "name": "the resource" }, "target": "https://foo/1...
import os import xml.dom.minidom as dom from .sound import Record, DataBase def check_year(year): if year not in [1, 2]: raise(ValueError, "Wrong year version: %d (should be 1 or 2)" % year) def _filter_XML(path): return (os.path.isfile(path) and os.path.splitext(path)[-1].lower() == '....
from django.core.urlresolvers import reverse from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from reviews.models import Review, ReviewFlag from mkt.account.serializers import AccountSerializer from mkt.api.fields import SlugOrPrimaryKeyRelatedField, SplitField from mkt.a...
import bpy import bmesh from mathutils import Vector import numpy as np import math # Blender import system clutter import sys from pathlib import Path UTILS_PATH = Path.home() / "Documents/python_workspace/data-science-learning" SRC_PATH = UTILS_PATH / "graphics" sys.path.append(str(SRC_PATH)) sys.path.append(str(UT...
import related from .models import Person, RoleModels def test_set_construction(): scientists = [Person(first_name="Grace", last_name="Hopper"), Person(first_name="Katherine", last_name="Johnson"), Person(first_name="Katherine", last_name="Johnson")] assert len(scientists)...
from django.conf import settings from os.path import join from txtalert.core.models import Visit from datetime import date, timedelta from txtalert.core.utils import MuninCommand class Command(MuninCommand): help = "Print out statistics on TherapyEdge, suitable as a Munin plugin" def config(self): ...
# -*- coding: utf-8 -*- """ abm.io ====== Reading and writing network configuration files, through :class:`ConfigReader`. """ from abm.generators import NO_VAL, ATTR_SCALE, DIFF import json import numpy as np class ConfigReader(object): """Interface to reading network settings from a file. Read a json co...
from __future__ import print_function from __future__ import absolute_import import os import re import resource # split out of get_memusage for profiling purposes def _read_proc_status(pid): procfn = '/proc/%d/status' % pid t = open(procfn).readlines() d = dict([(line.split()[0][:-1], line.split()[1:]) f...
import datetime import sys from textwrap import dedent from unittest import mock import pytest from .. import ledgerfile # noqa: F401 (is used in patch) from ..ledgerbilexceptions import LdgReconcilerError from ..ledgerfile import LedgerFile from ..ledgerthing import LedgerThing from . import filetester as FT from ....
#!/usr/bin/env python """ rules_basic_data.py contains dictionary with basic reactions. {rxncon_quick_string: 'Rules': [rule1, rule2 ...], 'Tags': [rtype ...]} It anables to check whether rxncon input produces correct bngl rules code. """ # TODO: Relocalisation reactions are not tested yet. REACTIONS_DATA = { # b...
import unittest2 from durabledict import MemoryDict from gutter.client import get_gutter_client from gutter.client.encoding import JsonPickleEncoding from gutter.client.testutils import switches from gutter.client.models import Switch from exam.decorators import around, fixture from exam.cases import Exam class Tes...
from __future__ import print_function import unittest import os import io from rdkit.six.moves import cPickle as pickle from rdkit import Chem from rdkit.Chem import rdPartialCharges from rdkit import RDConfig def feq(v1, v2, tol2=1e-4): return abs(v1 - v2) <= tol2 class TestCase(unittest.TestCase): def setU...
# -*- coding: utf-8 -*- import requests from datetime import datetime from api_health.models.base import session from api_health.verifier import Verifier class Worker(object): """ A worker is responsible for performing a task and iterating over its output in order to verify if it contains what would be ...
import datetime try: import asyncio except ImportError: ## Trollius >= 0.3 was renamed import trollius as asyncio from autobahn.asyncio.wamp import ApplicationSession class Component(ApplicationSession): """ An application component using the time service during 3 subsequent WAMP sessions, while ...
from ..parser.g11_file_parser import G11Parser from .common import BaseParserTest, BaseStatementImportTest class G11ParserTest(BaseParserTest): def setUp(self): super(BaseParserTest, self).setUp() self.parser = G11Parser( self.get_file_content('aus_dd_esr.g11') ) def test...