content
string
"""Module to host the VerboseSubprocess, ChangeDir, and ReSearch classes. """ import os import re import subprocess def print_subprocess_args(prefix, *args, **kwargs): """Print out args in a human-readable manner.""" def quote_and_escape(string): """Quote and escape a string if necessary.""" ...
from __future__ import unicode_literals import frappe from frappe.utils import cint from frappe.model import default_fields def execute(): for table in frappe.db.get_tables(): doctype = table[3:] if frappe.db.exists("DocType", doctype): fieldnames = [df["fieldname"] for df in frappe.get_all("DocField", fie...
import json import logging import os import sys import tempfile import unittest ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT_DIR) from utils import lru class LRUDictTest(unittest.TestCase): @staticmethod def prepare_lru_dict(keys): """Returns new LRUDict wit...
""" Views for the Matrix Synapse module. """ from django.shortcuts import redirect from django.urls import reverse_lazy from django.views.generic import FormView from plinth import actions from plinth import views from plinth.modules import matrixsynapse from plinth.forms import DomainSelectionForm from plinth.utils ...
"""Profiler setting methods.""" from __future__ import absolute_import import ctypes from .base import _LIB, check_call, c_str def profiler_set_config(mode='symbolic', filename='profile.json'): """Set up the configure of profiler. Parameters ---------- mode : string, optional Indicates whethe...
"""Options Class for save, restoring and getting parameters from the command line. This provides a class which handles both saving options to disk and gathering options from the command line. It behaves a little like optparse in that you can get or set the attributes by name. It uses ConfigParser to save the variabl...
"""Gradients for operators defined in linalg_ops.py. Useful reference for derivative formulas is An extended collection of matrix derivative results for forward and reverse mode algorithmic differentiation by Mike Giles: http://eprints.maths.ox.ac.uk/1079/1/NA-08-01.pdf A detailed derivation of formulas for backpropa...
from moves import find_possible_moves, find_impossible_moves, resolve_moves def test_find_possible_moves_1(): # the first item, with value 0, is 'missing'. find_possible_moves will tell us it should be a 9. state = [((i,i), i) for i in range(9)] moves = find_possible_moves(state) assert len(moves...
"""Symbolizes a log file produced by cyprofile instrumentation. Given a log file and the binary being profiled, creates an orderfile. """ import logging import multiprocessing import optparse import os import tempfile import string import sys import cygprofile_utils import symbol_extractor def _ParseLogLines(log_f...
from __future__ import absolute_import import logging import os import tempfile # TODO: Get this into six.moves.urllib.parse try: from urllib import parse as urllib_parse except ImportError: import urlparse as urllib_parse from pip.utils import rmtree, display_path from pip.vcs import vcs, VersionControl fro...
from django.test import TestCase from viewflow import flow from viewflow.base import Flow, this from .. import integration_test def create_test_flow(activation): activation.prepare() activation.done() return activation @flow.flow_func(task_loader=lambda flow_task, process: process.get_task(FunctionFlo...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from os.path import basename from ansible.errors import AnsibleParserError from ansible.playbook.attribute import FieldAttribute from ansible.playbook.task_include import TaskInclude from ansible.playbook.role import Role from ans...
# Copied from https://github.com/ohmu/ohmu_common_py ohmu_common_py/pgutil.py version 0.0.1-0-unknown-fa54b44 """ pghoard - postgresql utility functions Copyright (c) 2015 Ohmu Ltd See LICENSE for details """ try: from urllib.parse import urlparse, parse_qs # pylint: disable=no-name-in-module, import-error excep...
#!/usr/bin/python2.7 import argparse import json import sys from collections import defaultdict class Node(object): def __init__(self, node, datacenter): self.node = node self.datacenter = datacenter self.partitions = set() @property def hostname(self): return self.node["...
"Roi align in python" import math import numpy as np def roi_align_nchw_python(a_np, rois_np, pooled_size, spatial_scale, sample_ratio): """Roi align in python""" _, channel, height, width = a_np.shape num_roi = rois_np.shape[0] b_np = np.zeros((num_roi, channel, pooled_size, pooled_size), dtype=a_np.d...
from paddle.trainer_config_helpers import * # 1. read data. Suppose you saved above python code as dataprovider.py data_file = 'empty.list' with open(data_file, 'w') as f: f.writelines(' ') define_py_data_sources2( train_list=data_file, test_list=None, module='dataprovider', obj='process', args...
""" EventTransformers are data structures that represents events, and modify those events to match the format desired for the tracking logs. They are registered by name (or name prefix) in the EventTransformerRegistry, which is used to apply them to the appropriate events. """ import json import logging from opaque_...
from abc import ABCMeta, abstractmethod, abstractproperty import importlib import os import shlex import subprocess import socket import time import rpyc from dpa.app.entity import EntityRegistry from dpa.env.vars import DpaVars from dpa.ptask.area import PTaskArea from dpa.ptask import PTaskError, PTask from dpa.sin...
# -*- coding: utf-8 -*- import asyncio from .assertions import isiter from .concurrent import ConcurrentExecutor @asyncio.coroutine def wait(*coros_or_futures, limit=0, timeout=None, loop=None, return_exceptions=False, return_when='ALL_COMPLETED'): """ Wait for the Futures and coroutine objects given...
""" Grades Application Configuration Signal handlers are connected here. """ from django.apps import AppConfig from django.conf import settings from edx_proctoring.runtime import set_runtime_service from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType, PluginURLs, PluginSettings class Gra...
import atexit import os import sys import select import signal import shlex import socket import platform from subprocess import Popen, PIPE if sys.version >= '3': xrange = range from py4j.java_gateway import java_import, JavaGateway, GatewayClient from pyspark.find_spark_home import _find_spark_home from pyspark...
#!/usr/bin/python # Wsploit Project ''' this is simple joomla components scanner ''' try: import urllib2, Queue except: print 'You need urllib2 and Queue librarys installed.' try: from threading import Thread except: print 'You need threading library installed.' try: from time import sleep except: print 'You ...
from django.test import TestCase from oscar.apps.offer import models from oscar.test.factories import ( create_order, OrderDiscountFactory, UserFactory) class TestAPerUserConditionalOffer(TestCase): def setUp(self): self.offer = models.ConditionalOffer(max_user_applications=1) self.user = Us...
"""Remove old audit tables Revision ID: 53ef72c8a867 Revises: 526117e15ce4 Create Date: 2013-09-10 23:24:50.751098 """ # revision identifiers, used by Alembic. revision = '53ef72c8a867' down_revision = '526117e15ce4' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql NOT_NULL_COLS...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, mimetype2ext, ) class AparatIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?aparat\.com/(?:v/|video/video/embed/videohash/)(?P<id>[a-zA-Z0-9]+)' _TEST = { 'url': ...
#!/usr/bin/env python # pylint: disable=W0212 import leather from agate import utils def bar_chart(self, label=0, value=1, path=None, width=None, height=None): """ Render a bar chart using :class:`leather.Chart`. :param label: The name or index of a column to plot as the labels of the chart. ...
'''This file generates shell code for the setup.SHELL scripts to set environment variables''' from __future__ import print_function import argparse import copy import errno import os import platform import sys CATKIN_MARKER_FILE = '.catkin' system = platform.system() IS_DARWIN = (system == 'Darwin') IS_WINDOWS = (sy...
"""Manage the Wordfast Translation Memory format Wordfast TM format is the Translation Memory format used by the `Wordfast <http://www.wordfast.net/>`_ computer aided translation tool. It is a bilingual base class derived format with :class:`WordfastTMFile` and :class:`WordfastUnit` providing file and unit level acce...
"""a similarities / code duplication command line tool and pylint checker """ from __future__ import print_function import sys from collections import defaultdict from logilab.common.ureports import Table from pylint.interfaces import IRawChecker from pylint.checkers import BaseChecker, table_lines_from_stats import...
#!/usr/bin/env python from gnuradio import gr, gr_unittest class test_hier_block2(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_001_make(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) ...
from ..backend_object import BackendObject class BoolResult(BackendObject): def __init__(self, op=None, args=None): self._op = op self._args = args def value(self): raise NotImplementedError() def __len__(self): return BackendError() def __eq__(self, other): r...
import os, sys, shutil, platform, zipfile import string, subprocess, re from xml.etree.ElementTree import ElementTree from StringIO import StringIO from os.path import join, splitext, split, exists from shutil import copyfile from androidsdk import AndroidSDK from compiler import Compiler import bindings template_dir ...
# -*- coding: utf-8 -*- """ Created on 2018/3/14 @author: will4906 采集的内容、方式定义 """ from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import DataItem from entity.crawler_item import BaseItem, ResultItem class PatentId(BaseItem):...
"""Minio Test event.""" TEST_EVENT = { "Records": [ { "eventVersion": "2.0", "eventSource": "minio:s3", "awsRegion": "", "eventTime": "2019-05-02T11:05:07Z", "eventName": "s3:ObjectCreated:Put", "userIdentity": {"principalId": "SO9KNO6Y...
"""Tests for distutils.pypirc.pypirc.""" import sys import os import unittest import tempfile from distutils.core import PyPIRCCommand from distutils.core import Distribution from distutils.log import set_threshold from distutils.log import WARN from distutils.tests import support from test.support import run_unittes...
import pytest from django.contrib.auth.models import AnonymousUser from django.contrib.messages import SUCCESS as SUCCESS_LEVEL from django.contrib.messages import get_messages from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.urls import reverse from cruditor.views import Cruditor4...
from django.conf.urls import include, url from .utils import URLObject from .views import empty_view, view_class_instance testobj3 = URLObject('testapp', 'test-ns3') testobj4 = URLObject('testapp', 'test-ns4') app_name = 'included_namespace_urls' urlpatterns = [ url(r'^normal/$', empty_view, name='inc-normal-vie...
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import subprocess import shlex from svtplay_dl.log import log from svtplay_dl.utils import is_py2 from svtplay_dl.fetcher import VideoRetriever from svtplay_dl.output import output class RT...
KOI8R_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143...
import glob import logging import os import platform from reportlab import rl_config from openerp.tools import config #.apidoc title: TTF Font Table """This module allows the mapping of some system-available TTF fonts to the reportlab engine. This file could be customized per distro (although most Linux/Unix ones) ...
from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class LROsCustomHeaderOperations(object): """LROsCustomHeaderOperations operations. :param client: Client for servi...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_firewall_rule version_added: "2.0" author: Timothy Vandenbrande short_description: Windows firewall automation description: - allows you t...
""" XML serializer. """ from __future__ import unicode_literals from collections import OrderedDict from xml.dom import pulldom from xml.sax import handler from xml.sax.expatreader import ExpatParser as _ExpatParser from django.apps import apps from django.conf import settings from django.core.serializers import bas...
from __future__ import unicode_literals import base64 import binascii import hashlib import importlib from collections import OrderedDict from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from d...
''' >>> from shared_ptr_ext import * Test that shared_ptr<Derived> can be converted to shared_ptr<Base> >>> Y.store(YYY(42)) >>> x = X(17) >>> null_x = null(x) >>> null_x # should be None >>> identity(null_x) # should also be None >>> a = New(1) >>> A.call_f(a) 1 >>> New(0) >>> type(factory(3)) <class 'shared_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pelican.tests.support import unittest from pelican.urlwrappers import Author, Category, Tag, URLWrapper class TestURLWrapper(unittest.TestCase): def test_ordering(self): # URLWrappers are sorted by name wrapper_a = URLWrapper(na...
""" This module defines a class used to represent a choice for an enumerated-value field. """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (<EMAIL>)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http:/...
#!/usr/bin/python2 # -*- coding: utf-8 -*- import sys import matplotlib.pyplot as plt import numpy as np from sklearn import datasets from sklearn.cross_validation import cross_val_predict from sklearn import linear_model from sklearn import datasets X = [] Y = [] for line in sys.stdin: line = line.rstrip() X...
from xml.dom import minidom import webob import webob.dec import webob.exc from nova.api.openstack import common from nova.api.openstack import wsgi from nova.openstack.common import jsonutils from nova import test class TestFaults(test.TestCase): """Tests covering `nova.api.openstack.faults:Fault` class.""" ...
"""Basic loop for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import errors from tensorflow.python.util.tf_export import tf_export @tf_export(v1=["train.basic_train_loop"]) def basic_train_loop(supervisor, ...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_request, unified_strdate, str_to_int, parse_duration, clean_html, ) class FourTubeIE(InfoExtractor): IE_NAME = '4tube' _VALID_URL = r'https?://(?:www\.)?4tube\.com/vide...
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <<EMAIL>>' __docformat__ = 'restructuredtext en' import re, os, traceback, shutil from threading import Thread from operator import itemgetter from calibre.ptempfile import TemporaryD...
"""Tests for third_party.tensorflow.contrib.kernel_methods.python.losses.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.kernel_methods.python import losses from tensorflow.python.framework import constant_op ...
from twisted.trial import unittest # system imports import os, time, stat # twisted imports from twisted.python import logfile, runtime class LogFileTestCase(unittest.TestCase): """ Test the rotating log file. """ def setUp(self): self.dir = self.mktemp() os.makedirs(self.dir) ...
import sys import os from optparse import make_option, OptionParser from django.conf import settings from django.core.management.base import BaseCommand from django.test.utils import get_runner class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--noinput', actio...
"""Driver for sqlite""" import os.path # Import sqlite3. If it does not support the 'with' statement, then # import pysqlite2, which might... import sqlite3 if not hasattr(sqlite3.Connection, "__exit__"): del sqlite3 from pysqlite2 import dbapi2 as sqlite3 #@Reimport @UnresolvedImport import weedb def conne...
from __future__ import absolute_import from __future__ import with_statement import sys import socket from nose import SkipTest from celery.exceptions import ImproperlyConfigured from celery import states from celery.utils import uuid from celery.backends import redis from celery.backends.redis import RedisBackend ...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: win_package version_added: "1.7" short_description: Installs/uninstalls an installable package description: - Installs or uninstalls a package in either...
from .base import ReactionSystem, TerminationTime, TerminationConversion from .simple import SimpleReactor
# Fluorescence Analysis import os import cv2 import numpy as np import pandas as pd from plotnine import ggplot, geom_label, aes, geom_line from plantcv.plantcv import print_image from plantcv.plantcv import plot_image from plantcv.plantcv import fatal_error from plantcv.plantcv import params from plantcv.plantcv impo...
from __future__ import absolute_import from .packages.six.moves.http_client import ( IncompleteRead as httplib_IncompleteRead ) # Base Exceptions class HTTPError(Exception): "Base exception used by this module." pass class HTTPWarning(Warning): "Base warning used by this module." pass class Po...
import zmq import gevent.event import gevent.core STOP_EVERYTHING = False class ZMQSocket(zmq.Socket): def __init__(self, context, socket_type): super(ZMQSocket, self).__init__(context, socket_type) on_state_changed_fd = self.getsockopt(zmq.FD) self._readable = gevent.event.Event() ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Notification', fields=[ ...
""" Defines the URL parsing specific parts of :mod:`lars.datatypes`. """ from __future__ import ( unicode_literals, absolute_import, print_function, division, ) from collections import namedtuple try: from urllib import parse except ImportError: import urlparse as parse from .ipaddress im...
from timmy.analyze_health import GREEN, UNKNOWN, YELLOW, RED from timmy.env import project_name import logging import re import yaml logger = logging.getLogger(project_name) def register(function_mapping): function_mapping['rabbitmqctl-list-queues'] = parse_list_queues function_mapping['rabbitmqctl-status']...
from pele.amber import amberSystem as amb # create a new amber system and load database to be pruned sys = amb.AMBERSystem('coords.prmtop', 'coords.inpcrd') dbcurr = sys.create_database(db="aladipep.db") print 'Collecting minima to delete .. ' listTODel = [] for minimum in dbcurr.minima(): testOutCome1 = sy...
class ModuleDocFragment(object): # Parameters for FreeIPA/IPA modules DOCUMENTATION = ''' options: ipa_port: description: - Port of FreeIPA / IPA server. - If the value is not specified in the task, the value of environment variable C(IPA_PORT) will be used instead. - If both the environment v...
"""Word completion for GNU readline. The completer completes keywords, built-ins and globals in a selectable namespace (which defaults to __main__); when completing NAME.NAME..., it evaluates (!) the expression up to the last dot and completes its attributes. It's very cool to do "import sys" type "sys.", hit the com...
import survey import controllers import wizard
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutTrueAndFalse(Koan): def truth_value(self, condition): if condition: return 'true stuff' else: return 'false stuff' def test_true_is_treated_as_true(self): self.assertEqu...
import random import unittest from pyStock.models import ( Exchange, Stock, Account, Owner, ) from pyStock.models.money import Currency from analyzer.backtest.constant import ( SELL, BUY_TO_COVER, ) from analyzerstrategies.sma_strategy import SMAStrategy class TestSMAStrategy(unittest.TestCa...
ADMIN_EXTENSIONS = {} PUBLIC_EXTENSIONS = {} def register_admin_extension(url_prefix, extension_data): """Register extension with collection of admin extensions. Extensions register the information here that will show up in the /extensions page as a way to indicate that the extension is active. ...
"""Implementaton of :class:`GMPYRationalField` class. """ from sympy.polys.domains.rationalfield import RationalField from sympy.polys.domains.groundtypes import ( GMPYRationalType, SymPyRationalType, gmpy_numer, gmpy_denom, gmpy_factorial, ) from sympy.polys.polyerrors import CoercionFailed class GMPYRatio...
""" Interactive D3 rendering of matplotlib images ============================================= Functions: General Use ---------------------- :func:`fig_to_html` convert a figure to an html string :func:`fig_to_dict` convert a figure to a dictionary representation :func:`show` launch a web server to view...
"""Module for VNC Proxying.""" from oslo.config import cfg vnc_opts = [ cfg.StrOpt('novncproxy_base_url', default='http://127.0.0.1:6080/vnc_auto.html', help='Location of VNC console proxy, in the form ' '"http://127.0.0.1:6080/vnc_auto.html"'), cfg.StrOpt('x...
#!/usr/bin/python import os import sys THIS_NAME = "generate.py" # Note: these lists must be kept in sync with the lists in # Document-createElement-namespace.html, and this script must be run whenever # the lists are updated. (We could keep the lists in a shared JSON file, but # seems like too much effort.) FILES =...
from __future__ import unicode_literals import warnings from django.apps import apps from django.db import models from django.db.utils import IntegrityError, OperationalError, ProgrammingError from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import force_text, python_2_unicode...
class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: cities=[0]*(n+1) group={} nextGroupId=1 def union(source, to): if source==to: return for c in group[source]: ...
""" Python 'utf-16-be' Codec Written by Marc-Andre Lemburg (<EMAIL>). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_be_encode def decode(input, errors='strict'): return codecs.utf_16_be_decode(input, errors, True) class IncrementalEncoder(codec...
import os class Cert(object): def __init__(self, name, buff): self.name = name self.len = len(buff) self.buff = buff pass def __str__(self): out_str = ['\0']*32 for i in range(len(self.name)): out_str[i] = self.name[i] out_str = "".join(...
import os import sys import random import unittest sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../.."))) import base_test repo_root = os.path.abspath(os.path.join(__file__, "../../..")) sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver")) from webdriver import exceptions class SendKeysTe...
"""Constants used by the Spacewalk Proxy""" # HTTP Headers HEADER_ACTUAL_URI = 'X-RHN-ActualURI' HEADER_EFFECTIVE_URI = 'X-RHN-EffectiveURI' HEADER_CHECKSUM = 'X-RHN-Checksum' HEADER_LOCATION = 'Location' HEADER_CONTENT_LENGTH = 'Content-Length' HEADER_RHN_REDIRECT = 'X-RHN-Redirect' HEADER_R...
#!/usr/bin/env python # # A script to compare the --debug=memoizer output found int # two different files. import sys,string def memoize_output(fname): mout = {} lines=filter(lambda words: len(words) == 5 and words[1] == 'hits' and words[3] == 'misses', ...
"""Email backend that writes messages to a file.""" import datetime import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend from django.utils import six class EmailBackend(ConsoleEmailBackend...
import HTMLParser import json import random import re import urllib2 import urlparse import requests,os,time import xbmc,xbmcaddon USERDATA_PATH = xbmc.translatePath('special://home/userdata/addon_data') ADDON_DATA = os.path.join(USERDATA_PATH,'script.module.universalscrapers') full_file = ADDON_DATA + '/Log.txt' def ...
''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: lib_glx.py 597 2007-02-03 16:13:07Z Alex.Holkner $' import ctypes from ctypes import * import pyglet from pyglet.gl.lib import missing_function, decorate_function from pyglet.compat import asbytes __all__ = ['link_GL', 'link_GLU', 'link_WGL'] _debug_tr...
import time class BucketListingRef(object): """ Container that holds a reference to one result from a bucket listing, allowing polymorphic iteration over wildcard-iterated URIs, Keys, or Prefixes. At a minimum, every reference contains a StorageUri. If the reference came from a bucket listing (as opposed to...
"""Export a TensorFlow model. See: go/tf-exporter """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import six from google.protobuf.any_pb2 import Any from tensorflow.contrib.session_bundle import constants from tensorflow.contrib.s...
#!/usr/bin/env python from __future__ import print_function import unicodecsv as csv import argparse import panphon import Levenshtein import munkres import panphon.distance from functools import partial def levenshtein_dist(_, a, b): return Levenshtein.distance(a, b) def dogol_leven_dist(_, a, b): return ...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import re from datetime import date, datetime from decimal import Decimal from django import template from django.conf import settings from django.template import defaultfilters from django.utils.encoding import force_text from django.utils.formats imp...
# modified by: Sarwan Peiter """ So I have already written the driver for the AWG. Now the next step is to write an interface to communicates with driver. An also usefull interface is to write a library to generate pulses. """ import time import logging import numpy as np import struct import os,sys from datetime impo...
from ctypes import c_void_p from django.contrib.gis.geos.error import GEOSException class GEOSBase(object): """ Base object for GEOS objects that has a pointer access property that controls access to the underlying C pointer. """ # Initially the pointer is NULL. _ptr = None # Default all...
"""Test .dist-info style distributions. """ import os import shutil import tempfile import pytest import pkg_resources from .textwrap import DALS class TestDistInfo: def test_distinfo(self): dists = dict( (d.project_name, d) for d in pkg_resources.find_distributions(self.tmpdir)...
#!/usr/bin/python ''' Copyright 2013 Google Inc. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. ''' ''' Rewrites a JSON file to use Python's standard JSON pretty-print format, so that subsequent runs of rebaseline.py will generate useful diffs (only the actual check...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_urllib_request, ) from ..utils import ( ExtractorError, ) class ScreencastIE(InfoExtractor): _VALID_URL = r'https?://www\.screencast\.com/t/(?P<id>[a-zA-Z0-...
import hr_timesheet_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
#!/usr/bin/env python """ Example of the very basic, minimal framework for a wxPython application This version adds a single button """ import wx import os #-------------------------------------------------------------- # This is how you pre-establish a file filter so that the dialog # only shows the extension(s) ...
""" This module contains all of the GEOS ctypes function prototypes. Each prototype handles the interaction between the GEOS library and Python via ctypes. """ # Coordinate sequence routines. from django.contrib.gis.geos.prototypes.coordseq import (create_cs, get_cs, cs_clone, cs_getordinate, cs_setordinate, cs...
# A Python port of the MS knowledge base article Q157234 # "How to deal with localized and renamed user and group names" # http://support.microsoft.com/default.aspx?kbid=157234 import sys from win32net import NetUserModalsGet from win32security import LookupAccountSid import pywintypes from ntsecuritycon import * def...
#!/usr/bin/env python from xml.sax.saxutils import escape, quoteattr from param import * from emit import Emit # Emit APM documentation in an machine readable XML format class XmlEmit(Emit): def __init__(self): wiki_fname = 'apm.pdef.xml' self.f = open(wiki_fname, mode='w') preamble ...