content stringlengths 4 20k |
|---|
import email_template_preview
import mail_compose_message
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
"""Python version of cairo-demo/cairo_snippets/cairo_snippets_pdf.c
create a file for each example rather than one large file for all examples
"""
from __future__ import division
from math import pi as M_PI # used by many snippets
import sys
import cairo
if not cairo.HAS_PDF_SURFACE:
raise Sy... |
"""
Definitions of the cost for the gated-autoencoder.
"""
from pylearn2.costs.cost import Cost, DefaultDataSpecsMixin
from pylearn2.space import VectorSpace
class SymmetricCost(DefaultDataSpecsMixin, Cost):
"""
Summary (Class representing the symmetric cost).
Subclasses can define the type of data they... |
import os
import unittest
import urllib2
import json
import wptserve
from base import TestUsingServer, doc_root
class TestFileHandler(TestUsingServer):
def test_not_handled(self):
with self.assertRaises(urllib2.HTTPError) as cm:
resp = self.request("/not_existing")
self.assertEquals(c... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
unified_strdate,
)
class ExpoTVIE(InfoExtractor):
_VALID_URL = r'https?://www\.expotv\.com/videos/[^?#]*/(?P<id>[0-9]+)($|[?#])'
_TEST = {
'url': 'http://www.expotv.com/videos/reviews/... |
__author__ = 'gambit'
import boto
from boto.iam.connection import IAMConnection
from boto.s3.key import Key
import datetime
import time
import smtplib
import os
class IdentityAccessManagement():
admin_access_key = "XXXXXXXXXXXXXXXXXXXXXXX"
admin_secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
def create_u... |
import copy
from logr import Logr
GROUP_MATCHES = ['identifier']
class CaperNode(object):
def __init__(self, closure, parent=None, match=None):
"""
:type parent: CaperNode
:type weight: float
"""
#: :type: caper.objects.CaperClosure
self.closure = closure
... |
HALL_API_ENDPOINT = 'https://hall.com/api/1/services/generic/%s'
def send_request_to_hall(module, room_token, payload):
headers = {'Content-Type': 'application/json'}
payload=module.jsonify(payload)
api_endpoint = HALL_API_ENDPOINT % (room_token)
response, info = fetch_url(module, api_endpoint, data=p... |
from __future__ import print_function
import os, string, tempfile, shutil
from subprocess import Popen
from ase.io import write
from ase.units import Bohr
class Bader:
'''class for running bader analysis and extracting data from it.
The class runs bader, extracts the charge density and outputs it
to a cu... |
"""
This module provides views that proxy to the staff grading backend service.
"""
import json
import logging
from django.conf import settings
from django.http import HttpResponse, Http404
from django.utils.translation import ugettext as _
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from xmodule.o... |
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... |
"""
Chance (Random) Scheduler implementation
"""
import random
from manila import exception
from manila.scheduler import driver
from oslo.config import cfg
CONF = cfg.CONF
class ChanceScheduler(driver.Scheduler):
"""Implements Scheduler as a random node selector."""
def _filter_hosts(self, request_spec,... |
"""Handler for assisting with the machine install process."""
# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204, C6205, W0611
import logging
from django.utils import simplejson
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext impo... |
'''CTS: Cluster Testing System: AIS dependent modules...
'''
__copyright__ = '''
Copyright (C) 2007 Andrew Beekhof <<EMAIL>>
'''
#
# This program 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 versi... |
# from yowsup.layers.protocol_media import mediacipher
import tempfile
import os
class DownloadableMediaMessageBuilder(object):
def __init__(self, downloadbleMediaMessageClass, jid, filepath):
self.jid = jid
self.filepath = filepath
self.encryptedFilepath = None
self.cls = downloadbl... |
from invenio.dbquery import run_sql
depends_on = ['invenio_release_1_1_0']
def info():
return "New selfcite tables"
def do_upgrade():
run_sql("""
CREATE TABLE IF NOT EXISTS `rnkRECORDSCACHE` (
`id_bibrec` int(10) unsigned NOT NULL,
`authorid` bigint(10) NOT NULL,
PRIMARY KEY (`id_bibrec... |
"""
Extra HTML Widget classes
"""
from django.newforms.widgets import Widget, Select
from django.utils.dates import MONTHS
import datetime
__all__ = ('SelectDateWidget',)
class SelectDateWidget(Widget):
"""
A Widget that splits date input into three <select> boxes.
This also serves as an example of a Wi... |
from MySQLdb.constants import FIELD_TYPE
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.mysql.introspection import DatabaseIntrospection
class MySQLIntrospection(DatabaseIntrospection):
# Updating the data_types_reverse dictionary with the appropriate
# type for Geometry fields.
d... |
#!/usr/bin/python -u
# -*- coding: utf-8 -*-
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from mapas.models import *
from actores.models import *
class PerfilPublico(models.Model):
user = models.OneToOneField(User,verbose_name='Usuario')
per... |
'''
Debian and other distributions "unbundle" requests' vendored dependencies, and
rewrite all imports to use the global versions of ``urllib3`` and ``chardet``.
The problem with this is that not only requests itself imports those
dependencies, but third-party code outside of the distros' control too.
In reaction to t... |
"""The tests for local file camera component."""
from unittest import mock
from homeassistant.components.local_file.const import DOMAIN, SERVICE_UPDATE_FILE_PATH
from homeassistant.setup import async_setup_component
from tests.common import mock_registry
async def test_loading_file(hass, hass_client):
"""Test t... |
from django.contrib.auth.models import User
from concepts.importer import ConceptsImporter, ValidationLogger
from concepts.validation_messages import OPENMRS_NAMES_EXCEPT_SHORT_MUST_BE_UNIQUE, OPENMRS_MUST_HAVE_EXACTLY_ONE_PREFERRED_NAME, \
OPENMRS_SHORT_NAME_CANNOT_BE_PREFERRED, OPENMRS_PREFERRED_NAME_UNIQUE_PER_... |
'''Unit tests for misc.GritNode'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
import unittest
import StringIO
from grit import grd_reader
import grit.exception
from grit import util
from grit.format import rc
from grit.node import misc
class... |
from django.core.exceptions import FieldError
from django.test import TestCase
from models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild,
SelfReferChildSibling, Worksheet)
class M2MRegressionTests(TestCase):
def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs):
... |
"""
Tests for courseware middleware
"""
from django.http import Http404
from django.test.client import RequestFactory
from nose.plugins.attrib import attr
from lms.djangoapps.courseware.exceptions import Redirect
from lms.djangoapps.courseware.middleware import RedirectMiddleware
from xmodule.modulestore.tests.django... |
from odoo import api, models, fields
class Email(models.Model):
""" Add relation to communication configuration to track generated
e-mails.
"""
_inherit = 'mail.mail'
##########################################################################
# FIELDS ... |
import copy
# TODO: Note the functions 'rUpdate' are duplicated in
# the swarming.hypersearch.utils.py module
class DictObj(dict):
"""Dictionary that allows attribute-like access to its elements.
Attributes are read-only."""
def __getattr__(self, name):
if name == '__deepcopy__':
return super(DictO... |
import unittest
from ncclient.devices.junos import *
import ncclient.transport
from mock import patch
import paramiko
import sys
xml = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="/|comment()|processing-i... |
from spack import *
import glob
class Sw4lite(MakefilePackage):
"""Sw4lite is a bare bone version of SW4 intended for testing
performance optimizations in a few important numerical kernels of SW4."""
tags = ['proxy-app', 'ecp-proxy-app']
homepage = "https://geodynamics.org/cig/software/sw4"
url ... |
from highfive.runner import Configuration, Response
from highfive.api_provider.interface import APIProvider, CONTRIBUTORS_STORE_KEY, DEFAULTS
from handler_tests import TestStore
from datetime import datetime
from dateutil.parser import parse as datetime_parse
from unittest import TestCase
def create_config():
co... |
import sys
import random
read_file = open("data/user_profile.txt", 'r')
write_file = open("data/mini_user_profile.txt", 'w')
number_of_lines = int(sys.argv[1])
number_of_items = int(sys.argv[2])
#record number of lines
count = 0
random_num_list = []
# loop through the file to get number of lines in the file
for line ... |
from Plugins.Extensions.CutListEditor.plugin import CutListEditor
from Components.ServiceEventTracker import ServiceEventTracker
from enigma import iPlayableService, iServiceInformation
from Tools.Directories import fileExists
class TitleCutter(CutListEditor):
def __init__(self, session, t):
CutListEditor.__init__(... |
#!/usr/bin/env python
__author__ = 'saguinag' + '@' + 'nd.edu'
__version__ = "0.1.0"
##
## fname "b2CliqueTreeRules.py"
##
## TODO: some todo list
## VersionLog:
import net_metrics as metrics
import pandas as pd
import argparse, traceback
import os, sys
import networkx as nx
import re
from collections import deque,... |
import copy
from django.core.exceptions import FieldError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.fields import FieldDoesNotExist
class SQLEvaluator(object):
def __init__(self, expression, query, allow_joins=True, reuse=None):
self.expression = expression
self.opts... |
import unittest
from ctypes import *
class StructFieldsTestCase(unittest.TestCase):
# Structure/Union classes must get 'finalized' sooner or
# later, when one of these things happen:
#
# 1. _fields_ is set.
# 2. An instance is created.
# 3. The type is used as field of another Structure/Union.
... |
# run doom process on a series of maps
# can be used for regression testing, or to fetch media
# keeps a log of each run ( see getLogfile )
# currently uses a basic stdout activity timeout to decide when to move on
# using a periodic check of /proc/<pid>/status SleepAVG
# when the sleep average is reaching 0, issue a ... |
# -*- coding: utf-8 -*-
import inspect
import re
import urlparse
from module.network.HTTPRequest import BadHeader
from ..captcha.ReCaptcha import ReCaptcha
from ..internal.Addon import Addon
from ..internal.misc import parse_html_header
def plugin_id(plugin):
return ("<%(plugintype)s %(pluginname)s%(id)s>" %
... |
# -*- coding: utf-8 -*-
""" Tests for student profile views. """
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from util.testing import UrlResetMixin
from student.tests.factories import UserFactory
from stu... |
# encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
cl... |
"""
Tests For Scheduler Utils
"""
import contextlib
import uuid
import mock
from mox3 import mox
from oslo_config import cfg
from nova.compute import flavors
from nova.compute import utils as compute_utils
from nova import db
from nova import exception
from nova import objects
from nova import rpc
from nova.scheduler... |
import os.path
import copy
import PyQt4
from PyQt4.QtCore import QString, pyqtSlot
from PyQt4.QtGui import QWizard
from .gui.AddAttributeWizardDesign import Ui_AddAttributeWizardDesign
from base.backend.ObjectClassAttributeInfo import ObjectClassAttributeInfo
from base.util.IconTheme import pixmapFromTheme
class AddA... |
"""Test the zapwallettxes functionality.
- start two bitcoind nodes
- create two transactions on node 0 - one is confirmed and one is unconfirmed.
- restart node 0 and verify that both the confirmed and the unconfirmed
transactions are still available.
- restart node 0 with zapwallettxes and persistmempool, and veri... |
#import os
import sys
import time
import xmltodict
import pprint
pp = pprint.PrettyPrinter(indent=4,stream=sys.stderr)
testing = False
# def poll_condor(jonbr, bagnr):
def poll_condor(filename):
# filename = "hist-%d-%d.xml" % ( jobnr, bagnr )
# command = "condor_history -constraint 'HtcJob == %d && HtcBag ... |
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)
def posix_shell(chan):
import se... |
from typing import Any
from zerver.lib.actions import bulk_add_subscriptions, do_create_realm, do_create_user
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.onboarding import send_initial_realm_messages
from zerver.models import Realm, UserProfile
class Command(ZulipBaseCommand):
help = """Ad... |
# -*- coding: utf-8 -*-
"""
Tests for the newer CyberSource API implementation.
"""
from mock import patch
from django.test import TestCase
from django.conf import settings
import ddt
from student.tests.factories import UserFactory
from shoppingcart.models import Order, OrderItem
from shoppingcart.processors.CyberSour... |
try:
import wx
except ImportError:
raise ImportError, "You need to install the wxpython lib for this script"
class RootFrame(wx.Frame):
Y_OFFSET = 100
RECT_HEIGHT = 100
RECT_SPACE = 50
EVENT_MARKING_WIDTH = 5
def __init__(self, sched_tracer, title, parent = None, id = -1):
wx.Frame.__init__(self, parent, id... |
from rally.benchmark import context
from rally.common.i18n import _
from rally.common import log as logging
from rally.common import utils as rutils
from rally import objects
from rally import osclients
LOG = logging.getLogger(__name__)
# NOTE(boris-42): This context should be hidden for now and used only by
# ... |
# -*- coding: utf-8 -*-
import xbmc
import xbmcaddon
ADDON = xbmcaddon.Addon(id='screensaver.weather')
ADDON_ID = ADDON.getAddonInfo('id')
# Common logging module
def log(txt, loglevel=xbmc.LOGDEBUG):
if (ADDON.getSetting("logEnabled") == "true") or (loglevel != xbmc.LOGDEBUG):
if isinstance(txt, str):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='OpenIDNonce',
fields=[
('id', models.AutoField(... |
'''
Author: Jon Tsai
Created: May 29 2016
'''
import numpy as np
import theano
from time import sleep
import sys
def progress_bar(percent, speed):
i = int(percent)/2
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-50s] %d%% %f instances/s" % ('='*i, percent, spe... |
from common import *
from editorcommon import *
import weakref
class KPEditorObject(KPEditorItem):
SNAP_TO = (24,24)
def __init__(self, obj, layer):
KPEditorItem.__init__(self)
obj.qtItem = self
self._objRef = weakref.ref(obj)
self._layerRef = weakref.ref(layer)
self._updatePosition()
self._updateSize()... |
#!/usr/bin/env python
"""
Render Django templates.
Useful for generating fixtures for the JavaScript unit test suite.
Usage:
python render_templates.py path/to/templates.json
where "templates.json" is a JSON file of the form:
[
{
"template": "openassessmentblock/oa_base.html",
... |
"""EBS Mount - manually mount EBS device (simulates udev add trigger)
Arguments:
device EBS device to mount (e.g., /dev/xvdf, /dev/vda)
Options:
--format=FS Format device prior to mount (e.g., --format=ext3)
"""
import re
import os
import sys
import getopt
import ebsmount
import executil
from... |
from __future__ import division
from collections import deque
from datetime import timedelta
from math import ceil
from sys import stderr
from time import time
__version__ = '1.2'
class Infinite(object):
file = stderr
sma_window = 10
def __init__(self, *args, **kwargs):
self.index = 0
... |
import serial
from lxml import etree
import os
if os.name != 'nt':
import cups
class Device:
def __init__(self,config={}):
#self.xml = etree.parse(filename).getroot()
conf = {'width':0,'length':0,'name':'','interface':'serial','serial':{'port':'/dev/ttyUSB0','baud':9600}}
conf.update(config)
self.width = co... |
from django.db.models import Q, Sum
from django.db.models.deletion import ProtectedError
from django.db.utils import IntegrityError
from django.forms.models import modelform_factory
from django.test import TestCase, skipIfDBFeature
from .models import (
A, B, C, D, Address, Board, CharLink, Company, Contact, Conte... |
import vstruct
import vstruct.defs.inet as vs_inet
from vstruct.primitives import *
PCAP_LINKTYPE_ETHER = 1
PCAP_LINKTYPE_RAW = 101
PCAPNG_BOM = 0x1A2B3C4D
OPT_ENDOFOPT = 0
OPT_COMMENT = 1
#PCAPNG_BLOCKTYPE_SECTION_HEADER options
OPT_SHB_HARDWARE = 2
OPT_SHB_OS ... |
"""Test Element meta-class.
"""
import unittest
from zope.interface.interface import Element
class TestElement(unittest.TestCase):
def test_taggedValues(self):
"""Test that we can update tagged values of more than one element
"""
e1 = Element("foo")
e2 = Element("bar")
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Extractor to validate a METS file and check the existence and content of
the files linked from each fileSec/fileGrp/file/FLocat tag, assumed to
contain an MD5 checksum. The "md5sum" utility is required.
"""
#
# (C) Federico Leva and Fondazione BEIC, 2018
#
# Distr... |
import pytest
import sql_query_dict
def test_escape_string_with_single_quote():
assert sql_query_dict.quote_string("'a") == '"\'a"'
def test_escape_string_with_double_quote():
assert sql_query_dict.quote_string('"a') == "'\"a'"
def test_escape_string_with_single_and_double_quote():
assert sql_query_d... |
#!/usr/bin/env python3
"""Reddit bot for updating user flairs via PM requests"""
import sys
import re
import os
import time
import logging
import logging.handlers
import praw
import OAuth2Util
from config import cfg
def setup_logging():
"""Configure logging module for rotating logs and console output"""
r... |
"""Tests for sparse_feature_column.py (deprecated).
This module and all its submodules are deprecated. To UPDATE or USE linear
optimizers, please check its latest version in core:
tensorflow_estimator/python/estimator/canned/linear_optimizer/.
"""
from __future__ import absolute_import
from __future__ import division... |
import nose
import angr
from angr.calling_conventions import SimCCSystemVAMD64
import logging
l = logging.getLogger("angr.tests.test_rol")
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
def test_rol_x86_64():
binary_path = test_location + "/x86_64... |
import logging
import werkzeug
import openerp
from openerp.addons.auth_signup.res_users import SignupError
from openerp.addons.web.controllers.main import ensure_db
from openerp import http
from openerp.http import request
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
class AuthSignupHo... |
import datetime
import json
import luigi
from luigi.contrib.esindex import CopyToIndex
class FakeDocuments(luigi.Task):
"""
Generates a local file containing 5 elements of data in JSON format.
"""
#: the date parameter.
date = luigi.DateParameter(default=datetime.date.today())
def run(self)... |
"""Generates YAML configuration file for allreduce-based distributed TensorFlow.
The workers will be run in a Kubernetes (k8s) container cluster.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import k8s_generate_yaml_lib
#... |
from collections import MutableMapping
class OrderedDict(MutableMapping):
'''OrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(s... |
import os
from django.contrib.auth import validators
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import (
CommonPasswordValidator, MinimumLengthValidator, NumericPasswordValidator,
UserAttributeSimilarityValidator, get_default_password_validators,
get_password_v... |
import abc
import itertools
from oslo.config import cfg
from stevedore import dispatch
from ceilometer.logger import logger
from ceilometer.openstack.common import context
from ceilometer.openstack.common import log
from ceilometer import pipeline
LOG = log.getLogger(__name__)
class PollingTask(object):
"""Pol... |
from __future__ import unicode_literals
from django import forms, http
from django.conf import settings
from django.db import models
from django.test import TestCase
from django.template.response import TemplateResponse
from django.utils.importlib import import_module
from django.contrib.auth.models import User
from... |
from m5.params import *
from ClockedObject import ClockedObject
class BasicRouter(ClockedObject):
type = 'BasicRouter'
cxx_header = "mem/ruby/network/BasicRouter.hh"
router_id = Param.Int("ID in relation to other routers") |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.db import connection
from build.management.commands.base_build import Command as BaseBuild
from protein.models import (Protein, ProteinConformation, ProteinSequenceType, ProteinSegment,
ProteinConformati... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: mongodb_parameter
short_description: Change an administrat... |
"""TestCases for multi-threaded access to a DB.
"""
import os
import sys
import time
import errno
import shutil
import tempfile
from pprint import pprint
from whrandom import random
try:
True, False
except NameError:
True = 1
False = 0
DASH = '-'
try:
from threading import Thread, currentThread
... |
import sys
from gunicorn import six
PY26 = (sys.version_info[:2] == (2, 6))
PY33 = (sys.version_info >= (3, 3))
def _check_if_pyc(fname):
"""Return True if the extension is .pyc, False if .py
and None if otherwise"""
from imp import find_module
from os.path import realpath, dirname, basename, splite... |
import json
import os
import re
import unittest
from unittest import mock
import pytest
from google.auth import exceptions
from google.auth.environment_vars import CREDENTIALS
from airflow.providers.google.common.utils.id_token_credentials import (
IDTokenCredentialsAdapter,
get_default_id_token_credentials,
... |
from .sql import (
alias,
all_,
and_,
any_,
asc,
between,
bindparam,
case,
cast,
collate,
column,
delete,
desc,
distinct,
except_,
except_all,
exists,
extract,
false,
func,
funcfilter,
insert,
intersect,
intersect_all,
j... |
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
re_accepts_gzip = re.compile(r'\bgzip\b')
class GZipMiddleware(object):
"""
This middleware compresses content if the browser allows gzip compression.
It sets the Vary header accordingly, so that cac... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import collections
import os
from netrc import netrc as NetrcDb
from netrc import NetrcParseError
class Netrc(object):
"""Fetches username and password from ~/.net... |
# -*- coding: utf-8 -*-
##
# TRACK 7
# TOO BLUE
# Brian Foo (brianfoo.com)
# This file builds the sequence file for use with ChucK from the data supplied
##
# Library dependancies
import csv
import json
import math
import os
import pprint
import time
# Config
BPM = 100 # Beats per minute, e.g. 60, 75, 100, 120, 150
D... |
"""Platform-specific code for checking the integrity of the TensorFlow build."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
try:
from tensorflow.python.platform import build_info
except ImportError:
raise ImportError("Could not import te... |
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.decorators import register
from django.contrib.admin.filters import (
AllValuesFieldListFilter, BooleanFieldListFilter, ChoicesFieldListFilter,
DateFieldListFilter, Fiel... |
from django.test import TestCase
from .models import Article, Bar, Base, Child, Foo, Whiz
class StringLookupTests(TestCase):
def test_string_form_referencing(self):
"""
Regression test for #1661 and #1662
String form referencing of models works, both as pre and post
reference, o... |
import guardian
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
fr... |
# -*- coding: utf-8 -*-
"""
flask.module
~~~~~~~~~~~~
Implements a class that represents module blueprints.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
from .blueprints import Blueprint
def blueprint_is_module(bp):
"""Used to figure ou... |
"""
Copyright (c) 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import os
import subprocess
import tempfile
from flexmock import flexmock
import pytest
import json
import tarfile
import re
from atomic_rea... |
""" Support for Tellstick lights. """
import logging
# pylint: disable=no-name-in-module, import-error
from homeassistant.components.light import Light, ATTR_BRIGHTNESS
from homeassistant.const import ATTR_FRIENDLY_NAME
import tellcore.constants as tellcore_constants
def setup_platform(hass, config, add_devices_callb... |
# import modules
import mcpi.minecraft as minecraft
from time import sleep
# connect python to minecraft
mc = minecraft.Minecraft.create()
# create CONSTANTS for block and light colours
AIR = 0
STONE = 1
WOOL = 35
BLACK = 15
RED = 14
AMBER = 4
GREEN = 5
# clear area in middle of map and move player there
mc.setBlock... |
import sys
import os
import shlex
import time
from cbsh import __version__
try:
import sphinx_rtd_theme
except ImportError:
sphinx_rtd_theme = None
try:
from sphinxcontrib import spelling
except ImportError:
spelling = None
# -- Path setup ------------------------------------------------------------... |
import sys
import os
#Put pydevconsole in the path.
sys.argv[0] = os.path.dirname(sys.argv[0])
sys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0])))
print('Running tests with:', sys.executable)
print('PYTHONPATH:')
print('\n'.join(sorted(sys.path)))
import threading
import unittest
import pydevconsole
fro... |
from __future__ import absolute_import
from django.conf import settings
import logging
import traceback
import platform
from django.core import mail
from django.http import HttpRequest
from django.utils.log import AdminEmailHandler
from django.views.debug import ExceptionReporter, get_exception_reporter_filter
from... |
#github data scrapper
"""
variables of interest:
indp. variables
- language, given as a binary variable. Need 4 positions for 5 langagues
- #number of days created ago, 1 position
- has wiki? Boolean, 1 position
- followers, 1 position
- following, 1 position
- constant
dep. variab... |
from robot import utils
from robot.errors import DataError
from robot.model import Message as BaseMessage
LEVELS = {
'NONE' : 6,
'ERROR' : 5,
'FAIL' : 4,
'WARN' : 3,
'INFO' : 2,
'DEBUG' : 1,
'TRACE' : 0,
}
class AbstractLogger:
def __init__(self, level='TRACE'):
self._is_logged = IsLo... |
import errno
import logging
import math
import re
import os
import signal
import socket
import subprocess
import sys
import time
# Import for auto-install
if sys.platform not in ('cygwin', 'win32'):
# FIXME: webpagereplay doesn't work on win32. See https://bugs.webkit.org/show_bug.cgi?id=88279.
import webkitpy... |
from pkg_resources import resource_filename
_messages = None
MESSAGES_FILE = 'data/messages.properties'
def get_external_messages():
"""Return a table of externalized messages.
The table is lazzy instancied (loaded once when called the first time)."""
global _messages
if _messages is None:
p... |
import urllib
import urllib2
import base64
import re
import sickbeard
from sickbeard import logger
from sickbeard import common
from sickbeard.exceptions import ex
from sickbeard.encodingKludge import fixStupidEncodings
try:
import xml.etree.cElementTree as etree
except ImportError:
import elementtree.Elemen... |
# -*- coding: utf-8-*-
"""
Iterates over all the WORDS variables in the modules and creates a
vocabulary for the respective stt_engine if needed.
"""
import os
import tempfile
import logging
import hashlib
import subprocess
import tarfile
import re
import contextlib
import shutil
from abc import ABCMeta, abstractmetho... |
import sys
# from . import lowlevel # Python 3.X
# from . import frontend # Python 3.X
import lowlevel
import frontend
import string
class repository:
def __init__(self):
self.conf = lowlevel.config()
self.cmd = lowlevel.command()
self.link = lowlevel.linkname()
self... |
"""
linguistics module (imdb package).
This module provides functions and data to handle in a smart way
languages and articles (in various languages) at the beginning of movie titles.
Copyright 2009-2012 Davide Alberani <<EMAIL>>
2012 Alberto Malagoli <albemala AT gmail.com>
2009 H. Turgut Uyar <<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.