content
stringlengths
4
20k
from __future__ import print_function from __future__ import unicode_literals import os import sys import atexit import copy import logging try: from xml.etree import cElementTree as ET except ImportError: from xml.etree import ElementTree as ET try: from collections import OrderedDict except: from .bot...
""" Tests for block_structure_factory.py """ # pylint: disable=protected-access from mock import patch from unittest import TestCase from ..block_structure_factory import BlockStructureFactory from .test_utils import ( MockCache, MockModulestoreFactory, MockTransformer, ChildrenMapTestMixin ) class TestBlockStru...
import re from fnmatch import translate from conans.errors import RequestErrorException, NotFoundException, ForbiddenException, \ ConanException import os import jwt from conans.util.files import mkdir, list_folder_subdirs from conans.model.ref import PackageReference, ConanFileReference from conans.util.log impor...
from django.conf import settings from django.conf.urls import include, url, patterns from django.conf.urls.static import static from settings import API_BASE from website import settings as osf_settings from . import views base_pattern = '^{}'.format(API_BASE) urlpatterns = [ url(base_pattern, include(pa...
"""This module implements enough functionality to program the STM32F4xx over DFU, without requiringdfu-util. See app note AN3156 for a description of the DFU protocol. See document UM0391 for a dscription of the DFuse file. """ from __future__ import print_function import argparse import re import struct import sys ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_ssl_certificate short_description: Import/Del...
# cython: infer_types=True, language_level=3, py2_import=True # # Cython Scanner # import os import platform import cython cython.declare(EncodedString=object, any_string_prefix=unicode, IDENT=unicode, print_function=object) from Cython import Utils from Cython.Plex.Scanners import Scanner from Cyth...
"""Main executable module""" import os import argcomplete from airflow.cli import cli_parser from airflow.configuration import conf def main(): """Main executable function""" if conf.get("core", "security") == 'kerberos': os.environ['KRB5CCNAME'] = conf.get('kerberos', 'ccache') os.environ[...
from openerp.addons.hr_holidays.tests import test_holidays_flow checks = [ test_holidays_flow, ]
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} try: import shade from shade import meta HAS_SHADE = True except ImportError: HAS_SHADE = False def _system_state_change(state, device): """Check if system s...
"""This example demonstrates how to authenticate using OAuth2. This example is intended for users who wish to use the oauth2client library directly. Using a workflow similar to the example here, you can take advantage of the oauth2client in a broader range of contexts than caching your refresh token using the config.p...
{ 'name': 'Suppliers Payment Management', 'version': '1.1', 'author': 'OpenERP SA', 'category': 'Accounting & Finance', 'description': """ Module to manage the payment of your supplier invoices. ======================================================= This module allows you to create and manage your...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import ansible.module_utils.asa from ansible.module_utils.network import NetworkModule from ansible.module_utils.netcfg import NetworkConfig, dumps def get_config(module, acl_n...
import sys import re # Functions that change stacks STACKHOP = ['__send_disk_op'] # List of functions we can assume are never called. #IGNORE = ['panic', '__dprintf'] IGNORE = ['panic'] OUTPUTDESC = """ #funcname1[preamble_stack_usage,max_usage_with_callers]: # insn_addr:called_function [usage_at_call_point+caller...
import xlrd import logging from datetime import datetime, time from xlrd.biffh import XLRDError from followthemoney import model from ingestors.ingestor import Ingestor from ingestors.support.table import TableSupport from ingestors.support.ole import OLESupport from ingestors.exc import ProcessingException log = log...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import pty import json import subprocess import sys import termios from ansible import constants as C from ansible.plugins.connection import ConnectionBase from ansible.module_utils._text import to_text from ansible.modu...
import textwrap from mock import patch from twitter.common.contextutil import temporary_file from apache.aurora.client.cli import EXIT_COMMAND_FAILURE from apache.aurora.client.cli.client import AuroraCommandLine from .util import AuroraClientCommandTest, FakeAuroraCommandContext class TestClientCreateCommand(Auro...
from gnuradio import gru import digital_swig as digital import struct def gen_and_append_crc32(s): crc = digital.crc32(s) return s + struct.pack(">I", gru.hexint(crc) & 0xFFFFFFFF) def check_crc32(s): if len(s) < 4: return (False, '') msg = s[:-4] #print "msg = '%s'" % (msg,) actual = ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals """ adapted from https://github.com/martine/python-sourcemap into a reuasable module """ """ Apache License ...
import os import numpy as np import dimarray as da project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) inputdatadir = os.path.join(project_dir, "data/input/") ######## IPCC mean sl contributions ######## # see Chapter 13, Fifth IPCC Report of WG1, Table 13.5 ipccdata = np.loadtxt( inputdat...
categories = ["addition", "subtraction", "multiplication", "multiply_add", "average", "sum_of_absolute_differences"] microcode = ''' # 128 bit multimedia and scientific instructions ''' for category in categories: exec "import %s as cat" % categ...
from django.contrib.auth.tests.custom_user import * from django.contrib.auth.tests.auth_backends import * from django.contrib.auth.tests.basic import * from django.contrib.auth.tests.context_processors import * from django.contrib.auth.tests.decorators import * from django.contrib.auth.tests.forms import * from django....
""" Comparing two html documents. """ import re from HTMLParser import HTMLParseError from django.utils.encoding import force_unicode from django.utils.html_parser import HTMLParser WHITESPACE = re.compile('\s+') def normalize_whitespace(string): return WHITESPACE.sub(' ', string) class Element(object): d...
"""Test the wallet balance RPC methods.""" from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) RANDOM_COINBASE_ADDRESS = 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ' def create_transactions(node, address...
import os import getpass import logging # misc recommended_version = 1.1 production = True # user details current_user = getpass.getuser() centinel_home = "/opt/centinel-server/" # directory structure results_dir = os.path.join(centinel_home, 'results') experiments_dir = os.path.join(centinel_home, 'experiment...
from i3pystatus import IntervalModule class CpuFreq(IntervalModule): """ class uses by default `/proc/cpuinfo` to determine the current cpu frequency .. rubric:: Available formatters * `{avg}` - mean from all cores in MHz `4.3f` * `{avgg}` - mean from all cores in GHz `1.2f` * `{coreX}` - fr...
import decimal import json import stripe from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.forms.models import modelformset_factory from django.http import HttpResponse, JsonResponse from django.shortcuts import get_object_or_404,...
import unittest from test import test_support import os import subprocess MacOS = test_support.import_module('MacOS') TESTFN2 = test_support.TESTFN + '2' class TestMacOS(unittest.TestCase): @unittest.skipUnless(os.path.exists('/Developer/Tools/SetFile'), '/Developer/Tools/SetFile does no...
""" A test spanning all the capabilities of all the serializers. This class sets up a model for each model field type (except for image types, because of the Pillow dependency). """ from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import...
import getpass import re from typing import Union import click import releasetool.git import releasetool.github import releasetool.secrets import releasetool.commands.common from releasetool.commands.common import TagContext RELEASE_LINE_PATTERN = r"^(?:- )?Release ([^ ]*) version (\d+\.\d+.\d+(-[^ ]*)?)$" def det...
import os.path as op import warnings import numpy as np from numpy.testing import assert_raises # Set our plotters to test mode import matplotlib matplotlib.use('Agg') # for testing don't use X server import matplotlib.pyplot as plt from mne import io, read_events, Epochs from mne import pick_types from mne.channel...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'GeneratedCertificate.enabled' db.delete_column('certificates_generatedcertificate', 'enabl...
PKG = 'pomdp_node' import roslib; roslib.load_manifest(PKG) import exceptions import sys from os.path import basename import unittest import rospy import rostest from pomdp_node import default from pomdp_node import msg NODE_NAME = 'test_pomdp_run' def usage(): return ("USAGE: %s Z0 A0 Z1 A1...\n" ...
from xml.etree import ElementTree from collections import OrderedDict node_name = '/com/ford/hmi' class ParamDesc: pass class FordXmlParser: def __init__(self, in_el_tree, interface_path=None): self.interface_path = interface_path self.el_tree = in_el_tree self.find_enums() se...
import functools import os import multiprocessing import random import shutil import signal import time import tempfile from helpers import unittest, with_config, skipOnTravis import luigi.rpc import luigi.server from luigi.scheduler import CentralPlannerScheduler from luigi.six.moves.urllib.parse import urlencode, Pa...
from datetime import datetime from django.utils import simplejson import logging import sys import traceback from model.testfile import TestFile JSON_RESULTS_FILE = "results.json" JSON_RESULTS_FILE_SMALL = "results-small.json" JSON_RESULTS_PREFIX = "ADD_RESULTS(" JSON_RESULTS_SUFFIX = ");" JSON_RESULTS_VERSION_KEY = ...
import string import random import unittest def randomstring(size=6, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits): """ :Time_Created: 2014.7.15 Constructs random string with given size & charset :param size: (optional) desired length of st...
import subprocess import os FAILED_VOICE="Zarvox" REGULAR_VOICE="Trinoids" HAPPY_VOICE="Cellos" LASER_VOICE="Princess" SAY_CMD="/usr/bin/say" def say(msg, voice): subprocess.call([SAY_CMD, msg, "--voice=%s" % (voice)]) class CallbackModule(object): """ makes Ansible much more exciting on OS X. """ ...
# -*- coding: utf-8 -*- 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 model 'JabberGroup' db.create_table('Jabber_jabbergroup', ( ('id', self.gf('django.db.m...
"""Pylama's shell support.""" from __future__ import absolute_import, with_statement import sys from os import walk, path as op from .config import parse_options, CURDIR, setup_logger from .core import LOGGER, run from .async import check_async def check_path(options, rootdir=None, candidates=None, code=None): ...
import numpy as np import time def sigmoid(input): return 1.0 / (1 + np.exp(-input)) class BoltzmannMachine(object): def __init__(self, input_size, hidden_size, output_size): self.total_nodes = input_size + hidden_size + output_size self.state = np.random.randint(0, 2, self.total_nodes, dtyp...
import logging import time import discogs_client import requests from django.conf import settings DISCOGS_HOST = getattr(settings, "DISCOGS_HOST", None) log = logging.getLogger(__name__) def discogs_image_by_url(url, type="uri"): image = None log.debug("search image for %s" % url) try: id = ur...
import os.path as op import numpy as np from nose.tools import assert_raises, assert_true from numpy.testing import assert_equal, assert_allclose from mne import (make_bem_model, read_bem_surfaces, write_bem_surfaces, make_bem_solution, read_bem_solution, write_bem_solution, make_sphe...
#!/usr/bin/env python ''' Most basic flask application: Initialization: * All Flask applications must create an application instance. * The webserver passes all requests from clients to this object for handling using WSGI (Web Server Gateway Interface) Routes and View Functions: * Clients such as web browsers send...
from __future__ import unicode_literals """ Utilities for using modules """ import webnotes, os, conf transfer_types = ['Role', 'Print Format','DocType','Page','DocType Mapper', 'GL Mapper','Search Criteria', 'Patch', 'Report'] lower_case_files_for = ['DocType', 'Page', 'Search Criteria', 'Report', "Workflow", '...
#!/usr/bin/env python import sys import time import datetime import os import os.path import io import bz2 import gzip import zipfile import tarfile import pprint import subprocess import base64 # patch for handling unverified certificates import ssl if hasattr(ssl, '_create_unverified_context'): ssl._create_defa...
"""Orienteering problem solver Implementation of an integer linear formulation for maximizing the targets visited by a vehicle under cost constraint. The vehicle has to start and finish at the first point and it is allowed to skip targets. Described in: Vansteenwegen, Pieter, Wouter Souffriau, and Dirk Van Oudheusden....
import unittest from telemetry import decorators class FakePlatform(object): def GetOSName(self): return 'os_name' def GetOSVersionName(self): return 'os_version_name' class FakePossibleBrowser(object): def __init__(self): self.browser_type = 'browser_type' self.platform = FakePlatform() ...
#!/usr/bin/python import socket import socks SERVER_IP = '127.0.0.1' SERVER_PORT = 1081 if __name__ == '__main__': # Test 1: same source port IPv4 sock_out = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM, socket.SOL_UDP) sock_out.set_proxy(socks.SOCKS5, SERVER_IP, S...
# Note for contributors: # This example code is referred to from "Chainer at a Glance" tutorial. # If this file is to be modified, please also update the line numbers in # `docs/source/glance.rst` accordingly. import chainer as ch from chainer import datasets import chainer.functions as F import chainer.links as L fro...
import httplib from neutron.openstack.common import log as logging from neutron.plugins.vmware.api_client import base from neutron.plugins.vmware.api_client import eventlet_client from neutron.plugins.vmware.api_client import eventlet_request from neutron.plugins.vmware.api_client import exception from neutron.plugins...
#!/usr/bin/env python import os import sys import argparse import pat3dem.pdb as p3p from Bio.PDB import * def main(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <pdbs> Superimpose pdb """ args_def = {'fix':'','move':''} parser = argparse.ArgumentParser() parser.add_argument("...
""" Utility functions to compute ROC (Receiver Operator Characteristic) curves and AUC (Area Under the Curve). The ROCCurve() and AreaUnderCurve() functions are based on the roc_curve() and auc() functions found in metrics.py module of scikit-learn (http://scikit-learn.org/stable/). Scikit-learn has a BSD license (3 c...
import signal import subprocess import sys import tempfile from telemetry.core import exceptions from telemetry.core import util from telemetry.core.platform import profiler class _SingleProcessSampleProfiler(object): """An internal class for using iprofiler for a given process.""" def __init__(self, pid, output...
#!/usr/bin/python import os import sys import subprocess import re #all_benchmarks = os.listdir('tests') #all_benchmarks.remove('Makefile') #all_benchmarks.remove('defines.mk') #all_benchmarks.sort() #all_benchmarks = os.listdir('tests') #all_benchmarks.remove('Makefile') #all_benchmarks.remove('defines.mk') all_ben...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from wechatpy.fields import IntegerField, BaseField from wechatpy import events EVENT_TYPES = {} def register_event(event_type): def register(cls): EVENT_TYPES[event_type] = cls return cls return register @re...
''' Run the tests using testrunner.py script in the project root directory. Usage: testrunner.py SDK_PATH TEST_PATH Run unit tests for App Engine apps. SDK_PATH Path to the SDK installation TEST_PATH Path to package containing test modules Options: -h, --help show this help message and exit ''' import unitt...
from openstack_dashboard.test.integration_tests import helpers class TestFlavors(helpers.AdminTestCase): FLAVOR_NAME = helpers.gen_random_resource_name("flavor") def test_flavor_create(self): """tests the flavor creation and deletion functionalities: * creates a new flavor * verifies ...
"""Train and Eval the MNIST network. This version is like fully_connected_feed.py but uses data converted to a TFRecords file containing tf.train.Example protocol buffers. See tensorflow/g3doc/how_tos/reading_data.md#reading-from-files for context. YOU MUST run convert_to_records before running this (but you only nee...
import unittest from ansible.utils.helpers import pct_to_int class TestHelpers(unittest.TestCase): def test_pct_to_int(self): self.assertEqual(pct_to_int(1, 100), 1) self.assertEqual(pct_to_int(-1, 100), -1) self.assertEqual(pct_to_int("1%", 10), 1) self.assertEqual(pct_to_int("1...
"""Wrapper for mod_fcgid, for use as a CherryPy HTTP server when testing. To autostart fcgid, the "apache" executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, "apache" may be called "apachectl", "apache2ctl", or "httpd"--create a symlink to them if needed. ...
from m5.params import * from m5.proxy import * from Device import BasicPioDevice, PioDevice, IsaFake, BadAddr, DmaDevice from Pci import PciConfigAll from Ethernet import NSGigE, IGbE_e1000, IGbE_igb from Ide import * from Platform import Platform from Terminal import Terminal from Uart import Uart from SimpleMemory im...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'QuerySet.order_field' ...
#! /usr/bin/python import os import sys import glob import optparse import tempfile import logging import shutil import ConfigParser class Fail(Exception): def __init__(self, test, msg): self.msg = msg self.test = test def getMsg(self): return '\'%s\' - %s' % (self.test.path, self.msg)...
# LIBTBX_SET_DISPATCHER_NAME dev.dials.show_extensions import dials.util class Script: """The class to encapsulate the script.""" def __init__(self): """Initialise the script.""" from libtbx.phil import parse from dials.util.options import OptionParser # Create the phil pa...
""" Brazilian Portuguese-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'Autor', 'authors': 'Autores', 'organization': 'Organiza\u00E7\u00E3o', 'address': 'Endere\u00E7o', 'conta...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} # import cloudstack common from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_required_togeth...
import abc import os import six from nova import utils from nova.virt.libvirt.volume import volume as libvirt_volume @six.add_metaclass(abc.ABCMeta) class LibvirtBaseFileSystemVolumeDriver( libvirt_volume.LibvirtBaseVolumeDriver): """The base class for file system type volume drivers""" def __init__(se...
import time import re from openerp.tools.translate import _ from openerp.osv import orm from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class L10nEsAeatMod340CalculateRecords(orm.TransientModel): _name = "l10n.es.aeat.mod340.calculate_records" _description = u"AEAT Model 340 Wizard - Calculate Record...
import cherrypy from cherrypy._cpcompat import ntob from cherrypy.test import helper class WSGI_Namespace_Test(helper.CPWebCase): def setup_server(): class WSGIResponse(object): def __init__(self, appresults): self.appresults = appresults self.iter = iter(app...
#!/usr/bin/env python # coding=utf8 """ Create path entries for changelog exporting @contact: Debian FTP Master <<EMAIL>> @copyright: 2013 Luca Falavigna <<EMAIL>> @license: GNU General Public License version 2 or later """ # This program is free software; you can redistribute it and/or modify # it under the terms o...
import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc")) from decimal import Decimal, ROUND_DOWN import json import random import shutil import subprocess import time import re from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util impo...
import multiprocessing import os import shutil import subprocess import threading import time from . import daemon from . import local_handler from . import presence_handler from . import signatures from . import status_handler from . import work_handler from ..network import perfdata class Server(daemon.Daemon): ...
#!/usr/bin/env python3 import os import xml.etree.ElementTree as et def main(filename): if not os.path.isfile(filename): raise RuntimeError(f"Could not find junit file {repr(filename)}") tree = et.parse(filename) root = tree.getroot() current_class = "" for el in root.iter("testcase"): ...
#!/usr/bin/env python try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup import xmltodict setup(name='xmltodict', version=xmltodict.__version__, description=xmltodict.__doc__, author=xmltodict.__auth...
import os from twisted.trial import unittest from scrapy.utils.iterators import csviter, xmliter, _body_or_str, xmliter_lxml from scrapy.http import XmlResponse, TextResponse, Response from tests import get_testdata FOOBAR_NL = u"foo" + os.linesep + u"bar" class XmliterTestCase(unittest.TestCase): xmliter = st...
import re from .exceptions import KodionException from . import items from . import constants from . import utils class AbstractProvider(object): RESULT_CACHE_TO_DISC = 'cache_to_disc' # (bool) def __init__(self): self._local_map = { 'kodion.wizard.view.default': 30027, 'kod...
def recalibrate(): """ Rerun the WFC3 calibration pipeline to flatten the (potentially) variable ramps """ import matplotlib as mpl mpl.rcParams['backend'] = 'agg' import glob import os import stsci.tools from sgas import reprocess_wfc3 # In RAW files=glob.glob...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.tests.views import AuthViewsTestCase class LoginRequiredTestCase(AuthViewsTestCase): """ Tests the login_required decorators """ urls = 'django.contrib.auth.tests.urls' def testCalla...
from __future__ import print_function import os import sys import shutil import shlex import re import time from urllib.request import urlretrieve from urllib.request import urlopen from subprocess import Popen, PIPE from distutils.cmd import Command class OSXPortableBuild(Command): description = "custom build co...
from oslo_config import cfg from sqlalchemy.schema import Table, Column, MetaData from migrate.changeset.constraint import UniqueConstraint from designate.sqlalchemy.types import UUID meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine domains_table = Table('domains', meta, autoload=...
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
from openerp import fields, models import logging _logger = logging.getLogger(__name__) class attach_mail_manually(models.TransientModel): _name = 'fetchmail.attach.mail.manually' folder_id = fields.Many2one( 'fetchmail.server.folder', 'Folder', readonly=True) mail_ids = fields.One2many( ...
"""Sample statistics tests.""" from greplin.scales.samplestats import UniformSample, ExponentiallyDecayingReservoir import random import unittest class UniformSampleTest(unittest.TestCase): """Test cases for uniform sample stats.""" def testGaussian(self): """Test with gaussian random numbers.""" random....
# ! /usr/bin/python # -*- coding: utf-8 -*- from loguru import logger # logger = logging.getLogger() import numpy as np class GMMClassifier(): def __init__(self, each_class_params=None, **same_params): """ same_params: classifier params for each class are same each_class_params: is list ...
# coding=utf-8 import sys from unittest import TestResult, TextTestRunner import datetime import re from teamcity.messages import TeamcityServiceMessages from teamcity.common import is_string, get_class_fullname, convert_error_to_string, \ dump_test_stdout, dump_test_stderr, get_exception_message, to_unicode, Flus...
import numpy as np from pele.potentials.potential import potential as basepotential #from potentials.rigid_body_potential import RigidBodyPotential import copy class RigidBodySystem(basepotential): """ Defines a system of rigid body molecules """ def __init__(self, molecule_list, potential = None): ...
# -*- coding: utf-8 -*- 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 model 'Place' db.create_table('sa_api_place', ( ('id', self.gf('django.db.models.fields...
"""This module implements functions that have to do with number theory.""" import random from operator import mul _stock_primes = [2, 3, 5, 7, 11, 13, 17, 19] def int_pow(x, n): """Raise x to the power n (if n is negative a ValueError is raised). intPow(0, 0) is defined to be 0. """ if n < 0: ...
import re from decimal import Decimal from weboob.capabilities.bank import Account from weboob.tools.browser import BasePage from weboob.tools.capabilities.bank.transactions import FrenchTransaction as Transaction __all__ = ['HomePage', 'LoginPage', 'LoginErrorPage', 'AccountsPage', 'TransactionsPage'] class HomeP...
input_file = 'input' DEBUG = True DEBUG = False input_file = '/home/ksi/Downloads/dataset_44327_15(2).txt' memory = {} qr = list() with open(input_file) as fin: m = fin.read memory_n, queries_n, table_r_addr = [int(x) for x in next(fin).split()] for i in range(memory_n): paddr, value = [int(x) for x...
"""Implementation of tf.sets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops imp...
from openerp import models, api, fields from openerp.tools.translate import _ from openerp.exceptions import UserError class ResCompany(models.Model): _inherit = 'res.company' @api.model def _get_uom_hours(self): try: return self.env.ref("product.product_uom_hour") except Val...
# payment imports import datetime # django imports from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.db.models import Q from django.forms.util import ErrorList from django.utils.translation import ugettext_lazy as _ # lfs imports ...
# -*- coding: utf-8 -*- import logging import mock import requests from builtins import object from django.test import override_settings from requests import Response from typing import Any, Dict, Tuple, Text, Optional from zerver.lib.outgoing_webhook import do_rest_call, OutgoingWebhookServiceInterface from zerver....
import essentia.standard as ess # matplotlib without any blocking GUI import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np from smst.utils import audio (fs, x) = audio.read_wav('../../../sounds/oboe-A4.wav') M = 500 start = .8 * fs xp = x[start:start + M] / float(max(x[start:st...
__author__ = 'e.bidelman (Eric Bidelman)' import cgi import os import gdata.auth import gdata.docs import gdata.docs.service import gdata.alt.appengine from appengine_utilities.sessions import Session from django.utils import simplejson from google.appengine.api import users from google.appengine.ext impo...
"""Top-level presubmit script for Skia. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ import fnmatch import os import re import sys import traceback REVERT_CL_SUBJECT_PREFIX = 'Revert ' SKIA_TREE_STATUS_URL = 'http://skia-tr...
__author__ = "Simone Campagna" from zirkon.schema import Schema from zirkon.config import Config def test_Schema_validate_depend_up(): schema = Schema.from_string("""\ ax = Int() [sub] sx = Int(default=10) """) config = Config.from_string("""\ ax = SECTION["sub"]["sx"] * 5 """) validation = schema.v...
""" Testing signals before/after saving and deleting. """ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Person(models.Model): first_name = models.CharField(max_length=20) last_n...