content stringlengths 4 20k |
|---|
import dogstats_wrapper as dog_stats_api
import logging
from .grading_service_module import GradingService
log = logging.getLogger(__name__)
class ControllerQueryService(GradingService):
"""
Interface to controller query backend.
"""
METRIC_NAME = 'edxapp.open_ended_grading.controller_query_service... |
from gnuradio import gr
import pmt
def make_lengthtags(lengths, offsets, tagname='length', vlen=1):
tags = []
assert(len(offsets) == len(lengths))
for offset, length in zip(offsets, lengths):
tag = gr.tag_t()
tag.offset = offset/vlen
tag.key = pmt.string_to_symbol(tagname)
t... |
import logging
import sys
import time
log = logging.getLogger(__name__)
def run_client():
from examples import gclient as client
client.main()
def run_server():
from examples import gserver as server
server.main()
def main_greenlets():
from greenlet import greenlet, GreenletExit
s = greenl... |
import errno
import imp
import importlib
import os
import six
class Config(dict):
"""
Works exactly like a dict but provides ways to fill it from files
or special dictionaries. There are two common patterns to populate the
config.
Either you can fill the config from a config file::
app... |
import asyncio
from aiocore import Service
class AlertService(Service):
identifier = "moxie.cores.alert.AlertService"
def __init__(self):
self.callbacks = []
super(AlertService, self).__init__()
@asyncio.coroutine
def starting(self, job):
yield from self._emit("starting", job... |
"""
Tests For Scheduler Host Filters.
"""
from nova.scheduler import filters
from nova.scheduler.filters import all_hosts_filter
from nova.scheduler.filters import compute_filter
from nova import test
from nova.tests.unit.scheduler import fakes
class HostFiltersTestCase(test.NoDBTestCase):
def test_filter_handl... |
from metronus_app.model.role import Role
from metronus_app.model.company import Company
from metronus_app.model.employee import Employee
from metronus_app.model.project import Project
from metronus_app.model.department import Department
from django.contrib.auth.models import User
from metronus_app.model.administrator i... |
#!/usr/bin/env python
import os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
VERSION = '0.9.0'
PATH = os.path.dirname(os.path.abspath(__file__))
try:
LONG_DESC = '\n===='+open(os.path.join(PATH, 'README.rst'), 'r').read().split('====',... |
"""
NeuralNet class creates a neural network.
"""
from convnet import *
import numpy as np
import time
from collections import OrderedDict
class SimpleDataProvider:
dims = None
def __init__(self, data_dir, batch_range=None, init_epoch=1, init_batchnum=None, dp_params=None, test=False):
pass
de... |
"""Implementation of :class:`PolynomialRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.domains.compositedomain import CompositeDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.old_fractionf... |
from boto.regioninfo import RegionInfo
class RDSRegionInfo(RegionInfo):
def __init__(self, connection=None, name=None, endpoint=None,
connection_cls=None):
from boto.rds import RDSConnection
super(RDSRegionInfo, self).__init__(connection, name, endpoint,
... |
from . import models |
from __future__ import absolute_import
import logging
# App must be initialized before models or ADDONS_AVAILABLE are available
from website.app import init_app
init_app()
from osf.models import OSFUser, AbstractNode
from framework.database import paginated
from scripts.analytics.base import SnapshotAnalytics
from w... |
import mock
from oslo_context import context as context_utils
import six.moves as sm
import testtools
from poppy.transport.pecan import controllers
from poppy.transport.pecan.controllers import v1
from poppy.transport.validators import helpers
class BasePecanControllerUnitTest(testtools.TestCase):
def setUp(sel... |
"""Parser driver.
This provides a high-level interface to parse a file into a syntax tree.
"""
__author__ = "Guido van Rossum <<EMAIL>>"
__all__ = ["Driver", "load_grammar"]
# Python imports
import codecs
import io
import os
import logging
import sys
# Pgen imports
from . import grammar, parse, token, tokenize, p... |
"""This example displays all of the available permissions that a user role or
subnetwork may be endowed with. To get a subnetwork ID, run
get_subnetworks.py.
A user role may not be set with more permissions than the subnetwork it
belongs to. You may enter a subnetwork ID to see the maximum permissions a
user role belo... |
"""Tests for debugger functionalities in tf.Session with file:// URLs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.... |
'''
Basic definitions for the frontend.
Note that the frontend is broader in scope and functionality than the rpc
server. Another way to put that is the rpc server is a subset of the frontend.
'''
__all__ = ['AFE_SERVICE_NAME',
'TKO_SERVICE_NAME',
'AFE_URL_PREFIX',
'TKO_URL_PREFIX']
... |
"""This is like pexpect, but will work on any file descriptor that you pass it.
You are reponsible for opening and close the file descriptor.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier... |
"""Implementation of non-blocking server.
The main idea of the server is to receive and send requests
only from the main thread.
The thread poool should be sized for concurrent tasks, not
maximum connections
"""
import threading
import socket
import select
import struct
import logging
logger = logging.getLogger(__na... |
from celery import task
from API.models import APIKey, MemberAPIKey
from django.core.cache import cache
from django.contrib.auth import get_user_model
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
User = get_user_model()
@task()
def update_char_data():
#Get all users
user_list = User.objects.all()
... |
from zerver.decorator import JsonableError
def check_supported_events_narrow_filter(narrow):
for element in narrow:
operator = element[0]
if operator not in ["stream", "topic", "sender", "is"]:
raise JsonableError("Operator %s not supported." % (operator,))
def build_narrow_filter(narr... |
from cinder.api import extensions
from cinder.api.openstack import wsgi
from cinder import quota
QUOTAS = quota.QUOTAS
authorize = extensions.extension_authorizer('limits', 'used_limits')
class UsedLimitsController(wsgi.Controller):
@wsgi.extends
def index(self, req, resp_obj):
context = req.enviro... |
"""tensor_util tests."""
# pylint: disable=unused-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
from tensorflow.contrib.framework.python.framework import tensor_util
from tensorflow.contrib.framework.python.ops import v... |
"""BERT-based Classifier runner."""
from __future__ import absolute_import, division, print_function
from absl import flags
import run_classifier_utils
import tensorflow as tf
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string("training_file", None,
"Path to the TFRecord training fi... |
from spack import *
class TemplightTools(CMakePackage):
"""Supporting tools for the Templight Profiler"""
homepage = "https://github.com/mikael-s-persson/templight-tools"
git = "https://github.com/mikael-s-persson/templight-tools.git"
version('develop', branch='master')
depends_on('cmake @... |
# coding: utf-8
from os import path
from django.conf.urls.defaults import *
from models import *
import views
base_dir = path.dirname(path.abspath(__file__))
media_dir = path.join(base_dir, 'media')
locale_dir = path.join(base_dir, 'locale')
js_info_dict = {
'domain': 'djangojs',
'packages': ('regressionte... |
"""WebSubmit function - Video processing.
"""
__revision__ = "$Id$"
import os
from invenio.utils.json import json_decode_file
from invenio.ext.logging import register_exception
from invenio.modules.encoder.config import CFG_BIBENCODE_TEMPLATE_BATCH_SUBMISSION
from invenio.modules.encoder.utils import generate_times... |
# -*- coding: utf-8 -*-
import os
import re
import fnmatch
import threading
import urllib2
import xbmc
import xbmcaddon
from contextlib import contextmanager, closing
__addon__ = xbmcaddon.Addon()
CACHE_DIR = xbmc.translatePath(__addon__.getAddonInfo("profile"))
PAC_URL = "http://antizapret.prostovpn.org/proxy.pac"
U... |
from django.db.models import Q, Count
from django.apps import apps
import datetime
import copy
from taiga.projects.history.models import HistoryEntry
def _get_milestones_stats_for_backlog(project):
"""
Get collection of stats for each millestone of project.
Data returned by this function are used on backl... |
__version__ = '${version}'
from distutils.version import LooseVersion
try:
import requests
except ImportError:
REQUESTS_FOUND = False
else:
REQUESTS_FOUND = True
#
# Requires the clc-python-sdk.
# sudo pip install clc-sdk
#
try:
import clc as clc_sdk
from clc import CLCException
except ImportEr... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from copy import deepcopy
class Attribute:
def __init__(self, isa=None, private=False, default=None, required=False, listof=None, priority=0, class_type=None, always_post_validate=False, inherit=True):
"""
:cl... |
import cx_Oracle
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
from django.utils.encoding import force_text
class DatabaseIntrospection(BaseDatabaseIntrospection):
# Maps type objects to Django Field types.
data_types_reverse = {
cx_Oracle.... |
# -*- coding: utf-8 -*-
"""Parser for OLE Compound Files (OLECF)."""
import logging
import pyolecf
from plaso import dependencies
from plaso.lib import errors
from plaso.lib import specification
from plaso.parsers import interface
from plaso.parsers import manager
dependencies.CheckModuleVersion(u'pyolecf')
clas... |
"""WSGI support for the Tornado web framework.
WSGI is the Python standard for web servers, and allows for interoperability
between Tornado and other Python web frameworks and servers. This module
provides WSGI support in two ways:
* `WSGIApplication` is a version of `tornado.web.Application` that can run
inside ... |
{
'name': 'Password Encryption',
'version': '2.0',
'author': ['OpenERP SA', 'FS3'],
'maintainer': 'OpenERP SA',
'website': 'https://www.odoo.com',
'category': 'Tools',
'description': """
Encrypted passwords
===================
Replaces the default password storage with a strong cryptographi... |
""" Magnet.py
Demos the magnet controller. Electrons orbit protons.
"""
__version__ = '$Id: magnet.py 104 2008-11-08 06:49:41Z andrew.charles $'
from pyglet import image
from pyglet.gl import *
import os, math
from lepton import Particle, ParticleGroup, default_system
from lepton.renderer import BillboardRenderer... |
import abc
from functools import reduce
from operator import mul
import mmap
import os
import sys
import numpy as np
import ctypes
from ctypes.util import find_library
from devito.logger import logger
from devito.parameters import configuration
from devito.tools import dtype_to_ctype
__all__ = ['ALLOC_FLAT', 'ALLOC_... |
import json
from django.test import TestCase
from restlib2.http import codes
from avocado.conf import OPTIONAL_DEPS
from serrano.resources import API_VERSION
class ExporterResourceTestCase(TestCase):
def test_delete(self):
self.client.get('/api/data/export/csv/')
response = self.client.delete('/ap... |
import datetime
import os
from django import forms
from django.core import checks
from django.core.files.base import File
from django.core.files.images import ImageFile
from django.core.files.storage import default_storage
from django.db.models import signals
from django.db.models.fields import Field
from django.utils... |
from copy import copy
from branch_utility import BranchUtility
from compiled_file_system import SingleFile, Unicode
from docs_server_utils import StringIdentity
from extensions_paths import API_PATHS, JSON_TEMPLATES
from file_system import FileNotFoundError
from future import All, Future
from path_util import Join
fro... |
# * *
# * If you have any questions about the licensing restrictions on using *
# * Nmap in other works, are happy to help. As mentioned above, we also *
# * offer alternative license to integrate Nmap into proprietary *
# * appl... |
from pyGBot.Plugins.system.Commands import BaseCommand
from pyGBot.Plugins.system.Auth import AuthLevels as AL
class PlayGame(BaseCommand):
level = AL.Mod
def __init__(self, bot, channel, user, args):
args = args.split()
if channel == user or channel == None:
bot.noteout(use... |
import tensorflow as tf
# print(tf.__version__)
# tensor = n-dimensional array
hello = tf.constant("Hello ")
world = tf.constant("World")
# print(type(hello))
# print(hello)
# with tf.Session() as sess:
# result = sess.run(hello + world)
# print(result)
# a = tf.constant(10)
# b = tf.constant(20)
# print(type(a... |
from PySortAlgos import *
def example_1():
persons = {"Thomas":21, "Ursula":58, "Mike":19, "Max":30, "Tina":21}
person_sortedKeysByAge1 = BubbleSort(key=lambda p: persons[p]).sort(persons.keys())
person_sortedKeysByAge2 = QuickSort(key=lambda p: persons[p]).sort(persons.keys())
print(... |
from formencode.validators import Int
from pylons import request
__all__ = ['LimitFeedItemsValidator']
class LimitFeedItemsValidator(Int):
min = 1
def empty_value(self, value):
return self.default_limit(request.settings)
@property
def if_missing(self):
return self.default_li... |
# -*- coding:utf-8 -*-
import gettext
import os
from os import path
import unittest
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import LiveServerTestCase, TestCase
from django.test.utils import override_settings
from django.utils import six
from django.utils._os impor... |
import logging
from marshmallow import fields
from keystoneclient import exceptions
from cloudferrylib.os.discovery import model
LOG = logging.getLogger(__name__)
@model.type_alias('tenants')
class Tenant(model.Model):
class Schema(model.Schema):
object_id = model.PrimaryKey('id')
name = fields... |
"""Tests ParticipantPacket.py
"""
import unittest
from hashlib import md5
from struct import pack
from replayenhancer.ParticipantPacket import ParticipantPacket
class TestParticipantPacket(unittest.TestCase):
"""Unit tests against the ParticipantPacket object.
"""
expected_build_version_n... |
"""Python source expertise for coverage.py"""
import os.path
import zipimport
from coverage import env, files
from coverage.misc import contract, expensive, NoSource, join_regex, isolate_module
from coverage.parser import PythonParser
from coverage.phystokens import source_token_lines, source_encoding
from coverage.p... |
import six
import sys
import unittest
from airflow import configuration, models
from airflow.utils import db
from mock import patch, call
from airflow.contrib.hooks.spark_submit_hook import SparkSubmitHook
class TestSparkSubmitHook(unittest.TestCase):
_spark_job_file = 'test_application.py'
_config = {
... |
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from timetracker.tracker.models import Tbluser
from timetracker.tracker.trackingentry import TrackingEntry
from timetracker.utils.datemaps i... |
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
class ToughImageCasesPage(page_module.Page):
def __init__(self, url, page_set):
super(ToughImageCasesPage, self).__init__(
url=url, page_set=page_set,
shared_page_state_class=... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.utils.six.moves import http_client
from oscar.apps.catalogue.models import Category
from oscar.test.decorators import ignore_deprecation_warnings
from oscar.test.testcases import WebTestCase
f... |
#!/usr/bin/env python
import urllib
import cv2.cv as cv
import Image
import unittest
class TestLoadImage(unittest.TestCase):
def setUp(self):
open("large.jpg", "w").write(urllib.urlopen("http://www.cs.ubc.ca/labs/lci/curious_george/img/ROS_bug_imgs/IMG_3560.jpg").read())
def test_load(self):
... |
"""Tests update_user_photo method.
"""
__author__ = ['<EMAIL> (Ben Darnell)']
import time
from copy import deepcopy
from viewfinder.backend.base import util
from viewfinder.backend.db.db_client import DBKey
from viewfinder.backend.db.episode import Episode
from viewfinder.backend.db.photo import Photo
from viewfind... |
import argparse
import sys
import util
from seccomp import *
def test():
api = get_api()
if (api < 1):
raise RuntimeError("Failed getting initial API level")
set_api(1)
api = get_api()
if api != 1:
raise RuntimeError("Failed getting API level 1")
set_api(2)
api = get_api... |
"""
Tests for the bok-choy paver commands themselves.
Run just this test with: paver test_lib -t pavelib/paver_tests/test_paver_bok_choy_cmds.py
"""
import os
import unittest
from pavelib.utils.test.suites import BokChoyTestSuite
REPO_DIR = os.getcwd()
class TestPaverBokChoyCmd(unittest.TestCase):
def _expected... |
"""Access Ansible Core CI remote services."""
from __future__ import absolute_import, print_function
import pipes
from time import sleep
import lib.pytar
from lib.util import (
SubprocessError,
ApplicationError,
run_command,
)
from lib.core_ci import (
AnsibleCoreCI,
)
from lib.ansible_util impor... |
import numpy as np
import scipy as sp
from scipy import ndimage
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_raises
from ..image import img_to_graph, grid_to_graph
from ..image import (extract_patches_2d, reconstruct_from_patches_2d,
PatchExtractor, extract_pa... |
"""
This package offers ways to retreive ip addresses of the machine, and map ports
through UPnP devices.
@author: Raphael Slinckx
@copyright: Copyright 2005
@license: LGPL
@contact: U{<EMAIL><mailto:<EMAIL>>}
@version: 0.1.0
"""
__revision__ = "$id"
from nattraverso.pynupnp.upnp import search_upnp_device, UPnPMapper... |
import inspect
import os
import re
from importlib import import_module
from django.apps import apps
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.admindocs import utils
from django.core import urlresolvers
f... |
import mock
from oslo.config import cfg
from ceilometer.ipmi.pollsters import sensor
from ceilometer.tests.ipmi.notifications import ipmi_test_data
from ceilometer.tests.ipmi.pollsters import base
CONF = cfg.CONF
CONF.import_opt('host', 'ceilometer.service')
TEMPERATURE_SENSOR_DATA = {
'Temperature': ipmi_test_... |
# -*- coding: utf-8 -*-
"""
events plugin for Pelican
=========================
This plugin looks for and parses an "events" directory and generates
blog posts with a user-defined event date. (typically in the future)
It also generates an ICalendar v2.0 calendar file.
https://en.wikipedia.org/wiki/ICalendar
Author: ... |
import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.conf import settings
from django import http
from oauth import oauth
from common import api
from common import legacy
from common import exception
from common import oauth_util
def _xmlrpc_url():
if settings.SUBDOMAINS_E... |
import re
import sys
import xml.etree.ElementTree
import gdb_rsp
def AssertRaises(exc_class, func):
try:
func()
except exc_class:
pass
else:
raise AssertionError('Function did not raise %r' % exc_class)
def GetTargetArch(connection):
"""Get the CPU architecture of the NaCl application."""
rep... |
import socket
import sys
import platform
import json
import pprint
from datetime import datetime
import time
import subprocess
import couchdb
from multiprocessing import Process
import re
import config
import argparse
import time
pp = pprint.PrettyPrinter(indent=4)
parser = argparse.ArgumentParser(description='Log all... |
import types
class ObjectRegistry:
"""Registry for any type of objects named by a string-type name.
This class is for handling common registries of objects where it is
desirable to be able to lookup the object by a string name. It assumes
it is not desirable to overwrite an existing registered object... |
try:
from pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType import FirewallRuleType
from pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType import ProtocolsType
except ImportError:
# normally set a flag here but it will be caught when testing for
# the existence of pyvcloud (see module_utils/vca.py).... |
__author__ = 'Sean Lip'
import datetime
from core.platform import models
(email_models,) = models.Registry.import_models([models.NAMES.email])
import test_utils
class SentEmailModelUnitTests(test_utils.GenericTestBase):
"""Test the SentEmailModel class."""
def test_sent_email_model_instances_are_read_only(... |
# udp listener
#
# Run this in the background, and you will appear to the pipboy app as an instance of Fallout4
import socket
import struct
import sys
import time
import json
# debouncer magic number
min_delta=100
#return current millis
def now():
return time.time()*1000000
#return millis since 'then'
def dif(the... |
import os
import platform
from twisted.internet import defer
from .. import data, helper
from p2pool.util import pack
P2P_PREFIX = 'c0c0c0c0'.decode('hex')
P2P_PORT = 16639
ADDRESS_VERSION = 47
RPC_PORT = 26640
RPC_CHECK = defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
'pesetacoinaddress' in ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.fortios import fortios_argument_spec, fortios_required_if
from ansible.module_utils.fortios import backup
from ansible.module_utils.basic import Ansible... |
'''
Test offering client cert to origin
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Lice... |
"""Tests for tensorflow.python.training.saver.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
f... |
"""Shor's algorithm and helper functions.
Todo:
* Get the CMod gate working again using the new Gate API.
* Fix everything.
* Update docstrings and reformat.
* Remove print statements. We may want to think about a better API for this.
"""
from __future__ import print_function, division
import math
import random
fro... |
''' Simple Timing Function.
This function prints out a message with the elapsed time from the
previous call. It works with most Python 2.x platforms. The function
uses a simple trick to store a persistent variable (clock) without
using a global variable.
'''
import time
def dur( op=None, clock=[time.time()] ):
if... |
"""The tests for reproduction of state."""
import pytest
from homeassistant.components.media_player.const import (
ATTR_INPUT_SOURCE,
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_ENQUEUE,
ATTR_MEDIA_SEEK_POSITION,
ATTR_MEDIA_VOLUME_LEVEL,
ATTR_MEDIA_VOLUME_MUTED,
ATTR_SOU... |
"""
Tests for Django's bundled context processors.
"""
from django.test import TestCase
class RequestContextProcessorTests(TestCase):
"""
Tests for the ``django.core.context_processors.request`` processor.
"""
urls = 'context_processors.urls'
def test_request_attributes(self):
"""
... |
"""Module containing the trivial predictor OPF model implementation. """
import itertools
from nupic.data import fieldmeta
from nupic.frameworks.opf import model
from nupic.frameworks.opf import opfutils
from opfutils import InferenceType
class PreviousValueModel(model.Model):
"""Previous value model."""
def _... |
class OrganizationOrPersonRelatedField(serializers.RelatedField):
def __init__(self, hide_ld_context=False):
self.hide_ld_context = hide_ld_context
super(OrganizationOrPersonRelatedField, self).__init__(
queryset=Organization.objects, read_only=False)
def to_native(self, value):
... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import int_or_none
class MinotoIE(InfoExtractor):
_VALID_URL = r'(?:minoto:|https?://(?:play|iframe|embed)\.minoto-video\.com/(?P<player_id>[0-9]+)/)(?P<id>[a-zA-Z0-9]+)'
def _real_extract(self,... |
def shell_sort(array):
"""
Sorts the given array of integers using the Shell Sort algorithm
Time Complexity : O((len(array))^2)
Space Complexity : O(len(array))
:param array: A List of integers.
:return: returns the array sorted
"""
# calculate the gap using Knuth's formula
gap = 1
... |
#!/usr/bin/python
import datetime
import monthdelta
def parse_date(date_str):
return datetime.datetime.strptime(date_str, "%Y-%m-%d")
def unparse_date(date_obj):
return date_obj.strftime("%Y-%m-%d")
class Company(object):
def __init__(self, name):
self.name = name
self.flows = []
... |
import os
import sys
import string
def is_active():
return True
def get_name():
return "WinRT"
def can_build():
if (os.name=="nt"):
#building natively on windows!
if (os.getenv("VSINSTALLDIR")):
return True
return False
def get_opts():
return []
def get_flags():
... |
"""Different kinds of SAX Exceptions"""
#in brython the 4 lines below causes an $globals['Exception'] error
#import sys
#if sys.platform[:4] == "java":
# from java.lang import Exception
#del sys
# ===== SAXEXCEPTION =====
class SAXException(Exception):
"""Encapsulate an XML error or warning. This class can con... |
"""Tests for convolution related functionality in tensorflow.ops.nn."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.py... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_iis_virtualdirectory
version_added: "2.0"
short_description: Configures a virtual directory in IIS.
description:
- Creates, Removes and c... |
import crm_partner_binding
import crm_phonecall_to_phonecall
import crm_opportunity_to_phonecall
import crm_lead_to_opportunity
import crm_merge_opportunities
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import absolute_import
import sys
from uuid import uuid4
from proton import *
from . import common
class Test(common.Test):
def setUp(self):
self.data = Data()
def tearDown(self):
self.data = None
class DataTest(Test):
def testTopLevelNext(self):
assert self... |
__revision__ = "$Id$"
## Description: function Send_APP_Mail
## This function send an email informing the original
## submitter of a document that the referee has approved/
## rejected the document. The email is also sent to the
## referee for checkin... |
class ModuleDocFragment(object):
# common shelldocumentation fragment
DOCUMENTATION = """
options:
remote_tmp:
description:
- Temporary directory to use on targets when executing tasks.
default: '~/.ansible/tmp'
env: [{name: ANSIBLE_REMOTE_TEMP}, {name: ANSIBLE_REMOTE_TMP}]
ini:
-... |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable
import operator
import struct
class table_C_O_L_R_(DefaultTable.DefaultTable):
""" This table is structured so that you can treat it like a dict... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetR... |
from surveymonkey.calls.base import Call
class Batch(Call):
def __create_flow(self, survey, collector, email_message, **kwargs):
params = {
'survey': survey,
'collector': collector,
'email_message': email_message
}
assert collector.get('type') == 'email... |
from datetime import datetime
from sqlalchemy import Column, ForeignKey, MetaData, Table
from sqlalchemy import Boolean, DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
user_table = Table('user', metadata,
Column('id', Integer, primary_key=True),
Column('user_name', Unicode(255), nullable=False,... |
"""Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, <EMAIL>
"""
import sys
import re
__all__ = ['docopt']
__version... |
from contextlib import contextmanager
from xml.etree.ElementTree import Element, SubElement, tostring
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.netconf import send_request, children
from ansible.module_utils.netconf import discard_changes, validate
from ansible.module_utils.network... |
"""Element-level WebDriver operations."""
import searchcontext
class WebElement(searchcontext.SearchContext):
"""Corresponds to a DOM element in the current page."""
def __init__(self, driver, id):
self._driver = driver
self._id = id
# Set value of mode used by SearchContext
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.