content stringlengths 4 20k |
|---|
import copy
import optparse
__version__ = "1.0"
# Constants used by Visual Studio.
UNKNOWN_GUID = "{00000000-0000-0000-0000-000000000000}"
FOLDER_GUID = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
C_PROJECT_GUID = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}"
CSHARP_PROJECT_GUID = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
# ... |
import logging
import os
import tempfile
import shutil
import json
from subprocess import check_call
from tarfile import TarFile
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
"""Rebuild the internal timezone info in dateutil/zo... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import os
try:
import psutil
psutil_found = True
except ImportError:
psutil_fou... |
import os
from .base import NullBrowser, ExecutorBrowser, require_arg
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorservo import ServoTestharnessExecutor, ServoRefTestExecutor
here = os.path.join(os.path.split(__file__)[0])
__wptrunner__ = {"product": "servo",
... |
"""Functional tests for quantized convolutional operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# TODO(petewarden) - Remove this ugly hack to get around Python linking problems
# with Bazel.
# pylint... |
import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
from autobahn.websocket.compress import *
class EchoSer... |
import _plotly_utils.basevalidators
class MarkerValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="marker", parent_name="scattermapbox", **kwargs):
super(MarkerValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from django.template import Node, resolve_variable
from django.template import TemplateSyntaxError, TokenParser, Library
from django.template import TOKEN_TEXT, TOKEN_VAR
from django.utils import translation
register = Library()
class GetAvailableLanguagesNode(Node):
def __init__(self, variable):
self.var... |
"""
Converter for legacy block tree definitions in XML format
"""
from __future__ import absolute_import, print_function
from ..core.io import yaml
from . import xml
def from_xml(filename):
"""Load block tree description from xml file"""
element, version_info = xml.load(filename, 'block_tree.dtd')
try:... |
import re
def plural(noun):
# This is a dumb plural() implementation that is just enough for our uses.
if re.search("h$", noun):
return noun + "es"
else:
return noun + "s"
def pluralize(noun, count):
if count != 1:
noun = plural(noun)
return "%d %s" % (count, noun)
def ... |
from reportlab.lib.pagesizes import *
def layout():
return portrait(A4)
def corpo (c,row,Y):
#c.setLineWidth(1)
c.setFont('Helvetica',11)
c.drawString(42,Y,row['codart'])
c.drawString(137,Y,row['descrizart'])
c.drawRightString(468,Y,str(row['prezzo_1']))
c.drawRightString(550,Y,str(row['pr... |
"""tzinfo implementations for psycopg2
This module holds two different tzinfo implementations that can be used as
the 'tzinfo' argument to datetime constructors, directly passed to psycopg
functions or used to set the .tzinfo_factory attribute in cursors.
"""
# psycopg/tz.py - tzinfo implementation
#
# Copyright (C) ... |
#! /usr/bin/env python3
"""Tool for measuring execution time of small code snippets.
This module avoids a number of common traps for measuring execution
times. See also Tim Peters' introduction to the Algorithms chapter in
the Python Cookbook, published by O'Reilly.
Library usage: see the Timer class.
Command line... |
import os
import shutil
import sys
from common_function import RemoveUnusedFilesInReleaseMode
def Clean(dir_to_clean):
if os.path.isdir(dir_to_clean):
shutil.rmtree(dir_to_clean)
def PrepareFromXwalk(src_dir, target_dir):
'''Prepare different files for app packaging tools. All resources are used by
make_ap... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class WorldStarHipHopIE(InfoExtractor):
_VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/(?:videos|android)/video\.php\?v=(?P<id>.*)'
_TESTS = [{
"url": "http://www.worldstarhiphop.com/videos/video.p... |
import re
import json
from bs4 import BeautifulSoup
from page_parse.user import public
from decorators import parse_decorator
# 以下是通过认证企业主页进行解析
@parse_decorator(0)
def get_friends(html):
cont = public.get_left(html)
soup = BeautifulSoup(cont, 'html.parser')
return int(soup.find_all('strong')[0].get_text... |
from __future__ import unicode_literals
import re
import warnings
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from djblets.registries.registry import (ALREADY_REGISTERED,
AlreadyRegisteredError,
... |
"""Create nodejs template with the back-end and front-end templates."""
def GenerateConfig(context):
"""Generate configuration."""
backend = context.env['deployment'] + '-backend'
frontend = context.env['deployment'] + '-frontend'
firewall = context.env['deployment'] + '-application-fw'
application_port = ... |
# -*- coding: utf-8 -*-
"""
pygments.styles.vim
~~~~~~~~~~~~~~~~~~~
A highlighting style for Pygments, inspired by vim.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keywor... |
#coding:utf-8
import numpy
import re
import os
import sys
file_path = "../dataset/nuc/"
LABELED_DATA_NUM = 1000
if os.path.exists("../dataset/sentiment/unlabeled_text.txt"):
print "上書きしちゃうので終了"
sys.exit()
# sentenceの辞書を作る
sentences = []
sentence_num = 0
for doc_index in xrange(1, 101):
text_file = open(... |
from django.conf import settings
from django.template import loader
from django.views.i18n import set_language
from xadmin.plugins.utils import get_context_dict
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, CommAdminView, BaseAdminView
class SetLangNavPlugin(BaseAdminPlugin):
... |
"""private module containing functions used for copying data
between instances based on join conditions.
"""
from . import exc, util as orm_util, attributes
def populate(source, source_mapper, dest, dest_mapper,
synchronize_pairs, uowcommit, flag_cascaded_pks):
source_dict = source.dict
dest_di... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from builtins import str, bytes, dict, int
from builtins import map, zip, filter
from builtins import object, range
#--- STRING FUNCTIONS ----------------------------------------------------------------------... |
"""Event handlers that send email notifications."""
__metaclass__ = type
from email.Header import Header
from email.MIMEText import MIMEText
from email.Utils import (
formataddr,
make_msgid,
)
from zope.component import (
getAdapter,
getUtility,
)
from lp.registry.enums import TeamMembership... |
from oslo.config import cfg
import webob.dec
import webob.exc
import nova.api.ec2
from nova import context
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova import utils
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
def ec2_error_response(request_id, cod... |
# coding=utf8
"""
Test that C++ supports wchar_t correctly.
"""
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class CxxWCharTTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
"""Test that C++ supports wchar_t correctly."""
... |
from .main import PublicHD
def start():
return PublicHD()
config = [{
'name': 'publichd',
'groups': [
{
'tab': 'searcher',
'list': 'torrent_providers',
'name': 'PublicHD',
'description': 'Public Torrent site with only HD content. See <a href="https:... |
from io import IOBase
from qgis.core import QgsProject
import logging
import os
logger = logging.getLogger()
class ProjectStateMixin(object):
"""class mixin for writing and loading states of tools to the Qgis Project
files (``*.qgs``). Expects a class with:
- an array of tools (self.tools)
- in Qg... |
"""
Tutorial - The default method
Request handler objects can implement a method called "default" that
is called when no other suitable method/object could be found.
Essentially, if CherryPy2 can't find a matching request handler object
for the given request URI, it will use the default method of the object
located de... |
import os
import subprocess
import sys
import tempfile
from compile_error import CompileError
import re
# Method for finding index of certain characters in a string, n being the n'th occurence of the character/string
def find_nth(haystack, needle, n):
start = haystack.find(needle.encode())
while start >= 0 and... |
"""
Store database-specific configuration parameters
"""
import uuid
import datetime
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
from openerp.tools import misc, config
"""
A dictionary holding some configuration parameters to be initialized when the database is created.
"""
_default_paramete... |
"""Windows can't run .sh files, so this is a Python implementation of
update.sh. This script should replace update.sh on all platforms eventually."""
import os
import re
import shutil
import subprocess
import sys
# Do NOT CHANGE this if you don't know what you're doing -- see
# https://code.google.com/p/chromium/wiki... |
import sys
from _pytest.doctest import DoctestItem, DoctestModule, DoctestTextfile
import py
import pytest
class TestDoctests:
def test_collect_testtextfile(self, testdir):
w = testdir.maketxtfile(whatever="")
checkfile = testdir.maketxtfile(test_something="""
alskdjalsdk
>... |
from __future__ import print_function
import email.utils
import fcntl
import io
import os
import pkg_resources
import random
import resource
import socket
import sys
import textwrap
import time
import traceback
import inspect
import errno
import warnings
import cgi
from gunicorn.errors import AppImportError
from guni... |
"""
This script calculates the minimum spanning tree of a shapefile network
"""
import networkx as nx
import cea.inputlocator
from geopandas import GeoDataFrame as gdf
import cea.config
import os
__author__ = "Jimeno A. Fonseca"
__copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich"
__cr... |
# PYTHON 3
# The concatenator for the segment embeddings with ALWAYS 3 segments, but concatenating always 9 segments.
# The segment embeddings have been created using the TIGER corpus and RESCAL.
import sys
import pickle as cPickle
import datetime
import random
def createEmbeddings(embeddingFile, useRandomSegVect... |
# -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (<EMAIL>)
- Weixuan Fu (<EMAIL>)
- Daniel Angell (<EMAIL>)
- and many more generous open source contributors
TPOT is free software: you can redistribu... |
#!/usr/bin/env python
import argparse
import datetime
import time
from wrfpy import utils
from wrfpy.upp import upp
from wrfpy.config import config
import os
class run_upp(config):
''''
'''
def __init__(self, datestring):
config.__init__(self)
dt = utils.convert_cylc_time(datestring)
postprocess = u... |
# -*- 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 model 'HistoricalVerificationDeadline'
db.create_table('verify_s... |
"""
* Copyright 2008 Google Inc.
* Copyright (C) 2009 Luke Kenneth Casson Leighton <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* ... |
from django.db import models
from taggit.managers import TaggableManager
from kitsune.tags.forms import TagField
class BigVocabTaggableManager(TaggableManager):
"""TaggableManager for choosing among a predetermined set of tags
Taggit's seems hard-coupled to taggit's own plain-text-input widget.
"""
... |
"""
.. dialect:: mysql+oursql
:name: OurSQL
:dbapi: oursql
:connectstring: mysql+oursql://<user>:<password>@<host>[:<port>]/<dbname>
:url: http://packages.python.org/oursql/
Unicode
-------
Please see :ref:`mysql_unicode` for current recommendations on unicode
handling.
"""
import re
from .base i... |
"""Helper to provide extensibility for pickle.
This is only useful to add pickle support for extension types defined in
C, not for instances of user-defined classes.
"""
__all__ = ["pickle", "constructor",
"add_extension", "remove_extension", "clear_extension_cache"]
dispatch_table = {}
def pickle(ob_typ... |
"""Tests for handshake._base module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket.common import ExtensionParameter
from mod_pywebsocket.common import ExtensionParsingException
from mod_pywebsocket.common import format_extensions
from mod_pywebsocke... |
import glob
import os
import numpy as np
from chainer.dataset import download
from chainercv.chainer_experimental.datasets.sliceable import GetterDataset
from chainercv.datasets.cityscapes.cityscapes_utils import cityscapes_labels
from chainercv.utils import read_image
from chainercv.utils import read_label
class ... |
""" This is the utils module that collects convenience functions and code that are
useful for charts ecosystem.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# Th... |
"""Word cloud is ungraded xblock used by students to
generate and view word cloud.
On the client side we show:
If student does not yet answered - `num_inputs` numbers of text inputs.
If student have answered - words he entered and cloud.
"""
import json
import logging
from pkg_resources import resource_string
from x... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_vpc_interface
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosVpcModule(TestNxosModule):
... |
# Scan an Apple header file, generating a Python file of generator calls.
import sys
import os
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner_OSX
LONG = "Files"
SHORT = "file"
def main():
input = ["Files.h", "Aliases.h", "Finder.h"]
output = SHORT + "gen.... |
import time
from SequenceBase import SequenceBase
class SequenceLightSingle( SequenceBase ):
def __init__(self, pins):
super(SequenceLightSingle, self).__init__(pins)
print("pins %d" % len(pins))
self.seq = 0
self.lastSeq = 0
self.pinsChanged = []
self.delay = 0.05
def Restart(self):
... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class R(models.Model):
is_default = models.BooleanField(default=False)
def __str__(self):
return "%s" % self.pk
def get_default_r():
r... |
"""
Created on 23 Mar 2017
@author: Bruno Beloff (<EMAIL>)
"""
import optparse
from scs_core.data.str import Str
# --------------------------------------------------------------------------------------------------------------------
class CmdMQTTClient(object):
"""unix command line handler"""
def __init__... |
import datetime
from nova.api.openstack.compute.plugins.v3 import migrations
from nova import context
from nova import exception
from nova import objects
from nova.objects import base
from nova.openstack.common.fixture import moxstubout
from nova import test
fake_migrations = [
{
'id': 1234,
'sou... |
"""
Supports flushing metrics to graphite
"""
import sys
import socket
import logging
class GraphiteStore(object):
def __init__(self, host="localhost", port=2003, prefix="statsite.", attempts=3):
"""
Implements an interface that allows metrics to be persisted to Graphite.
Raises a :class:`... |
# -*- coding: utf-8 -*-
import logging
import os
from pysqlcipher import dbapi2 as sqlite
logging.basicConfig(level=logging.INFO)
class DbWorker:
def __init__(self, tasks, results):
logging.info(u'create DbWorker object')
self.tasks, self.results = tasks, results
self.db_name = u'data.sql... |
import re
import sys
import os
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll
winterm = None
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
return hasattr(stream, 'isatty') and stream.isatty()
class Strea... |
"""
defines a command extension system that is used by billy-util
new commands can be added by deriving from BaseCommand and overriding a few
attributes:
name: name of subcommand
help: help string displayed for subcommand
add_args(): method that calls `self.add_argument`
han... |
from pyjamas.ui.Composite import Composite
from pyjamas.ui.FlexTable import FlexTable
from pyjamas.ui.HTML import HTML
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.Widget import Widget
from pyjamas.ui.Label import Label
from pyjamas.ui import HasAlignment
from MailItems import MailItems
from L... |
from openerp.osv import fields, osv
class product_template(osv.osv):
_inherit = "product.template"
def _bom_orders_count(self, cr, uid, ids, field_name, arg, context=None):
Bom = self.pool('mrp.bom')
res = {}
for product_tmpl_id in ids:
nb = Bom.search_count(cr, uid, [('pro... |
"""Unit tests for Cells4."""
import cPickle as pickle
import os
import numpy
import unittest2 as unittest
from nupic.bindings.math import Random
from nupic.bindings.algorithms import Cells4
_RGEN = Random(43)
class Cells4Test(unittest.TestCase):
@staticmethod
def _cellsDiff(cell1, cell2):
"""Test that ... |
#!/usr/bin/env python
import os
import unittest
import tempfile
import common
from staging import utils_cgroup
from autotest.client.shared import error
# Mount file content, Controllers and mount points from RHEL-6
mount_1 = """rootfs / rootfs rw 0 0
proc /proc proc rw,relatime 0 0
sysfs /sys sysfs rw,seclabel,relati... |
"""
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
def CheckChange(input_api, output_api):
"""Checks that histograms.xml is pretty-printed and well-formatted."""
for f in input_api.AffectedTextFiles():
p = f.Absolut... |
#-------------------------------------------------------------------------------
# Name: Find and Replace Data Sources in MXD
# Purpose: Takes an input workspace to recursively walk through a directory
# and replace a specified path. A common use case is when the name
# of a server ... |
# Test various flavors of legal and illegal future statements
import unittest
from test import support
import os
import re
rx = re.compile('\((\S+).py, line (\d+)')
def get_error_location(msg):
mo = rx.search(str(msg))
return mo.group(1, 2)
class FutureTest(unittest.TestCase):
def check_syntax_error(se... |
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Web Notes Technologies Pvt. Ltd. and Contributors"
app_description = "Open Source Enterprise Resource Planning for Small and Midsized Organizations"
app_icon = "icon-th"
app_color = "#e74c3c"
app_version = "4.11.1"
error_report_email = "<EMAIL>"
app_include_... |
"""Twisted database connection pools."""
from twisted.enterprise import adbapi
from twisted.python import log
import MySQLdb
class ReconnectingConnectionPool(adbapi.ConnectionPool):
"""Reconnecting adbapi connection pool for MySQL."""
def _runInteraction(self, interaction, *args, **kw):
"""Overrides the s... |
import Sofa
def createScene(node):
node.gravity="0 0 0"
node.createObject('VisualStyle', displayFlags="showBehaviorModels showMechanicalMappings" )
node.createObject('EulerImplicit',vdamping=1)
node.createObject('CGLinearSolver', iterations="25", tolerance="1e-5", threshold="1e-5")
linenode = n... |
"""This module represents Kannada language.
For more information, see U{http://en.wikipedia.org/wiki/Kannada_language}
"""
from translate.lang import common
class kn(common.Common):
"""This class represents Kannada."""
ignoretests = ["startcaps", "simplecaps"] |
from openerp import models, fields, api
QUOTATION_STATES = ['draft', 'sent']
class LogisticRequisitionCancel(models.TransientModel):
""" Ask a reason for the sale order cancellation."""
_name = 'sale.order.cancel'
_description = __doc__
reason_id = fields.Many2one(
'sale.order.cancel.reason... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that invoking scons-test with no arguments prints the
fall-back message and exits non-zero.
"""
import TestSCons_time
test = TestSCons_time.TestSCons_time()
expect = """\
Type "scons-time help" for usage.
"""
test.run(arguments = '', status=1... |
from sympy import Symbol, exp, log, oo, Rational, I, sin, gamma, loggamma, S, \
atan, acot, pi, cancel, E, erf, sqrt, zeta, cos, digamma, Integer
from sympy.series.gruntz import compare, mrv, rewrite, mrv_leadterm, gruntz, \
sign
from sympy.utilities.pytest import XFAIL, skip
"""
This test suite is testing the... |
from __future__ import unicode_literals
from collections import OrderedDict
import logging
import re
import six
from storops.lib.common import Dict, cache
from storops.lib.parser import OutputParser, PropDescriptor, \
ParserConfigFactory
log = logging.getLogger(__name__)
class VNXPropDescriptor(PropDescriptor... |
from __future__ import unicode_literals
from django.contrib import auth
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.signals import user_logged_in
from django.contrib.contenttypes.models import ContentType
from django.core import validators
from django.core.excep... |
"""
=================================================
Hyper-parameters of Approximate Nearest Neighbors
=================================================
This example demonstrates the behaviour of the
accuracy of the nearest neighbor queries of Locality Sensitive Hashing
Forest as the number of candidates and the numb... |
import numpy as np
from scipy import stats
def max_slope(t, x):
"""Compute the largest rate of change in the observed data."""
slopes = np.diff(x) / np.diff(t)
return np.max(np.abs(slopes))
def maximum(x):
"""Maximum observed value."""
return np.max(x)
def median(x):
"""Median of observed ... |
# -*- coding: utf-8 -*-
"""
HipparchiaServer: an interface to a database of Greek and Latin texts
Copyright: E Gunderson 2016-21
License: GNU GENERAL PUBLIC LICENSE 3
(see LICENSE in the top level directory of the distribution)
"""
import json
from flask import session
from server import hipparchia
def require... |
# coding=utf-8
"""
Collect statistics from Nginx
#### Dependencies
* urllib2
#### Usage
To enable the nginx status page to work with defaults,
add a file to /etc/nginx/sites-enabled/ (on Ubuntu) with the
following content:
<pre>
server {
listen 127.0.0.1:8080;
server_name localhost;
location /... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from fabric import api as fab
from fabric.contrib import files as fab_files
from fabric.contrib.files import exists
from fab_deploy.utils import run_as
from ..base import _, Daemon
from ..deployment import command
from ..utils import ... |
"""shared options and groups"""
from optparse import make_option, OptionGroup
from pip.locations import build_prefix
def make_option_group(group, parser):
"""
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
"""
option_group ... |
from Qt import QtCore, QtWidgets
from rezgui.models.ContextModel import ContextModel
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rez.utils.formatting import readable_time_duration
import time
class ContextResolveTimeLabel(QtWidgets.QLabel, ContextViewMixin):
def __init__(self, context_model=N... |
from dbus.exceptions import DBusException
try:
from gi.repository import Notify
except ImportError:
import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
... |
#!/usr/bin/python
'''Test cases for QEnum and QFlags'''
import unittest
from PySide.QtCore import *
class TestEnum(unittest.TestCase):
def testToInt(self):
self.assertEqual(QIODevice.NotOpen, 0)
self.assertEqual(QIODevice.ReadOnly, 1)
self.assertEqual(QIODevice.WriteOnly, 2)
self... |
import os
import shutil
import sys
import time
if sys.platform == 'win32':
import wmi
from oslo_config import cfg
from oslo_log import log as logging
from nova.i18n import _
from nova import utils
from nova.virt.hyperv import constants
from nova.virt.hyperv import vmutils
LOG = logging.getLogger(__name__)
hype... |
""" A module for reading id3 tags.
"""
from .import_util import LazyImport
_id3tag = LazyImport('id3tag.id3tag', globals(), locals(),
['id3tag'], 1)
class ID3Tags(dict):
""" A dictionary of the id3 tags in a file.
"""
def __init__(self, filename):
""" ID3Tags(filename) ->... |
from __future__ import print_function
import argparse
import distutils.version
import os
import re
import subprocess
import sys
import textwrap
def _AsVersion(string):
return distutils.version.StrictVersion(string)
def _RunXCRun(args, sdk=None):
xcrun_args = ['xcrun']
if sdk is not None:
xcrun_args.exten... |
import requests
from allauth.account.utils import get_next_redirect_url
from allauth.socialaccount.providers.oauth2.views import (OAuth2LoginView,
OAuth2CallbackView)
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from kuma.core.u... |
"""
SWF (Macromedia/Adobe Flash) file parser.
Documentation:
- Alexis' SWF Reference:
http://www.m2osw.com/swf_alexref.html
Author: Sebastien Ponce
Creation date: 26 April 2008
"""
from lib.hachoir_core.field import (FieldSet, ParserError,
Bit, Bits, UInt8, UInt32, Int16, UInt16, Float32, CString,
RawBy... |
from spack import *
class PyHttpbin(PythonPackage):
"""HTTP Request and Response Service"""
homepage = "https://github.com/Runscope/httpbin"
url = "https://pypi.io/packages/source/h/httpbin/httpbin-0.7.0.tar.gz"
version('0.7.0', sha256='cbb37790c91575f4f15757f42ad41d9f729eb227d5edbe89e4ec175486db8df... |
# TODO: Disabled the RETURN as it was breaking docs building. Someone needs to
# fix this
def run_command(command, module, check_rc=True):
"""
Run a command using the module, return
the result code and std{err,out} content.
:param command: list of command arguments
:param module: Ansible make modul... |
"""
Views for managing Neutron Routers.
"""
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.networks import views as n... |
"""
Filter support
"""
from oslo_log import log as logging
import six
from cinder.i18n import _LI
from cinder.scheduler import base_handler
LOG = logging.getLogger(__name__)
class BaseFilter(object):
"""Base class for all filter classes."""
def _filter_one(self, obj, filter_properties):
"""Return Tr... |
from mock import patch
from decimal import Decimal as D
from django.core.urlresolvers import reverse
from oscar.test.factories import create_product, create_order
from oscar.test.testcases import WebTestCase
from oscar.core.compat import get_user_model
from oscar.apps.basket.models import Basket
from oscar.apps.partn... |
# -*- coding: utf-8 -*-
""" Tests for the profile API. """
from django.test import TestCase
import ddt
from nose.tools import raises
from dateutil.parser import parse as parse_datetime
from user_api.api import account as account_api
from user_api.api import profile as profile_api
from user_api.models import UserProfi... |
"""Class representing a TLS session."""
from .utils.compat import *
from .mathtls import *
from .constants import *
class Session:
"""
This class represents a TLS session.
TLS distinguishes between connections and sessions. A new
handshake creates both a connection and a session. Data is
transm... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.playbook_executor import PlaybookExecutor
from ansi... |
"""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)... |
# -*- coding: utf-8 -*-
"""
Read the Order details xlsx and extract data from it to the Order classes
"""
from openpyxl import load_workbook, Workbook
from collections import OrderedDict
from itertools import repeat
ORDER_START_TOKEN = 'Line Item:'
SIZE_BEGIN_TOKEN = 'Size'
SIZE_END_TOKEN = 'Total Qty:'
class State... |
from openerp import api, models, fields
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
sale_type_id = fields.Many2one(
comodel_name='sale.order.type', string='Sale Type')
@api.multi
def _prepare_refund(self, invoice, date=None, period_id=None,
descri... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class VerifyCreditCardPayment(Choreography):
def __init__(self, temboo_session):
"""
... |
# -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.binding.datatypes as xs
import pyxb.binding.basis
import pyxb.utils.domutils
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.