content
stringlengths
4
20k
from __future__ import unicode_literals import errno import io import hashlib import json import os.path import re import types import sys import youtube_dl.extractor from youtube_dl import YoutubeDL from youtube_dl.utils import ( compat_str, preferredencoding, write_string, ) def get_params(override=No...
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ from ...
""" Represents an EC2 Security Group """ from boto.ec2.ec2object import TaggedEC2Object from boto.exception import BotoClientError class SecurityGroup(TaggedEC2Object): def __init__(self, connection=None, owner_id=None, name=None, description=None, id=None): TaggedEC2Object.__init__(self,...
from openerp import tools from openerp.osv import orm, osv def _get_exception_message(exception): msg = isinstance(exception, (osv.except_osv, orm.except_orm)) and exception.value or exception return tools.ustr(msg)
from odoo.tests import common from odoo import fields @common.at_install(False) @common.post_install(True) class TestHrTimesheetSheetFixAnalytic(common.SavepointCase): @classmethod def setUpClass(cls): super(TestHrTimesheetSheetFixAnalytic, cls).setUpClass() cls.analytic_line_obj = cls.env['a...
""" This module defines the following constants: *InputText options* * BGUI_INPUT_NONE = 0 * BGUI_INPUT_SELECT_ALL = 1 * BGUI_INPUT_DEFAULT = BGUI_INPUT_NONE """ from .widget import Widget, WeakMethod, BGUI_DEFAULT, BGUI_CENTERY, \ BGUI_NO_FOCUS, BGUI_MOUSE_ACTIVE, BGUI_MOUSE_CLICK, BGUI_MOUSE_RELEASE, \ BGUI_...
"""Contains the logic for `aq del room`.""" from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.del_location import CommandDelLocation class CommandDelRoom(CommandDelLocation): required_parameters = ["room"] def render(self, session, room, **arguments): ...
""" rv_video.py - Starts video player Video is played in a loop, usually kill_app test should be called later to close totem. Requires: binaries Xorg, totem, gnome-session Test starts video player """ import logging import os import time import re from autotest.client.shared import error from virttest impo...
#!/usr/bin/python import dbus import os import sys def printusage(): print 'bthstereoheadset.py <options>' print ' create - create a stereo headset' print ' start - connect sink' print ' stop - disconnect sink' return headsetAddress = os.getenv("BTSTEREO_HEADSET") print 'BT Stereo Headset Is : =>...
from __future__ import absolute_import from .treemixin import TreeMixin from array import array __all__ = ['AVLTree'] MAXSTACK = 32 class Node(object): """ Internal object, represents a treenode """ __slots__ = ['left', 'right', 'balance', 'key', 'value'] def __init__(self, key=None, value=None): ...
#Bibliotheken einbinden import sys sys.path += ['../util'] from Observer import Observer, Observable import RPi.GPIO as GPIO import time class ObservedDistanceSensor: def measure(self): # setze Trigger auf HIGH GPIO.output(self.GPIO_TRIGGER, True) # setze Trigger nach 0.01ms aus LOW time....
"""Implements a parallel data reader with queues and optional shuffling.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes as tf_dtypes from tensorflow.python.framework import ops from tensorflow.python.ops im...
"""SAX document handlers that support output generation of XML, SGML, and XHTML. This module provides three different groups of objects: the actual SAX document handlers that drive the output, DTD information containers, and syntax descriptors (of limited public use in most cases). Output Drivers -------------- The...
"""Test for dbcore's date-based queries. """ from __future__ import (division, absolute_import, print_function, unicode_literals) from test import _common from test._common import unittest from datetime import datetime import time from beets.dbcore.query import _parse_periods, DateInterval, Dat...
import sys from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List # Shim to wrap setup.py invocation with setuptools # # We set sys.argv[0] to the path to the underlying setup.py file so # setuptools / distutils don't take the path to the setup.py to be "-c" when...
#! /usr/bin/env python import roslib import rospy from controller import Controller, ActionStatus from geometry_msgs.msg import PoseStamped from bebop_controller.msg import * from actionlib import SimpleActionClient from BebopActionServer import BebopActionServer from actionlib_msgs.msg import GoalStatus from geomet...
# -*- coding: utf-8 -*- """Define dashboard specific DRF API routes. Copyright (C) 2021 Gitcoin Core This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at yo...
import time from twisted.application import service, internet from twisted.python import log from twisted.internet import reactor from buildbot.scheduler import Periodic, BaseUpstreamScheduler, Scheduler, Nightly from buildbot.sourcestamp import SourceStamp from buildbot import buildset, util def SerialScheduler(nam...
""" Functions for flexible generation of sample input job JSON. """ import json import os import time from datetime import timedelta def ref_data_json(): """Return reference data json structure""" filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), "ref_data.json", ) ...
# -*- coding: utf-8 -*- # disable missing docstring # pylint: disable=missing-docstring from lettuce import world, step from nose.tools import assert_true # pylint: disable=no-name-in-module from video_editor import RequestHandlerWithSessionId, success_upload_file @step('I (?:upload|replace) handout file(?: by)? "(...
from django.db import models from django.test import SimpleTestCase class AbsoluteUrlOverrideTests(SimpleTestCase): def test_get_absolute_url(self): """ get_absolute_url() functions as a normal method. """ get_absolute_url = lambda o: '/test-a/%s/' % o.pk TestA = self._cre...
"""Subpackage where each product is defined. Each product is created by adding a a .py file containing a __wptrunner__ variable in the global scope. This must be a dictionary with the fields "product": Name of the product, assumed to be unique. "browser": String indicating the Browser implementation used to launch tha...
import subprocess import inspect import json import time import git import os import msc_globals LAST_BLOCK_NUMBER_FILE='last_block.txt' # needed for deciding on error format: exodus_address='1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P' def run_command(command, input_str=None, ignore_stderr=False): if ignore_stderr: ...
import re import socket import time def RspChecksum(data): checksum = 0 for char in data: checksum = (checksum + ord(char)) % 0x100 return checksum class EofOnReplyException(Exception): pass class GdbRspConnection(object): def __init__(self, addr): self._socket = self._Connect(addr) def _Co...
"""Support for Slide slides.""" import logging from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASS_CURTAIN, STATE_CLOSED, STATE_CLOSING, STATE_OPENING, CoverEntity, ) from homeassistant.const import ATTR_ID from .const import API, DEFAULT_OFFSET, DOMAIN, SLIDES _LOGGER =...
""" This module represents a violation against a MISRA guideline """ class Violation: """ Represents a violation against a MISRA guideline """ def __init__(self, file, line, column, guideline, entity): """ Construct a violation """ self.file = file self.line = line self.colum...
# video_deque.py from PIL import Image from fs.memoryfs import MemoryFS import fs.path import PIL import io import numpy as np import cv2 import collections import datetime import tempfile import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choi...
"Functions that help with dynamically creating decorators for views." import types try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance)...
__doc__ = """hashlib module - A common interface to many hash functions. new(name, string='') - returns a new hash object implementing the given hash function; initializing the hash using the given string data. Named constructor functions are also available, these are muc...
import permstruct import permstruct.dag # Since we usually don't want overlays: overlays = False #------------------------------------------------# # Avoidance of one classical pattern of length 1 # As is expected the first dag suffices # perm_prop = lambda p: p.avoids([1]) # perm_bound = 6 # inp_dag ...
class Schema(object): """ Represents a DynamoDB schema. :ivar hash_key_name: The name of the hash key of the schema. :ivar hash_key_type: The DynamoDB type specification for the hash key of the schema. :ivar range_key_name: The name of the range key of the schema or None if no range...
import gtk import gtk.gdk import gobject import pango from virtaal.views import markup class LabelExpander(gtk.EventBox): __gproperties__ = { "expanded": (gobject.TYPE_BOOLEAN, "expanded", "A boolean indicating whether this widget has been expanded to show its con...
from django.conf import settings from django.db import migrations, models from opaque_keys.edx.django.models import CourseKeyField, UsageKeyField class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations...
"""Utilities for loading op libraries. @@load_op_library """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re from tensorflow.python.framework import load_library from tensorflow.python.platform import resource_loader def load_op_libra...
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' ...
""" Integration tests for the stem.response.ControlMessage class. """ import re import unittest import stem.socket import stem.version import test.runner class TestControlMessage(unittest.TestCase): def test_unestablished_socket(self): """ Checks message parsing when we have a valid but unauthenticated so...
import six _GOODBYE_MESSAGE = u'Goodbye' def web_socket_do_extra_handshake(request): # This example handler accepts any request. See origin_check_wsh.py for how # to reject access from untrusted scripts based on origin value. pass # Always accept. def web_socket_transfer_data(request): while True...
import os import sys from appengine_django.db.base import destroy_datastore from appengine_django.db.base import get_test_datastore_paths from django.core.management.base import BaseCommand class Command(BaseCommand): """Overrides the default Django testserver command. Instead of starting the default Django de...
"""Registrations for LinearOperator.inverse.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops import math_ops from tensorflow.python.ops.linalg import linear_operator from tensorflow.python.ops.linalg import linear_operator_addi...
'Artmaking, a tiny demonstration game for Curveship.' __author__ = 'Nick Montfort' __copyright__ = 'Copyright 2011 Nick Montfort' __license__ = 'ISC' __version__ = '0.5.0.0' from item_model import Actor, Room, Thing from action_model import Modify, Sense import can import when discourse = { 'metadata': { ...
from denim.constants import RootUser from tests._utils import ApiTestCase from denim.service import supervisor class TestServiceSupervisor(ApiTestCase): def test_manager_start(self): supervisor.manager_start() self.assertSudo('/etc/init.d/supervisor start', user=RootUser) def test_manager_st...
from __future__ import absolute_import import os import ujson # from adaptivemd.task import PythonTask from adaptivemd.file import Location, File from adaptivemd.engine import (Engine, Frame, Trajectory, TrajectoryGenerationTask, TrajectoryExtensionTask) exec_file = File('file://' + o...
from __future__ import with_statement from robot.model import Statistics from robot.reporting.outputwriter import OutputWriter from .executionerrors import ExecutionErrors from .configurer import SuiteConfigurer from .testsuite import TestSuite class Result(object): """Contains results of test execution. :...
from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .. import Rule #-----------------------------------------------...
# -*- coding: utf-8 -*- """Updates the Emby Library whenever the beets library is changed. emby: host: localhost port: 8096 username: user password: password """ from __future__ import division, absolute_import, print_function from beets import config from beets.plugins import Bee...
# -*- coding: utf-8 -*- import urllib2, httplib, cookielib import StringIO import gzip from urlparse import urlparse import logging import socket import os import urllib import time import re # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) class HTTPClient(object): def __init__(self, ww...
#! /usr/bin/env python import sys from pexpect import spawn if __name__ == "__main__": try: if len(sys.argv) > 1: expected_received = int(sys.argv[1]) else: expected_received = 5 except TypeError: sys.stderr.write("Usage: "+str(sys.argv[0])+" [<expected 'receive...
import os, json cur_dir = os.path.dirname(__file__) project_root = os.path.join(cur_dir, '..') CONFIG_PATH = os.path.join(project_root, 'config') PIPELINE_CONFIG_PATH = os.path.join(CONFIG_PATH, 'experiment_config.json') class _pipeline_config(object): def __init__(self): self._config = json.load(open(...
import configparser from pathlib import Path import unittest from TM1py import Element from TM1py.Objects import Dimension, Hierarchy, Subset from TM1py.Services import TM1Service config = configparser.ConfigParser() config.read(Path(__file__).parent.joinpath('config.ini')) DIMENSION_PREFIX = 'TM1py_Tests_Hierarchy_...
""" Tests for mirrormanager2 messages """ import unittest from fedmsg_meta_fedora_infrastructure.tests.base import Base from .common import add_doc class TestCrawlerStart(Base): """ `Mirrormanager <https://mirrors.fedoraproject.org>`_ is the system that (surprise) manages the mirror network for Fedora (and...
from peewee import ( Model, Database, SqliteDatabase, AutoField, CharField, IntegerField ) from peewee_migrate import Migrator import constants if False: # MYPY from typing import Dict, Any def migrate(migrator, database, fake=False, **kwargs): # type: (Migrator, Database, bool, Dict[Any, Any]) -> N...
__revision__ = "$Id$" __all__ = ['PythonOSURandomRNG'] import os from rng_base import BaseRNG class PythonOSURandomRNG(BaseRNG): name = "<os.urandom>" def __init__(self): self._read = os.urandom BaseRNG.__init__(self) def _close(self): self._read = None def new(*args, **kwargs...
# $Id$ import inc_sip as sip import inc_sdp as sdp # In this test we simulate broken server, where: # - it wants to signal that NONCE has change # - but it sets stale=false # For this case pjsip will retry authentication until # PJSIP_MAX_STALE_COUNT is exceeded. # pjsua = "--null-audio --id=sip:CLIENT --registrar s...
from .core import ( abort, override_template, Pecan, Request, Response, load_app, redirect, render, request, response ) from .decorators import expose from .hooks import RequestViewerHook from .middleware.debug import DebugMiddleware from .middleware.errordocument import ErrorDocumentMiddleware from .middlewar...
import unittest, sys sys.path.extend(['.','..','../..','py']) import os import h2o2 as h2o import h2o_cmd, h2o_import as h2i, h2o_browse as h2b from h2o_test import find_file, dump_json, verboseprint expectedZeros = [0 for i in range(11)] CAUSE_FAIL = False def assertEqualMsg(a, b): assert a == b, "%s %s" % (a, b) ...
""" Portable file locking utilities. Based partially on an example by Jonathan Feignberg in the Python Cookbook [1] (licensed under the Python Software License) and a ctypes port by Anatoly Techtonik for Roundup [2] (license [3]). [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 [2] http://sourceforg...
"""distutils.command.install_headers Implements the Distutils 'install_headers' command, to install C/C++ header files to the Python include directory.""" __revision__ = "$Id$" from distutils.core import Command # XXX force is never used class install_headers(Command): description = "install C/C+...
import docutils import os import re # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'SkyWater SKY130 PDK' copyright = '2020, SkyWater PDK Authors' author = 'SkyWater PDK Authors' # The short X.Y version version = '' # T...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import re from datetime import date from bson.objectid import ObjectId from elasticsearch_dsl import Q, A from elasticsearch_dsl.faceted_search import ( Facet as DSLFacet, TermsFacet as DSLTermsFacet, RangeFacet as DSLRangeFac...
from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'outline06.xlsx' ...
""" The I{doctor} module provides classes for fixing broken (sick) schema(s). """ from logging import getLogger from suds.sax import splitPrefix, Namespace from suds.sax.element import Element from suds.plugin import DocumentPlugin, DocumentContext log = getLogger(__name__) class Doctor: """ Schema Doctor. ...
""" ============================= Species distribution dataset ============================= This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Bro...
from importlib import import_module import inspect import os import re import warnings from django import template from django.apps import apps from django.conf import settings from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from django.db import models from dja...
"""ExportStrategy class represents different flavors of model export (deprecated). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for migration instructions. """ from __future__ import absolute_import from __future__...
from __future__ import unicode_literals import unittest from nose.tools import * # PEP8 asserts from nose.plugins.attrib import attr from textblob.sentiments import PatternAnalyzer, NaiveBayesAnalyzer, DISCRETE, CONTINUOUS class TestPatternSentiment(unittest.TestCase): def setUp(self): self.analyzer = ...
""" Audit interactions in real-time In this example we create a shell with one simple command: audit - command: audit - provides clear status if this channel is currently audited or not - command: audit on - starts auditing - command: audit off - ensure private interactions for some time Multiple questions are ad...
# -*- coding: utf-8 -*- import random import unittest2 from ..controllers.main import module_topological_sort as sort def sample(population): return random.sample( population, random.randint(0, min(len(population), 5))) class TestModulesLoading(unittest2.TestCase): def setUp(self): ...
import unzip import zipfile import sys import re import os import random import myparser class metaInfoMS: def __init__(self): self.template ="" self.totalTime ="" self.pages ="" self.words ="" self.characters ="" self.application ="" self.docSecurity ="" self.lines ="" self.paragraphs ="" self.sc...
import os from django.core.management.base import NoArgsCommand from optparse import make_option class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--plain', action='store_true', dest='plain', help='Tells Django to use plain Python, not IPython.'), ) ...
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from .models import ExternalUserData User = get_user_model() class Backend(ModelBackend): def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExi...
# dbpop.py # cwilliamson226 # Python script that uses nflgame to pull stats of all players then pushes them to the MongoDB import nflgame from pymongo import MongoClient # Imports the stats from the 2016 season games = nflgame.games(2016) plays = nflgame.combine_plays(games) # Creates a connection through...
from datetime import datetime import naoqi from naoqi import ALBroker from naoqi import ALModule from naoqi import ALProxy instance = None SoundLocator = None def log(text): instance.nao.log("SoundLocationModule: " + text) return; class SoundLocationModule(object): nao = None proxy = None lastD...
import time from openerp import SUPERUSER_ID from openerp import tools from openerp.osv import fields, osv, expression from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.misc import unquote as unquote class ir_rule(osv.osv): _name = 'ir.rule' _order = 'name' _MODES = ['read', 'write'...
# https://www.codewars.com/kata/where-is-my-parent-cry/python def find_children(input_string): print('original = [{}]'.format(input_string)) ########### # Method 1: 1st Attempt ########### string_sorted = ''.join(sorted(input_string)) # Separate the string by case upper = [c ...
from nose import SkipTest from nose.tools import * import networkx as nx try: import numpy as np except: raise SkipTest('NumPy not available.') from networkx.algorithms.tree import branchings from networkx.algorithms.tree import recognition from networkx.testing import * # # Explicitly discussed examples fr...
from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Runs the command-line client for specified database, or the " "default database if none is provided." ) requires_system_checks = Fals...
import maya.cmds as cmds import RMUncategorized def MirrorChildren(Objects): for eachObject in Objects: children = cmds.listRelatives(eachObject, children = True,type='transform') if (children): MirrorChildren(children) for eachObject in Objects: ObjectTransformDic = RMUn...
import sys import os if sys.version > '3': basestring = str from pyspark import since, keyword_only, SparkContext from pyspark.ml.base import Estimator, Model, Transformer from pyspark.ml.param import Param, Params from pyspark.ml.util import * from pyspark.ml.wrapper import JavaParams from pyspark.ml.common impo...
from peachpy.arm.isa import Extension, Extensions class Microarchitecture: def __init__(self, name, extensions): self.name = name self.extensions = Extensions(*[prerequisite for extension in extensions for prerequisite in extension.prerequisites]) def is...
import partner import invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
#! /bin/env python # -*- coding: utf-8 -*- import sys import argparse from harvester.couchdb_init import get_couchdb from harvester.couchdb_sync_db_by_collection import delete_id_list from harvester.post_processing.couchdb_runner import CouchDBCollectionFilter def confirm_deletion(count, objChecksum, cid): prompt...
from datetime import datetime, date from decimal import Decimal from ..adapters.sqlite import SQLite from .base import ListsParser, DateParser, TimeParser, DateTimeParser, \ JSONParser from . import parsers, for_type, before_parse @parsers.register_for(SQLite) class SQLiteParser( ListsParser, DateParser, Time...
import os from distutils import log from setuptools import Command from pex.bin.pex import build_pex, configure_clp from pex.common import die from pex.variables import ENV # Suppress checkstyle violations due to setuptools command requirements. class bdist_pex(Command): # noqa description = "create a PEX file f...
import requests from pytz import UTC from datetime import datetime from django.db import IntegrityError import itertools from time import sleep from chain.core.api import BadRequestException from itertools import izip from time import sleep EPOCH = UTC.localize(datetime.utcfromtimestamp(0)) HTTP_STATUS_SUCCESSFUL_WRI...
""" FI-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class FIZipCodeField(RegexField): default_error_messages = { ...
from lib.utils import ( juju_log, relation_ids, relation_list, relation_get, get_unit_hostname, config_get ) import subprocess import os def is_clustered(): for r_id in (relation_ids('ha') or []): for unit in (relation_list(r_id) or []): clustered = relation_get('cl...
def leastsquares(x, y): ''' Example implementation of the Least Squares method for calculating a best-fit line through a set of points. Linear least squares Args: x: array of floats representing x values for each point y: array of floats representing y values for each point Returns...
import requests from cloudbot import hook api_url_metar = "http://api.av-wx.com/metar/" api_url_taf = "http://api.av-wx.com/taf/" def lookup(text, url): station = text.split(' ')[0].upper() if len(station) != 4: return "please specify a valid station code see http://weather.rap.ucar.edu/surface/stat...
""" parser.sql.objectadapter module (imdb.parser.sql package). This module adapts the SQLObject ORM to the internal mechanism. Copyright 2008-2010 Davide Alberani <<EMAIL>> 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 Fr...
import vtk from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase from vtk.util import numpy_support from vtk.numpy_interface import dataset_adapter as dsa from Utilities import DebugTimeVTKFilter import numpy as np from scipy import ndimage from timeit import default_timer as timer import logging class FilterDe...
from reportlab.pdfbase.pdfmetrics import getFont import time from sys import getrefcount font = getFont('Times-Roman') _py_stringWidth = font._py_stringWidth stringWidth = font.stringWidth assert stringWidth!=_py_stringWidth #print "font=%s(%d) widths=%s(%d)" % ( # hex(id(font)), getrefcount(font), # hex(id...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst...
import luigi import tempfile from helpers import unittest from luigi.contrib.hadoop_jar import HadoopJarJobError, HadoopJarJobTask from mock import patch, MagicMock class TestHadoopJarJob(HadoopJarJobTask): path = luigi.Parameter() def jar(self): return self.path class TestMissingJarJob(HadoopJarJo...
from sympy.core import pi, oo, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt from sympy.utilities.pytest import raises from sympy.printing.jscode import JavascriptCodePrinter from sympy.utilities.lambdify import imple...
from __future__ import division import collections import gzip import itertools from cdec.sa._sa import gzip_or_text # Same as Cython implementation. Collisions with NULL in bitext? NULL_WORD = 'NULL' def learn_vocab(text_f): vocab = set() for line in gzip_or_text(text_f): for word in line.strip()....
import subprocess from django.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = 'mysql' @classmethod def settings_to_cmd_args(cls, settings_dict): args = [cls.executable_name] db = settings_dict['OPTIONS'].get('db', settings_dic...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} import os def _fail(module, cmd, out, err, **kwargs): msg = '' if out: msg += "stdout: %s" % (out, ) if err: msg += "\n:stderr: %s" % (err, ) module.fail_js...
''' This converts the simulation parmatetor into dimensionless quantiteis and give is the physical uints that the feilds should be scaled whit. ''' # import external packs import dolfin as df import h5py import os import glob import numpy as np import sys # import internal BERNAISE packs # Find path to the BERNAISE ...
import logging from scap.Model import Model from scap.model.oval_5 import OPERATOR_ENUMERATION logger = logging.getLogger(__name__) class StateType(Model): MODEL_MAP = { 'elements': [ {'xmlns': 'http://www.w3.org/2000/09/xmldsig#', 'tag_name': 'Signature', 'min': 0, 'max': 1}, {'xm...
""" JSON password reset handling plugin """ import base64 import binascii import logging import os import subprocess import time from Crypto.Cipher import AES import agentlib import commands # This is to support older python versions that don't have hashlib try: import hashlib except ImportError: import md5 ...