content string |
|---|
#!/usr/bin/env python
"""
mbed
Copyright (c) 2017-2017 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 applicab... |
"""Support for Meteo-France weather data."""
import datetime
import logging
import voluptuous as vol
from homeassistant.const import CONF_MONITORED_CONDITIONS, TEMP_CELSIUS
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform
from homeassistant.util import Thr... |
"""Controllers for queries relating to recent commits."""
__author__ = '<EMAIL> (Sean Lip)'
from core.controllers import base
from core.domain import exp_services
class RecentCommitsHandler(base.BaseHandler):
"""Returns a list of recent commits."""
# TODO(sll): Accept additional URL parameters that filter... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from nodeshot import get_version
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteration if comm... |
"""
Defines the translator and utilities for mapping
a Nova server to an Azure VM.
"""
import logging
from heat2arm.translators.instances.base_instance import (
BaseInstanceARMTranslator
)
from heat2arm.translators.instances import nova_utils as utils
LOG = logging.getLogger(__name__)
class NovaServerA... |
from msrest.serialization import Model
class ExpressRouteCircuitStats(Model):
"""Contains stats associated with the peering.
:param primarybytes_in: Gets BytesIn of the peering.
:type primarybytes_in: long
:param primarybytes_out: Gets BytesOut of the peering.
:type primarybytes_out: long
:pa... |
# -*- coding: utf-8 -*-
"""
************
Vertex Cover
************
Given an undirected graph `G = (V, E)` and a function w assigning nonnegative
weights to its vertices, find a minimum weight subset of V such that each edge
in E is incident to at least one vertex in the subset.
http://en.wikipedia.org/wiki/Vertex_cov... |
"""
Provide a mock light platform.
Call init before using it in your tests to ensure clean test data.
"""
from homeassistant.components.light import LightEntity
from homeassistant.const import STATE_OFF, STATE_ON
from tests.common import MockToggleEntity
ENTITIES = []
def init(empty=False):
"""Initialize the p... |
import asyncio
import discord
import sys
import traceback
from discord.ext import commands
from discord import errors
from Cogs import Message
def setup(bot):
bot.add_cog(Errors())
class Errors(commands.Cog):
def __init__(self):
pass
@commands.Cog.listener()
async def on_command_error(s... |
"""Largest Prime Factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
from collections import OrderedDict
def find_next_prime(primes):
last = primes[-1]
candidates = OrderedDict((k, 1) for k in range(last + 1, last * 2 + 1))
for p in ... |
import mock
import webob
from nova.api.openstack.compute.contrib import deferred_delete
from nova.api.openstack.compute.plugins.v3 import deferred_delete as dd_v21
from nova.compute import api as compute_api
from nova import context
from nova import exception
from nova import test
from nova.tests.api.openstack import ... |
"""Build the inference graph, load a checkpoint, and export."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from classifaedes import hparams_lib
from classifaedes import inputs_lib
from classifaedes import metadata
from classifaedes import model_lib
im... |
import cherrypy
import datetime
import six
from girder import events
from girder.constants import AccessType
from girder.exceptions import RestException
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource
from girder.api import access
from girder.models.setting import Se... |
'''
Audio tests
===========
'''
import unittest
import os
SAMPLE_FILE = os.path.join(os.path.dirname(__file__), 'sample1.ogg')
SAMPLE_LENGTH = 1.402
DELTA = SAMPLE_LENGTH * 0.01
DELAY = 0.2
class AudioTestCase(unittest.TestCase):
def get_sound(self):
import os
assert os.path.exists(SAMPLE_FILE)... |
'''
Created on Mar 17, 2011
@author: jsalvatier
'''
from theano import scalar, tensor
import numpy
from scipy import special, misc
from .dist_math import *
__all__ = ['gammaln', 'multigammaln', 'psi', 'trigamma', 'factln']
class GammaLn(scalar.UnaryScalarOp):
"""
Compute gammaln(x)
"""
@staticmethod... |
'''
This checks if all command line args are documented.
Return value is 0 to indicate no error.
Author: @MarcoFalke
'''
from subprocess import check_output
import re
FOLDER_GREP = 'src'
FOLDER_TEST = 'src/test/'
CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/%s' % FOLDER_GREP
CMD_GREP_ARGS = r"egrep -r -I '(map(Mu... |
import ctypes
from ctypes import windll
from ctypes import wintypes
AF_UNSPEC = 0
AF_INET = 2
AF_INET6 = 23
VERSION_2_2 = (2 << 8) + 2
class SOCKADDR(ctypes.Structure):
_fields_ = [
('sa_family', wintypes.USHORT),
('sa_data', ctypes.c_char * 14),
]
class WSADATA(ctypes.Structure):
_fi... |
from django.db import models
import random
import math
from race.models import Race
class GameSize(models.Model):
name = models.CharField(max_length=50)
numsystems = models.IntegerField(default=10)
max_x = models.IntegerField(default=20)
max_y = models.IntegerField(default=20)
class Game(models.Mode... |
# -*- coding: utf-8 -*-
"""
Example from robust test_rlm, fails on Mac
Created on Sun Mar 27 14:36:40 2011
"""
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
RLM = sm.RLM
DECIMAL_4 = 4
DECIMAL_3 = 3
DECIMAL_2 = 2
DECIMAL_1 = 1
from statsmodels.datasets.stackloss import load
d... |
import os
import sys
from functools import partial
from twisted.trial.unittest import TestCase, SkipTest
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware
from scrapy.exceptions import NotConfigured
from scrapy.http import Response, Request
from scrapy.spiders import Spider
from scrapy.crawler imp... |
import unittest
from StringIO import StringIO
import simplejson as json
class TestTuples(unittest.TestCase):
def test_tuple_array_dumps(self):
t = (1, 2, 3)
expect = json.dumps(list(t))
# Default is True
self.assertEqual(expect, json.dumps(t))
self.assertEqual(expect, json.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
import json
import re
import urllib2
from datetime import datetime
COMMAND_PATTERN = "nsenter --target %s --mount --uts --ipc --net --pid -- %s"
def execute(command):
p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIP... |
import json
from tornado import web, gen
from ..base.handlers import APIHandler, json_errors
from ..utils import url_path_join
class TerminalRootHandler(APIHandler):
@web.authenticated
@json_errors
def get(self):
tm = self.terminal_manager
terms = [{'name': name} for name in tm.terminals]
... |
#!/usr/bin/env python
# - * - coding: UTF-8 - * -
"""
This script generates tests text-emphasis-ruby-001 ~ 004 which tests
emphasis marks with ruby in four directions. It outputs a list of all
tests it generated in the format of Mozilla reftest.list to the stdout.
"""
from __future__ import unicode_literals
TEST_FIL... |
def WebIDLTest(parser, harness):
threw = False
try:
parser.parse("""
interface I {
[PutForwards=B] readonly attribute long A;
};
""")
results = parser.finish()
except:
threw = True
harness.ok(threw, "Should have thrown.")
parse... |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp import api, fields, models, _
from openerp.exceptions import UserError
class AccountAgedTrialBalance(models.TransientModel):
_name = 'account.aged.trial.balance'
_inherit = 'accoun... |
"""utilities for generating and formatting literal Python code."""
import re
from mako import exceptions
class PythonPrinter(object):
def __init__(self, stream):
# indentation counter
self.indent = 0
# a stack storing information about why we incremented
# the indentation counte... |
import sys
if sys.version_info < (3, 0):
base_str = (str, unicode)
else:
base_str = (bytes, str)
def wrap_ord(a):
if sys.version_info < (3, 0) and isinstance(a, base_str):
return ord(a)
else:
return a |
# coding: utf-8
from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote_plus
class YnetIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?ynet\.co\.il/(?:.+?/)?0,7340,(?P<id>L(?:-[0-9]+)+),00\.html'
_TESTS = [
... |
import json
from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange, Range
from django.contrib.postgres import forms, lookups
from django.db import models
from django.utils import six
from .utils import AttributeSetter
__all__ = [
'RangeField', 'IntegerRangeField', 'BigIntegerRangeField',
'Floa... |
{
"name": "MRP Project Link - MTO",
"summary": "Link production with projects for MTO",
"version": "8.0.1.0.0",
"depends": [
"mrp_project",
],
"author": "OdooMRP team,"
"AvanzOSC,"
"Serv. Tecnol. Avanzados - Pedro M. Baeza",
"category": "Manufacturing",
... |
from peewee import Node
from peewee import *
from playhouse.tests.base import PeeweeTestCase
class TestNodeAPI(PeeweeTestCase):
def test_extend(self):
@Node.extend()
def add(self, lhs, rhs):
return lhs + rhs
n = Node()
self.assertEqual(n.add(4, 2), 6)
delattr(N... |
#!/usr/bin/env python3
from flask import Flask
from flask import jsonify
from flask import render_template
from flask.ext.cors import CORS
from firebase import firebase
app = Flask(__name__)
CORS(app)
firebase = firebase.FirebaseApplication('https://tvhack.firebaseio.com', None)
_calling = False
@app.route('/')
... |
#!/usr/env python
from error import SaveError,LoadError,CompressedError
from zipfs import fsopen,isZip,GetFileNameInZip
import os
import pygame
class TextureConverter:
def __init__(self,palette=None):
if palette is not None:
self.palette_surf=palette
else:
self.palette_surf=pygame.image.load('code/palette.bm... |
EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0
EUCKR_TABLE_SIZE = 2352
# Char to FreqOrder table ,
EUCKR_CHAR_TO_FREQ_ORDER = (
13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87,
1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398,
1399,1729,1730,1731, 141, 621, 326,1... |
from .base_function import read_enum, build_function_input_dict
from simpy.core.result.container import ResultContainer, Result
class TestConfiguration(object):
def __init__(self, name, enable, config_name, overwrite):
if not isinstance(enable, bool):
raise Exception('enable must be a boolean'... |
import StringIO
class MockWeb(object):
def __init__(self, urls=None):
self.urls = urls or {}
self.urls_fetched = []
def get_binary(self, url, convert_404_to_None=False):
self.urls_fetched.append(url)
if url in self.urls:
return self.urls[url]
return "MOCK W... |
"""
Django settings for ResumeView project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE... |
from setuptools import setup, find_packages
try:
fo = open('README.rst')
long_description = fo.read()
except:
long_description="""OFS - provides plugin-orientated low-level blobstore. """,
finally:
fo.close()
setup(
name="ofs",
version="0.4.3",
description="OFS - provides plugin-orientated... |
from __future__ import print_function
import re
import sys
from formatter import AbstractFormatter, DumbWriter
from color import Coloring
from command import PagedCommand, MirrorSafeCommand, GitcAvailableCommand, GitcClientCommand
import gitc_utils
class Help(PagedCommand, MirrorSafeCommand):
common = False
helpS... |
from openid.test import datadriven
import unittest
from openid.message import Message, BARE_NS, OPENID_NS, OPENID2_NS
from openid import association
import time
from openid import cryptutil
import warnings
class AssociationSerializationTest(unittest.TestCase):
def test_roundTrip(self):
issued = int(time.... |
from bson import Code
from django.core.management.base import BaseCommand
from optparse import make_option
from crits.emails.email import Email
from crits.targets.target import Target
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--delete',
'-d',
... |
import croniter
import eventlet
import netaddr
import pytz
import six
from oslo_utils import netutils
from oslo_utils import timeutils
from heat.common.i18n import _
from heat.engine import constraints
class TestConstraintDelay(constraints.BaseCustomConstraint):
def validate_with_client(self, client, value):
... |
"""
Distance and Area objects to allow for sensible and convenient calculation
and conversions.
Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio
Inspired by GeoPy (http://exogen.case.edu/projects/geopy/)
and Geoff Biggs' PhD work on dimensioned units for robotics.
"""
__all__ = ['A', 'Area', 'D', 'Distance']
... |
"""Common functionalities used by both Keras and Estimator implementations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from absl import flags
from absl import logging
import numpy as np
import tensorflow as tf
from official.c... |
# coding=utf-8
"""
Unit tests for ``octoprint.server.util.flask``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <<EMAIL>>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of... |
# coding: utf-8
#
from django.utils.translation import ugettext as _
from django.db.models import Q
from orgs.utils import set_to_root_org
from ..models import DatabaseAppPermission
from common.tree import TreeNode
from applications.models import DatabaseApp
from assets.models import SystemUser
__all__ = [
'Dat... |
import os
import sys
import time
import unittest
from pyspark.serializers import read_int
class DaemonTests(unittest.TestCase):
def connect(self, port):
from socket import socket, AF_INET, SOCK_STREAM
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('127.0.0.1', port))
# send a s... |
from unittest import TestCase
import simplejson as json
class TestBigintAsString(TestCase):
# Python 2.5, at least the one that ships on Mac OS X, calculates
# 2 ** 53 as 0! It manages to calculate 1 << 53 correctly.
values = [(200, 200),
((1 << 53) - 1, 9007199254740991),
((1... |
from functools import partial
from operator import is_not
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from taiga.base import response
from taiga.base.decorators import detail_route
from taiga.base.api import serializers
from taiga.base.api.utils import get_obje... |
#!/usr/bin/python
#coding:utf-8
from PyQt4 import QtGui,QtCore
from mainwindow import Ui_MainWindow
from PyQt4.QtCore import *
from filter import filterImages
class Widget(QtGui.QMainWindow, Ui_MainWindow):
"""QtGui.QWidget和界面设计时选择的类型一致"""
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
s... |
"""Hue sensor entities."""
from aiohue.sensors import (
TYPE_ZLL_LIGHTLEVEL,
TYPE_ZLL_ROTARY,
TYPE_ZLL_SWITCH,
TYPE_ZLL_TEMPERATURE,
)
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_ILLUMINAN... |
import sublime, sublime_plugin, locale, datetime
import calendar,locale,sys
# view.run_command("dr_calendar_insert_month")
def add_month(y,m,x):
r_m = m + x
r_y = y
if (r_m < 1):
r_y -= 1
r_m = 12
if (r_m > 12):
r_m = 1
r_y += 1
r... |
from __future__ import absolute_import
from __future__ import print_function
from buildbot_worker import runprocess
from buildbot_worker.test.util import command
class SourceCommandTestMixin(command.CommandTestMixin):
"""
Support for testing Source Commands; an extension of CommandTestMixin
"""
def... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import subprocess
from ansible.plugins.connection.jail import Connection as Jail
from ansible.errors import AnsibleError
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
... |
#!/usr/bin/env python
"""
The simplest TF-IDF library imaginable.
Add your documents as two-element lists `[docname, [list_of_words_in_the_document]]` with `addDocument(docname, list_of_words)`. Get a list of all the `[docname, similarity_score]` pairs relative to a document by calling `similarities([list_of_words])`.... |
from config import Configuration
from phases import CompileC
from phases import CompileCxx
from phases import Assemble
from phases import BuildAction
from phases import MergeSwiftModule
from target import OSType
from path import Path
import os
class Product(BuildAction):
name = None
product_name = None
ph... |
from webob import exc
import nova
from nova.api.openstack import common
from nova.api.openstack.compute.views import addresses as view_addresses
from nova.api.openstack import wsgi
from nova.i18n import _
class Controller(wsgi.Controller):
"""The servers addresses API controller for the OpenStack API."""
_v... |
"""
Tests to verify correct number of MongoDB calls during course import/export and traversal
when using the Split modulestore.
"""
from tempfile import mkdtemp
from shutil import rmtree
from unittest import TestCase, skip
import ddt
from xmodule.modulestore.xml_importer import import_course_from_xml
from xmodule.mod... |
"""Test tag notation for template generation."""
from __future__ import with_statement
import os.path
import shutil
import sys
import syslog
import unittest
import configobj
os.environ['TZ'] = 'America/Los_Angeles'
import weewx.reportengine
import weewx.station
import weeutil.weeutil
import gen_fake_data
# Find th... |
"""POSIX specific tests. These are implicitly run by test_psutil.py."""
import datetime
import os
import subprocess
import sys
import time
import psutil
from psutil._compat import PY3, callable
from test_psutil import LINUX, SUNOS, OSX, BSD, PYTHON, POSIX, TRAVIS
from test_psutil import (get_test_subprocess, skip_o... |
import sqblUI
from SQBLutil import * # Dont like this, need to fix later.
from PyQt4 import QtGui, QtCore
import isoLangCodes
from lxml import etree
def languagePickerDialog(title = "Enter Language", default = None):
lang,success = QtGui.QInputDialog.getItem(None,
title,
"""Enter a <a href='http://... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
from yaml import load, YAMLError
from ansible.errors import AnsibleParserError
from ansible.errors.yaml_strings import YAML_SYNTAX_ERROR
from ansible.parsing.vault import VaultLib
from ansible.parsing.splitt... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import ujson
from typing import Any, Dict, List
from six import string_types
from zerver.lib.test_helpers import tornado_redirected_to_list, get_display_recipient
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import get_user_profile... |
from fabric.api import cd, run, sudo, put
from cStringIO import StringIO
base_dir = '/usr/local'
hostname = 'searx.me'
searx_dir = base_dir + '/searx'
searx_ve_dir = searx_dir + '/searx-ve'
current_user = run('whoami').stdout.strip()
uwsgi_file = '''
[uwsgi]
# Who will run the code
uid = {user}
gid = {user}
# Numbe... |
import sys
import os
import unittest
sys.path.insert(0, os.path.abspath(".."))
from cStringIO import StringIO
from .. import parser
from ..parser import token_types
class TokenizerTest(unittest.TestCase):
def setUp(self):
self.tokenizer = parser.Tokenizer()
def tokenize(self, input_str):
rv... |
"""
The DBAPI driver, will use by default the same driver SQLAlchemy is using for trump.
There is currently no way to change this default. It's assumed that the driver
is DBAPI 2.0 compliant.
Required kwargs include:
- 'dbinsttype' which must be one of 'COMMAND', 'KEYCOL', 'TWOKEYCOL'
- 'dsn', 'user', 'password', '... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"""
This tool is totally deprecated
Try using:
.pc.in files for .pc files
the feature intltool_in - see demos/intltool
make-like rules
"""
import shutil, re, os
from waflib import TaskGen, Node, Task, Utils, Build, Errors
from waflib.TaskGen i... |
import struct
try:
Exception, Warning
except ImportError:
try:
from exceptions import Exception, Warning
except ImportError:
import sys
e = sys.modules['exceptions']
Exception = e.Exception
Warning = e.Warning
from .constants import ER
import sys
class MySQLEr... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
USER_AGENT = 'ansible-ipinfoio-module/0.0.1'
class IpinfoioFacts(object):
def __init__(self, module):
self.url = 'https://ipinfo.io/json'
self.timeout = mod... |
import robot,os
from robot import libraries
#from robot import robot_imports
#from robot.api import ExecutionResult
#from robot.api import TestData
def main():
#Push required data in builtins
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--test", dest="testlist... |
import sys
from unicode_parse_common import *
# http://www.unicode.org/Public/5.1.0/ucd/extracted/DerivedGeneralCategory.txt
category_to_harfbuzz = {
'Mn': 'HB_Mark_NonSpacing',
'Mc': 'HB_Mark_SpacingCombining',
'Me': 'HB_Mark_Enclosing',
'Nd': 'HB_Number_DecimalDigit',
'Nl': 'HB_Number_Letter',
'No': 'H... |
import os
import subprocess
import common
def get_drclient_command(client_args,exec_args):
dr32 = os.environ.get('DYNAMORIO_32_RELEASE_HOME')
dr_path = dr32 + '/bin32/drrun.exe'
command = dr_path + ' -root ' + dr32 + ' -syntax_intel -c exalgo.dll ' + client_args + ' -- ' + exec_args
re... |
import os
import tempfile
def package_installed(module, name, category):
cmd = [module.get_bin_path('pkginfo', True)]
cmd.append('-q')
if category:
cmd.append('-c')
cmd.append(name)
rc, out, err = module.run_command(' '.join(cmd))
if rc == 0:
return True
else:
return... |
import netaddr
from neutron.common import exceptions
from neutron.extensions import securitygroup as sg_ext
from oslo_config import cfg
from oslo_log import log as logging
from quark import exceptions as q_exc
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
# Neutron doesn't officially support any other ethertype... |
from tincan.serializable_base import SerializableBase
from tincan.activity_list import ActivityList
from tincan.activity import Activity
class ContextActivities(SerializableBase):
_props = [
'category',
'parent',
'grouping',
'other',
]
def __init__(self, *args, **kwargs):
... |
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from xml.dom import minidom
from django.test import TestCase
from django.template import Template, Context
from django.conf import settings
from django.utils.unittest import skipIf
from billing import get_integration
@s... |
import numpy as np
from scipy.sparse import csc_matrix
import warnings
from .open import read_tag
from .tree import dir_tree_find
from .write import (start_block, end_block, write_int, write_float,
write_string, write_float_matrix, write_int_matrix,
write_float_sparse_rcs, write... |
import warnings
def _provenance_str(provenance):
"""Utility function used by compare_provenance to print diff
"""
return ["%s==%s" % (key, value) for (key, value) in provenance]
def compare_provenance(
this_provenance, other_provenance,
left_outer_diff = "In current but not comparison",
... |
import argparse
from director.consoleapp import ConsoleApp
from director import cameraview
from director import vtkAll as vtk
import PythonQt
from PythonQt import QtCore, QtGui, QtUiTools
def addWidgetsToDict(widgets, d):
for widget in widgets:
if widget.objectName:
d[str(widget.objectName)] =... |
"""
Unit tests for gating.signals module
"""
from mock import patch
from ddt import ddt, data, unpack
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.helpers import LoginEnrollmentTestCase
from miles... |
# The default ``config.py``
# flake8: noqa
def set_prefs(prefs):
"""This function is called before opening the project"""
# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_fil... |
import string, Utils
# list of directory options to offer in configure
dir_options = {
'with-cachedir' : [ '${PREFIX}/var/locks', 'where to put temporary cache files' ],
'with-codepagedir' : [ '${PREFIX}/lib/samba', 'where to put codepages' ],
'with-configdir' ... |
"""Base classes for server/gateway implementations"""
from types import StringType
from util import FileWrapper, guess_scheme, is_hop_by_hop
from headers import Headers
import sys, os, time
__all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
try:
dict
except NameError:
def dict(items)... |
{
'name': 'Memos pad',
'version': '0.1',
'category': 'Tools',
'description': """
This module update memos inside OpenERP for using an external pad
=================================================================
Use for update your text memo in real time with the following user that you invite.
""",
... |
"""
Tests for the InstructorService
"""
import json
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from courseware.models import StudentModule
from lms.djangoapps.instructor.access import allow_access
from lms.djangoapps.instru... |
"""This implements a virtual screen. This is used to support ANSI terminal
emulation. The screen representation and state is implemented in this class.
Most of the methods are inspired by ANSI screen control codes. The ANSI class
extends this class to add parsing of ANSI escape codes.
PEXPECT LICENSE
This license... |
from zap import ZAP
import datetime
# Change this if your version of ZAP is running on a different host and/or port:
zapUrl = 'http://127.0.0.1:8090'
# Dictionary of abbreviation to keep the output a bit shorter
abbrev = {
'Cookie set without HttpOnly flag' : 'HttpOnly',\
'Cookie set without secure flag'... |
#!/usr/bin/env python
#coding:utf-8
# Email : <EMAIL>
# Last modified : 2015-06-09 15:20:13
# Description :
from gale.web import app_run, router, RequestHandler
class BaseHandler(RequestHandler):
def get_current_user(self):
return self.session.get('username')
@router(url = '/login', is_login = ... |
import find_mxnet
import mxnet as mx
import logging
import argparse
import train_model
import time
# don't use -n and -s, which are resevered for the distributed training
parser = argparse.ArgumentParser(description='train an image classifer on Kaggle Data Science Bowl 1')
parser.add_argument('--network', type=str, de... |
from odoo import api, models, fields
class WebsiteConfigSettings(models.TransientModel):
_inherit = 'website.config.settings'
def _default_order_mail_template(self):
if self.env['ir.module.module'].search([('name', '=', 'website_quote')]).state in ('installed', 'to upgrade'):
return self.... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from ast import literal_eval
HAS_PYTHON26 = True
except ImportError:
HAS_P... |
"""Loss scaling optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_control_flow_ops
from tensorflow.python.ops imp... |
import yaml, canonical
def test_canonical_scanner(canonical_filename, verbose=False):
data = open(canonical_filename, 'rb').read()
tokens = list(yaml.canonical_scan(data))
assert tokens, tokens
if verbose:
for token in tokens:
print token
test_canonical_scanner.unittest = ['.canoni... |
import os
import shutil
from .. import constants, logger
from . import _json
def copy_registered_textures(dest, registration):
"""Copy the registered textures to the destination (root) path
:param dest: destination directory
:param registration: registered textures
:type dest: str
:type registrat... |
from gnuradio import gr, gr_unittest, blocks
import random
class test_unpack(gr_unittest.TestCase):
def setUp(self):
random.seed(0)
self.tb = gr.top_block ()
def tearDown(self):
self.tb = None
def test_001(self):
src_data = (1,0,1,1,0,1,1,0)
expected_resu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('mediaplayer', '0001_initial'),
]
... |
__author__ = 'Sean Lip'
from core.domain import value_generators_domain
import test_utils
class ValueGeneratorsUnitTests(test_utils.GenericTestBase):
"""Test the value generator registry."""
def test_value_generator_registry(self):
COPIER_ID = 'Copier'
copier = value_generators_domain.Regis... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.nxos import nxos_vrf
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosVrfModule(TestNxosModule):
module = nxos_vrf
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.