content stringlengths 4 20k |
|---|
import ioutil
import string
import io
EndSenitel = object()
class Decoder():
def __init__(self, stream):
self.stream = stream
def decode(self):
c = self.stream.read(1)
if c == b'i':
data = ioutil.read_until(self.stream, b'e')
if data != b'0' and data.startswith... |
"""
Scrapy Shell
See documentation in docs/topics/shell.rst
"""
from threading import Thread
from scrapy.commands import ScrapyCommand
from scrapy.shell import Shell
from scrapy.http import Request
from scrapy.utils.spider import spidercls_for_request, DefaultSpider
class Command(ScrapyCommand):
requires_proj... |
"""
Check python source code files for possible errors and print warnings
Contact Info:
http://pychecker.sourceforge.net/
<EMAIL>
"""
import string
import types
import sys
import imp
import os
import glob
# see __init__.py for meaning, this must match the version there
LOCAL_MAIN_VERSION = 3
def setupNamespace... |
from cinder import exception
from cinder.openstack.common import log as logging
from cinder import test
from cinder.volume.drivers.san.hp_lefthand import HpSanISCSIDriver
LOG = logging.getLogger(__name__)
class HpSanISCSITestCase(test.TestCase):
def setUp(self):
super(HpSanISCSITestCase, self).setUp()
... |
from osv import osv, fields
import base64
from tools.translate import _
from log import *
def _reopen(self, res_id, model):
return {'type': 'ir.actions.act_window',
'view_mode': 'form',
'view_type': 'form',
'res_id': res_id,
'res_model': self._name,
'targ... |
class Hints(object):
"""Encapsulate driver hints for listing entities.
Hints are modifiers that affect the return of entities from a
list_<entities> operation. They are typically passed to a driver to give
direction as to what filtering, pagination or list limiting actions are
being requested.
... |
import numpy as np
import logging as lg
import random
import os
import cv2
from copy import deepcopy
def learn(X):
""" Learns the fundamental memories represented in the input vector X
Args:
Take flattened (1-D) input vectors arranged in an array
Returns:
The interconnection mat... |
import unittest
from page_models import *
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from belay_test_utils import *
import time
class StationTests(BelayTest):
def setUp(self):
super(StationTests,self).setUp()
self.ba = open_belay_admin(self.driver)
... |
import os
import logging
# validate, , validate things, internal
from .lib import validate
# CMakeGen, , generate build files, internal
from .lib import cmakegen
def addOptions(parser):
parser.add_argument('program', default=None,
help='name of the program to be debugged'
)
def execCommand(args, fo... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
import logging
from oauthlib.common import Request
from oauthlib.oauth2.rfc6... |
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2012 Lincoln de Sousa <<EMAIL>>
Copyright (C) 2007 Gabriel Falcão <<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 version 2 of the
Lic... |
"""
The gntp.notifier module is provided as a simple way to send notifications
using GNTP
.. note::
This class is intended to mostly mirror the older Python bindings such
that you should be able to replace instances of the old bindings with
this class.
`Original Python bindings <http://code.google.com/p/growl/sour... |
#! /usr/bin/env python
"""Very simple test script for the SGI gl library extension module
taken mostly from the documentation.
Roger E. Masse
"""
from test_support import verbose, TestSkipped
import gl, GL, time
glattrs = ['RGBcolor', 'RGBcursor', 'RGBmode', 'RGBrange', 'RGBwritemask',
'__doc__', '__name__', '... |
"""Support for remote Python debugging.
Some ASCII art to describe the structure:
IN PYTHON SUBPROCESS # IN IDLE PROCESS
#
# oid='gui_adapter'
+----------+ # +------------+ ... |
# BS mark.1-55
# /* coding: utf-8 */
# BlackSmith plugin
# cipher_plugin.py
# http://jabbrik.ru
strip_tags = re.compile(r'<[^<>]+>')
def handler_msk_time(type, source, body):
try:
body = re_search(read_url('http://www.zln.ru/time/', 'Mozilla/5.0'), '<div id="servertime" style="margin-top:40px; margin-bottom:30... |
"""Starter script for all nova services.
This script attempts to start all the nova services in one process. Each
service is started in its own greenthread. Please note that exceptions and
sys.exit() on the starting of a service are logged and the script will
continue attempting to launch the rest of the services.
... |
import sys
wires = {}
computed = {}
for i in range(0, 65536):
def f(j):
return lambda: j
wires[str(i)] = f(i)
for line in sys.stdin.readlines():
def cache(key, f):
def g():
if key in computed:
return computed[key]
else:
r = f()
... |
"""
Python Enhancement Proposal (PEP) Reader.
"""
__docformat__ = 'reStructuredText'
from docutils.readers import standalone
from docutils.transforms import peps, references, misc, frontmatter
from docutils.parsers import rst
class Reader(standalone.Reader):
supported = ('pep',)
"""Contexts this reader su... |
import os
import grpc
# Load ResInsight Processing Server Client Library
import rips
# Connect to ResInsight instance
resInsight = rips.Instance.find()
# Get all GeoMech cases
cases = resInsight.project.descendants(rips.GeoMechCase)
# Get all well paths
well_paths = resInsight.project.well_paths()
# Ensure there's... |
"""
List all mounted disk partitions a-la "df -h" command.
$ python examples/disk_usage.py
Device Total Used Free Use % Type Mount
/dev/sdb3 18.9G 14.7G 3.3G 77% ext4 /
/dev/sda6 345.9G 83.8G 244.5G 24% ext4 /home
/dev/sda1 296.0... |
"""Package containing pyleus implementation of major Storm entities.
"""
from __future__ import absolute_import
from collections import namedtuple
DEFAULT_STREAM = "default"
LOG_TRACE = 0
LOG_DEBUG = 1
LOG_INFO = 2
LOG_WARN = 3
LOG_ERROR = 4
StormTuple = namedtuple('StormTuple', "id comp stream task values")
"""Nam... |
'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
rng = numpy.random
# Parameters
learning_rate = 0.01
training_epochs = 2000
displ... |
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from confirmation.models import Confirmation
from zerver.models import Pre... |
from gaphor.core import gettext
from gaphor.core.modeling.properties import attribute
from gaphor.diagram.presentation import (
Classified,
ElementPresentation,
from_package_str,
)
from gaphor.diagram.shapes import (
Box,
EditableText,
FontStyle,
FontWeight,
Text,
TextAlign,
Vert... |
'''
Textinput tests
===============
This test is used to demonstrate virtual keyboard according to current
configuration.
Run this test as::
# use dock virtual keyboard (one instance)
python textinput.py -c kivy:keyboard_mode:dock
# use multi users virtual keyboard (multiples instance)
python textinpu... |
"""Contains the loop merge scenario class."""
from flow.scenarios.base_scenario import Scenario
from flow.core.params import InitialConfig
from flow.core.params import TrafficLightParams
from numpy import pi, sin, cos, linspace
ADDITIONAL_NET_PARAMS = {
# radius of the loops
"ring_radius": 50,
# length of... |
from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
import time
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
#----------------------------------------------------------------------
# Purpose: This test is to run GLRM on airline data ... |
import re
from ipalib import api, LocalOrRemote, _, ngettext
from ipalib.output import Output, summary
from ipalib import Flag
__doc__ = _("""
Misc plug-ins
""")
# FIXME: We should not let env return anything in_server
# when mode == 'production'. This would allow an attacker to see the
# configuration of the server... |
"""Single slice vgg with normalised scale.
"""
import functools
import lasagne as nn
import numpy as np
import theano
import theano.tensor as T
import data_loader
import deep_learning_layers
import layers
import preprocess
import postprocess
import objectives
import theano_printer
import updates
# Random params
rng ... |
import testtools
from heat.db.sqlalchemy.types import LongText
from heat.db.sqlalchemy.types import Json
from sqlalchemy import types
from sqlalchemy.dialects.mysql.base import MySQLDialect
from sqlalchemy.dialects.sqlite.base import SQLiteDialect
class LongTextTest(testtools.TestCase):
def setUp(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 6 09:47:47 2015
@author: Ingmar Schuster
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import scipy as sp
import scipy.stats as stats
from numpy import exp, log, sqrt
from scipy.misc import logsumexp
from numpy.linalg import i... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
plugin_test.py
---------------------
Date : May 2017
Copyright : (C) 2017, Sandro Santilli
Email : strk at kbt dot io
***********************************... |
#!/usr/bin/env python
'''
Tapaoux Config Extractor
'''
__description__ = 'Tapaoux Config Extractor'
__author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com'
__version__ = '0.1'
__date__ = '2015/05/11'
import re
import sys
import string
from operator import xor
from optparse import OptionParser
keys... |
from .compat import wrap_ord
NUM_OF_CATEGORY = 6
DONT_KNOW = -1
ENOUGH_REL_THRESHOLD = 100
MAX_REL_THRESHOLD = 1000
MINIMUM_DATA_THRESHOLD = 4
# This is hiragana 2-char sequence table, the number in each cell represents its frequency category
jp2CharContext = (
(0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0... |
from boto.dynamodb.exceptions import DynamoDBItemError
class Item(dict):
"""
An item in Amazon DynamoDB.
:ivar hash_key: The HashKey of this item.
:ivar range_key: The RangeKey of this item or None if no RangeKey
is defined.
:ivar hash_key_name: The name of the HashKey associated with thi... |
"""Mapping Interfaces
$Id: mapping.py 110536 2010-04-06 02:59:44Z tseaver $
"""
from zope.interface import Interface
class IItemMapping(Interface):
"""Simplest readable mapping object
"""
def __getitem__(key):
"""Get a value for a key
A KeyError is raised if there is no value for the key... |
from nose.tools import *
from airtime_analyzer.replaygain_analyzer import ReplayGainAnalyzer
'''
The tests in here were all tagged with the 'rgain' tag so the can be exluded from being run
with nosetest -a '!rgain'. This was needed due to the fact that it is not readily possible
to install replaygain on a containerize... |
from odoo import api, models, tools
import logging
import threading
_logger = logging.getLogger(__name__)
class StockSchedulerCompute(models.TransientModel):
_name = 'stock.scheduler.compute'
_description = 'Run Scheduler Manually'
def _procure_calculation_orderpoint(self):
with api.Environment... |
try:
import boto
import boto.ec2
import boto.vpc
from boto.exception import BotoServerError
HAS_BOTO=True
except ImportError:
HAS_BOTO=False
def boto_exception(err):
'''generic error message handler'''
if hasattr(err, 'error_message'):
error = err.error_message
elif hasattr(... |
# This file is generated by /private/var/folders/w8/mp6r1h_s51dfzfhtclzq7jdjj2krv0/T/pip-build-_1SLS7/numpy/-c
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
atlas_3_10_blas_info={}
atlas_3_10_blas_threads_info={}
atlas_threads_info={}
blas_opt_info={'extra_link_a... |
from base import *
FILE1 = 'special_file_for_180'
FILE2 = 'foobar180_file'
MAGIC = 'Alvaro: http://www.alobbs.com/'
FORBIDDEN = 'This is forbidden string'
CONF = """
vserver!1!rule!1800!match = exists
vserver!1!rule!1800!match!exists = %s
vserver!1!rule!1800!match!final = 1
vserver!1!rule!1800!handler = f... |
import StringIO
import __builtin__
import buildbot.status.web.auth
import contextlib
import os
import unittest
from committer_auth import CommitterAuth
# This subclass of StringIO supports the context manager protocol so it works
# with "with" statements, just like real files.
class CMStringIO(StringIO.StringIO):
... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RenameRecipientList(Choreography):
def __init__(self, temboo_session):
"""
Cr... |
"""
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.
"""
from atomic_reactor.utils.cachito import (
CachitoAPI, CachitoAPIInvalidRequest, CachitoAPIRequestTimeout, CachitoAPIUnsuccessfulRequest)... |
from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.corbaserver.rbprm.rbprmfullbody import FullBody
from hpp.gepetto import Viewer
packageName = "hrp2_14_description"
meshPackageName = "hrp2_14_description"
rootJointType = "freeflyer"
##
# Information to retrieve urdf and srdf files.
urdfName = "hrp2_14"... |
from datetime import datetime
import json
from flask import Blueprint, request
from flask_appbuilder import BaseView, expose
import pandas as pd
from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook
from airflow.hooks.mysql_hook import MySqlHook
from airflow.hooks.presto_hook import PrestoHook
from airf... |
"""
Interfaces for serializing Django objects.
Usage::
from django.core import serializers
json = serializers.serialize("json", some_query_set)
objects = list(serializers.deserialize("json", json))
To add your own serializers, use the SERIALIZATION_MODULES setting::
SERIALIZATION_MODULES = {
... |
from unittest.mock import patch
import pytest
from eth_utils import is_same_address, to_canonical_address
from raiden.constants import (
RED_EYES_PER_CHANNEL_PARTICIPANT_LIMIT,
RED_EYES_PER_TOKEN_NETWORK_LIMIT,
)
from raiden.exceptions import AddressWithoutCode, InvalidToken, RaidenRecoverableError
from raide... |
"""This package is deprecated. Please use `airflow.hooks` or `airflow.providers.*.hooks`."""
import warnings
warnings.warn(
"This package is deprecated. Please use `airflow.hooks` or `airflow.providers.*.hooks`.",
DeprecationWarning,
stacklevel=2,
) |
import dns
from dns.resolver import Resolver
from dns.resolver import NoNameservers, NXDOMAIN, Timeout, NoAnswer
from urllib import urlencode
from inbox.log import get_logger
import re
log = get_logger('inbox.util.url')
from inbox.providers import providers
# http://www.regular-expressions.info/email.html
EMAIL_REGEX... |
"""Order types used by Interactive Brokers."""
from dataclasses import dataclass, field
from typing import ClassVar, List, NamedTuple, Set
from eventkit import Event
from .contract import Contract, TagValue
from .objects import Fill, SoftDollarTier, TradeLogEntry
from .util import UNSET_DOUBLE, UNSET_INTEGER, datacl... |
#!/usr/bin/env python
from vtk import *
source = vtkRandomGraphSource()
source.DirectedOff()
source.SetNumberOfVertices(100)
source.SetEdgeProbability(0) # Basically generates a tree
source.SetUseEdgeProbability(True)
source.SetStartWithTree(True)
source.IncludeEdgeWeightsOn()
# Connect to the Boost centrality filter... |
import sys # used for taking input from the command line
from bs4 import BeautifulSoup # used for parsing and doing some funky HTML stuff
import urllib # used for grabbing data from URLs
import unicodedata # for converting unicode to ascii
"""
Jon Hurlock's Google Scholar Tools by Jon Hurlock (@jonhurlock)
* is licens... |
"""
Polygon path.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities import evaluate
__author__... |
from bluetooth import *
import blumote
import cPickle
import os
import sys
import time
class Blumote_Client(blumote.Services):
def __init__(self):
blumote.Services.__init__(self)
self.addr = None
def find_blumote_pods(self, pod_name = None):
if pod_name is None:
pod_name = self.service["name"]
print "Sea... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'ghost'
import urlparse
import tornado.web
from tornado.httputil import HTTPServerRequest
from .auth.models import User
class BaseAuthHandler(tornado.web.RequestHandler):
def get_current_user(self):
cookie = self.get_secure_cookie('user')
... |
"""
Various tests for PDF metrics.
The main test prints out a PDF documents enabling checking of widths of every
glyph in every standard font. Long!
"""
__version__='''$Id: test_pdfbase_pdfmetrics.py 3288 2008-09-15 11:03:17Z rgbecker $'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile,... |
# -*- coding: utf-8 -*-
'''
Utilities for managing Debian preseed
.. versionadded:: Beryllium
'''
from __future__ import absolute_import
import yaml
import shlex
import salt.utils
def mksls(src, dst=None):
'''
Convert a preseed file to an SLS file
'''
ps_opts = {}
with salt.utils.fopen(src, 'r') ... |
# A couple of samples using SHBrowseForFolder
import sys, os
from win32com.shell import shell, shellcon
import win32gui
# A callback procedure - called by SHBrowseForFolder
def BrowseCallbackProc(hwnd, msg, lp, data):
if msg== shellcon.BFFM_INITIALIZED:
win32gui.SendMessage(hwnd, shellcon.BFFM_SE... |
import base64
import accept
import asyncio
import calendar
import functools
import hmac
import logging
import markupsafe
import pytz
import sockjs
import time
import traceback
from aiohttp import web
from email import utils
from anubis import app
from anubis import error
from anubis import template
from anubis.model ... |
""" Template of stock location path object """
from openerp.osv.orm import Model
from openerp.addons.stock_orderpoint_creator.base_product_config_template import BaseProductConfigTemplate
class StockLocationPath(BaseProductConfigTemplate, Model):
_name = 'stock.location.path.template'
_inherit = 'stock.locat... |
"""Visual Studio project reader/writer."""
import common
import xml.dom
import xml.dom.minidom
import MSVSNew
#------------------------------------------------------------------------------
class Tool(object):
"""Visual Studio tool."""
def __init__(self, name, attrs=None):
"""Initializes the tool.
Arg... |
from setuptools import setup, find_packages
setup(
name="monolithe",
packages=find_packages(exclude=["*tests*"]),
include_package_data=True,
version="1.1.8",
description="Monolithe is a sdk generator",
author="Christophe Serafin, Antoine Mercadal",
author_email="<EMAIL>, <EMAIL>",
url="... |
from datetime import datetime
from openerp import api, fields, models
class Summary(models.Model):
_name = "myo.summary"
@api.multi
@api.depends('name', 'code')
def name_get(self):
result = []
for record in self:
result.append(
(record.id,
... |
# -*- coding: utf-8 -*-
"""Copyright 2015 Roger R Labbe Jr.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
This is licensed under an MIT license. See the readme.MD file
for mor... |
#!/usr/bin/env python
import argparse
import cPickle
import traceback
import logging
import time
import sys
import numpy
import experiments.nmt
from experiments.nmt import\
RNNEncoderDecoder,\
prototype_state,\
parse_input
from experiments.nmt.numpy_compat import argpartition
logger = logging.getLogger... |
#this import statement allows access to the karamba functions
import karamba
images = [0,0,0,0,0,0,0,0,0,0,0,0,0,0]
c = 0
#this is called when you widget is initialized
def initWidget(widget):
global images
images[0] = karamba.getThemeImage(widget, "image0")
images[1] = karamba.getThemeImage(widget, "imag... |
"""Find common substrings.
"""
from itertools import combinations
import numpy as np
from tde.substrings.ccss import allcommonsubstrings as _acss
from tde.data.interval import Interval
from tde.data.fragment import FragmentToken
def pairwise_substring_completion(fragment1, fragment2, corpus,
... |
"""
Query subclasses which provide extra functionality beyond simple data retrieval.
"""
from django.core.exceptions import FieldError
from django.db import connections
from django.db.models.query_utils import Q
from django.db.models.sql.constants import (
CURSOR, GET_ITERATOR_CHUNK_SIZE, NO_RESULTS,
)
from django... |
from django.conf import settings
from django.db.models import signals
from django.utils.translation import ugettext_noop as _
import logging
logger = logging.getLogger(__name__)
if "notification" in settings.INSTALLED_APPS:
import notification
def create_notice_types(app, created_models, verbosity, **kwargs):... |
"""Tests for pil_renderer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import colorsys
from absl.testing import absltest
import numpy as np
from spriteworld import sprite
from spriteworld.renderers import pil_renderer
class PilRendererTest(absltest... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.... |
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.utils import filters_from_querystring
class ElasticIPAddresses(BaseResponse):
def allocate_address(self):
domain = self._get_param('Domain', if_none='standard')
if self.is_not_dryrun('AllocateAddres... |
"""
The GeometryProxy object, allows for lazy-geometries. The proxy uses
Python descriptors for instantiating and setting Geometry objects
corresponding to geographic model fields.
Thanks to Robert Coup for providing this functionality (see #4322).
"""
class GeometryProxy(object):
def __init__(self, klass, field... |
"""Runs Octane 2.0 javascript benchmark.
Octane 2.0 is a modern benchmark that measures a JavaScript engine's performance
by running a suite of tests representative of today's complex and demanding web
applications. Octane's goal is to measure the performance of JavaScript code
found in large, real-world web applicati... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.bbcode
~~~~~~~~~~~~~~~~~~~~~~~~~~
BBcode formatter.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments.util import get_bool_opt
__al... |
import pytest
from share.regulate.steps.block_extra_values import BlockExtraValues
from share.util.graph import MutableGraph
class TestBlockExtraValuesStep:
@pytest.fixture
def graph(self):
g = MutableGraph()
g.add_node(1, 'creativework', {
'title': 'A work!',
'extra':... |
import base64
import json
import logging
import time
import threading
import requests
# This is designed for OpenHab
# TODO: Refactor to work with arbitrary REST Server
class OpenHabRestInterface(threading.Thread):
prev_state = {} # stores item states
update = False
def __init__(self, host, port, user,... |
from functools import partial
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
def my_kde_bandwidth(obj, fac=1./5):
"""We use Scott's Rule, multiplied by a constant factor."""
return np.power(obj.n, -1./(obj.d+4)) * fac
loc1, scale1, size1 = (-2, 1, 175)
loc2, scale2, size2 = (2, ... |
import gtk
from gcompris import gcompris_gettext as _
import profile_widget
class ProfileEdit(gtk.Window):
def __init__(self, db_connect, db_cursor,
profile_id, profile_name, profile_description,
profile_list):
# Create the toplevel window
gtk.Window.__init__(s... |
from setup import tc, rm, get_sandbox_path
import logging
logger = logging.getLogger(__name__)
# Tests binary classification with string values
def test_binary_classification_metrics_001(tc):
logger.info("create frame")
rows = [["red", "red"],["blue", "green"],["green", "green"],["green", "green"]]
schem... |
"""Helper functions for XML.
This module has misc. helper functions for working with XML DOM nodes."""
import re
from compat import *
import os
if os.name != "java":
from xml.dom import minidom
from xml.sax import saxutils
def parseDocument(s):
return minidom.parseString(s)
else:
from javax.... |
"""
This module will download dataset from
http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html
and parse train/test set intopaddle reader creators.
This set contains images of flowers belonging to 102 different categories.
The images were acquired by searching the web and taking pictures. There are a
minimum o... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
v_distance.py
-------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************************... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expd... |
# Taken from Python 2.7 with permission from/by the original author.
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import distributions
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.pytho... |
from __future__ import print_function
from datetime import date
import random
random.seed(1)
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models.glyphs import Line, Circle
from bokeh.models import (
Plot, ColumnDataSource, DataRange1d,
LinearAxis, DatetimeAxis, Grid, HoverTool
... |
"""
Template for PDF Receipt/Invoice Generation
"""
from PIL import Image
import logging
from reportlab.lib import colors
from django.conf import settings
from django.utils.translation import ugettext as _
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units imp... |
# -*- coding: utf-8 -*-
"""
flask._compat
~~~~~~~~~~~~~
Some py2/py3 compatibility support based on a stripped down
version of six so we don't have to depend on a specific version
of it.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
PY... |
from __future__ import print_function
import os
import gzip
from six.moves import cPickle as pickle
from importlib import import_module
from time import time
from weakref import WeakKeyDictionary
from email.utils import mktime_tz, parsedate_tz
from w3lib.http import headers_raw_to_dict, headers_dict_to_raw
from scrapy.... |
import os
import sys
# Add path to python source to path.
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "python"))
import SmoothParticleNets as spn
import itertools
import numpy as np
import torch
import torch.autograd
from gradcheck import gradcheck
from test_convsdf impor... |
from wtforms.compat import with_metaclass, iteritems, itervalues
__all__ = (
'BaseForm',
'Form',
)
class BaseForm(object):
"""
Base Form Class. Provides core behaviour like field construction,
validation, and data and error proxying.
"""
def __init__(self, fields, prefix=''):
""... |
from __future__ import print_function
import os
import numpy as np
import random
import shutil
import time
import unittest
import logging
import paddle
import six
import paddle.fluid as fluid
from paddle.nn import functional
from paddle.nn import Linear, Conv2D, Softmax, BatchNorm
from paddle.fluid.layers import nn
fr... |
"""SCons.Tool.link
Tool-specific initialization for the generic Posix linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2019 The SCons Foundation
#
# Permission is hereby grant... |
from __future__ import unicode_literals
import binascii
import hashlib
import unittest
from django.utils.crypto import constant_time_compare, pbkdf2
class TestUtilsCryptoMisc(unittest.TestCase):
def test_constant_time_compare(self):
# It's hard to test for constant time, just test the result.
s... |
"""Support for WebDav Calendar."""
import copy
from datetime import datetime, timedelta
import logging
import re
import caldav
import voluptuous as vol
from homeassistant.components.calendar import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
CalendarEventDevice,
calculate_offset,
get_date,
is_offset_... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "script-src 'self' 'un... |
"""Tasks used for main OAI harvesting workflow."""
import os
import time
from functools import wraps
from invenio.base.globals import cfg
def init_harvesting(obj, eng):
"""Get all the options from previous state.
This function gets all the option linked to the task and stores them into the
object to b... |
import bpy
# noinspection PyUnresolvedReferences
import bgl
# noinspection PyUnresolvedReferences
import blf
# noinspection PyUnresolvedReferences
import mathutils
# noinspection PyUnresolvedReferences
import bmesh
import os
import sys
# noinspection PyUnresolvedReferences
import bpy_extras.image_utils as img_utils
# n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.