content stringlengths 4 20k |
|---|
"""Database type conversions."""
__all__ = [
'Enum',
'UUID',
]
import uuid
from sqlalchemy import Integer
from sqlalchemy.dialects import postgresql
from sqlalchemy.types import TypeDecorator, CHAR
class Enum(TypeDecorator):
"""Handle Python 3.4 style enums.
Stores an integer-based Enum as ... |
import types
def ToDER(obj):
'''ToDER converts the given object into DER encoding'''
if type(obj) == types.NoneType:
# None turns into NULL
return TagAndLength(5, 0)
if type(obj) == types.StringType:
# Strings are PRINTABLESTRING
return TagAndLength(19, len(obj)) + obj
if type(obj) == types.Bo... |
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <CommonCrypto/CommonCryptor.h>
"""
TYPES = """
enum {
kCCAlgorithmAES128 = 0,
kCCAlgorithmDES,
kCCAlgorithm3DES,
kCCAlgorithmCAST,
kCCAlgorithmRC4,
kCCAlgorithmRC2,
kCCAlgorithmBlowfish
};
typedef uint... |
import socket
# 3p
from nose.plugins.attrib import attr
# project
from tests.checks.common import AgentCheckTest
@attr(requires='riak')
class RiakTestCase(AgentCheckTest):
CHECK_NAME = 'riak'
CHECK_GAUGES = [
'riak.node_gets',
'riak.node_gets_total',
'riak.node_puts',
'riak... |
'Represent different user inputs (commands, directives, unrecognized).'
__author__ = 'Nick Montfort'
__copyright__ = 'Copyright 2011 Nick Montfort'
__license__ = 'ISC'
__version__ = '0.5.0.0'
__status__ = 'Development'
class RichInput(object):
'Encapsulates a user input string and information derived from it.'
... |
import logging
import boto.ec2
class SecurityGroup():
def __init__(self, name, conn):
'''
Create a connection to an AWS region and add the security group if it
doesn't exist.
'''
self.__log = logging.getLogger('SecurityGroup')
self.name = name
self.desc = 'Au... |
"""Throughput test."""
import time, sys
from twisted.internet import reactor, protocol
from twisted.python import log
TIMES = 10000
S = "0123456789" * 1240
toReceive = len(S) * TIMES
class Sender(protocol.Protocol):
def connectionMade(self):
start()
self.numSent = 0
self.received = 0
... |
from __future__ import absolute_import
import math
import collections
from ansible import errors
def unique(a):
if isinstance(a,collections.Hashable):
c = set(a)
else:
c = []
for x in a:
if x not in c:
c.append(x)
return c
def intersect(a, b):
if is... |
from setuptools import setup, find_packages
XMODULES = [
"abtest = xmodule.abtest_module:ABTestDescriptor",
"book = xmodule.backcompat_module:TranslateCustomTagDescriptor",
"chapter = xmodule.seq_module:SequenceDescriptor",
"combinedopenended = xmodule.combined_open_ended_module:CombinedOpenEndedDescri... |
import os.path
from ocrfeeder.util import graphics
import Image
import gobject
from ocrfeeder.util.graphics import getImagePrintSize, getImageResolution
from ocrfeeder.util import TEXT_TYPE, IMAGE_TYPE, ALIGN_LEFT, lib
from pango import WEIGHT_NORMAL, STYLE_NORMAL
class TextData:
def __init__(self, face = 'Sans',... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import socket
import unittest
import warnings
from unittest import skipUnless
from django.conf import settings
from django.contrib.gis.geoip import HAS_GEOIP
from django.contrib.gis.geos import HAS_GEOS, GEOSGeometry
from django.test import ign... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import namedtuple
from lxml.etree import tostring
from cal... |
"""Test loadblock option
Test the option to start a node with the option loadblock which loads
a serialized blockchain from a file (usually called bootstrap.dat).
To generate that file this test uses the helper scripts available
in contrib/linearize.
"""
import os
import subprocess
import sys
import tempfile
import u... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
# NOQA
import os
import uuid
from ansible.module_utils.basic import AnsibleModule
HAS_PA... |
from .dataset import Dataset
class ServiceNowObjectDataset(Dataset):
"""ServiceNow server dataset.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param description: Dataset description.
:typ... |
m5.util.addToPath('../configs/common')
from cpu2000 import bzip2_source
workload = bzip2_source(isa, opsys, 'lgred')
root.system.cpu.workload = workload.makeLiveProcess() |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import glob
from ansible.module_utils.facts.utils import get_file_lines
from ansible.module_utils.facts.collector import BaseFactCollector
class FcWwnInitiatorFactCollector(BaseFactCollector):
name = 'fibre_channe... |
"""Tests for homomorphisms."""
from sympy import QQ, S
from sympy.abc import x, y
from sympy.polys.agca import homomorphism
from sympy.utilities.pytest import raises
def test_printing():
R = QQ.old_poly_ring(x)
assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \
'Matrix([[0]]) : Q... |
#!/usr/bin/env python
import socket
import agoclient
client = agoclient.AgoConnection("wifi370")
COMMAND_ON="\xcc\x23\x33"
COMMAND_OFF="\xcc\x24\x33"
# COMMAND_RGB="\x56\xRR\xGG\xBB\xaa"
COMMAND_STATUS="\xef\x01\x77"
try:
deviceconfig = agoclient.get_config_option("wifi370", "devices", "192.168.80.44:5577")
device... |
"""Tests for oauth2client.gce.
Unit tests for oauth2client.gce.
"""
__author__ = '<EMAIL> (Joe Gregorio)'
import unittest
import httplib2
import mock
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import Credentials
from oauth2client.client import save_to_well_known_file
from oaut... |
# coding: utf-8
from __future__ import unicode_literals
import math
import random
import re
import time
from .common import InfoExtractor
from ..utils import (
ExtractorError,
)
class YoukuIE(InfoExtractor):
_VALID_URL = r'''(?x)
(?:
http://(?:v|player)\.youku\.com/(?:v_show/id_|player\... |
from node import nullid
from i18n import _
import changegroup, statichttprepo, error, httpconnection, url, util, wireproto
import os, urllib, urllib2, zlib, httplib
import errno, socket
def zgenerator(f):
zd = zlib.decompressobj()
try:
for chunk in util.filechunkiter(f):
while chunk:
... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
qualities,
unified_strdate,
)
class MgoonIE(InfoExtractor):
_VALID_URL = r'''(?x)https?://(?:www\.)?
(?:(:?m\.)?mgoon\.com/(?:ch/(?:.+)/v|play/view)|
... |
from slicc.ast.StatementAST import StatementAST
from slicc.symbols import Type
class ExprStatementAST(StatementAST):
def __init__(self, slicc, expr):
super(ExprStatementAST, self).__init__(slicc)
self.expr = expr
def __repr__(self):
return "[ExprStatementAST: %s]" % (self.expr)
de... |
{
'name': 'Automated Action Rules',
'version': '1.0',
'category': 'Sales Management',
'description': """
This module allows to implement action rules for any object.
============================================================
Use automated actions to automatically trigger actions for various screens.
... |
import random
import sys
from rlglue.agent.Agent import Agent
from rlglue.agent import AgentLoader as AgentLoader
from rlglue.types import Action
from rlglue.types import Observation
class test_message_agent(Agent):
whichEpisode=0
def agent_init(self,taskSpec):
pass
def agent_start(self,observation):
retur... |
import time
import os
import sickbeard
from sickbeard import encodingKludge as ek
from sickbeard import logger,db
from sickbeard import helpers
from sickbeard import search_queue
from sickbeard.common import SNATCHED, SNATCHED_PROPER, SNATCHED_FRENCH, DOWNLOADED, SKIPPED, UNAIRED, IGNORED, ARCHIVED, WANTED, UNKNOWN
fr... |
"""Estimator: High level tools for working with models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long,wildcard-import
from tensorflow.python.estimator.canned.baseline import BaselineClassifier
from tensorfl... |
import urllib.parse
from bs4 import BeautifulSoup
import requests
import requests.exceptions
from cloudbot import hook
@hook.command("down", "offline", "up")
def down(text):
"""<url> - checks if <url> is online or offline
:type text: str
"""
if "://" not in text:
text = 'http://' + text
... |
import time
import logging
from django import http
from django.conf import settings
from django.utils.http import http_date
from common.display import prep_stream_dict, prep_entry_list, prep_entry, prep_comment_list
from common import decorator
from common import exception
from common import api
@decorator.cache_fo... |
from django.contrib.auth.models import AnonymousUser
from django.test import TestCase
from mock import MagicMock, patch
from . import BillingAddressStep, ShippingStep
from ..checkout import STORAGE_SESSION_KEY
from ..checkout.steps import BaseAddressStep
from ..userprofile.models import Address
NEW_ADDRESS = {
'f... |
import json
import decimal
from datetime import datetime, date, time
from django.db import models
from django.db.models.query import QuerySet
from django.core.serializers import serialize
from django.utils.functional import Promise
from django.utils.encoding import force_unicode
class RobustEncoder(json.J... |
class ParameterGroup(dict):
def __init__(self, connection=None):
dict.__init__(self)
self.connection = connection
self.name = None
self.description = None
self.engine = None
self._current_param = None
def __repr__(self):
return 'ParameterGroup:%s... |
from django.contrib.gis.db import models
from django.conf import settings
from django.contrib.gis.measure import A, D
from lingcod.unit_converter.models import length_in_display_units, area_in_display_units
class SpacingPoint(models.Model):
name = models.CharField(max_length=200)
geometry = models.PointField(s... |
__author__ = 'John Sirois'
import unittest
from twitter.common.collections import OrderedDict
from twitter.common.config import Properties
from twitter.common.contextutil import temporary_file
from twitter.common.lang import Compatibility
class PropertiesTest(unittest.TestCase):
def test_empty(self):
self.asse... |
#!/usr/bin/env python
# Pretty print 9p simpletrace log
# Usage: ./analyse-9p-simpletrace <trace-events> <trace-pid>
#
import os
import simpletrace
symbol_9p = {
6 : 'TLERROR',
7 : 'RLERROR',
8 : 'TSTATFS',
9 : 'RSTATFS',
12 : 'TLOPEN',
13 : 'RLOPEN',
14 : 'TLCREATE',
15 : '... |
from exception import BadElementCompositionError
# Clase base ModelElement.
class ModelElement(dict):
# Identificador del elemento es obligatorio en toda instancia
def __init__(self, xmi_id, name=None):
# Todos los atributos de elementos son tuplas: el primer item
# es donde guardo el objeto ... |
"""A BSON wrapper for long (int in python3)"""
from bson.py3compat import PY3
if PY3:
long = int
class Int64(long):
"""Representation of the BSON int64 type.
This is necessary because every integral number is an :class:`int` in
Python 3. Small integral numbers are encoded to BSON int32 by default,
... |
from gi.repository import GObject
from gi.repository import Gtk
from gnomedvb import _
import datetime
import gnomedvb
from gnomedvb import global_error_handler
from gnomedvb.ui.timers.MessageDialogs import TimerFailureDialog
from gnomedvb.ui.timers.TimerDialog import TimerDialog
from gnomedvb.ui.widgets.CellRendererDa... |
from casadi import *
# Declare variables
x = ssym("x",2)
# Form the NLP objective
f = SXFunction([x],[x[0]**2 + x[1]**2])
# Form the NLP constraints
g = SXFunction([x],[x[0]+x[1]-10])
# Pick an NLP solver
MySolver = IpoptSolver
#MySolver = WorhpSolver
#MySolver = SQPMethod
# Allocate a solver
solver = MySolver(f,g... |
import re
import time
import isodate
import requests
from cloudbot import hook
from cloudbot.util import timeformat
from cloudbot.util.formatting import pluralize
youtube_re = re.compile(r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I)
base_url = 'https://www.googleapis.com/youtube... |
import os
import json
from profile_chrome import chrome_controller
from profile_chrome import controllers_unittest
class ChromeControllerTest(controllers_unittest.BaseControllerTest):
def testGetCategories(self):
# Not supported on stable yet.
# TODO(skyostil): Remove this once category queries roll into s... |
import subprocess
from errorwindow import ErrorDialogue
class ModeError(Exception):
pass
class ProcessStderr(ChildProcessError):
def __init__(self, value):
self.value = value
class CommandExecution:
def __init__(self, binder):
self.input = binder
def execute(self):
try:
... |
"""
=======================
Region Adjacency Graphs
=======================
This example demonstrates the use of the `merge_nodes` function of a Region
Adjacency Graph (RAG). The `RAG` class represents a undirected weighted graph
which inherits from `networkx.graph` class. When a new node is formed by
merging two node... |
import math
import gtk
from ginga.misc import Bunch
from ginga.gtkw import FitsImageCanvasGtk
from ginga.gtkw import FitsImageCanvasTypesGtk as CanvasTypes
from ginga import GingaPlugin
class Pan(GingaPlugin.GlobalPlugin):
def __init__(self, fv):
# superclass defines some variables for us, like logger
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The code needs to handle uptil 5D phase space. However, ArrayFire
sets a hard limit on the dimensionality of the array to be 4.
To surpass this, we internally use 2 different forms in which the array
can be stored:
- q_expanded - shape:(Nq1, Nq2, Np1 * Np2 * Np3)
- p... |
# -*- coding: utf-8 *-*
import inspect
__all__ = ['wrap_decorator']
class wrap_decorator(object):
"""
Writing wrappers for instance methods can be a pain in the ass, so maybe this will grow into
some helper which can deal with all kinds functions, methods, classmethods some day.
For now it's the base... |
import enum
import json
import logging
import os
import site
import warnings
from pathlib import Path
from typing import Any, Dict
from qkan import enums
log = logging.getLogger("QKan.config")
class ConfigEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
if isinstance(o, enum.Enum):
... |
import sys
from paste import deploy
from rainicorn.openstack.common import local
class BasePasteFactory(object):
"""A base class for paste app and filter factories.
Sub-classes must override the KEY class attribute and provide
a __call__ method.
"""
KEY = None
def __init__(self, data):
... |
from spack import *
class RRaster(RPackage):
"""Reading, writing, manipulating, analyzing and modeling of gridded
spatial data. The package implements basic and high-level functions.
Processing of very large files is supported."""
homepage = "http://cran.r-project.org/package=raster"
url = "... |
import re
import time
from datetime import timedelta
from urlparse import urlparse, urlunparse
import requests
from requests import Response, Request
from requests.auth import HTTPBasicAuth
from requests.exceptions import (RequestException, MissingSchema,
InvalidSchema, InvalidURL)
import events
from exception im... |
import sys
import numpy as np
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import SkipTest
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import asser... |
root.system.cpu[0].workload = LiveProcess(cmd = 'insttest',
executable = binpath('insttest')) |
"""Tests for tfx.orchestration.component_launcher."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from unittest import mock
import tensorflow as tf
from tfx.dsl.io import fileio
from tfx.orchestration import data_types
from tfx.orchestration ... |
import mock
import unittest
from pinball_ext.executor import local_executor
__author__ = 'Changshu Liu'
__copyright__ = 'Copyright 2015, Pinterest, Inc.'
__credits__ = [__author__]
__license__ = 'Apache'
__version__ = '2.0'
class LocalExecutorTest(unittest.TestCase):
@mock.patch('os.system')
def test_hadoo... |
import warnings
from rope.base import exceptions, pyobjects, pynames, taskhandle, evaluate, worder, codeanalyze
from rope.base.change import ChangeSet, ChangeContents, MoveResource
from rope.refactor import occurrences, sourceutils
class Rename(object):
"""A class for performing rename refactoring
It can re... |
"""
Django Template Context Processor for CMS Online Contextual Help
"""
import ConfigParser
from django.conf import settings
from util.help_context_processor import common_doc_url
# Open and parse the configuration file when the module is initialized
CONFIG_FILE = open(settings.REPO_ROOT / "docs" / "cms_config.ini"... |
"""Script to compile the dependencies of _tkinter
Copyright (c) 2007 by Christian Heimes <<EMAIL>>
Licensed to PSF under a Contributor Agreement.
"""
import os
import sys
here = os.path.abspath(os.path.dirname(__file__))
par = os.path.pardir
TCL = "tcl8.5.9"
TK = "tk8.5.9"
TIX = "tix-8.4.3.x"
ROOT = os.path.abspa... |
from openerp.osv import fields,orm
import decimal_precision as dp
from openerp.tools.translate import _
class cashFlowtype(orm.Model):
_name = "cash.flow.type"
_description = "Cash Flow Type"
_columns = {
'name': fields.char('Name', size=128),
'code': fields.char('Code', size=128... |
"""Comment.root_target should always point to a Guid. A few comments on production were missed by a migration and point
to TrashedFileNodes and restored StoredFileNodes instead. This migration points the root_target to the Guids for
those TrashedFileNodes.
"""
import logging
import sys
from modularodm import Q
from mo... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_router_access_list6
except ImportError:
... |
"""
MNIST is a handwritten digit image dataset.
More info at: http://yann.lecun.com/exdb/mnist/
"""
import gzip
import logging
import numpy as np
import os
import struct
from neon.datasets.dataset import Dataset
from neon.util.compat import PY3, range
if PY3:
from urllib.parse import urljoin as basejoin
else:
... |
# encoding: utf-8
from video.management.commands.sub_commands import SubCommand
from video.utils.youtube import GetYoutubeVideos
from mks.models import Member
from video.utils.parse_dict import validate_dict
from video.utils import get_videos_queryset
from video.models import Video
class UpdateMembersRelatedVideos(Su... |
""" Benchmark functions for fftpack.pseudo_diffs module
"""
from __future__ import division, print_function, absolute_import
import sys
from numpy import arange, sin, cos, pi, exp, tanh, sign
from numpy.testing import *
from scipy.fftpack import diff, fft, ifft, tilbert, hilbert, shift, fftfreq
def random(size):
... |
"""
A python program to plot a grade histogram
Usage: python plot_grade_hist.py [filename] [colname] [maxy] ([nscorecols])
Required inputs:
filename - text file containing either two columns (name total) or
three columns (name, score_multiple-choice, score_short-answer)
colname - the name of th... |
{
# Tests of Materialized Views defined using Joins
"joined-matview-default-full": {"schema": "joined-matview-schema.py",
"ddl": "joined-matview-DDL.sql",
"template": "joined-matview-default-full.sql",
"n... |
from PyQt4 import QtGui
from PyQt4 import QtCore
class Deslizador(QtGui.QWidget):
def __init__(self, parent, cursor, valor_inicial, funcion_cuando_cambia):
QtGui.QWidget.__init__(self, parent)
self.funcion_cuando_cambia = funcion_cuando_cambia
layout = QtGui.QGridLayout(self)
sli... |
from django.utils import timezone
import mock
import pytest
from addons.wiki.tests.factories import WikiFactory
from api.base.settings.defaults import API_BASE
from api_tests import utils as test_utils
from osf.models import Guid
from osf_tests.factories import (
ProjectFactory,
AuthUserFactory,
CommentFac... |
_API_UTIL_NAMESPACE = 'json_schema_compiler::util'
class UtilCCHelper(object):
"""A util class that generates code that uses
tools/json_schema_compiler/util.cc.
"""
def __init__(self, type_manager):
self._type_manager = type_manager
def PopulateArrayFromListFunction(self, optional):
"""Returns the ... |
"""
EasyBuild support for building and installing the libsmm library, implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
... |
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSql import *
from decimal import *
class TreeItem():
def __init__(self, db, row, parent_item):
self.db = db
self.row = row
self.parent_item = parent_item
self.query_done = False;
self.child_count = 0
self.child_items = []
s... |
# http://pyrocko.org - GPLv3
#
# The Pyrocko Developers, 21st Century
# ---|P------/S----------~Lg----------
from __future__ import absolute_import, division, print_function
import time
import re
import logging
from pyrocko import util, guts
from pyrocko.io import io_common
from pyrocko.io import stationxml as sxml
... |
from lib.hachoir_core.i18n import _
from lib.hachoir_core.tools import (
humanDuration, humanBitRate,
humanFrequency, humanBitSize, humanFilesize,
humanDatetime)
from lib.hachoir_core.language import Language
from lib.hachoir_metadata.filter import Filter, NumberFilter, DATETIME_FILTER
from datetime import ... |
r"""Tests for tf_agents.policies.policy_info_updater_wrapper.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tf_agents.policies import po... |
# This example demonstrates a simple temperature sensor peripheral.
#
# The sensor's local value updates every second, and it will notify
# any connected central every 10 seconds.
#
# Work-in-progress demo of implementing bonding and passkey auth.
import bluetooth
import random
import struct
import time
import json
im... |
import unittest
import raco.fakedb
from raco.relation_key import RelationKey
from raco.algebra import *
from raco.expression import *
import raco.relation_key as relation_key
from raco.expression import StateVar
class TestQueryFunctions():
emp_table = collections.Counter([
# id dept_id name salary
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from multiprocessing import Lock
from ansible.module_utils.facts.system.pkg_mgr import PKG_MGRS
if 'action_write_locks' not in globals():
# Do not initialize this more than once because it seems to bash
# the existing one... |
import logging
import copy
try:
from zabbix_api import ZabbixAPI, ZabbixAPISubClass
HAS_ZABBIX_API = True
except ImportError:
HAS_ZABBIX_API = False
# Extend the ZabbixAPI
# Since the zabbix-api python module too old (version 1.0, no higher version so far).
class ZabbixAPIExtends(ZabbixAPI):
def __i... |
from airflow.contrib.kubernetes.pod import Pod
import uuid
from airflow.contrib.kubernetes.volume_mount import VolumeMount # noqa
from airflow.contrib.kubernetes.volume import Volume # noqa
class PodGenerator:
"""Contains Kubernetes Airflow Worker configuration logic"""
def __init__(self, kube_config=None)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
In this assignment you will implement one or more algorithms for the travelling
salesman problem, such as the dynamic programming algorithm covered in the
video lectures. Here is a data file describing a TSP instance. The first line
indicates the number of cities. E... |
from .. import dataformat
from struct import Struct, unpack_from
from ..util import dbg, zstr
from .empiresdat import endianness
class SoundItem(dataformat.Exportable):
name_struct = "sound_item"
name_struct_file = "sound"
struct_description = "one possible file for a sound."
data_format = ... |
"""Support for Velux covers."""
from homeassistant.components.cover import (
ATTR_POSITION,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverDevice,
)
from homeassistant.core import callback
from . import DATA_VELUX
async def async_setup_platform(hass, config, async_add_e... |
import numpy as np
from numba import cuda, int32, float32
from numba.cuda.testing import unittest, CUDATestCase
N = 100
def simple_smem(ary):
sm = cuda.shared.array(N, int32)
i = cuda.grid(1)
if i == 0:
for j in range(N):
sm[j] = j
cuda.syncthreads()
ary[i] = sm[i]
S0 = 10
S... |
# pylint: disable=missing-docstring
HEHE = {}
def function1(value=[]): # [dangerous-default-value]
"""docstring"""
return value
def function2(value=HEHE): # [dangerous-default-value]
"""docstring"""
return value
def function3(value):
"""docstring"""
return value
def function4(value=set()):... |
"""
Giving models custom methods
Any method you add to a model will be available to instances.
"""
import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100)
... |
from i18n import _
import osutil, encoding
import errno, msvcrt, os, re, stat, sys, _winreg
import win32
executablepath = win32.executablepath
getuser = win32.getuser
hidewindow = win32.hidewindow
makedir = win32.makedir
nlinks = win32.nlinks
oslink = win32.oslink
samedevice = win32.samedevice
samefile = win32.samefil... |
from oslo.config import cfg
import webob.exc
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import exception
from nova.openstack.common.gettextutils import _
from nova import conductor
from nova import utils
from nova import db as db_api
f... |
import os
import stat
import urllib
import urllib2
import rfc822
DEBUG = None
try:
from cStringIO import StringIO
except ImportError, msg:
from StringIO import StringIO
class RangeError(IOError):
"""Error raised when an unsatisfiable range is requested."""
pass
class HTTPRangeHandler(urllib... |
import subprocess
import os
import sys
from openerp import report
import tempfile
import time
import logging
from functools import partial
from report_helper import WebKitHelper
import openerp
from openerp.modules.module import get_module_resource
from openerp.report.report_sxw import *
from openerp import tools
from ... |
from __future__ import print_function
import numpy as np
import matplotlib.pylab as plt
from openmdao.api import IndepVarComp, Component, Group, Problem, ExecComp, ScipyOptimizer
class StructuralOptimization(Component):
"""
Notes
-----
Estimates tube tunnel cost and pylon material cost
Optimizes t... |
# Test Spectre simulator interface
from pyopus.simulator import simulatorClass
if __name__=='__main__':
# Job list for simulator
jobList=[
{ # First job - op analysis
'name': 'dcop',
'definitions': [
{ 'file': 'cmos180n.scs', 'section': 'tm' },
{ 'file': 'opamp.scs' }
],
'param... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test suite for aescrypt.py."""
from __future__ import print_function, unicode_literals
from io import BytesIO
from aescrypt import encrypt, decrypt
from Crypto.Cipher import AES
from nose.tools import raises
password = 'q1w2e3r4'
plaintext = """\
Lorem ipsum dolor s... |
# Configuration file for ipython-kernel.
c = get_config()
#------------------------------------------------------------------------------
# IPKernelApp configuration
#------------------------------------------------------------------------------
# IPython: an enhanced interactive Python shell.
# IPKernelApp will in... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: ucs_disk_group_policy
short_description: Configures disk gr... |
#
# distutils/version.py
#
# Implements multiple version numbering conventions for the
# Python Module Distribution Utilities.
#
# $Id: version.py 71270 2009-04-05 21:11:43Z georg.brandl $
#
"""Provides classes to represent module version numbers (one class for
each style of version numbering). There are currently tw... |
import config
import httplib
import urllib
import base64
import sys
import requests
# #### HTTP Headers + Encoding the URL
def vision(filepath):
file = open(filepath, 'rb').read()
files = {'file': file}
headers = {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': c... |
import Node
import time
import sys
# Create a node instance
# Programmer can give any name
# The infrastucture will assign unigue names ???
node = Node.ParticipantNode("HelloWorld reactive")
# Discover Smart Spaces around you
# Use the technologies used at the "vertical business domain"
# E.g. mDNS, UPnP, UDDI, B... |
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
@six.add_metaclass(abc.ABCMeta)
class Ed448PublicKey(object):
@classmethod
def from_public_bytes(cls, data):
from cryptography.hazmat.backends.op... |
# pylint: disable=C0111
# pylint: disable=W0621
# Lettuce formats proposed definitions for unimplemented steps with the
# argument name "step" instead of "_step" and pylint does not like that.
# pylint: disable=W0613
from lettuce import world, step
from nose.tools import assert_true, assert_in # pylint: disable=E061... |
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.NodeGroups import NodeGroup, NodeGroups
from PLC.Auth import Auth
can_update = lambda field_value: field_value[0] in ['groupname','value']
class UpdateNodeGroup(Method):
"""
Updates a custom node group.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.