content string |
|---|
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack i... |
"""Distribution of a vectorized Laplace, with uncorrelated components."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contrib.distributions.python.ops import vecto... |
from jsparser import *
from utils import *
import re
from utils import *
#Note all white space sent to this module must be ' ' so no '\n'
REPL = {}
#PROBLEMS
# <<=, >>=, >>>=
# they are unusual so I will not fix that now. a++ +b works fine and a+++++b (a++ + ++b) does not work even in V8
ASSIGNMENT_MATCH = '(?<!=|!... |
version = "1.0"
start_date = '2009-01-01' # Start date for all the computations
ref_symbol = 'ETFMIB.MI' # Symbol used to map main market (SPY, ETFMIB,...)
test_portfolio = ['STS.MI', 'ENEL.MI', 'SFER.MI']
ftsemib_symbols = ['A2A.MI', 'ATL.MI', 'BMPS.MI', 'BAMI.MI',
'BMED.MI', 'BPE.MI',
'BRE.MI', 'BZU.MI', 'CPR.MI', ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from libcloud.compute.types import Provider
_ = Provider.GCE
HAS_LIBCLOUD ... |
from copy import deepcopy
import numpy
from PIDParameters import *
class PID(object):
def __init__(self):
p = PIDParameters()
p.Beta = 1.0
p.H = 0.05
p.integratorOn = False
p.K = 0.25 # start 0.1 # used to be 0.20
p.N = 10
p.Td = 0.0 # start 0.1
p... |
{
'name': 'Sale Require Purchase Order Number',
'version': '8.0.0.1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Sale Require Purchase Order Number
==================================
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar'... |
from unittest import TestCase
from unittest.mock import MagicMock
from DownloaderForReddit.core.content_filter import ContentFilter
from DownloaderForReddit.database.database_handler import DatabaseHandler
from DownloaderForReddit.utils import injector
from Tests.mockobjects.mock_objects import (get_user, get_post, ge... |
import re
class OEList(list):
"""OpenEmbedded 'list' type
Acts as an ordinary list, but is constructed from a string value and a
separator (optional), and re-joins itself when converted to a string with
str(). Set the variable type flag to 'list' to use this type, and the
'separator' flag may be ... |
import os
from base import *
DIR = "/FCGI-EmptyVars/"
MAGIC = "Cherokee and FastCGI rocks!"
PORT = get_free_port()
PYTHON = look_for_python()
SCRIPT = """
from fcgi import *
def app (environ, start_response):
start_response('200 OK', [("Content-Type", "text/plain")])
resp = ""
for k in environ:
... |
import crm_todo
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
{
'name': 'Guatemala - Accounting',
'version': '3.0',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Guatemala.
=====================================================================
Agrega una nomenclatura contable para Guatemala... |
"""TODO: module-level docstring."""
__authors__ = "Pascal Lamblin and Razvan Pascanu"
__copyright__ = "Copyright 2010-2013, Universite de Montreal"
__credits__ = ["Pascal Lamblin", "Razvan Pascanu", "Ian Goodfellow",
"Mehdi Mirza"]
__license__ = "3-clause BSD"
__maintainer__ = "Pascal Lamblin"
__email__ ... |
import os
from PySide import QtGui, QtCore
import FreeCAD
import FreeCADGui
from FreeCAD import Base
import Spreadsheet
import matplotlib.ticker as mtick
class Plot(object):
def __init__(self, l, z, v, tank):
""" Constructor. performs the plot and shows it.
@param l Percentages of filling level.
... |
from scipy.optimize import minpack2
import numpy as np
from numpy.compat import asbytes
__all__ = ['line_search_wolfe1', 'line_search_wolfe2',
'scalar_search_wolfe1', 'scalar_search_wolfe2',
'line_search_armijo']
#------------------------------------------------------------------------------
# M... |
# -*- coding: utf-8 -*-
"""
flask.templating
~~~~~~~~~~~~~~~~
Implements the bridge to Jinja2.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import posixpath
from jinja2 import BaseLoader, Environment as BaseEnvironment, \
TemplateNotFound
from .glo... |
#! /usr/bin/env python
# Selectively preprocess #ifdef / #ifndef statements.
# Usage:
# ifdef [-Dname] ... [-Uname] ... [file] ...
#
# This scans the file(s), looking for #ifdef and #ifndef preprocessor
# commands that test for one of the names mentioned in the -D and -U
# options. On standard output it write... |
from __future__ import with_statement, division
from io import BytesIO
from mapproxy.compat.image import Image
from mapproxy.request.wms import WMS111MapRequest
from mapproxy.test.http import mock_httpd
from mapproxy.test.image import tmp_image
from mapproxy.test.system import module_setup, module_teardown, SystemTes... |
"""add slug to task group task
Revision ID: 3605dca868e4
Revises: 1431e7094e26
Create Date: 2015-07-14 22:06:05.063945
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "3605dca868e4"
down_revision = "1431e7094e26"
_table_name = "task_group_tasks"
_column_name ... |
from mpfmc.tests.MpfIntegrationTestCase import MpfIntegrationTestCase
class TestTutorialStep16(MpfIntegrationTestCase):
def getConfigFile(self):
return 'config.yaml'
def getMachinePath(self):
return self.get_abs_path('tutorial_step_16')
def get_platform(self):
return 'smart_virt... |
"""
Test signal handlers for the survey app
"""
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import fake_completed_retirement
from student.tests.factories import UserFactory
from survey.models import SurveyAnswer
from survey.tests.factories import SurveyAnswerFactory
from xmodule.modulestore... |
import unittest
from test import support
from test.test_urllib2 import sanepathname2url
import os
import socket
import urllib.error
import urllib.request
import sys
try:
import ssl
except ImportError:
ssl = None
support.requires("network")
TIMEOUT = 60 # seconds
def _retry_thrice(func, exc, *args, **kwarg... |
"""Tests for ceilometer/hardware/inspector/snmp/inspector.py
"""
from ceilometer.hardware.inspector import snmp
from ceilometer.openstack.common.fixture import mockpatch
from ceilometer.openstack.common import network_utils
from ceilometer.tests import base as test_base
from ceilometer.tests.hardware.inspector import ... |
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.urls import reverse
from django.utils.translation import ugettext as _
from celery import task
from kitsune.messages.models import InboxMessage
from kitsune.sumo.email_utils import make_mail, safe_translation, se... |
#!/usr/bin/env python
import os
import sys
import re
import string
from itertools import izip
from time import time
from bisect import bisect_left
from subprocess import Popen, PIPE
from cStringIO import StringIO
import spacy
from .process import Process
from ..model import recognition
from ..doc import Mention, Cha... |
from __future__ import absolute_import
import six.moves.cPickle
import gzip
from .data_utils import get_file
import random
from six.moves import zip
import numpy as np
def load_data(path="imdb.pkl", nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113,
start_char=1, oov_char=2, index_from=3)... |
"""Topological sorting algorithms."""
from ..exc import CircularDependencyError
from .. import util
__all__ = ['sort', 'sort_as_subsets', 'find_cycles']
def sort_as_subsets(tuples, allitems, deterministic_order=False):
edges = util.defaultdict(set)
for parent, child in tuples:
edges[child].add(pare... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from subprocess import Popen, PIPE
import re
# change those symbols to whatever you prefer
symbols = {
'ahead of': '↑',
'behind': '↓',
'staged': '♦',
'changed': '‣',
'untracked': '…',
'clean': '⚡',
'unmerged': '≠',
'sha1': ':'
}
output, err... |
from django import forms
from maps.models import ShapeFile
from django.core.exceptions import ValidationError
from django.db.models.fields.files import FieldFile
from maps.utils import *
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
class ShapeFileForm(fo... |
import unittest
import numpy as np
from pylearn2.datasets.cifar10 import CIFAR10
from pylearn2.space import Conv2DSpace
from pylearn2.testing.skip import skip_if_no_data
class TestCIFAR10(unittest.TestCase):
def setUp(self):
skip_if_no_data()
self.test = CIFAR10(which_set='test')
def test_top... |
"""The Flavor Disabled API extension."""
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
authorize = extensions.soft_extension_authorizer('compute', 'flavor_disabled')
class FlavorDisabledController(wsgi.Controller):
def _extend_flavors(self, req, flavors):
for flavor in f... |
#! /usr/bin/env python
# Module ndiff version 1.7.0
# Released to the public domain 08-Dec-2000,
# by Tim Peters (<EMAIL>).
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
# ndiff.py is now simply a front-end to the difflib.ndiff() function.
# Originally, it contained the difflib.Se... |
from django.apps import apps as global_apps
from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction
from django.db.utils import IntegrityError
from django.utils import six
class RenameContentType(migrations.RunPython):
def __init__(self, app_label, old_model, new_model):
self.app_label = a... |
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from .filepost import encode_multipart_formdata
__all__ = ['RequestMethods']
class RequestMethods(object):
"""
Convenience mixin for classes who implement a :meth:`urlopen` method, such
as :class:`~urllib3.... |
import os
import subprocess
from marathon import MarathonClient
from jinja2 import Environment, ChoiceLoader, FileSystemLoader, PackageLoader
class MarathonProxyManagerCommand(object):
DEFAULT_TEMPLATE_LOADER = PackageLoader(u'marathon_proxy_manager', u'templates')
DEFAULT_MARATHON_URL = u'http://localhost:... |
from openerp.osv import fields, osv
class portal(osv.osv):
""" A portal is simply a group of users with the flag 'is_portal' set to True.
The flag 'is_portal' makes a user group usable as a portal.
"""
_inherit = 'res.groups'
_columns = {
'is_portal': fields.boolean('Portal', help="If ... |
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 = 'l, j F, Y'
TIME_FORMAT = 'h:i a'
DATETIME_FORMAT = 'j F, Y h:i a'
YEAR_MONTH_FORMAT = 'F, Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMA... |
import unittest
from spyne.test.protocol._test_dictdoc import TDictDocumentTest
from spyne.protocol.yaml import YamlDocument
from spyne import MethodContext
from spyne.application import Application
from spyne.decorator import srpc
from spyne.service import Service
from spyne.server import ServerBase
from spyne.prot... |
"""Branch naming conventions for 'arcyd-review/description/base' style."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_classicnaming
#
# Public Classes:
# Naming
# .make_tracker_bra... |
#!/usr/bin/python
import sys
import os
import glob
import time
import logging
from optparse import OptionParser
logging.basicConfig(level=logging.DEBUG)
parser = OptionParser()
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't prin... |
from collections import defaultdict
import colorsys
import random
import time
import threading
from razer.client import DeviceManager
from razer.client import constants as razer_constants
# Create a DeviceManager. This is used to get specific devices
device_manager = DeviceManager()
print("Found {} Razer devices".f... |
from django.db.models.manager import Manager
from django.contrib.gis.db.models.query import GeoQuerySet
class GeoManager(Manager):
"Overrides Manager to return Geographic QuerySets."
# This manager should be used for queries on related fields
# so that geometry columns on Oracle and MySQL are selected
... |
"""
Base class for pages specific to a course in Studio.
"""
import os
from opaque_keys.edx.locator import CourseLocator
from bok_choy.page_object import PageObject
from . import BASE_URL
class CoursePage(PageObject):
"""
Abstract base class for page objects specific to a course in Studio.
"""
# Ove... |
import openerp
from openerp import models, fields, api, SUPERUSER_ID as SI, exceptions
from openerp.tools import config
from openerp.tools.translate import _
from openerp.addons.saas_utils import connector
class ResUsers(models.Model):
_name = 'res.users'
_inherit = 'res.users'
_defaults = {
'oau... |
from collections import defaultdict
from . import dataformat
from .util import dbg
class StringResource(dataformat.Exportable):
name_struct = "string_resource"
name_struct_file = "string_resource"
struct_description = "string id/language to text mapping, extracted from language.dll file."
dat... |
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class S... |
"""Calculate kmeans against known dataset with known centroids """
import unittest
from sparktkregtests.lib import sparktk_test
class KMeansClustering(sparktk_test.SparkTKTestCase):
def setUp(self):
"""Import the files to test against."""
super(KMeansClustering, self).setUp()
schema = [("... |
"""Custom SQLAlchemy types."""
from sqlalchemy.dialects import postgresql
from sqlalchemy import types
from nova import utils
class IPAddress(types.TypeDecorator):
"""An SQLAlchemy type representing an IP-address."""
impl = types.String(39).with_variant(postgresql.INET(), 'postgresql')
def process_bind... |
'''VARBLOCK file support
The VARBLOCK file format is as follows, where || denotes byte concatenation:
FILE := VERSION || BLOCK || BLOCK ...
BLOCK := LENGTH || DATA
LENGTH := varint-encoded length of the subsequent data. Varint comes from
Google Protobuf, and encodes an integer into a variable number... |
#!/usr/bin/env python3
""" A command-line client to manage qb environments. """
import argparse
import logging.handlers
import sys
from client.config import Config
from container.container import Container
from machine.machine import Machine
__author__ = "Daniel Middleton"
__email__ = "<EMAIL>"
__status__ = "Protot... |
import operator
from django.template import Engine, Library
from django.utils import six
engine = Engine(app_dirs=True)
register = Library()
@register.inclusion_tag('inclusion.html')
def inclusion_no_params():
"""Expected inclusion_no_params __doc__"""
return {"result": "inclusion_no_params - Expected resul... |
# -*- coding: utf-8 -*-
import fnmatch
import os
import pysped
def list_recursively(directory, pattern):
"""Returns files recursively from directory matching pattern
:param directory: directory to list
:param pattern: glob mattern to match
"""
matches = []
for root, dirnames, filenames in os.... |
import distutils.command.build_clib as orig
from distutils.errors import DistutilsSetupError
from distutils import log
from setuptools.dep_util import newer_pairwise_group
class build_clib(orig.build_clib):
"""
Override the default build_clib behaviour to do the following:
1. Implement a rudimentary time... |
from watcher._i18n import _
from watcher.decision_engine.goal import base
from watcher.decision_engine.goal.efficacy import specs
class Dummy(base.Goal):
"""Dummy
Reserved goal that is used for testing purposes.
"""
@classmethod
def get_name(cls):
return "dummy"
@classmethod
def... |
import res_company
import ir_translation
import wizard
import controller
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.pat... |
import sys
sys.path.append('../JSON_Common')
import json_dict_common as jdc
def get_overview_data(jsonDict):
"""
Gets the overview element from the given dictionary of items
Args:
jsonDict (dict): A dictionary which we assume to be of a JSON format
Returns:
Value of the overview eleme... |
"""
Provide the mathematical functions that numpy doesn't.
Specifically, the secant/cosecant/cotangents and their inverses and
hyperbolic counterparts
"""
import numpy
# Normal Trig
def sec(arg):
"""
Secant
"""
return 1 / numpy.cos(arg)
def csc(arg):
"""
Cosecant
"""
return 1 / nump... |
from keystoneclient import base
class Role(base.Resource):
"""Represents a Keystone role."""
def __repr__(self):
return "<Role %s>" % self._info
def delete(self):
return self.manager.delete(self)
class RoleManager(base.ManagerWithFind):
"""Manager class for manipulating Keystone rol... |
"""Code for generating Android.mk for a tool."""
import android_framework_gyp
import gypd_parser
import makefile_writer
import os
import vars_dict_lib
def write_tool_android_mk(target_dir, var_dict):
"""Write Android.mk for a Skia tool.
Args:
target_dir: Destination for the makefile. Must not be None.
... |
import binascii
from graph.filter_base import FilterBase, FilterState, FilterType
from graph.pad_template import PadTemplate
from graph.pad_capabilities import PadCapabilities
from graph.input_pin import InputPin
from graph.output_pin import OutputPin
class LoggerSink(FilterBase):
"""
A logger sink filter.
... |
import FreeCAD
from lasercut import helper
from lasercut.material import retrieve_thickness_from_biggest_face
from lasercut.makehinges import complete_hinges_properties, create_solid_corner, estimate_min_link
import copy
class HingesProperties(helper.ObjectProperties):
_allowed = ('freecad_face_1_name', 'freecad... |
import mock
from oslo_serialization import jsonutils
from nova import exception
from nova import objects
from nova.tests.unit.objects import test_instance_numa_topology
from nova.tests.unit.objects import test_objects
from nova.tests import uuidsentinel as uuids
fake_instance_uuid = uuids.fake
fake_migration_contex... |
"""Functions that read and write gzipped files.
The user of the file doesn't have to worry about the compression,
but random access is not allowed."""
# based on Andrew Kuchling's minigzip.py distributed with the zlib module
import struct, sys, time, os
import zlib
import io
import __builtin__
__all__ = ["GzipFile"... |
policy_data = """
{
"admin_api": "is_admin:True",
"cells_scheduler_filter:TargetCellFilter": "is_admin:True",
"context_is_admin": "role:admin or role:administrator",
"compute:create": "",
"compute:create:attach_network": "",
"compute:create:attach_volume": "",
"compute:get": "",
"comp... |
import webnotes
def execute():
# removed following fields
webnotes.reload_doc("stock", "doctype", "stock_entry")
custom_fields()
deprecate_process()
webnotes.delete_doc("doctype", "sandbox")
def custom_fields():
fields = [
{
"label": "Is Excisable Goods",
"fieldname": "is_excisable_goods",
"fieldtype... |
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
import os
import re
import shutil
import subprocess
import stat
import string
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# A regex matching an argument corresponding to th... |
#
# Genre types taken from DVB standards documentation
#
# some broadcaster do define other types so this list
# may grow or be replaced..
#
maintype = [ _("Reserved"),
_("Movie/Drama"),
_("News Current Affairs"),
_("Show Games show"),
_("Sports"),
_("Children/Youth"),
_("Music/Ballet/Dance"),
_("Arts/Cul... |
"""factory methods to build real storage objects that conform to base.py"""
import os
import six
#TODO: Monolingual formats (with template?)
decompressclass = {
'gz': ("gzip", "GzipFile"),
'bz2': ("bz2", "BZ2File"),
}
classes_str = {
"csv": ("csvl10n", "csvfile"),
"tab": ("omegat", "OmegaTFileTab"... |
from django.conf.urls import url
from oscar.core.application import Application
from oscar.core.loading import get_class
class FlatPageManagementApplication(Application):
name = None
default_permissions = ['is_staff', ]
list_view = get_class('dashboard.pages.views', 'PageListView')
create_view = get... |
#!/usr/bin/env python
import struct
import sys
import vaxutils
import numpy
import math
def readNCNRData(inputfile):
f = open(inputfile, 'rb')
data = f.read()
f.close()
#filename
dat = struct.unpack('<21s',data[2:23])
filename = dat[0].replace(' ','')
#metadata
metadata = {}
... |
"""
Implementation of "Instructor" service
"""
import logging
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey, UsageKey
from commerce.signals import create_zendesk_ticket
from courseware.models import StudentModule
from instructor.views.tools import get_student_from_identifier
from ... |
"""
Create data files from a user's GoViral data.
Copyright (C) 2016 PersonalGenomes.org
This software is shared under the "MIT License" license (aka "Expat License"),
see LICENSE.TXT for full license text.
"""
import json
import os
import requests
from base_source import BaseSource
GO_VIRAL_DATA_URL = 'https://w... |
import re
from textwrap import dedent
import click
from click.testing import CliRunner
import pytest
from straitlets import (
Serializable,
StrictSerializable,
Bool,
Unicode,
Integer,
)
from straitlets.ext.click import (
JsonConfigFile,
YamlConfigFile,
)
from straitlets.test_utils import a... |
import re
from django.conf import settings
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy
from django.utils.translation import ugettext_lazy
from htmlentitydefs import name2codepoint
# Capitalizes the first letter of a string.
capfirst = lambda x: x and force_unicode(x)[... |
from __future__ import absolute_import, division, unicode_literals
def f1():
x = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
y = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
z = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
x += y + z
def f2():
x = "ABCDEFGHIJKLMNOP... |
from __future__ import unicode_literals
import frappe
from frappe import _
from erpnext.setup.utils import insert_record
def setup_healthcare():
if frappe.db.exists('Medical Department', 'Cardiology'):
# already setup
return
create_medical_departments()
create_antibiotics()
create_test_uom()
create_duration(... |
import unittest
import json
from api_list_data_source import APIListDataSource
from api_models import ContentScriptAPI
from extensions_paths import CHROME_EXTENSIONS
from server_instance import ServerInstance
from test_file_system import TestFileSystem
def _ToTestData(obj):
'''Transforms |obj| into test data by tu... |
from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except subprocess.CalledProcessError:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import requests
import sys
import tempfile
import zipfile
from . import Command
class Deploy(Command):
"""Deploy a module on an Odoo instance"""
def __init__(self):
super(Deploy, self).__init_... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"""Create the Afrikaans Locale."""
orm.Locale.objects.create(locale='af')
def backwards(self, orm):
... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import sys, os, cPickle, time, tempfile, errno
from math import ceil
from threading import Thread... |
"""
This module includes some utility functions for inspecting the layout
of a GDAL data source -- the functionality is analogous to the output
produced by the `ogrinfo` utility.
"""
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.geometries import GEO_CLASSES
def ogrinfo(data_source, num_... |
"""Command-line application that streams data into BigQuery.
This sample is used on this page:
https://cloud.google.com/bigquery/streaming-data-into-bigquery
For more information, see the README.md under /bigquery.
"""
import argparse
import ast
import json
import uuid
import googleapiclient.discovery
from six... |
import os.path
import unittest
import anyconfig.backend.json as TT
import anyconfig.tests.common
from anyconfig.tests.common import dicts_equal
CNF_0_S = """{
"a": 0,
"b": "bbb",
"sect0": {
"c": ["x", "y", "z"]
}
}
"""
CNF_0 = {'a': 0, 'b': 'bbb', 'sect0': {'c': ['x', 'y', 'z']}}
class Test10(unitte... |
import matplotlib.pyplot as plt
import pandas as pd
import seaborn.apionly as sns
from os import path
from matplotlib import rcParams
EXTRA_COLORSET = ["#797979","#000000","#505050","#FFFFFF","#B0B0B0",]
def registration_qc(df,
cmap="Set3",
extra=False,
extra_cmap=EXTRA_COLORSET,
group={"sub":"Subject"},
repeat=... |
"""
Verifies --generator-output= behavior when using rules.
"""
import TestGyp
# Android doesn't support --generator-output.
test = TestGyp.TestGyp(formats=['!android'])
test.writable(test.workpath('rules'), False)
test.run_gyp('rules.gyp',
'--generator-output=' + test.workpath('gypfiles'),
... |
"""
================================
Gradient Boosting regularization
================================
Illustration of the effect of different regularization strategies
for Gradient Boosting. The example is taken from Hastie et al 2009.
The loss function used is binomial deviance. Regularization via
shrinkage (``lear... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_delete_old_unclaimed_attachments
from zerver.models import Attachment, get_old_unclaimed_attach... |
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import int_or_none
class MporaIE(InfoExtractor):
_VALID_URL = r'^https?://(www\.)?mpora\.(?:com|de)/videos/(?P<id>[^?#/]+)'
IE_NAME = 'MPORA'
_TEST = {
'url': 'http://mpora.de/videos/AAd... |
#!/usr/bin/python
"""
XmConsole.py - Interact with a xen console, getting return codes and
output from commands executed there.
Copyright (C) International Business Machines Corp., 2005
Author: Dan Smith <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the t... |
from pyanaconda.modules.common import init
init()
from pyanaconda.modules.security.security import SecurityService
service = SecurityService()
service.run() |
"""
Verifies --generator-output= behavior when using actions.
"""
import TestGyp
test = TestGyp.TestGyp()
# All the generated files should go under 'gypfiles'. The source directory
# ('actions') should be untouched.
test.writable(test.workpath('actions'), False)
test.run_gyp('actions.gyp',
'--generator-... |
"""Tests for the conversion code and for feature importances export.
Tests that cover conversion from TFBT format to a tensorflow.contrib.
decision_tree generic_tree_model format and feature importances export.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_fun... |
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 EntityOverview(Choreography):
def __init__(self, temboo_session):
"""
Create ... |
from __future__ import division
from collections import Counter
from linear_algebra import distance, vector_subtract, scalar_multiply
import math, random
def sum_of_squares(v):
"""computes the sum of squared elements in v"""
return sum(v_i ** 2 for v_i in v)
def difference_quotient(f, x, h):
return (f(x +... |
"""
Verifies that extra filters are pruned correctly for Visual Studio 2008.
"""
import re
import TestGyp
def strip_ws(str):
return re.sub('^ +', '', str, flags=re.M).replace('\n', '')
test = TestGyp.TestGyp(formats=['msvs'])
test.run_gyp('filters.gyp', '-G', 'standalone', '-G', 'msvs_version=2008')
test.mus... |
#!/usr/bin/env python
# kamene.contrib.description = EIGRP
# kamene.contrib.status = loads
"""
EIGRP Scapy Extension
~~~~~~~~~~~~~~~~~~~~~
:version: 2009-08-13
:copyright: 2009 by Jochen Bartl
:e-mail: <EMAIL> / <EMAIL>
:license: GPL v2
This program is free software; you can r... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.**
Contact : <EMAIL>
.. note:: 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... |
import unittest
from paddle.dataset.common import download, DATA_HOME
from paddle.distributed.fleet.dataset import TreeIndex
class TestTreeIndex(unittest.TestCase):
def test_tree_index(self):
path = download(
"https://paddlerec.bj.bcebos.com/tree-based/data/demo_tree.pb",
"tree_ind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.