content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
import functools
import openerp
from openerp.http import Controller, route, request, Response
def webservice(f):
@functools.wraps(f)
def wrap(*args, **kw):
try:
return f(*args, **kw)
except Exception, e:
return Response(response=str(e), status=500... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import paramiko
import time
import argparse
import socket
import array
import json
import time
import re
try:
from ansible.module_utils import cnos
HAS_LIB = True
except:... |
"""A Julia set computing workflow: https://en.wikipedia.org/wiki/Julia_set.
We use the quadratic polinomial f(z) = z*z + c, with c = -.62772 +.42193i
"""
# pytype: skip-file
import argparse
import apache_beam as beam
from apache_beam.io import WriteToText
def from_pixel(x, y, n):
"""Converts a NxN pixel positio... |
from __future__ import print_function
import json
import mmap
import os
import re
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*')
parser.add_argument("-e", "--skip-exceptions", help="ignore hack/verify-f... |
"""
Test contentstore.mongo functionality
"""
import logging
from uuid import uuid4
import unittest
import mimetypes
from tempfile import mkdtemp
import path
import shutil
from opaque_keys.edx.locator import CourseLocator, AssetLocator
from opaque_keys.edx.keys import AssetKey
from xmodule.tests import DATA_DIR
from ... |
from __future__ import unicode_literals
import yaml
class CategoryConf(object):
def __init__(self, name, description):
self.name = name
self.description = description
class MediaConf(object):
def __init__(self, pattern, tags, description):
self.pattern = pattern
self.tags = ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
sieve.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*********************************... |
"""Executor manager."""
from __future__ import absolute_import
import logging
import numpy as np
from .base import mx_real_t
from . import ndarray as nd
from .context import cpu
from .io import DataDesc
def _split_input_slice(batch_size, work_load_list):
"""Get input slice from the input shape.
Parameters
... |
from __future__ import absolute_import
import datetime
try:
import pytz
except ImportError:
pytz = None
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from django.utils.unittest import skipIf
from .models import Article, Comment, Category
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
"""L2HMC compatible with TensorFlow's eager execution.
Reference [Generalizing Hamiltonian Monte Carlo with Neural
Networks](https://arxiv.org/pdf/1711.09268.pdf)
Code adapted from the released TensorFlow graph implementation by original
authors https://github.com/brain-research/l2hmc.
"""
from __future__ import abso... |
"""The Tornado web server and tools."""
from __future__ import absolute_import, division, print_function, with_statement
# version is a human-readable version number.
# version_info is a four-tuple for programmatic comparison. The first
# three numbers are the components of the version number. The fourth
# is zero ... |
#! /usr/bin/env python
import ctypes
from ctypes.util import find_library
__author__ = 'Suresh Sundriyal'
__license__ = 'CC0 - No rights reserved.'
__version__ = '0.0.1'
__credits__ = [ 'Joongi Kim: https://gist.github.com/achimnol/3021995',
'sqlite3.org: http://www.sqlite.org/backup.html' ]
SQLITE_O... |
"""An example gRPC Python-using server-side application."""
import grpc
# requests_pb2 is a semantic dependency of this module.
from tests.testing import _application_common
from tests.testing.proto import requests_pb2 # pylint: disable=unused-import
from tests.testing.proto import services_pb2
from tests.testing.pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import upsidedown
import sys
from response import Response
from pb_logging import PBLogger
logger = PBLogger("Rage")
# flips text using upsidedown module and has a donger for emohasis
def run(response, args=[]):
response_obj = Response(sys.modules[__name__])
toFli... |
"""Declare exceptions and warnings that are specific to PyTables."""
from __future__ import absolute_import
import six
__docformat__ = 'reStructuredText'
"""The format of documentation strings in this module."""
import os
import warnings
import traceback
class HDF5ExtError(RuntimeError):
"""A low level HDF5 op... |
## Regression Plots
from __future__ import print_function
from statsmodels.compat import lzip
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
### Duncan's Prestige Dataset
#### Load the Data
# We can use a utility function ... |
"""
State Space Model
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
from .representation import Representation
from .kalman_filter import KalmanFilter
import statsmodels.tsa.base.tsa_model as tsbase
class Model(KalmanFilter, Repr... |
""" Modified version of build_scripts that handles building scripts from functions.
"""
from __future__ import division, absolute_import, print_function
from distutils.command.build_scripts import build_scripts as old_build_scripts
from numpy.distutils import log
from numpy.distutils.misc_util import is_string
class... |
import random
from twisted.internet import defer, endpoints, protocol, reactor
from twisted.trial import unittest
from p2pool import networks, p2p
from p2pool.bitcoin import data as bitcoin_data
from p2pool.util import deferral
class Test(unittest.TestCase):
@defer.inlineCallbacks
def test_sharereq(self):
... |
import os
import re
import imp
import json
class TweetProcessor:
plugins = {}
commands = {}
base_path = os.path.dirname(os.path.realpath(__file__))
plugin_path = os.path.join(base_path, "plugins")
def __init__(self):
self.load_plugins()
def load_plugins(self):
"""Loads plu... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
class OrderedDict(dict):
"""
A dictionary that keeps its keys in the order in which they're inserted.
Copied from Django's SortedDict with some modifications.
"""
def __new__(cls, *args, **kwargs):
instance = super(OrderedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrd... |
import json
from random import randint
from dateutil.relativedelta import relativedelta
from libmozdata import utils as lmdutils
from libmozdata.bugzilla import BugzillaUser
from auto_nag import logger, utils
from auto_nag.people import People
from auto_nag.round_robin_calendar import Calendar
class RoundRobin(obje... |
import event_confirm
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/python
import os
import subprocess
import re
def runCommand(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
p.wait()
return iter(p.stdout.readline, b'')
def dumpRunCommand(command,... |
"""
Base file upload handler classes, and the built-in concrete subclasses
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.uploadedfile import TemporaryUplo... |
# coding: utf8
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOI... |
"""
==========================================================
Sample pipeline for text feature extraction and evaluation
==========================================================
The dataset used in this example is the 20 newsgroups dataset which will be
automatically downloaded and then cached and reused for the do... |
from IPy import IP
from collections import namedtuple
from gi.repository import GLib
from pyanaconda import constants
from pyanaconda.threads import threadMgr, AnacondaThread
from pyanaconda.ui.gui import GUIObject
from pyanaconda.ui.gui.utils import escape_markup
from pyanaconda.i18n import _
from pyanaconda import n... |
from ctypes import *
import os
from constants import *
#### STRUCTURES ####
#### GList C structure
class GList(Structure):
pass
GList._fields_ = [("data", c_void_p),
("next", POINTER(GList)),
("pred", POINTER(GList))]
#### GNode C structure
class GNode(Structure):
pass
G... |
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import (generate_binary_structure,
iterate_structure, binary_erosion)
import hashlib
from operator import itemgetter
IDX... |
import os
import shutil
import time
import unittest
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[],[]]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
... |
import random
import socket
from furl import furl
import bzrest
import requests
from requests import RequestException
from flask import current_app
from functools import wraps
from redo import retry
from relengapi.blueprints.slaveloan import bugzilla
from relengapi.blueprints.slaveloan import slave_mappings
from re... |
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
DRIVER_PATH = "neutron.plugins.nec.drivers.%s"
DRIVER_LIST = {
'trema': DRIVER_PATH % "trema.TremaPortBaseDriver",
'trema_port': DRIVER_PATH % "trema.TremaPortBaseDriver",
... |
"""
Use this module to get and run all tk tests.
tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
"""
import os
import sys
import unittest
import importlib
import test.support
this_dir_path ... |
"""
Helper functions
"""
import numpy as np
def xgrad(gray_image):
"""
Returns the X gradient of grayscale image,
imitating MatLab's gradient function
Parameters
----------
gray_image : numpy.ndarray
Grayscale image
Returns
-------
numpy.ndarray
X gradient of imag... |
"""This module maps elements from the {EXIF} namespace[1] to GData objects.
These elements describe image data, using exif attributes[2].
Picasa Web Albums uses the exif namespace to represent Exif data encoded
in a photo [3].
Picasa Web Albums uses the following exif elements:
exif:distance
exif:exposure
exif:flas... |
from m5.params import *
from BaseKvmCPU import BaseKvmCPU
class X86KvmCPU(BaseKvmCPU):
type = 'X86KvmCPU'
cxx_header = "cpu/kvm/x86_cpu.hh"
@classmethod
def export_methods(cls, code):
code('''
void dumpFpuRegs();
void dumpIntRegs();
void dumpSpecRegs();
void dumpXCRs();... |
from __future__ import unicode_literals
import frappe, os
from frappe.model.meta import Meta
from frappe.modules import scrub, get_module_path, load_doctype_module
from frappe.model.workflow import get_workflow_name
from frappe.utils import get_html_format
from frappe.translate import make_dict_from_messages, extract_m... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True, type='list'),
state=dict(
default='present',
... |
# coding=utf-8
import struct
import time
import os, sys
def parse_hst_csv(src_path, des_path, time_from=None, time_to=None):
content = open(src_path, 'rb').read()
# 读取头文件结构信息
# 基础版本
print "basic verison: %i" % struct.unpack("i", content[0:4])[0]
# 版本信息
print "versoin: %s" % "".join(struct.unpack("64c"... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
contour.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander bruy at gmail dot com
*******************... |
from django.conf import settings
from django.core.checks.security import base, csrf, sessions
from django.core.checks.utils import patch_middleware_message
from django.test import SimpleTestCase
from django.test.utils import override_settings
class CheckSessionCookieSecureTest(SimpleTestCase):
@property
def f... |
from __future__ import division
from datetime import datetime
from dateutil.relativedelta import relativedelta
import openerp.addons.decimal_precision as dp
from openerp import models, fields, api
from openerp.tools.float_utils import float_round as round, float_compare
class AccountPaymentTerm(models.Model):
_i... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt impo... |
import os
class SparkFiles(object):
"""
Resolves paths to files added through
L{SparkContext.addFile()<pyspark.context.SparkContext.addFile>}.
SparkFiles contains only classmethods; users should not create SparkFiles
instances.
"""
_root_directory = None
_is_running_on_worker = False... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
from operator import itemgetter
class account_move_line(osv.osv):
_inherit = "account.move.line"
# delegate to parent, used for local fields.function redefinition
def _amount_to_pay(self, cr, uid, ids, field_names, args, context=Non... |
"""
interface device support class(es)
http://libvirt.org/formatdomain.html#elementsNICS
http://libvirt.org/formatnwfilter.html#nwfconceptsvars
"""
from virttest.libvirt_xml import accessors, xcepts
from virttest.libvirt_xml.devices import base, librarian
class Interface(base.TypedDeviceBase):
__slots__ = ('so... |
import hypothesis
import hypothesis.strategies as strategies
import pytest
from testix import fake
from testix import scenario
from testix import testixexception
from testix import argumentexpectations
class TestArgumentExpectations:
@hypothesis.given(A=strategies.integers(),B=strategies.integers())
def test_a... |
from django.template.defaultfilters import slugify
from django.contrib import admin
from cms.models import *
from django.conf import settings
from PIL import Image
import glob, os
from cms.forms import *
class SubNavInline(admin.TabularInline):
model = SubNav
extra = 0
class NavAdmin(admin.ModelAdmin):
li... |
"""Argument-less script to select what to run on the buildbots."""
import filecmp
import os
import shutil
import subprocess
import sys
if sys.platform in ['win32', 'cygwin']:
EXE_SUFFIX = '.exe'
else:
EXE_SUFFIX = ''
BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__))
TRUNK_DIR = os.path.dirname(BUILDBO... |
from mock import MagicMock
from mock import patch
from paasta_tools.cli.cmds import get_latest_deployment
def test_get_latest_deployment(capfd):
mock_args = MagicMock(
service='',
deploy_group='',
soa_dir='',
)
with patch(
'paasta_tools.cli.cmds.get_latest_deployment.get_c... |
# coding:utf-8
'''
Created on 2017/12/8.
@author: chk01
'''
import scipy.io as scio
# data = scio.loadmat(file)
# from sklearn.model_selection import train_test_split
#
# print(data['X'].shape)
# print(data['Y'].shape)
# X_train, X_test, Y_train, Y_test = train_test_split(data['X'], data['Y'], test_size=0.2)
# print(... |
from boto.resultset import ResultSet
from boto.ec2.elb.listelement import ListElement
class Alarm(object):
def __init__(self, connection=None):
self.connection = connection
self.name = None
self.alarm_arn = None
def __repr__(self):
return 'Alarm:%s' % self.name
def startEl... |
from django.core.exceptions import ValidationError
from django.core.validators import (
MaxLengthValidator, MaxValueValidator, MinLengthValidator,
MinValueValidator,
)
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _, ngettext_lazy
class ArrayMaxLengt... |
#!/usr/bin/env python
import queue
import sched
import time
import unittest
from test import support
try:
import threading
except ImportError:
threading = None
TIMEOUT = 10
class Timer:
def __init__(self):
self._cond = threading.Condition()
self._time = 0
self._stop = 0
def ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
try:
from lxml.etree import fromstring
except ImportError:
from xml.etree.ElementTree import fromstring
from units.compat.mock import patch
from ansible.modules.network.junos import junos_command
from units.modules.utils i... |
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
class EchoLayer(YowInterfaceLayer):
@ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
if messageProtocolEntity.getType() == 'text':
self.onTextMessage(messa... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackPortforwarding(AnsibleCloudStack):
def __init__(self, module):
... |
from __future__ import absolute_import
from django.test import TestCase
from .models import Place, Restaurant, Bar, Favorites, Target, UndergroundBar
class OneToOneRegressionTests(TestCase):
def setUp(self):
self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
self.p1.save()
s... |
import sys
import itk
itk.auto_progress(2)
inputImage = sys.argv[1]
outputImage = sys.argv[2]
radiusValue = int(sys.argv[3])
PixelType = itk.UC
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
ReaderType = itk.ImageFileReader[ImageType]
reader = ReaderType.New()
reader.SetFileName(inputImage)
StructuringE... |
"""Redo the builtin repr() (representation) but with limits on most sizes."""
__all__ = ["Repr", "repr", "recursive_repr"]
import builtins
from itertools import islice
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
'Decorato... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import warnings
from typing import Optional, Union
import numpy as np
import pandas as pd
import typic
from solarpy import declination
from tstoolbox import tsutils
from . import meteolib, utils
warnings.filterwarnings("ignore... |
"""Extend OptionParser with commands.
Example:
>>> parser = OptionParser()
>>> parser.usage = '%prog COMMAND [options] <arg> ...'
>>> parser.add_command('build', 'mymod.build')
>>> parser.add_command('clean', run_clean, add_opt_clean)
>>> run, options, args = parser.parse_command(sys.argv[1:])
>>> return run(options,... |
"""
File-like objects that read from or write to a bsddb record.
This implements (nearly) all stdio methods.
f = DBRecIO(db, key, txn=None)
f.close() # explicitly release resources held
flag = f.isatty() # always false
pos = f.tell() # get current position
f.seek(pos) # set current position
f... |
import gc
import os
import sys
import signal
import weakref
from cStringIO import StringIO
import unittest
@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on f... |
import dropbox
import sys
from sqlsync import *
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import os
from pushover import message
import json
if check_lock() == 1:
print 'Database is locked or unreachable, quitting...'
sys.exit()
conn = S3Connection('', '')
pb = conn.get_bucket('')
a... |
"""Implementation of Cluster Resolvers for TF_CONFIG Environment Variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver
from tensorflow... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard.usage import base
class UsageView(tables.DataTableView):
usage_class = None
show_terminated = True
csv_template_name = None
pa... |
from __future__ import print_function
try:
import nltk.corpus
except ImportError:
print("nltk not found")
print("please install it")
raise
from scipy.spatial import distance
import numpy as np
import string
from gensim import corpora, models, similarities
import sklearn.datasets
import nltk.stem
from c... |
# -*- 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 field 'Response.answer_number'
db.add_column(u'survey_response', 'answer_number',
... |
"""Regular expression-based rules."""
import logging
import re
import regex
from .cpr import CPRRule
from .rule import Rule
from ..items import MatchItem
class RegexRule(Rule):
"""Represents a rule which matches using a regular expression."""
def __init__(self, name, pattern_strings, sensitivity, cpr_enab... |
#! /usr/bin/env python
'''
Run this script from Source/Core/ to find all the #include cycles.
'''
import subprocess
def get_local_includes_for(path):
lines = open(path).read().split('\n')
includes = [l.strip() for l in lines if l.strip().startswith('#include')]
return [i.split()[1][1:-1] for i in include... |
from glance.common import wsgi
from glance.registry.api.v2 import rpc
def init(mapper):
rpc_resource = rpc.create_resource()
mapper.connect("/rpc", controller=rpc_resource,
conditions=dict(method=["POST"]),
action="__call__")
class API(wsgi.Router):
"""WSGI entry po... |
"""
from datetime import timedelta
from airflow.utils.dates import days_ago
from airflow import DAG
from airflow.providers.docker.operators.docker_swarm import DockerSwarmOperator
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': days_ago(1),
'email': ['<EMAIL>'],
'email_... |
"""Support for binary sensor using the PiFace Digital I/O module on a RPi."""
import voluptuous as vol
from homeassistant.components import rpi_pfio
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME
import homeassistant... |
import unittest
from lightning_core.vg.vg import *
from lightning_core.vg.parser import *
from lxml import etree
class TestLinearGrad(unittest.TestCase):
def test_constructor(self):
c1 = [256,256,256,256]
c2 = [ 0, 0, 0, 0]
sp1 = Stop(c1, '100')
sp2 = Stop(c2, '0')
gtf ... |
"""Tests OPF descriptionTemplate.py-based experiment/sub-experiment pair"""
import os
import pprint
import sys
import unittest2 as unittest
from pkg_resources import resource_filename
from nupic.frameworks.opf.opfhelpers import (
loadExperimentDescriptionScriptFromDir,
getExperimentDescriptionInterfaceFromModule... |
from __future__ import absolute_import, division, print_function, \
with_statement
from ctypes import c_char_p, c_int, c_long, byref,\
create_string_buffer, c_void_p
from shadowsocks import common
from shadowsocks.crypto import util
__all__ = ['ciphers']
libcrypto = None
loaded = False
buf_size = 2048
de... |
"""Conversion functions between RGB and other color systems.
This modules provides two functions for each color system ABC:
rgb_to_abc(r, g, b) --> a, b, c
abc_to_rgb(a, b, c) --> r, g, b
All inputs and outputs are triples of floats in the range [0.0...1.0]
(with the exception of I and Q, which covers a ... |
#!/usr/bin/env python
# vim: fileencoding=utf-8 et ts=4 sts=4 sw=4 tw=0 fdm=indent
"""
A simple RPC server that shows how to:
* start several worker processes
* use zmq proxy device to load balance requests to the workers
* make each worker to serve multiple RPC services asynchronously
using the Python Threading mu... |
"""
Preference models, queryset and managers that handle the logic for persisting preferences.
"""
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.utils.functional import cached_property
from dynamic_preferences import user_preferences_registry, gl... |
# A demo of the Windows CE Remote API
#
# This connects to a CE device, and interacts with it.
import wincerapi
import win32event
import win32api
import win32con
import os
import sys
import getopt
from repr import repr
def DumpPythonRegistry():
try:
h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHIN... |
"""
Test suite for PictureHandler and ItemPictureHandler
"""
from tests.test_case import TestCase
import json
from io import BytesIO
import os
import uuid
import http.client as client
from models import Item, Picture
from tests import test_utils
import utils
EXPECTED_RESULTS = test_utils.RESULTS['pictures']
TEST_... |
from moto.core import BaseBackend
import boto.ec2.cloudwatch
import datetime
class Dimension(object):
def __init__(self, name, value):
self.name = name
self.value = value
class FakeAlarm(object):
def __init__(self, name, comparison_operator, evaluation_periods, period,
thres... |
"""Display the details of a record on which some operation is to be carried
out and prompt for the user's confirmation that it is the correct record.
Upon the clicking of the confirmation button, augment step by one.
"""
__revision__ = "$Id$"
import cgi
from invenio.config import CFG_SITE_ADMIN_EMAIL
from inven... |
from tornado.options import define, options
define('debug', default=True, help='debug mode')
define('port', default=8888, help='port to listen on', type=int)
define('redis_port', default=6379, help='redis port')
define('redis_host', default='localhost', help='redis hostname or IP')
define('es_hosts', default='localhos... |
import ecto
import ecto_test
import sys
def test_nodelay():
plasm = ecto.Plasm()
ping = ecto_test.Ping("Ping")
metrics = ecto_test.Metrics("Metrics", queue_size=10)
plasm.connect(ping[:] >> metrics[:])
sched = ecto.Scheduler(plasm)
sched.execute(niter=10000)
print "Hz:", metrics.outp... |
"""
Relabel a cluster.
@author: Ewan Higgs (Universiteit Gent)
@author: Kenneth Hoste (Universiteit Gent)
"""
import sys
from vsc.utils.generaloption import GeneralOption
from hod import VERSION as HOD_VERSION
from hod.subcommands.subcommand import SubCommand
import hod.cluster as hc
class RelabelOptions(GeneralO... |
microcode = '''
def macroop PUSHF {
.adjust_env oszIn64Override
rflags t1
st t1, ss, [1, t0, rsp], "-env.stackSize", dataSize=ssz
subi rsp, rsp, ssz
};
def macroop POPF {
.adjust_env oszIn64Override
ld t1, ss, [1, t0, rsp], dataSize=ssz
addi rsp, rsp, ssz
wrflags t1, t0
};
''' |
import logging
import poplib
import time
from imaplib import IMAP4
from imaplib import IMAP4_SSL
from poplib import POP3
from poplib import POP3_SSL
try:
import cStringIO as StringIO
except ImportError:
import StringIO
import zipfile
import base64
from openerp import addons
from openerp.osv import fields, osv... |
import os, sys, time
try:
import thread
except ImportError:
import dummy_thread as thread
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
try:
import threading
except ImportError:
pass
RUN_RELOADE... |
from PyQt5.QtCore import pyqtSlot, QFile, QRegExp, Qt, QTextStream
from PyQt5.QtWidgets import (QApplication, QDialog, QFileDialog, QMessageBox,
QStyleFactory)
from ui_stylesheeteditor import Ui_StyleSheetEditor
class StyleSheetEditor(QDialog):
def __init__(self, parent=None):
super(StyleSheetEdi... |
"""
Time related utilities and helper functions.
"""
import calendar
import datetime
import time
import iso8601
import six
# ISO 8601 extended time format with microseconds
_ISO8601_TIME_FORMAT_SUBSECOND = '%Y-%m-%dT%H:%M:%S.%f'
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
PERFECT_TIME_FORMAT = _ISO8601_TIME_FORMAT_S... |
"""Read the balance of your bank accounts via FinTS."""
from collections import namedtuple
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_USERNAME, CONF_PIN, CONF_URL, CONF_NAME
import homeassistan... |
"""
Django's support for templates.
The django.template namespace contains two independent subsystems:
1. Multiple Template Engines: support for pluggable template backends,
built-in backends and backend-independent APIs
2. Django Template Language: Django's own template engine, including its
built-in loaders, ... |
"""
Copyright 2017 Oliver Smith
This file is part of pmbootstrap.
pmbootstrap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pmbootstrap ... |
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import GB2312DistributionAnalysis
from .mbcssm import GB2312SMModel
class GB2312Prober(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
sel... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
user.py
---------------------
Date : January 2015
Copyright : (C) 2015 by Nathan Woodrow
Email : woodrow dot nathan at gmail dot com
********************... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.