content stringlengths 4 20k |
|---|
# From https://github.com/r0wb0t/markdown-urlize/blob/master/urlize.py
"""A more liberal autolinker
Inspired by Django's urlize function.
Positive examples:
>>> import markdown
>>> md = markdown.Markdown(extensions=['urlize'])
>>> md.convert('http://example.com/')
u'<p><a href="http://example.com/">http://example.... |
from openerp.openupgrade import openupgrade, openupgrade_80
from openerp import pooler, SUPERUSER_ID
@openupgrade.migrate()
def migrate(cr, version):
pool = pooler.get_pool(cr.dbname)
openupgrade_80.set_message_last_post(
cr, SUPERUSER_ID, pool, ['hr.job', 'hr.employee']) |
from tastypie.test import ResourceTestCase
class TodoListResourceTest(ResourceTestCase):
fixtures = [
'todo_users.json',
'todo_lists_items.json'
]
DEFAULT_USER_ID = 1
DEFAULT_USER = 'user_1'
DEFAULT_PASSWORD = 'user_1'
LIST_URL = '/api/v1/users/%s/lists/'
DETAIL_URL = '/... |
import pytest
from numpy import allclose, array, asarray, add, ndarray, generic
from thunder import series, images
pytestmark = pytest.mark.usefixtures("eng")
def test_first(eng):
data = series.fromlist([array([1, 2, 3]), array([4, 5, 6])], engine=eng)
assert allclose(data.first(), [1, 2, 3])
data = ima... |
"""Tests for digraph ops."""
import tensorflow as tf
from dragnn.python import digraph_ops
class DigraphOpsTest(tf.test.TestCase):
"""Testing rig."""
def testArcPotentialsFromTokens(self):
with self.test_session():
# Batch of two, where the second batch item is the reverse of the first.
source_... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y.'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. E Y. H:i'
YEAR_MONTH_FORMAT = 'F Y.'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT ... |
from __future__ import with_statement
import os
import unittest
from werkzeug import cached_property
from tipfy.app import App, Request, Response
from tipfy.handler import RequestHandler
from tipfy.json import json_b64decode
from tipfy.local import local
from tipfy.routing import Rule
from tipfy.sessions import (Sec... |
"""
TLS Lite is a free python library that implements SSL v3, TLS v1, and
TLS v1.1. TLS Lite supports non-traditional authentication methods
such as SRP, shared keys, and cryptoIDs, in addition to X.509
certificates. TLS Lite is pure python, however it can access OpenSSL,
cryptlib, pycrypto, and GMPY for faster crypt... |
import re
import functools
import distutils.core
import distutils.errors
import distutils.extension
from setuptools.extern.six.moves import map
from .monkey import get_unpatched
def _have_cython():
"""
Return True if Cython can be imported.
"""
cython_impl = 'Cython.Distutils.build_ext'
try:
... |
import logging
from django.views import generic
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.mail import send_mail
from django import http
from django.core.urlresolvers import reverse
from django.template.loader import get_template
from django.template import Context... |
from django.db import models
from django.utils import timezone
from misago.conf import settings
from misago.threads import threadtypes
from misago.threads.checksums import is_event_valid
class Event(models.Model):
forum = models.ForeignKey('misago_forums.Forum')
thread = models.ForeignKey('Thread')
auth... |
import sys
import distutils.sysconfig
import os.path
cv = distutils.sysconfig.get_config_vars()
def do_win32():
executable = sys.executable
incpath = distutils.sysconfig.get_python_inc(False)
libpath = os.path.join(distutils.sysconfig.PREFIX,'libs')
return (executable,incpath,libpath,'Python26','',sys... |
from neon.optimizers.gradient_descent import (GradientDescent, # noqa
GradientDescentPretrain,
GradientDescentMomentum,
GradientDescentMomentumWeightDecay)
from neon.optimizers.adadelta import AdaDelta # noqa
from neon.opt... |
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard.api import glance
def get_available_images(request, project_id=None, images_cache=None):
"""
Returns a list of images that are public or owned by the given
project_id. If project_id is... |
from __future__ import unicode_literals
from . import ValidationTestCase
from .models import ModelToValidate
class TestModelsWithValidators(ValidationTestCase):
def test_custom_validator_passes_for_correct_value(self):
mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42,
... |
import hr_timesheet_sheet
import wizard
import report
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
AT-specific Form helpers
"""
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _
re_ssn = re.compile(r'^\d{4} \d{6}')
class ATZipCodeField(RegexField)... |
from __future__ import absolute_import
from __future__ import unicode_literals
from inspect import getdoc
from docopt import docopt
from docopt import DocoptExit
def docopt_full_help(docstring, *args, **kwargs):
try:
return docopt(docstring, *args, **kwargs)
except DocoptExit:
raise SystemEx... |
import numpy as np
from simulator.series_functions import SinSeries, ConstantSeries, GaussianSeries
class RandomSinSeries(SinSeries):
def __init__(self, create_ts, update_period,
amplitude_low=1.0, amplitude_high=10.0,
frequency_low=0.1, frequency_high=2.0):
amplitude = ... |
import sys
import json
def make_column_to_candidate_dict(header_row):
my_dict = {}
for colIndex, candidate in enumerate(header_row):
my_dict[colIndex] = candidate.strip()
return my_dict
def return_candidates_in_order(row, col_to_candidate_dict):
ballot = []
for i in range(0,len(row)):
... |
import datetime
from django.contrib.auth import signals
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
@override_settings(USE_TZ=False,
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLC... |
from wtforms import fields
from peewee import (CharField, DateTimeField, DateField, TimeField,
PrimaryKeyField, ForeignKeyField, BaseModel)
from wtfpeewee.orm import ModelConverter, model_form
from flask_admin import form
from flask_admin._compat import iteritems, itervalues
from flask_admin.mode... |
from optparse import OptionParser
import sys
from elbepack.elbeproject import ElbeProject
from elbepack.elbexml import ValidationError
from elbepack.updatepkg import gen_update_pkg, MissingData
def run_command( argv ):
oparser = OptionParser(usage="usage: %prog gen_update [options] [xmlfile]")
oparser.add_opt... |
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 CityStateLookup(Choreography):
def __init__(self, temboo_session):
"""
Create... |
# -*- 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 'User.public_name'
db.add_column(u'users_user', 'public_name',
self.gf(... |
import logging
from ryu.base import app_manager
from ryu.controller import event
LOG = logging.getLogger(__name__)
class EventQuantumIfaceSet(event.EventBase):
def __init__(self, iface_id, key, value):
super(EventQuantumIfaceSet, self).__init__()
self.iface_id = iface_id
self.key = key
... |
"""App Engine Files API."""
from __future__ import with_statement
__all__ = [
'ApiTemporaryUnavailableError',
'Error',
'ExclusiveLockFailedError',
'ExistenceError',
'FileNotOpenedError',
'FileTemporaryUnavailableError',
'FinalizationError',... |
"""usage: git clone [options] [--] <repo> [<dir>]
-v, --verbose be more verbose
-q, --quiet be more quiet
--progress force progress reporting
-n, --no-checkout don't create a checkout
--bare create a bare repository
--mirror create a ... |
from __future__ import unicode_literals
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.feedgenerator import Atom1Feed
from django.utils.html import strip_tags
from mezzanine.core.templatetags.mezzanine_tag... |
"""
Provides basic functionality for all pyamf.amf?.[De|E]ncoder classes.
"""
import types
import datetime
import pyamf
from pyamf import util, python, xml
__all__ = [
'IndexedCollection',
'Context',
'Decoder',
'Encoder'
]
try:
unicode
except NameError:
# py3k support
unicode = str
s... |
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUser(models.Model):
_inherit = 'res.users'
@api.model
def default_get(self, fields_list):
"""Invert name when getting default values."""
result = super(ResUser, self).default_get(fields_list)
... |
import unittest
import etcd
class TestClient(unittest.TestCase):
def test_instantiate(self):
""" client can be instantiated"""
client = etcd.Client()
assert client is not None
def test_default_host(self):
""" default host is 127.0.0.1"""
client = etcd.Client()
... |
import os
# Owners to use in testing...
VALID_OWNERS = ('Data Center',)
# Database stuff
DATABASE_ENGINE = 'sqlite3'
# The prefix is... ME! (Abs path to the current file)
PREFIX = os.path.dirname(os.path.abspath(__file__))
# .tacacsrc Stuff
DEFAULT_REALM = 'aol'
TACACSRC_KEYFILE = os.getenv('TACACSRC_KEYFILE', os.p... |
#!/usr/bin/python
"""
Convert .geno files to json
This file goes through all of the genofiles in the genofile directory (.geno)
and converts them to json files that are used when running the marker regression
code
"""
from __future__ import print_function, division, absolute_import
import sys
sys.path.append("..")
... |
import os
from django import forms, http
from django.conf import settings
from django.contrib.formtools import preview, wizard, utils
from django.test import TestCase
from django.utils import unittest
success_string = "Done was called!"
class TestFormPreview(preview.FormPreview):
def get_context(self, request, ... |
from random import randint
import sys, traceback, threading, socket
from VideoStream import VideoStream
from RtpPacket import RtpPacket
class ServerWorker:
SETUP = 'SETUP'
PLAY = 'PLAY'
PAUSE = 'PAUSE'
TEARDOWN = 'TEARDOWN'
INIT = 0
READY = 1
PLAYING = 2
state = INIT
OK_200 = 0
FILE_NOT_FOUND_404 = 1
CO... |
"""
Implementation of the class `PetIBMSimulation`.
"""
import os
import sys
import struct
import numpy
try:
sys.path.append(os.path.join(os.environ['PETSC_DIR'], 'bin'))
import PetscBinaryIO
except:
pass
from ..barbaGroupSimulation import BarbaGroupSimulation
from ..field import Field
from ..force import For... |
from netforce.model import Model, fields, get_model
import time
from decimal import Decimal
import math
class CartLine(Model):
_name = "ecom.cart.line"
_fields = {
"cart_id": fields.Many2One("ecom.cart", "Cart", required=True, on_delete="cascade"),
"sequence": fields.Integer("Item No.", require... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import time
try:
import boto
import boto.ec2
import boto.ec2.autoscale
imp... |
"""
The nxos lacp fact class
It is in this file the configuration is collected from the device
for a given resource, parsed, and the facts tree is populated
based on the configuration.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
from copy import deepcopy
from an... |
DATE_FORMAT = 'N j, Y'
TIME_FORMAT = 'P'
DATETIME_FORMAT = 'N j, Y, P'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'F j'
SHORT_DATE_FORMAT = 'm/d/Y'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
FIRST_DAY_OF_WEEK = 0 # Sunday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/librar... |
import Biskit.Mod.modUtils as modUtils
from Biskit.Mod import *
from Biskit.Mod import Modeller as M
from Biskit.Mod import TemplateCleaner as TS
from Biskit.Mod import TemplateFilter as TF
import Biskit.tools as tools
from Biskit import EHandler
from Biskit import LogFile
from Biskit.Pymoler import Pymoler
from Bisk... |
"""This launches several fuzzing experiments on GCP.
Description:
This experiment measures the runtime required to reach every state of several
lock state machines of various sizes using a cocotb testbench that reads input
from binary files generated by the AFL fuzzer. The Verilator simulation engine
is used to simula... |
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from . import base
from ..constants import namespaces, voidElements
from ..constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
class Filter(base.Filter):
def __init__(self, source, r... |
#!/usr/bin/python
import os
from optparse import OptionParser
import logging
# Manually import django
sys.path.append(os.path.join(os.getcwd(), os.pardir))
os.environ['DJANGO_SETTINGS_MODULE'] = "routez.settings"
from routez.travel.models import Route
usage = "usage: %prog [options] <base path> <generated path>"
pa... |
from openstack_dashboard import api
from openstack_dashboard.api.rest import network
from openstack_dashboard.test import helpers as test
class RestNetworkApiSecurityGroupTests(test.TestCase):
@test.create_mocks({api.neutron: ['security_group_list']})
def test_security_group_detailed(self):
request =... |
import httplib
from flask import request
from framework.exceptions import HTTPError
from framework.auth.decorators import must_be_logged_in
from website.addons.s3 import utils
from website.project.decorators import must_have_addon
from website.project.decorators import must_have_permission
from website.project.decor... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Sparsity Example: Fitting only features 1 and 2
=========================================================
Features 1 and 2 of the diabetes-dataset are fitted and
plotted below. It illustrates that although feature... |
# Imports
# Python
import cgi
import os
import json
import urllib2
# App
from login import app
from login import login_manager
# Flask
from flask import render_template, flash, redirect, request, url_for
from flask import session, abort
from flask.ext.login import login_user, logout_user, login_required, current_us... |
'''Cached information about version and extensions of current WGL
implementation.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: glx_info.py 615 2007-02-07 13:17:05Z Alex.Holkner $'
from ctypes import *
import warnings
from pyglet.gl.lib import MissingFunctionException
from pyglet.gl.gl import *
from pyg... |
"""Utility functions for testing gjslint components."""
# Allow non-Google copyright
# pylint: disable=g-bad-file-header
__author__ = ('<EMAIL> (Nathan Naze)')
import StringIO
from closure_linter import ecmametadatapass
from closure_linter import javascriptstatetracker
from closure_linter import javascripttokenizer... |
#!/usr/bin/python
# File created on 27 Jan 2012.
from __future__ import division
__author__ = "Kishori M Konwar"
__copyright__ = "Copyright 2013, MetaPathways"
__credits__ = ["r"]
__version__ = "1.0"
__maintainer__ = "Kishori M Konwar"
__status__ = "Release"
try:
import os, re
from os import makedirs, sys, ... |
"""Test allocating asset ids from the server.
"""
__author__ = ['<EMAIL> (Matt Tracy)']
from viewfinder.backend.base import util
from viewfinder.backend.db.user import User
from viewfinder.backend.www.test import service_base_test
class AllocateIdsTestCase(service_base_test.ServiceBaseTestCase):
def setUp(self):
... |
# 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):
# Adding field 'Field.order'
db.add_column('forms_field', 'order', self.gf('django.db.models.fields.Intege... |
'''
SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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 3 of the License, or
(at your option) any later version.
... |
"""
Script to migrate repository from sqlalchemy <= 0.4.4 to the new
repository schema. This shouldn't use any other migrate modules, so
that it can work in any version.
"""
import os
import sys
import logging
log = logging.getLogger(__name__)
def usage():
"""Gives usage information."""
print("Usag... |
"""Builds CSR matrices which store the MAG graphs."""
import pathlib
from absl import app
from absl import flags
from absl import logging
import numpy as np
import scipy.sparse
# pylint: disable=g-bad-import-order
import data_utils
Path = pathlib.Path
FLAGS = flags.FLAGS
_DATA_FILES_AND_PARAMETERS = {
'autho... |
"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
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
... |
from unittest import skipUnless
from django.contrib.gis.db.models import F, GeometryField, Value, functions
from django.contrib.gis.geos import Point, Polygon
from django.db import connection
from django.db.models import Count, Min
from django.test import TestCase, skipUnlessDBFeature
from ..utils import postgis
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Piece classes"""
from __future__ import absolute_import, division
import logging
from pyrochess.config import SETTINGS
from pyrochess.square import Square
from pyrochess.metadata import PROGRAM
LOG = logging.getLogger(PROGRAM)
class Piece(object):
point = 0.
... |
from __future__ import unicode_literals
import os
import webnotes
def make(site=None):
"""make public folder symlinks if missing"""
from webnotes.utils import get_site_base_path, get_base_path, get_path
webnotes.init(site=site)
site_path = get_site_base_path() if site else get_base_path()
# setup standard f... |
# dllexports2def.py
# from http://takumakei.blogspot.jp/2009/04/dlldef.html
#======================================================================
def dllexports2def(path):
from sys import stderr
from os.path import exists
if not exists(path):
print >>stderr, 'dllexports2def: %s is not fou... |
import wx
from wx import xrc
from .base import ModuleBase, bind
class AntennaModule(ModuleBase):
def __init__(self, name, pos, antenna_controller):
self._antenna_controller = antenna_controller
self._panel = None
self.title = 'Antenna ({})'.format(name)
self.grid_pos = ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from copy import deepcopy
from functools import partial
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.utils import remove_... |
import sys
import os
import unittest
import logging
import threading
# Add the parent directory to the top of the search paths list so the
# distribution copy of the Skype4Py module can be imported instead of
# the installed one.
sys.path.insert(0, os.path.abspath('..'))
import Skype4Py
from Skype4Py.skype import *
f... |
"""Tests for custom user ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.framework import load_library
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import resource_loader
from tensorflow... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import time
import pytest
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.module_utils.facts import timeout
@pytest.fixture
def set_gather_timeout_higher():
default_timeout = t... |
#!/usr/bin/env python
'''Pygame module for image transfer.
The image module contains functions for loading and saving pictures, as
well as transferring Surfaces to formats usable by other packages.
Note that there is no Image class; an image is loaded as a
Surface object. The Surface class allows manipulation (drawi... |
class StMainSubplot:
def __init__(self, ax, st_name):
self.st_curve_line, = ax.plot([0], [0], "k.", lw=3, alpha=0.5)
self.kernel_cruise_line, = ax.plot([0], [0], "g.", lw=3, alpha=0.5)
self.kernel_follow_line, = ax.plot([0], [0], "y.", lw=3, alpha=0.5)
self.obstacle_boundary_lines = ... |
"""
Copyright (C) 2014, Jaguar Land Rover
This program is licensed under the terms and conditions of the
Mozilla Public License, version 2.0. The full text of the
Mozilla Public License is at https://www.mozilla.org/MPL/2.0/
Maintainer: Rudolf Streif (<EMAIL>)
"""
from logging import Handler
from django.utils imp... |
"""Testing File IO operations in file_io.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
from tensorflow.python.framework import errors
from tensorflow.python.lib.io import file_io
from tensorflow.python.platform import test
class F... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon.utils.memoized import memoized # noqa
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.vol... |
#!/usr/bin/env python
import re
import sys
MINTEDOPS = r""" [
framesep=2mm,
baselinestretch=1.2,
fontsize=\footnotesize,
breaklines,
linenos
]
"""
MINTLANGMAPS={r'F\#': 'ocaml',
'Fsharp': 'ocaml',
'Scala': 'javascript',
'Go': 'go'}
def main():
... |
#-*- coding:utf-8 -*-
"""JsHamcrest build script.
"""
import re
import cStringIO as StringIO
from fabric.api import *
# Project
env.project = 'jshamcrest'
env.version = '0.6.7'
env.full_name = '%s-%s' % (env.project, env.version)
# Build output
env.build_dir = 'build'
env.dist_dir = 'dist'
env.rev_in... |
# -*- coding: utf-8 -*-
"""
Created on 30 Apr 2017
@author: Mayank Johri
Description:
In the below example we will be create a sample
for Many to one relationship using sqlalchemy
and then use back_populates feature
Tip:
-----
- backref: Add it two one relationship and another is not
needed anymore.
"""
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import oscar.models.fields
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0001_initial'),
('contenttypes', '0001_initial'),
]
operations = [
migration... |
from django.contrib.auth.models import User
from rest_framework import serializers
#IITBombayX added Mooc_state
from student.models import UserProfile,Mooc_state
from .models import UserPreference
class UserSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.SerializerMethodField("get_name")
... |
import networkx as nx
#from networkx.generators.smax import li_smax_graph
def s_metric(G, normalized=True):
"""Returns the s-metric of graph.
The s-metric is defined as the sum of the products deg(u)*deg(v)
for every edge (u,v) in G. If norm is provided construct the
s-max graph and compute it's s_me... |
"""Implementation of JSONEncoder
"""
import re
try:
from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError:
c_encode_basestring_ascii = None
try:
from simplejson._speedups import make_encoder as c_make_encoder
except ImportError:
c_make_encoder = None
... |
"""Load the VGG imagenet model into TensorFlow.
Download the model from http://www.robots.ox.ac.uk/~vgg/research/very_deep/
and point to the file 'imagenet-vgg-verydeep-19.mat'
"""
import numpy as np
from scipy import io
import tensorflow as tf
def load(filename, images):
vgg19 = io.loadmat(filename)
vgg19Laye... |
'''
Firefox 2
@author: Peter Parente <<EMAIL>>
@copyright: Copyright (c) 2008 Peter Parente
@license: BSD License
All rights reserved. This program and the accompanying materials are made
available under the terms of The BSD License which accompanies this
distribution, and is available at
U{http://www.opensource.org/... |
"""
=========================
Train error vs Test error
=========================
Illustration of how the performance of an estimator on unseen data (test data)
is not the same as the performance on training data. As the regularization
increases the performance on train decreases while the performance on test
is optim... |
# -*- coding:utf-8 -*-
"""
通联数据
Created on 2015/10/12
@author: Jimmy Liu
@group : waditu
@contact: <EMAIL>
"""
from pandas.compat import StringIO
import pandas as pd
from tushare.util import vars as vs
from tushare.util.common import Client
from tushare.util import upass as up
class IV():
def __init__(self,... |
from __future__ import print_function
from bokeh.layouts import row
from bokeh.models import (
Range1d, WMTSTileSource, ColumnDataSource, HoverTool,
)
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.airports import data as airports
from bokeh.tile_providers import CARTODBPOSITRON
points... |
import os
import sys
import inspect
from robot.errors import DataError
from .encoding import decode_from_system
from .error import get_error_details
from .platform import JYTHON
from .robotpath import abspath, normpath
from .robottypes import type_name, is_unicode
if JYTHON:
from java.lang.System import getPrope... |
# -*- coding: utf-8 -*-
import itertools
import openerp.modules.registry
import openerp
from openerp.tests import common
class CreatorCase(common.TransactionCase):
model_name = False
def __init__(self, *args, **kwargs):
super(CreatorCase, self).__init__(*args, **kwargs)
self.model = None
... |
"""Invenio WebAccess Administrator Interface."""
__revision__ = "$Id$"
from invenio.config import CFG_SITE_LANG
import invenio.modules.access.admin_lib as wal
from invenio.modules.access.local_config import CFG_ACC_EMPTY_ROLE_DEFINITION_SRC
# reload(wal)
# from invenio.modules.access.admin_lib import index
index = w... |
"""Find the number of unique substrings from a string."""
import sys
import time
def lcp(s1, s2):
"""Return the length of the longest common prefix
between strings `s1` and `s2`."""
comp = 0
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
break
comp += 1
retu... |
import os
from django.utils import timezone
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
from .local_settings import *
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""views
This file contains the endpoints for rendering the interface and implementing
the backend modules
"""
from os import path
from flask import jsonify, render_template, request
from werkzeug import secure_filename
from .config import allowed_file, app, UPLOAD_FOL... |
# -*- coding: utf-8 -*-
"""
Customised instruments with extra features such as voltage dividers and derived
parameters for use with T10
"""
import numpy as np
from qcodes.instrument_drivers.QDev.QDac_channels import QDac
from qcodes.instrument_drivers.stanford_research.SR830 import SR830
from qcodes.instrument_drivers... |
import sys
try:
from twisted.python import dist
except ImportError:
raise SystemExit("twisted.python.dist module not found. Make sure you "
"have installed the Twisted core package before "
"attempting to install any other Twisted projects.")
if __name__ == '__main__... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os.path
import warnings
import sys
try:
from setuptools import setup
setuptools_available = True
except ImportError:
from distutils.core import setup
setuptools_available = False
try:
# This will create an... |
""" Test the graph_lasso module.
"""
import sys
import numpy as np
from scipy import linalg
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_less
from sklearn.covariance import (graph_lasso, GraphLasso, GraphLassoCV,
empirical_... |
#!/usr/bin/env python
import asyncio
import statistics
import tracemalloc
import websockets
from websockets.extensions import permessage_deflate
CLIENTS = 10
INTERVAL = 1 / 10 # seconds
MEM_SIZE = []
async def mem_client(client):
# Space out connections to make them sequential.
await asyncio.sleep(clien... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='EmailUser',
... |
"""
Test for contentstore signals receiver
"""
import mock
from django.test import TestCase
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore, SignalHandler
class CCXConSignalTestCase(TestCase):
"""
The only tests currently implemented are for verifying that
t... |
import string
class predictions(object):
def __init__(self, positions=None, scores=None):
self.positions=positions
self.scores=scores
def set_positions(self, positions):
self.positions=positions;
def get_positions(self):
return self.positions
def set_scores(self, scores):
self.scores=scores
def get_sc... |
from __future__ import absolute_import
from __future__ import print_function
from twisted.internet import defer
from twisted.python import runtime
from buildbot.process.results import SUCCESS
from buildbot.test.util.integration import RunMasterBase
# This integration test creates a master and worker environment
# an... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# © 2012 Bruno Chareyre <<EMAIL>>
"""Script showing how large bodies can be combined with periodic boundary conditions using InsertioSortCollider::allowBiggerThanPeriod=True (1)."""
from __future__ import print_function
from yade import pack
from pylab import rand
from yade im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.