content stringlengths 4 20k |
|---|
"""TensorFlow Eager Execution: Sanity tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
from tensorflow.contrib.eager.python import tfe
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import error... |
#!/usr/bin/env python
import smbc
import settings
import hashlib
import os
basedir = 'smb://' + settings.SERVER + '/' + settings.SHARE + '/'
testdir = basedir + '/' + settings.TESTDIR
def auth_fn(server, share, workgroup, username, password):
return (workgroup, settings.USERNAME, settings.PASSWORD)
def creat_r... |
import os
import sys
from nose.tools import *
from nose.tools import with_setup
from ci.jenkins.storage import Storage
NAME = 'hello'
PORT = 3001
PATH = os.path.expanduser('~/.jenkins-clone/clone')
store = None
def flushwrite(text):
sys.stdout.write(text + '\n')
sys.stdout.flush()
def setup_store():
global sto... |
"""lesson_4_1_Classwork "Data processing tools"
"""
import os
import pandas as pd
def count_of_len(row):
return len(row.Name)
def agg_count(row):
# row.Count += row.Count_1900 + row.Count_1950 + row.Count
return row.Count_1900 + row.Count_1950 + row.Count
def main():
source_path = 'D:\Python_my... |
"""Helpers for an Ubuntu application."""
import logging
import os
import gtk
from . labalyzerconfig import get_data_file
from . Builder import Builder
import gettext
from gettext import gettext as _
gettext.textdomain('labalyzer')
def get_builder(builder_file_name):
"""Return a fully-instantiated gtk.Builder in... |
from odoo import fields, models
class Product(models.Model):
_inherit = "product.product"
def action_open_quants(self):
# Override to hide the `removal_date` column if not needed.
if not any(product.use_expiration_date for product in self):
self = self.with_context(hide_removal_da... |
"""
Test http checking.
"""
from tests import need_network
from .httpserver import HttpServerTest, CookieRedirectHttpRequestHandler
class TestHttpRedirect(HttpServerTest):
"""Test http:// link redirection checking."""
def __init__(self, methodName="runTest"):
super().__init__(methodName=methodName)
... |
import sys
from OpenSSL.crypto import (
FILETYPE_PEM, TYPE_DSA, Error, PKey, X509, load_privatekey, CRL, Revoked,
get_elliptic_curves, _X509_REVOKED_dup, load_certificate)
from OpenSSL._util import lib as _lib
class BaseChecker(object):
def __init__(self, iterations):
self.iterations = iteratio... |
from tkinter import Tk, Canvas
from PIL import ImageTk
from libraries.pyrobot import Robot
_r = Robot()
def take_screenshot_whole(path):
pimage = _r.take_screenshot()
pimage.save(path, "PNG")
def take_screenshot_crop(path):
pimage = _r.take_screenshot()
_, _, width, height = pimage.getbbox()
... |
#-*- coding: utf8
from __future__ import print_function, division
import dataio
import numpy as np
import os
from prme import sgd
def learn(trace_fpath, nk, rate, regularization, alpha, tau,
from_=0, to=np.inf, validation=0.1):
dts, Trace, seen, hyper2id, obj2id = \
dataio.initialize_trace(t... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import time
import subprocess
import sys
try:
import caffeine
except ImportError:
pass
from module.plugins.internal.Addon import Addon, Expose
from module.utils import save_join as fs_encode, fs_join
class Kernel32(object):
ES_AWA... |
from unittest import TestCase
import sqlalchemy
from nose.tools import raises
from ytcc.database import Database, Video, Channel
def init_db():
insert_list = [
Video(yt_videoid="0", title="title1", description="description1", publisher="id_publisher1", publish_date=1488286166,
watched=Fals... |
"""
Django conf file for Jenkins. The test db is an sqlite, and users and variants cohabit.
"""
from varmed.settings.base import *
from os.path import join
import os, sys, logging
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(message)s')
logging.info("\n----------- << RESTART >> -----------\n")... |
"""The Binomial distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.frame... |
import arcpy
# Attempt to create a code to fill the valve fields that are dependent on
# other information within the map
valves = r'C:\Users\erentschlar\Desktop\ToDelete\valve.shp'
rows = arcpy.SearchCursor(valves)
vrows = arcpy.SearchCursor("WATER_VALVES")
mapGrid = r'G:\4_LAYERS\IMAGERY\GRID_INDEX\MAP GRID.lyr'
gr... |
"""
desisim.pixelsplines
====================
Pixel-integrated spline utilities.
Written by A. Bolton, U. of Utah, 2010-2013.
"""
from __future__ import absolute_import, division, print_function
import numpy as n
from scipy import linalg as la
from scipy import sparse as sp
from scipy import special as sf
def compu... |
# -*- coding: utf8 -*-
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.dropdown import DropDown
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button as Button
... |
"""Wrappers around standard crypto data elements.
Includes root and intermediate CAs, SSH key_pairs and x509 certificates.
"""
from __future__ import absolute_import
import base64
import binascii
import os
from cryptography.hazmat import backends
from cryptography.hazmat.primitives.asymmetric import padding
from cr... |
def code_string(string_to_count):
return len(string_to_count)
def encode_string(string_to_encode):
modified_string = "\"";
for char in string_to_encode:
if char == "\\":
modified_string += "\\\\"
elif char == "\"":
modified_string += "\\\""
else:
... |
import os
import sys
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.parsing.vault import VaultEditor
from ansible.cli import CLI
from ansible.utils.display import Display
class VaultCLI(CLI):
""" Vault command line class """
VALID... |
"""This script is used to synthesize generated parts of this library."""
import subprocess
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICBazel()
library = gapic.php_library(
service="billing",
version="v1",
bazel_target='//goog... |
import MySQLdb
import psycopg2
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
class cons():
dbDrivers={'mysql':MySQLdb,'postgresql':psycopg2}
typeItem={'cap':'cap','pro':'provincia','com':'comune','reg':'regione','ope':'regione'}
queryList=unicode("select distinct nome1, in... |
"""
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
... |
import sys
import os
import time
import Queue
import BaseDevice
import socket
import signal
import logging
from pkg.utils.debug import debug_mesg
class Shenitech(BaseDevice.Device):
def __init__(self, id, params):
super(Shenitech,self).__init__("Shenitech", id, params)
self.decription = "Shenitech_STUF200H"
if ... |
# -*- coding: utf-8 -*-
import math
from ensure import ensure_annotations
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import Avg
from celery import shared_task
from core.models import KarmicUserEvent
User = get_user_model()
@ensure_annotations
def get_k... |
#!/usr/bin/env python
# coding: utf8
"""
ROI.ru data processor
"""
import csv
import json
import os, os.path
from urllib import urlopen, unquote_plus, urlencode
import urllib2
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
import time
from urlparse import urljoin
from StringIO import StringIO
from datetim... |
"""
This module contains code for parsing tabular HMMer output files. Note that
different parse routines are required for --tblout files of both hmmsearch and
nhmmer, and also probably for other programs such as phmmer.
"""
from util.directories import dirfiles
from searches.hmmer import hmmer_record
class HMMerParse... |
"""Client side criteria that checks if the drag source is one of the given
components."""
from muntjac.event.transferable_impl import TransferableImpl
from muntjac.event.dd.acceptcriteria.client_side_criterion import \
ClientSideCriterion
class SourceIs(ClientSideCriterion):
"""Client side criteria that che... |
r"""Return all active recommendations on a given project.
python get_recommendation.py \
--project="[YOUR-PROJECT-ID]" \
--service_account_file_path="[FILE-PATH-TO-SERVICE-ACCOUNT]" \
--to_json="[FILE-PATH-TO-STORE-THE-DATA]"
"""
import argparse
import logging
import common
from googleapiclient.discovery import buil... |
"""Unit tests for complex validator
"""
import unittest
import sys
from pywps.validator.complexvalidator import *
from pywps.inout.formats import FORMATS
import tempfile
import os
try:
import osgeo
except ImportError:
WITH_GDAL = False
else:
WITH_GDAL = True
def get_input(name, schema, mime_type):
cl... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import setup, find_pack... |
from defusedxml.sax import make_parser
from xml.sax import handler
from xml.sax.xmlreader import InputSource
import xml.sax.saxutils
from odf.element import Element
from odf.namespaces import OFFICENS
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
#
# Parse the XML files
#
clas... |
# -*- coding: utf-8 -*-
from docutils import nodes
from docutils.parsers.rst import Directive
from sphinx.locale import _
import requests
import json
class swaggerdoc(nodes.Admonition, nodes.Element):
pass
def visit_swaggerdoc_node(self, node):
self.visit_admonition(node)
def depart_swaggerdoc_node(self, ... |
import imp
import inspect
import os
import sys
import mock
from oslo_utils import uuidutils
from ironic.tests import base as test_base
class TestExposedAPIMethodsCheckPolicy(test_base.TestCase):
"""Ensure that all exposed HTTP endpoints call authorize."""
def setUp(self):
super(TestExposedAPIMethod... |
#!/usr/bin/env python2
# python setup.py sdist --format=zip,gztar
from setuptools import setup
import os
import sys
import platform
import imp
import argparse
version = imp.load_source('version', 'lib/version.py')
if sys.version_info[:3] < (2, 7, 0):
sys.exit("Error: Electrum requires Python version >= 2.7.0...... |
'''
synbiochem (c) University of Manchester 2016
synbiochem is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=no-member
# pylint: disable=too-few-public-methods
import operator
import random
import sys
from B... |
"""
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... |
import datetime
import sys
logging = True
log_to_stderr = True
log_file_name = "/tmp/StalkerBot.log"
def log (msg) :
if logging :
line = "[%s] %s\n" % (datetime.datetime.today(), msg)
LOG = open (log_file_name, "a")
LOG.write(line)
LOG.close()
if log_to_stderr :
... |
"""
This module replaces the Django mail implementation with a version that sends
email via the mail API provided by Google App Engine.
Multipart / HTML email is not yet supported.
"""
import logging
from django.core import mail
from django.core.mail import SMTPConnection
from django.conf import settings
from googl... |
"""Record serialization."""
from __future__ import absolute_import, print_function
import json
import arrow
from marshmallow import Schema, fields
from ...models import ObjectType
class IdentifierSchema(Schema):
"""Identifier schema."""
identifier = fields.Function(lambda o: o)
identifierType = field... |
import hashlib
import os, sys, re
import boto3
from os.path import join
from datetime import datetime
import threading
from ubr.conf import logging
from ubr import utils, conf
from ubr.utils import ensure
LOG = logging.getLogger(__name__)
def remove_targets(path_list, rooted_at=conf.WORKING_DIR):
"deletes the li... |
#templates to generate PE structures via MakePE
Imports = """
DESCRIPTORS_START|
IMPORT_DESCRIPTOR: ; replace with imports:
|IMAGE_IMPORT_DESCRIPTOR|
%(dll)s_DESCRIPTOR:
dd %(dll)s_hintnames - IMAGEBASE ; OriginalFirstThunk/Characteristics, IMAGE_IMPORT_BY_NAME array
dd 0 ... |
# from dto import *
# from dao import *
from service import PodService
import pd_util
import dao
import os
pd_util.init_dirs()
dao.init_database()
# list of podcasts to subscribe to:
sub_urls = [
('http://www.npr.org/rss/podcast.php?id=510208','Car Talk'),
('http://www.npr.org/rss/podcast.ph... |
from unittest.mock import Mock
from app.master.build import Build
from app.master.build_scheduler_pool import BuildSchedulerPool
from app.master.slave import Slave
from app.master.slave_allocator import SlaveAllocator
from test.framework.base_unit_test_case import BaseUnitTestCase
class TestSlaveAllocator(BaseUnitTe... |
"""
URLconf for registration and activation, using django-registration's
HMAC activation workflow.
"""
from django.conf.urls import include, url
from django.views.generic.base import TemplateView
from .views import ActivationView, RegistrationView
urlpatterns = [
url(r'^activate/complete/$',
TemplateVi... |
"""
===============================
Univariate Feature Selection
===============================
An example showing univariate feature selection.
Noisy (non informative) features are added to the iris data and
univariate feature selection is applied. For each feature, we plot the
p-values for the univariate feature s... |
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
import unittest
from gi.repository import GLib
from gi.repository import Gio
class TestGDBusClient(unittest.TestCase):
def setUp(self):
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
self.dbus_proxy = Gi... |
# coding: utf-8
import time
import typing
from PIL import Image
from PIL.ImageDraw import Draw
from PIL.ImageFont import truetype
from calcium import core
class RawPixelsFilter(core.BaseFilter):
def __init__(self, pixels: typing.List[int]):
super().__init__()
self._pixels: typing.List[int] = pi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.db.models import Q
from django import forms
from django.utils.timezone import now
from django.utils.translation import ugettext, ugettext_lazy as _
from timezones.fields import TimeZoneField
CONFERENCE_CACHE = {... |
'''
Created on Jul 4, 2014
@author: lzrak47
'''
import os
import shutil
import unittest
from command import Command
from repository import Repository
from utils import write_to_file
class TestRm(unittest.TestCase):
def setUp(self):
self.workspace = 'test_rm'
Command.cmd_init(self.workspace)
... |
Import ('plugin_base')
Import ('env')
prefix = env['PREFIX']
plugin_env = plugin_base.Clone()
sqlite_src = Split(
"""
sqlite_datasource.cpp
sqlite_featureset.cpp
"""
)
libraries = [ 'sqlite3' ]
# Link Library to Dependencies
libraries.append('mapnik')
libraries.append(env['ICU_LIB_NAME'])
lib... |
from datetime import timedelta
import pytest
from mock import mock
import bomb_defusal.modules.capacitor_discharge
import bomb_defusal.modules.module
from bomb_defusal.modules import CapacitorDischarge
from tests.utils.controllable_clock import ControllableClock
@pytest.fixture(autouse=True)
def clock(monkeypatch):... |
"""
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 ... |
# -*- 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 'Notification.facebook'
db.add_column(u'notifications_notification', 'facebook',
... |
""" basic collect and runtest protocol implementations """
import bdb
import sys
from time import time
import py
import pytest
from py._code.code import TerminalRepr
def pytest_namespace():
return {
'fail' : fail,
'skip' : skip,
'importorskip' : importorskip,
'exit'... |
import asyncio
import socket
import ssl
import logging
import async_timeout
import contextlib
logger = logging.getLogger(name="general")
def get_ssl_context(
enable=False, cafile=None, client_crt=None, client_key=None):
if not enable:
return None
ssl_context = ssl.create_default_context(
... |
"""
# Example:
# RUN TEST SUITE
import mutils.tests
reload(mutils.tests)
mutils.tests.run()
"""
import unittest
import logging
logging.basicConfig(
filemode='w',
level=logging.DEBUG,
format='%(levelname)s: %(funcName)s: %(message)s',
)
def testSuite():
"""
Return a test suite containing all the... |
import os
import time
import pytest
from twitter.common.contextutil import temporary_dir
from pex.common import safe_copy
from pex.compatibility import PY2
from pex.crawler import Crawler
from pex.fetcher import Fetcher
from pex.package import EggPackage, SourcePackage
from pex.resolvable import ResolvableRequirement... |
#!
#!-----------------------
#! CHAPTER 5 - FUNCTIONS
#!-----------------------
#!
from functools import partial
import numpy
import time
from pylab import figure, show
from pacal import *
from pacal.distr import demo_distr
if __name__ == "__main__":
tic = time.time()
#! Example 5.1.3
d = Normal... |
"""
Nyaa.se (Anime Bittorrent tracker)
@website http://www.nyaa.se/
@provide-api no
@using-api no
@results HTML
@stable no (HTML can change)
@parse url, title, content, seed, leech, torrentfile
"""
from urllib import urlencode
from lxml import html
from searx.engines.xpath import ext... |
#!/usr/bin/env python3
import os
import json
raw_data_dir = 'rawdata'
unpacked_data_dir = 'unpacked'
for (_, _, filenames) in os.walk(raw_data_dir):
for filename in filenames:
filename = os.path.join(raw_data_dir, filename)
print(filename, '##################')
with open(filename, 'r')... |
'''
main.py
A module that contains the main forklift pallets for deq
Note: There is a separate scheduled task that runs this pallet for
SGID.ENVIRONMENT.DAQAirMonitorByStation on an hourly basis.
'''
from os import path
import arcpy
import build_json
import settings
import update_fgdb
import update_sgid
import upda... |
from datetime import date, datetime, time
from dateutil.relativedelta import relativedelta
from indico.core.db import db
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import Reservation
from indico.util.date_time import iterdays
WORKING... |
# -*- coding: utf-8 -*-
import logging
from pymongo.errors import BulkWriteError
from karsender.database import get_collection
from .database import session
__author__ = 'Sergey Smirnov <<EMAIL>>'
import datetime
import pymongo
from .database import Order
logging.basicConfig(filename='opencart.log', level=logging.... |
from typing import Any, Dict, Optional
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from ... |
#=========================================================================
# TestSink
#=========================================================================
from pymtl import *
from pclib.test import TestRandomDelay
from pclib.ifcs import InValRdyBundle, OutValRdyBundle
from TestSimpleSink import TestSimpleS... |
import os
import re
import codecs
import numpy as np
import theano
models_path = "./models"
eval_path = "./evaluation"
eval_temp = os.path.join(eval_path, "temp")
eval_script = os.path.join(eval_path, "conlleval")
def get_name(parameters):
"""
Generate a model name from its parameters.
"""
l = []
... |
"""
Unit tests for courseware context_processor
"""
from django.contrib.auth.models import AnonymousUser
from mock import Mock
from courseware.context_processor import user_timezone_locale_prefs
from openedx.core.djangoapps.user_api.preferences.api import set_user_preference
from student.tests.factories import UserFac... |
import json
import gzip
import os.path
from collections import defaultdict
from pprint import pprint
from urllib.parse import urlparse
import pymysql
import yaml
with open('config.yml', 'r') as config_file:
config = yaml.load(config_file)
conn = pymysql.connect(
host='127.0.0.1',
charset='utf8',
use_... |
def handleTextInput( text ):
text = text.lower()
if 'who knows' in text:
return True, 'Jeff knows.'
if 'llama' in text:
return True, 'Tinaface!'
if 'regulators' in text:
return True, 'Mount up!'
if 'destiny' in text:
return True, 'Eyes up, guardian.'
if 'what a save' in text:
return True, 'SAVAGE'... |
from nova.tests.functional.api_sample_tests import test_servers
from nova.tests.unit.image import fake
class PersonalitySampleJsonTest(test_servers.ServersSampleBase):
extension_name = 'os-personality'
extra_extensions_to_load = ["os-access-ips"]
_api_version = 'v2'
def test_servers_post(self):
... |
import plasTeX
from plasTeX.TeX import TeX
from plasTeX.Config import config
from plasTeX.ConfigManager import *
from plasTeX.Renderers.XHTML import Renderer as XHTMLRenderer
from plasTeX.Renderers.PageTemplate.simpletal import simpleTAL, simpleTALES
#
import codecs
import datetime
import os
import sgmllib
i... |
import pytest
from pip._internal.exceptions import InstallationError
from pip._internal.req import InstallRequirement
@pytest.mark.parametrize(('source', 'expected'), [
("pep517_setup_and_pyproject", True),
("pep517_setup_only", False),
("pep517_pyproject_only", True),
])
def test_use_pep517(data, source... |
from functools import wraps
from flask import session
from apikit import jsonify
from aleph.core import oauth, app
class Stub():
""" A stub authorization handler to sit in for auth methods that
are not currently enabled. """
def __init__(self, name):
self.name = name
def authorize(self, **... |
import sys, os, os.path, time, stat
"""
this renamer strips of everything from the first colon in the file name to the end.
This does the same thing as a 'WHATFN' config on a sundew sender.
takes px name : /apps/dms/dms-metadata-updater/data/international_surface/import/mdicp4d:pull-international-metadata:CMC:... |
"""
Base classes for our unit tests.
Allows overriding of flags for use of fakes,
and some black magic for inline callbacks.
"""
import logging
import time
import unittest
from nova import vendor
import mox
from tornado import ioloop
from twisted.internet import defer
from twisted.python import failure
from twisted.... |
from __future__ import absolute_import
import os.path
import shutil
def get_tree_size(start_path):
"""
return size (in bytes) of filesystem tree
"""
if not os.path.exists(start_path):
raise ValueError("Incorrect path: %s" % start_path)
total_size = 0
for dirpath, dirnames, filenames in... |
"""
Author: Pablo Winant
Filename: test_cartesian.py
Tests for cartesian.py file
"""
from quantecon.cartesian import cartesian, _repeat_1d
def test_cartesian_C_order():
from numpy import linspace
x = linspace(0,9,10)
prod = cartesian([x,x,x])
correct = True
for i in range(999):
n = pr... |
#!/usr/bin/python
__author__ = "Amish Anand"
__copyright__ = "Copyright (c) 2015 Juniper Networks, Inc."
"""
This script will be used by the yang file for retrieving the statistics
"""
import sys
import xmlrpclib
import xml.etree.ElementTree as ET
def PRINT_TAG(node, tag):
if node.tag == tag:
print '<'+ta... |
"""
OPUS (http://opus.nlpl.eu/) is a great collection of different parallel datasets for more than 400 languages.
On the website, you can download parallel datasets for many languages in different formats. I found that
the format "Bottom-left triangle: download plain text files (MOSES/GIZA++)" requires minimal
overhea... |
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class PrintArrayTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test_print_array... |
# Visualizer
try:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
except:
print('PyQtGraph is not installed, can not visualize the network.')
exit(0)
class Viewer(object):
" Class to visualize the network activity using PyQtGraph."
def __init__(self, func):
self.... |
import json
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from starthinker_ui.recipe.models import Recipe
from django.core import serializers
class Command(BaseCommand):
help = 'Replace task or field in recipes with new value.'
def add_arguments(self, parser)... |
"""URL Route Handlers
.. module:: application.views
:synopsis: URL Route Handlers
.. moduleauthor:: Devin Schwab <<EMAIL>>
.. moduleauthor:: Jon Chan <<EMAIL>>
"""
from google.appengine.api import users
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
from flask import render_templat... |
"""Prints all non-system dependencies for the given module.
The primary use-case for this script is to generate the list of python modules
required for .isolate files.
This script should be compatible with Python 2 and Python 3.
"""
import argparse
import fnmatch
import os
import pipes
import sys
# Don't use any he... |
import contextlib
import gzip
import os
import re
import string
import tarfile
import zipfile
class Archive:
def __init__(self, filename):
self._names = None
self._unpack = None
self._file = None
self.filename = filename
@property
def filename(self):
return self.... |
from unittest import TestCase
from base.field import BaseField, ListField
from jsonparser.documents import BaseJsonDocument
class TestBaseObjectLoad(TestCase):
def test_load_base_field(self):
class TestClass(BaseJsonDocument):
field = BaseField()
obj = TestClass().load({"field": "val... |
from django.db.models import FloatField, IntegerField
from django.db.models.aggregates import Aggregate
__all__ = [
'CovarPop', 'Corr', 'RegrAvgX', 'RegrAvgY', 'RegrCount', 'RegrIntercept',
'RegrR2', 'RegrSlope', 'RegrSXX', 'RegrSXY', 'RegrSYY', 'StatAggregate',
]
class StatAggregate(Aggregate):
output_f... |
"""A unified and split coordinator for distributed TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import json
import os
import threading
from tensorflow.core.protobuf import cluster_pb2
from tensorflow.python.training import ser... |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Dust sensor(http://www.seeedstudio.com/depot/Grove-Dust-Sensor-p-1050.html) with the GrovePi
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question abo... |
from datamodel.datamodel import LoraRadioMessage
from settings.settings import SettingsClass
class LoraStatusToLoraAckTransform(object):
@staticmethod
def GetInputMessageType():
return "LORA"
@staticmethod
def GetInputMessageSubType():
return "Status"
@staticmethod
def GetOut... |
from openerp.osv import orm
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
FY_SLOT = '%(fy)s'
YEAR_SLOT = '%(year)s'
class Sequence(orm.Model):
_inherit = 'ir.sequence'
def _create_fy_sequence(self, cr, uid, seq, fiscalyear, context=None):
""" Create a FY sequence by cloning ... |
import os
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.flatpages.models import FlatPage
from django.test import TestCase
class FlatpageMiddlewareTests(TestCase):
fixtures = ['sample_flatpages']
urls = 'django.contrib.flatpages.tests.urls'
def setUp(self)... |
from __future__ import print_function
# Note: this code was initially copied from the 'pyutools' package by its
# original author, and re-licensed under Theano's license.
import numpy
import theano
from theano.compile.mode import Mode
class MonitorMode(Mode):
"""
`MonitorMode` is a debug mode to easily step ... |
import hashlib
import os
import zipfile
try:
from StringIO import StringIO as IOStream
except ImportError: # 3+
from io import BytesIO as IOStream
import base64
from .command import Command
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import InvalidSelectorExceptio... |
# -*- coding: utf-8 -*-
"""
@author: kevinhikali
@email: <EMAIL>
"""
from __future__ import division
import os
import numpy as np
from PIL import Image
import sys
dataname = sys._getframe().f_code.co_filename
dataname = dataname.split('/')[-1]
dataname = dataname.split('.')[0]
RES_PATH = '/home/kevin/catkin_ws/src/re... |
"""Tests for tensorflow.ops.test_util."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import random
import threading
import numpy as np
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from te... |
from __future__ import unicode_literals
from django.test import TestCase
from accelerator.tests.factories import (
UserRoleFactory,
ProgramFactory
)
from accelerator_abstract.models.base_user_role import (
BaseUserRole,
is_finalist_user,
is_judge,
is_mentor,
)
from accelerator.tests.test_core_... |
import pytest
from cfme.containers.pod import Pod
from cfme.containers.service import Service
from cfme.containers.node import Node
from cfme.containers.replicator import Replicator
from cfme.containers.image import Image
from cfme.containers.project import Project
from cfme.fixtures import pytest_selenium as sel
from... |
# Enthought library imports.
from traits.api import HasTraits, Instance
from traitsui.api import UI
# Local imports.
from task_pane import TaskPane
class TraitsTaskPane(TaskPane):
""" A TaskPane that displays a Traits UI View.
"""
#### TraitsTaskPane interface ###########################################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.