content stringlengths 4 20k |
|---|
from glance.api.v2 import image_data
from glance.api.v2 import image_members
from glance.api.v2 import image_tags
from glance.api.v2 import images
from glance.api.v2 import schemas
from glance.common import wsgi
class API(wsgi.Router):
"""WSGI router for Glance v2 API requests."""
def __init__(self, mapper)... |
import scrapy
import csv
import psycopg2
import re
from scrapy_splash import SplashRequest
class GoogleSpider(scrapy.Spider):
name = "googlev2"
def start_requests(self):
urls = [
'https://cloud.google.com/compute/pricing',
]
for url in urls:
yield scrapy.Reque... |
# -*- coding: utf-8 -*-
#! /usr/bin/env python3
from gensim import corpora, models
import gensim
from operator import itemgetter
import numpy as np
import sys
import os
import re
import codecs
import io
import math
from scipy import sparse
from sklearn.cross_validation import train_test_split
from sklearn.feature_extra... |
import wpan
from wpan import verify
# -----------------------------------------------------------------------------------------------------------------------
# Test description: Network Data update and version changes (stable only vs. full version).
#
# Network topology
#
# leader
# / | \
# / | \
#... |
import io
import os
import sys
import time
from IOST_Prepare import IOST_Prepare
from IOST_Config import *
from IOST_WRun import *
import gtk
import gtk.glade
class IOST_WMain_CTRL():
"""
"""
def __init__(self, glade_filename, object, builder=None):
"""
"""
if not builder:
... |
# -*- coding: utf-8 -*-
"""
pygments.styles.tango
~~~~~~~~~~~~~~~~~~~~~
The Crunchy default Style inspired from the color palette from
the Tango Icon Theme Guidelines.
http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines
Butter: #fce94f #edd400 #c4a000
Orange: #fcaf3e ... |
import pickle
import os
from kernel import settings
from kconfig import helpdeskBookByName, labsBookByName
from kernel.DataBoard import Data
from kernel.NM_Aggregates import Deck, WorkBacklog
from kernel.NM_BacklogReporter import BacklogReporter
from kernel.NM_HelpDeskReporter import DeckReporter
__author__ = 'Manuel... |
# -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import Blueprint
from data_wrangler.services.blog import get_page, get_post_detail
from data_wrangler.utils import flash_errors, render_extensions
blueprint = Blueprint('blog', __name__, static_folder="../static")
@blueprint.rou... |
import pytest
from mock import patch
from pip.vcs.git import Git
from tests.lib import _create_test_package
from tests.lib.git_submodule_helpers import (
_change_test_package_submodule,
_pull_in_submodule_changes_to_module,
_create_test_package_with_submodule,
)
@pytest.mark.network
def test_get_refs_sh... |
import logging
import imp
from autotest.client import utils
from virttest import propcan, xml_utils, virsh
from virttest.libvirt_xml import xcepts
class LibvirtXMLBase(propcan.PropCanBase):
"""
Base class for common attributes/methods applying to all sub-classes
Properties:
xml:
vir... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from msrestazure.azure_exceptions import CloudError
except:
# This is handled ... |
COLOUR_FIGURE = False
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from load import load_dataset
import numpy as np
from knn import learn_model, apply_model, accuracy
feature_names = [
'area',
'perimeter',
'compactness',
'length of kernel',
'width of kernel',
... |
import sys
import types
# Test imports.
import android
import BeautifulSoup
import gdata.docs.service
import sqlite3
import termios
import time
import xmpp
droid = android.Android()
def event_loop():
for i in range(10):
e = droid.eventPoll(1)
if e.result is not None:
return True
time.sleep(2)
... |
from dftestlib import dftest
class testDouble(dftest.DFTest):
trace_file = "ntp.pcap"
def test_eq_1(self):
dfilter = "ntp.rootdelay == 0.0626983642578125"
self.assertDFilterCount(dfilter, 1)
def test_eq_2(self):
dfilter = "ntp.rootdelay == 0.0626"
self.assertDFilterCount(... |
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import random
import re
import string
import urllib2
import logging
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
from openerp.tools import html2plaintext
from py_etherpad import EtherpadLiteClient
_logger = logging.getLogger(__name__... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ansible.compat.te... |
from django.apps import AppConfig
from django.apps import apps
from django.db.models import signals
from . import signals as handlers
from taiga.projects.history.models import HistoryEntry
class TimelineAppConfig(AppConfig):
name = "taiga.timeline"
verbose_name = "Timeline"
def ready(self):
sign... |
# This test is exactly like uctypes_le.py, but uses native structure layout.
# Codepaths for packed vs native structures are different. This test only works
# on little-endian machine (no matter if 32 or 64 bit).
import sys
import uctypes
if sys.byteorder != "little":
print("SKIP")
sys.exit()
desc = {
"s... |
"""Certificate chain with 1 intermediary and a trusted root. The intermediary
has a basic constraints extension but does not mark it as critical.
Verification is expected to succeed, since although not critical, the
basicConstraints indicates CA=true as expected."""
import common
# Self-signed root certificate (part ... |
"""Tool for checking a lot of DNS servers from stdin for possible inclusion."""
__author__ = '<EMAIL> (Thomas Stromberg)'
import re
import sys
import pygeoip
sys.path.append('..')
sys.path.append('/Users/tstromberg/namebench')
import third_party
from libnamebench import nameserver_list
from libnamebench import config... |
import os
import unittest
import mock
from telemetry.testing import system_stub
from catapult_base import cloud_storage
def _FakeReadHash(_):
return 'hashthis!'
def _FakeCalulateHashMatchesRead(_):
return 'hashthis!'
def _FakeCalulateHashNewHash(_):
return 'omgnewhash'
class CloudStorageUnitTest(unittest.... |
#!/usr/bin/python3
import sys, getopt
import log, logging
import os
import argparse
import signal
import threading
from config import *
import ivylinker
from ui import UI
from database import importxml
from md5checker import findMD5
from interop.client import AsyncClient
from interoperability import MissionInformat... |
import os
from pprint import pformat
import sys
from warnings import warn
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.core.urlresolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_unic... |
import urllib2
import urllib
import json
import subprocess
def genAllCodes():
base_url = "http://query.yahooapis.com/v1/public/yql?format=json&env=store%3A%2F%2F\
datatables.org%2Falltableswithkeys&q="
codes = []
for industry in range(110, 137):
print "Industry: {}".format(industry)
query =... |
import os
import email
import unittest
from datetime import datetime, timedelta
from frappe.email.receive import InboundMail, SentEmailInInboxError, Email
from frappe.email.email_body import get_message_id
import frappe
from frappe.test_runner import make_test_records
from frappe.core.doctype.communication.email impor... |
from PIL import Image, ImageDraw
#image naming convention xcoord_ycoord_alpha.png
#where coords are those of left corner of box to fill
class ImageDuplicator:
def __init__(self, orig_path, diameter, root_dir):
self.BALL_DIAMETER = diameter
self.IMAGE_ROOT_DIRECTORY = root_dir
# open gras... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# e-mail : kcraj2[AT]gmail[DOT]com
# Date created : 08 Jul 2016
# Last modified : 11 Jul 2016
"""------------------------------------------------------------------------
Browse the WSJ0 and WSJ1 corpora, parse the prompts (transcriptions),
and categorize the utts into do... |
import os
import cv2
import random
import numpy as np
image_dir = "/home/mscvadmin/action/FineGrainedAction/data/test_image/"
frame_dir = "/home/mscvadmin/action/FineGrainedAction/data/test_video/"
def delete_last_empty_line(s):
while(len(s) >= 1 and s[-1] == '\n'):
s = s[:-1]
return s
# assume there... |
#!/usr/bin/env python3
import ast
import difflib
import glob
import subprocess as sub
import sys
from sys import stdout, stderr
TEMP = "/tmp/28d8vjsdfu239ur0z89fd8f23pq2038h8vc"
devnull = open("/dev/null", "w")
def main(asm_name):
fail = []
for testname in sorted(glob.glob("test-lex/*")):
stdout... |
"""
Classes to represent the definitions of aggregate functions.
"""
from django.db.models.constants import LOOKUP_SEP
def refs_aggregate(lookup_parts, aggregates):
"""
A little helper method to check if the lookup_parts contains references
to the given aggregates set. Because the LOOKUP_SEP is contained i... |
"""
Create a queue of RDDs that will be mapped/reduced one at a time in
1 second intervals.
To run this example use
`$ bin/spark-submit examples/src/main/python/streaming/queue_stream.py
"""
import time
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
if __name__ == "__main__":
... |
#!/usr/bin/env python
"""Seeing monitor
History:
2010-10-01 ROwen Initial version.
2010-11-17 ROwen Added measured and applied offsets for all guider corrections.
Split RA, Dec and rotator into separate graphs.
Added net rotator offset.
2010-11-19 ROwen Display scaleFac... |
"""
Test the NuPIC imports run as expected in
nab/detectors/numenta/numenta_detector.py. They are
nupic/algorithms/anomaly_likelihood and
nupic/frameworks/opf/modelfactory.ModelFactory. The intent here is not to test
functionality but rather that the functions are able to run in NAB.
NAB repo: https://github.com/num... |
import cStringIO
import struct
import dns.exception
import dns.dnssec
import dns.rdata
import dns.tokenizer
_ctype_by_value = {
1 : 'PKIX',
2 : 'SPKI',
3 : 'PGP',
253 : 'URI',
254 : 'OID',
}
_ctype_by_name = {
'PKIX' : 1,
'SPKI' : 2,
'PGP' : 3,
'URI' : 253,
'OID' : 254,
... |
from datetime import datetime
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.backends import RemoteUserBackend
from django.contrib.auth.middleware import RemoteUserMiddleware
from django.contrib.auth.models import User
from django.test import TestCase, modify_set... |
import re
from django.db import migrations, models
def _replace_text_body(model, input_pattern, output_tag, id_format):
regex = re.compile(input_pattern)
def _do_replace(match):
before_id, plugin_id, after_id = match.groups()
if not plugin_id:
return ''
bits = []
... |
import unittest
import boto3
from airflow import configuration
from airflow.models import Connection
from airflow.contrib.hooks.aws_hook import AwsHook
try:
from unittest import mock
except ImportError:
try:
import mock
except ImportError:
mock = None
try:
from moto import mock_emr, m... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import codecs
import csv
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.utils.unicode import to_bytes, to_str, to_unicode
class CSVRecoder:
"""
Iterator that reads an en... |
"""
Defines a test function, check_has_course_method, useful in various modulestore tests.
This file should potentially be renamed "utilties" since this file contains no tests.
"""
from nose.tools import assert_equals, assert_true, assert_false # pylint: disable=no-name-in-module
def check_has_course_method(modules... |
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[]]
servers = []
server_manager = None
test_executor = None
class basicTest(mysqlBaseTestCase):
def test_drizzledump1(self):
test_cmd = "./gentest.pl --gendata=conf/drizzle/drizzle.zz --grammar=conf/drizzle/drizzledump.yy --V... |
from asap3 import CoordinationNumbers
import numpy as np
from asap3.MonteCarlo.Moves import SurfaceMove
from ase import Atom
import random as rd
def mychoice(a, n):
"Replaces numpy.random.choice(a, n, False) as our numpy is ancient."
a = list(a)
while len(a) > n:
# Remove a random element
del a[np.random.randin... |
import time
from openerp.osv import osv, fields
class pos_details(osv.osv_memory):
_name = 'pos.details'
_description = 'Sales Details'
_columns = {
'date_start': fields.date('Date Start', required=True),
'date_end': fields.date('Date End', required=True),
'user_ids': fields.many2... |
"""Test of utilities module."""
from __future__ import absolute_import, print_function
import pytest
from mock import patch
from six import BytesIO
from invenio_previewer import current_previewer
from invenio_previewer.utils import detect_encoding
def test_default_file_reader(app, record_with_file):
"""Test vi... |
# 各組分別在各自的 .py 程式中建立應用程式 (第1步/總共3步)
from flask import Blueprint, render_template, make_response
# 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄
ag7_40123149_3 = Blueprint('ag7_40123149_3', __name__, url_prefix='/ag7_40123149', template_folder='templates')
# scrum1_task1 為完整可以單獨執行的繪圖程式
@ag7_40123149_3.route('... |
from __future__ import print_function
import sys, requests, random, optparse, time, json
from itertools import islice
from threading import Thread
from collections import Counter
import requests
import six
from six.moves.queue import Queue
from .utils import SplashServer, MockServer
class StressTest():
def __i... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'AliasPluginModel.alias_placeholder'
db.add_column(u'cms_a... |
from recipe_engine import recipe_api
TEST_DEFAULT_ASSET_VERSION = '42'
class SkiaStepApi(recipe_api.RecipeApi):
def __init__(self, *args, **kwargs):
"""Initialize the recipe module."""
super(SkiaStepApi, self).__init__(*args, **kwargs)
self._already_ran = {}
self._ccache = None
self._checked_... |
#!/usr/bin/env python
#coding=utf-8
#
# ./download-deps.py
#
# Download Cocos2D-X resources from github (https://github.com/cocos2d/cocos2d-x-3rd-party-libs-bin) and extract from ZIP
#
# Helps prevent repo bloat due to large binary files since they can
# be hosted separately.
#
"""*************************************... |
from keyword import iskeyword as _iskeyword
from operator import itemgetter as _itemgetter
import sys as _sys
def namedtuple(typename, field_names):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y')
>>> Point.__doc__ # docstring for the new cla... |
import scipy.io
from sklearn.metrics import accuracy_score
from sklearn import cross_validation
from sklearn import svm
from skfeature.function.information_theoretical_based import CIFE
def main():
# load data
mat = scipy.io.loadmat('../data/colon.mat')
X = mat['X'] # data
X = X.astype(float)
y... |
from nova.api.openstack.compute import floating_ip_pools \
as fipp_v21
from nova.api.openstack.compute.legacy_v2.contrib import floating_ip_pools \
as fipp_v2
from nova import context
from nova import exception
from nova import network
from nova import test
from nova.tests.unit.api.openstack import fake... |
import hashlib
import re
import time
import gntp.shim
import gntp.errors as errors
__all__ = [
'GNTPRegister',
'GNTPNotice',
'GNTPSubscribe',
'GNTPOK',
'GNTPError',
'parse_gntp',
]
#GNTP/<version> <messagetype> <encryptionAlgorithmID>[:<ivValue>][ <keyHashAlgorithmID>:<keyHash>.<salt>]
GNTP_INFO_LINE = re.comp... |
import fcntl
import re
import struct
import sys
import termios
import time
from datetime import timedelta
import click
from click.types import convert_type
from colorclass import Color
from termcolor import colored
from indico.util.date_time import format_human_timedelta
from indico.util.string import validate_email
... |
# encoding: utf-8
"""
Utilities using Growl on OS X for notifications.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distribute... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
import os
import optparse
import sys
import manifest_loader
from error import NoSuchProjectError
class Command(object):
"""Base class for any command line action in repo.
"""
common = False
_optparse = None
def WantPager(self, opt):
return False
@property
def OptionParser(self):
if self._opt... |
from setuptools import setup, find_packages
import os
def expand_package_data(src_dirs, strip=""):
ret = []
for src_dir in src_dirs:
for path, dnames, fnames in os.walk(src_dir):
for fname in fnames:
ret.append(os.path.join(path, fname).replace(strip, ""))
return ret
os.chdir(os.pat... |
import numpy as np
import scipy.stats as stats
__all__ = ['double_to_single_step', 'cad_prob', 'delta_t_hist',
'normalize_hist', 'find_sorted_peaks', 'peak_ratio', 'peak_bin']
def double_to_single_step(cads):
"""Ratios (t[i+2] - t[i]) / (t[i+1] - t[i])."""
cads = np.asarray(cads)
return (cads... |
from alsaaudio import Mixer, ALSAAudioError
from math import exp, log, log10, ceil, floor
from i3pystatus import IntervalModule
class ALSA(IntervalModule):
"""
Shows volume of ALSA mixer. You can also use this for inputs, btw.
Requires pyalsaaudio
.. rubric:: Available formatters
* `{volume}` ... |
from __future__ import division, print_function, absolute_import
import warnings
from . import _zeros
from numpy import finfo, sign, sqrt
_iter = 100
_xtol = 1e-12
_rtol = finfo(float).eps * 2
__all__ = ['newton', 'bisect', 'ridder', 'brentq', 'brenth']
CONVERGED = 'converged'
SIGNERR = 'sign error'
CONVERR = 'con... |
"""Tests for Adam."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.... |
"""
Test gyp_to_android.py
"""
import os
import shutil
import sys
import tempfile
import test_variables
import unittest
sys.path.append(test_variables.ANDROID_DIR)
import gyp_gen.android_framework_gyp
GYPD_SUFFIX = ".gypd"
GYP_SUFFIX = ".gyp"
GYPI_SUFFIX = ".gypi"
OTHER_SUFFIX = ".txt"
class CleanGypdTest(unittest... |
import eucadmin.deregisterrequest
class DeregisterObjectStorageGateway(eucadmin.deregisterrequest.DeregisterRequest):
ServiceName = 'ObjectStorageGateway' |
import os
import sys
from setuptools import setup
from setuptools.command.test import test
here = os.path.abspath(os.path.dirname(__file__))
class PyTest(test):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
test.initialize_options(self)
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
import optparse
import re
import string
import sys
template_h = string.Template("""// Code generated from InspectorInstrumentation.idl
#ifndef ${file_name}_h
#define ${file_name}_h
${includes}
namespace blink {
${forward_declarations}
namespace InspectorInstrumentation {
$methods
} // namespace InspectorInstrume... |
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
class SingleObjectMixin(Conte... |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function normalizes the encoding names before
doing the lookup, so the mapping will have to map normalized
encoding names to module names.
... |
__author__ = 'quentin'
from ethoscope.tracking.roi_builders import SleepDepROIBuilder
from ethoscope.tracking.cameras import MovieVirtualCamera
from ethoscope.tracking.monitor import Monitor
from ethoscope.tracking.trackers import AdaptiveBGModel
from ethoscope.tracking.interactors import SystemPlaySoundOnStop
from ... |
from django.db.models import get_model, Q
from cyder.cydhcp.utils import start_end_filter, two_to_one, one_to_two
from django.http import HttpResponse
from cyder.base.constants import STATIC, DYNAMIC
import json
import ipaddr
def find_range(ip_str):
Range = get_model('cyder', 'range')
ip_upper, ip_lower ... |
from ApiRequest import ApiRequest
from kol.database import ItemDatabase
class ItemInformationRequest(ApiRequest):
"This class is used to get information about a particular item."
def __init__(self, session, itemId):
super(ItemInformationRequest, self).__init__(session)
self.requestData["what"]... |
import sys
import time
sys.path.append(".")
from IPython import embed
import opcua
class SubHandler(opcua.SubscriptionHandler):
"""
Client to subcsription. It will receive events from server
"""
def __init__(self, *args):
opcua.SubscriptionHandler.__init__(self, *args)
self.ev = Messag... |
"""
Tests for the django comment client integration models
"""
from django.test.testcases import TestCase
from nose.plugins.attrib import attr
from opaque_keys.edx.keys import CourseKey
import django_comment_common.models as models
from xmodule.modulestore.tests.django_utils import (
TEST_DATA_MIXED_MODULESTORE, M... |
"""
.. dialect:: mssql+adodbapi
:name: adodbapi
:dbapi: adodbapi
:connectstring: mssql+adodbapi://<username>:<password>@<dsnname>
:url: http://adodbapi.sourceforge.net/
.. note::
The adodbapi dialect is not implemented SQLAlchemy versions 0.6 and
above at this time.
"""
import datetime
from s... |
"""
Dictionary with lazy evaluation on access, via a supplied update function
"""
import itertools
class LazyDict(dict):
"""
A dictionary type that lazily updates values when they are accessed.
All the usual dictionary methods work as expected, with automatic lazy
updates occuring behind the scen... |
from hachoir_core.field import FieldSet, ParserError
class StaticFieldSet(FieldSet):
"""
Static field set: format class attribute is a tuple of all fields
in syntax like:
format = (
(TYPE1, ARG1, ARG2, ...),
(TYPE2, ARG1, ARG2, ..., {KEY1=VALUE1, ...}),
...
)
... |
from django import http
from django.test import TestCase
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.messages import constants, utils, get_level, set_level
from django.contrib.messages.api import MessageFailure
from django.contrib.messages.storage import defau... |
# This is a simple serial port terminal demo.
#
# Its primary purpose is to demonstrate the native serial port access offered via
# win32file.
# It uses 3 threads:
# - The main thread, which cranks up the other 2 threads, then simply waits for them to exit.
# - The user-input thread - blocks waiting for a keyboard cha... |
ASANA_API_KEY = "0123456789abcdef0123456789abcdef"
# Change these values to the credentials for your Asana bot.
ZULIP_USER = "<EMAIL>"
ZULIP_API_KEY = "0123456789abcdef0123456789abcdef"
# The Zulip stream that will receive Asana task updates.
ZULIP_STREAM_NAME = "asana"
### OPTIONAL CONFIGURATION ###
# Set to None... |
import json
from textwrap import dedent
import pytest
import responses
from freight import checks
from freight.exceptions import CheckFailed, CheckPending
from freight.testutils import TestCase
class CloudbuilderCheckBase(TestCase):
def setUp(self):
self.check = checks.get("cloudbuilder")
self.u... |
import numpy as np
from sklearn import datasets, svm
"""
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
np.unique(iris_y)
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indices[:-10]]
iris_y_train = iris_y[indices[:-10]]
iris_X_test = iris_X[indices[-10:]]
i... |
# -*- coding: utf-8 -*-
import logging
import pymysql
from scrapy.conf import settings
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class FspiderPipeline(object):
def process_item(self, it... |
# -*- coding: utf-8 -*-
"""
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import copy
import time
import calendar
import collections
from .compat import cookielib, urlparse, urlunparse, Mo... |
from openerp.osv import osv, fields
from openerp.tools.translate import _
import openerp.addons.one2many_sorted as one2many_sorted
class payment_order(osv.osv):
_name = 'payment.order'
_inherit = 'payment.order'
# def _get_type(self, cr, uid, context=None):
# if context is None:
# conte... |
import os
import os.path
import sys
import subprocess
from glob import glob
from cmakeast import ast as cmakeast
os.chdir(os.path.dirname(sys.argv[0]))
os.chdir('..')
ctests = []
test_decs = ['add_unittest', 'add_fulltest']
with open('test/unit/CMakeLists.txt', 'r') as f:
ast = cmakeast.parse(f.read())
for s in as... |
"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
To determine which creative wrappers exist, run get_all_creative_wrappers.py.
Tags: CreativeWrapperService.getCreativeWrapper
Tags: CreativeWrapperService.updateCreativeWrappers
"""
__author__ = '<EMAIL> (Jeff Sham)'
# Locate the client ... |
#!/usr/bin/python -u
#
# Original script modified in November 2003 to take advantage of
# the character-validation range routines, and updated to the
# current Unicode information (Version 4.0.1)
#
# NOTE: there is an 'alias' facility for blocks which are not present in
# the current release, but are needed for ABI com... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import parse_duration
class RadioBremenIE(InfoExtractor):
_VALID_URL = r'http?://(?:www\.)?radiobremen\.de/mediathek/(?:index\.html)?\?id=(?P<id>[0-9]+)'
IE_NAME = 'radiobremen'
_TE... |
from __future__ import unicode_literals
import json
import re
import socket
from .common import InfoExtractor
from ..compat import (
compat_http_client,
compat_str,
compat_urllib_error,
compat_urllib_parse_unquote,
compat_urllib_request,
)
from ..utils import (
ExtractorError,
int_or_none,... |
from __future__ import unicode_literals
import logging
import os
import subprocess
import sys
def execute(command,
env=None,
split_lines=False,
ignore_errors=False,
extra_ignore_errors=(),
translate_newlines=True,
with_errors=True,
r... |
# This module offers two Cursors:
# * DataCursor,
# where you have to click the data point, and
# * FollowDotCursor,
# where the bubble is always on the point
# nearest to your pointer.
#
# All the code was copied from
# http://stackoverflow.com/a/13306887
# DataCursor Example
# x=[1,2,3,4,5]
# y=[... |
"""
.. dialect:: sqlite+pysqlcipher
:name: pysqlcipher
:dbapi: pysqlcipher
:connectstring: sqlite+pysqlcipher://:passphrase/file_path[?kdf_iter=<iter>]
:url: https://pypi.python.org/pypi/pysqlcipher
``pysqlcipher`` is a fork of the standard ``pysqlite`` driver to make
use of the `SQLCipher <htt... |
from __future__ import unicode_literals
import unittest
from .models import PersonWithCustomMaxLengths, PersonWithDefaultMaxLengths
class MaxLengthArgumentsTests(unittest.TestCase):
def verify_max_length(self, model, field, length):
self.assertEqual(model._meta.get_field(field).max_length, length)
... |
import threading
import eventlet
from eventlet import greenpool
from keystone.openstack.common import log as logging
from keystone.openstack.common import loopingcall
LOG = logging.getLogger(__name__)
def _thread_done(gt, *args, **kwargs):
"""Callback function to be passed to GreenThread.link() when we spawn(... |
# -*- 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 'GeneratedCertificate.download_url'
db.add_column('certificates_generatedcertificate', 'downl... |
#!/usr/bin/env python3
import sys
import argparse
from delphin.mrs import simplemrs, mrx, dmrx, eds, simpledmrs
from delphin.extra.latex import dmrs_tikz_dependency
mrsformats = {
'simplemrs': simplemrs,
'mrx': mrx,
'dmrx': dmrx,
'eds': eds,
'simpledmrs': simpledmrs
}
extraformats = {
'dmrs-ti... |
#!/usr/bin/env python
import unittest
import rostest
import sys
from art_projected_gui.gui import UICore
from art_projected_gui.items import ObjectItem, PlaceItem
from PyQt4.QtGui import QApplication
from art_msgs.msg import ObjectType
import rospy
from shape_msgs.msg import SolidPrimitive
from geometry_msgs.msg impor... |
from LogAnalyzer import Test,TestResult
import DataflashLog
import numpy
class TestVibration(Test):
'''test for accelerometer vibration (accX/accY/accZ) within recommendations'''
def __init__(self):
Test.__init__(self)
self.name = "Vibration"
def run(self, logdata, verbose):
se... |
"""
Parser for DBF fields.
"""
import sys
import datetime
import struct
from decimal import Decimal
from .memo import BinaryMemo
PY2 = sys.version_info[0] == 2
if PY2:
decode_text = unicode
else:
decode_text = str
class InvalidValue(bytes):
def __repr__(self):
text = bytes.__repr__(self)
... |
# flake8: noqa
# encoding: 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):
# Deleting model 'Country'
db.delete_table('shop_country')
# Deleting model 'Address'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.