content stringlengths 4 20k |
|---|
from __future__ import absolute_import
import logging
from functools import partial
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
from edxmako.shortcuts import render_to_st... |
import unittest
import amulet
class TestDeploy(unittest.TestCase):
"""
Trivial deployment test for Apache Bigtop Slave.
This charm cannot do anything useful by itself, so integration testing
is done in the bundle.
"""
def test_deploy(self):
self.d = amulet.Deployment(series='xenial')... |
"""
Utilities for unit tests.
"""
import sys
import os
import random
import uuid
import tempfile
import imp
import unittest
import shutil
import warnings
import subprocess
import pydoop
import pydoop.utils.jvm as jvm
from pydoop.utils.py3compat import StringIO
JAVA_HOME = jvm.get_java_home()
JAVA = os.path.join(JAVA... |
# -*- coding: utf-8 -*-
###############################################################################
#
# AddRecipientList
# Add one or more recipient lists to a newsletter.
#
# Python version 2.6
#
###############################################################################
from temboo.core.choreography import ... |
# The quadratically constrained 1-norm minimization example of section 8.7
# (Exploiting structure).
from cvxopt import blas, lapack, solvers, matrix, mul, div, setseed, normal
from math import sqrt
def qcl1(A, b):
"""
Returns the solution u, z of
(primal) minimize || u ||_1
... |
#!/usr/bin/env python
''' Project Metal Box Template for BitX40 http://www.hfsigs.com/
This is a executable python program that generates DXF (2-d CAD Files) that are templates for a project metal box for the BitX40 radio (http://www.hfsigs.com/ ). 3 DXF files are created - Top pattern, Bottom pattern and Front Pa... |
# coding: utf-8
from __future__ import unicode_literals
import re
import hashlib
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unified_strdate,
)
class WatIE(InfoExtractor):
_VALID_URL = r'http://www\.wat\.tv/video/(?P<display_id>.*)-(?P<short_id>.*?)_.*?\.html'
IE_NAME = '... |
{
'name': 'Mass Mailing Campaigns',
'summary': 'Design, send and track emails',
'description': """
Easily send mass mailing to your leads, opportunities or customers. Track
marketing campaigns performance to improve conversion rates. Design
professional emails and reuse templates in a few clicks.
""",
... |
# -*- coding: utf-8 -*-
import copy
from lxml import etree, html
from openerp import SUPERUSER_ID, api
from openerp.addons.website.models import website
from openerp.http import request
from openerp.osv import osv, fields
class view(osv.osv):
_inherit = "ir.ui.view"
_columns = {
'page': fields.boolea... |
import math
import pickle
import glob
import os
import sys
import paddle.v2 as paddle
import paddle.v2.dataset.common as common
embsize = 32
hiddensize = 256
N = 5
# NOTE: You need to generate and split dataset then put it under your cloud storage.
# then you can use different size of embedding.
# NOTE: must c... |
import pytest
asdf = pytest.importorskip('asdf')
import numpy as np
from packaging.version import Version
import astropy.units as u
from astropy import table
from astropy.time import Time, TimeDelta
from astropy.coordinates import SkyCoord, EarthLocation
from astropy.io.misc.asdf.tags.helpers import skycoord_equal
... |
from compiler import ast
# XXX should probably rename ASTVisitor to ASTWalker
# XXX can it be made even more generic?
class ASTVisitor:
"""Performs a depth-first walk of the AST
The ASTVisitor will walk the AST, performing either a preorder or
postorder traversal depending on which method is called.
... |
__revision__ = "src/engine/SCons/Tool/MSCommon/arch.py 2014/03/02 14:18:15 garyo"
__doc__ = """Module to define supported Windows chip architectures.
"""
import os
class ArchDefinition(object):
"""
A class for defining architecture-specific settings and logic.
"""
def __init__(self, arch, synonyms=[... |
import asyncio.tasks
from copy import deepcopy
from cerberus import Validator
import virtool.analyses.utils
import virtool.analyses.db
import virtool.api.utils
import virtool.files.db
import virtool.jobs.db
import virtool.samples.db
import virtool.db.utils
import virtool.errors
import virtool.http.routes
import virtoo... |
from unittest import TestCase
import lazydict
class TestLazyDictionary(TestCase):
def test_circular_reference_error(self):
d = lazydict.LazyDictionary()
d['foo'] = lambda s: s['foo']
self.assertRaises(lazydict.CircularReferenceError, d.__getitem__, 'foo')
def test_constant_redefinitio... |
"""
OpenERP - Server
OpenERP is an ERP+CRM program for small and medium businesses.
The whole source code is distributed under the terms of the
GNU Public Licence.
(c) 2003-TODAY, Fabien Pinckaers - OpenERP SA
"""
import logging
import os
import signal
import sys
import threading
import traceback
import time
import... |
"""
Author: James Ma
Email stuff here: <EMAIL>
"""
from datetime import datetime
import pandas as pd
import datetime as dt
class StrategyParameters:
def __init__(self, evaluation_time_secs, resample_interval_secs):
self.resample_interval_secs = resample_interval_secs
self.__evaluation_time_secs =... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
# This is a modification of @bcoca's `svc` module
import platform
import shlex
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.basic i... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016-2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
from taiga.base.api import serializers
from taiga.base.fields import TagsField
from taiga.base.fields import PgArrayField
from taiga.base.neighbors import NeighborsSerializerMixin
from taiga.mdrender.service import render as mdrender
from taiga.projects.validators import ProjectExistsValidator
from taiga.projects.mi... |
"""Gradients for operators defined in tensor_array_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import tensor_array_ops
# TODO(b/31222613): These ops may be differentiable,... |
import numpy as np
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_raises... |
"""Tests for backend_config."""
from tensorflow.python.keras import backend
from tensorflow.python.keras import backend_config
from tensorflow.python.keras import combinations
from tensorflow.python.platform import test
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class BackendConfigTest(tes... |
import sys
import cx_Oracle
from django.db.backends.oracle.introspection import DatabaseIntrospection
from django.utils import six
class OracleIntrospection(DatabaseIntrospection):
# Associating any OBJECTVAR instances with GeometryField. Of course,
# this won't work right on Oracle objects that aren't MDS... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Image pipeline
reader = vtk.vtkImageReader()
reader.ReleaseDataFlagOff()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0,63,0,63,1,93)
reader.SetDataSpacing(3.2,3.2,1... |
#!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_GROUP_",
"example_kwargs": {
"path": "/etc/ssh/sshd_config",
},
"example_value": """
[
{
"key": "PermitRootLogin",
"op": "=",
"value": "yes"
}
]
or
{
"path": "/etc/ssh/sshd_config",
"keys": [
{
"key": "PermitRootLog... |
import json, time
import pprint
import argparse
try:
import mosquitto
except ImportError:
import paho.mqtt.client as mosquitto
from mqttrpc.client import TMQTTRPCClient
from jsonrpc.exceptions import JSONRPCError
def main():
parser = argparse.ArgumentParser(description='Sample RPC client', add_help=Fa... |
from __future__ import absolute_import, division
import __builtin__
import math
import random
import time
def median(x, use_float=True):
# there exist better algorithms...
y = sorted(x)
if not y:
raise ValueError('empty sequence!')
left = (len(y) - 1)//2
right = len(y)//2
sum = y[left]... |
# -*- 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 model 'VumiChannel'
db.create_table(u'core_vumichannel', (
... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_crossovered_analytic(osv.osv_memory):
_name = "account.crossovered.analytic"
_description = "Print Crossovered Analytic"
_columns = {
'date1': fields.date('Start Date', required=True),
'date... |
import poems
def call():
session.forget()
return _service()
def index():
response.title = 'Daoistic'
if request.args or request.vars:
logger.error('Bad index: %s, %s', request.args, request.vars)
raise HTTP(404)
try:
idx = cache.ram('poems-1', lambda: poems.index(1, db))
... |
from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
class SimpleModel(models.Model):
objects = models.GeoManager()
class Meta:
abstract = True
@python_2_unicode_compatible
class Location(SimpleModel):
point = models.PointField()
def __str... |
from requestbuilder import Arg, MutuallyExclusiveArgList
from euca2ools.commands.cloudformation import CloudFormationRequest
from euca2ools.commands.cloudformation.argtypes import parameter_list
class UpdateStack(CloudFormationRequest):
DESCRIPTION = 'Update a stack with a new template'
ARGS = [Arg('StackNam... |
"""Blockly Demo: Storage
Copyright 2012 Google Inc.
https://developers.google.com/blockly/
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 requ... |
#!/usr/bin/env python
# Simple translation model and language model data structures
import sys
from collections import namedtuple
# A translation model is a dictionary where keys are tuples of French words
# and values are lists of (english, logprob) named tuples. For instance,
# the French phrase "que se est" has two... |
import json, os, urllib, urlparse
def redirect(url, response):
response.add_required_headers = False
response.writer.write_status(301)
response.writer.write_header("access-control-allow-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.wri... |
"""
A generic HTML whitelisting engine, designed to accommodate subclassing to override
specific rules.
"""
from __future__ import absolute_import, unicode_literals
import re
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
ALLOWED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'tel']
PROTOCOL_RE = re... |
#!/usr/bin/env python3
"""
Very basic player.dat inspection script
"""
import os
import sys
import argparse
from pathlib import Path
# incantation to be able to import overviewer_core
if not hasattr(sys, "frozen"):
sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')))
from overview... |
# -*- coding: utf-8 -*-
"""
pygments.styles
~~~~~~~~~~~~~~~
Contains built-in styles.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.plugin import find_plugin_styles
from pygments.util import ClassNotFound
#: Maps sty... |
'''
Created on Nov 3, 2016
The set of cards in the deck
@author: mjw
'''
from random import randint
from .Baron import Baron
from .Countess import Countess
from .Prince import Prince
from .Priest import Priest
from .Princess import Princess
from .King import King
from .Guard import Guard
from .Handmaid import Handmai... |
import os
import json
import urllib
import shutil
import urlparse
import tempfile
from mimetypes import MimeTypes
from requests_toolbelt.multipart.encoder import MultipartEncoder
from cloudify_rest_client import utils
from cloudify_rest_client.responses import ListResponse
class DeploymentUpdate(dict):
def __... |
import unittest
import xen.xend.XendConfig as XendConfig
class test_XendConfig(unittest.TestCase):
def testParseFromSXP(self):
cfg = XendConfig.XendConfig(
sxp_obj = (
['vm',
['bootloader_args', '-q --default_args="root=/dev/sda1 ro" --extra_args="quiet" /images/VM1.... |
# coding: utf-8
from __future__ import unicode_literals
from django.forms import CharField, Form, Media
from django.http import HttpRequest
from django.middleware.csrf import CsrfViewMiddleware, get_token
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.template.backends.dummy import ... |
import textwrap
import pycodestyle
from keystone.tests.hacking import checks
from keystone.tests import unit
from keystone.tests.unit.ksfixtures import hacking as hacking_fixtures
class BaseStyleCheck(unit.BaseTestCase):
def setUp(self):
super(BaseStyleCheck, self).setUp()
self.code_ex = self.u... |
from Tkinter import *
from keys import OPEN_WEATHER_API_KEY
from urllib2 import urlopen
from io import BytesIO
from PIL import Image, ImageTk
import datetime
import tkFont
import contextlib
import json
from sys import platform as sp
import socket
import string
# check for internet connectivity
def is_connected():
... |
# Unquoted List Association Locater and Reporter, by RemieRichards V1.0 - 26/11/16
# list("string" = value) is valid in DM
# unfortunately, so is list(string = value) (Notice the lack of quotes? BAD BAD, it conflicts with var names!)
import sys
import os
import re
from datetime import date
#Climbs up from /tools/Unq... |
from config import *
from moodle_ws_client import moodle
mdl = moodle.MDL()
# xmlrpc Connection
"""
Enrol users
"""
enrols =[{
'roleid': 1,
'userid': 3,
'courseid': 1,
}]
print mdl.enrol_users(server, enrols) |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal
from sys import float_info
from unittest import TestCase
from django.utils.numberformat import format as nformat
class TestNumberFormat(TestCase):
def test_format_number(self):
self.assertEqual(nformat(1234, '... |
"""Handles control flow statements: while, for, if."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast
from tensorflow.contrib.autograph.pyct import anno
from tensorflow.contrib.autograph.pyct import ast_util
from tensorflow.contrib.autograph.p... |
from rez.packages import iter_packages
from rez.exceptions import ConfigurationError
from rez.config import config
from rez.utils.data_utils import cached_property, cached_class_property
from rez.vendor.six import six
from rez.vendor.version.requirement import VersionedObject, Requirement
from hashlib import sha1
impor... |
from termprop import Termprop, MockTermprop
if __name__ == "__main__":
Termprop().test() |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import str_or_none
class ReverbNationIE(InfoExtractor):
_VALID_URL = r'^https?://(?:www\.)?reverbnation\.com/.*?/song/(?P<id>\d+).*?$'
_TESTS = [{
'url': 'http://www.reverbnation.com/alkilados/song/16965... |
import logging
import binascii
from flask_restful import reqparse, abort
import flask_restful
from flask import request, g
from functools import wraps
from jormungandr.exceptions import RegionNotFound
import datetime
import base64
from navitiacommon.models import User, Instance, db, Key
from jormungandr import cache, ... |
#!/usr/bin/env python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'dynmain', """
# DURATION TID FUNCTION
[ 26661] | main() {
[ 26661] | lib_a() {
[ 26661] | lib_b() {
1.187 us [ 26661] | lib_c();
2.271 us... |
import subprocess
import sys
import re
VALGRIND_ARGUMENTS = [
'valgrind',
'--error-exitcode=1',
'--leak-check=full',
'--smc-check=all'
]
# Compute the command line.
command = VALGRIND_ARGUMENTS + sys.argv[1:]
# Run valgrind.
process = subprocess.Popen(command, stderr=subprocess.PIPE)
code = process.wait();
e... |
from oslo_config import cfg
from oslo_log import log as logging
import routes as routes_mapper
import six
import six.moves.urllib.parse as urlparse
import webob
import webob.dec
import webob.exc
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron import... |
"""Utilities and helper functions."""
import base64
import datetime
import hashlib
import random
import socket
from oslo_log import log as logging
from oslo_utils import excutils
LOG = logging.getLogger(__name__)
def get_hostname():
return socket.gethostname()
def get_random_string(length):
"""Get a rand... |
from collections import OrderedDict
import numpy as np
import pandas as pd
import pytz
from qstrader.broker.portfolio.position_handler import PositionHandler
from qstrader.broker.transaction.transaction import Transaction
def test_transact_position_new_position():
"""
Tests the 'transact_position' method fo... |
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
import re
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--unset',
action='store_true',
... |
from __future__ import unicode_literals
import os
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils._os import upath
class Person(models.Model):
name = models.CharField(max_length=100)
class Triple(mod... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import range # pylint: disable=redefined-builtin
from tensorflow.contrib.labeled_tensor.python.ops import core
from tensorflow.contrib.labeled_tensor.python.ops import ops
from tensorflow.contr... |
#! /usr/bin/env python
"""
XCode Build Script
$Id: XCodeMake.py 655 2010-09-29 22:40:22Z soothe $
"""
import os
import sys
import getopt
import subprocess
# ------------------------------------------------------------
# usage
# ------------------------------------------------------------
def usage(errMsg):
... |
#!/usr/bin/python3
"""FRACTALS: LINDENMAYER SYSTEM"""
import numpy as np
import matplotlib.pyplot as plt
PRECISION = np.float32
def calc_rot_matrix(angle):
"""
Input:
angle
-- integer or float number
-- rotation angle in radians
-- positive number gives counter-clockwi... |
"""Support for Rflink binary sensors."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA,
PLATFORM_SCHEMA,
BinarySensorDevice,
)
from homeassistant.const import CONF_DEVICE_CLASS, CONF_FORCE_UPDATE, CONF_NAME
import homeassistant.helpers.c... |
#BSME: Beltran Sarmiento Mario Edwin
#CVCE: Cardoso Valencia Carlos ErIc
#MPVS: Martinez Pozos Victor Sebastian
#MI: Marin Ivan
import random
def granSuperVillano(numero_villanos,numero_superVillanos):
habilidades = ["MALDAD","VOLAR","FUERZA","EGO","MONOLOGAR","TRIUNFOS","INGENIO","PODER MENTAL","AUD... |
from nupic.encoders.base import Encoder
from nupic.encoders.delta import DeltaEncoder
from nupic.encoders.adaptivescalar import AdaptiveScalarEncoder
class ScalarSpaceEncoder(Encoder):
"""An encoder that can be used to permute the encodings through different spaces
These include absolute value,delta, log space, e... |
"""A python script to manage minecraft servers
Designed for use with MineOS: http://minecraft.codeemo.com
"""
__author__ = "William Dizon"
__license__ = "GNU GPL v3.0"
__version__ = "0.6.0"
__email__ = "<EMAIL>"
STOCK_PROFILES = {
'vanilla179': {
'name': 'vanilla179',
'type': 'standard_jar',
... |
import sys
import time
import math
import rospy
import cv2
import sensor_msgs.msg
from cv_bridge import CvBridge
# Send each image by iterate it from given array of files names to a given topic,
# as a regular and compressed ROS Images msgs.
class Source:
def __init__(self, topic, filenames):
self.pub ... |
from subprocess import PIPE
from subprocess import Popen
import sublime
import sublime_plugin
from Dart.sublime_plugin_lib import PluginLogger
from Dart.sublime_plugin_lib.plat import supress_window
from Dart import analyzer
from Dart.lib.sdk import DartFormat
_logger = PluginLogger(__name__)
class DartFormatCom... |
import sublime
import sublime_plugin
import re
import os
import json
def msg(msg):
print "[PHP Getters and Setters] %s" % msg
class Prefs:
"""
Plugin preferences
"""
@staticmethod
def load():
settings = sublime.load_settings('php-getters-setters.sublime-settings')
Prefs.t... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
from operator import itemgetter
from ansible.module_utils.basic import AnsibleModu... |
from .control import Control
class ActionableControl(Control):
def __init__(self, dialog, id, type, parent_id, properties, element):
super().__init__(dialog, id, type, parent_id, properties, element)
self.action_name = properties.get('an')
@property
def action(self):
if not self.a... |
# -*- coding: utf-8 -*-
###############################################################################
# (C) 2010 Oliver Gutiérrez <<EMAIL>>
# LOTROAssist experience plugin
###############################################################################
# Python Imports
import re
# GTK Imports
import gobject
import g... |
import itertools
import random
ASCII_TABLE = " | | \n" \
" | | \n" \
"_____|_____|_____\n" \
" | | \n" \
" | | \n" \
"_____|_____|_____\n" \
" | | \n" \
" | ... |
"""@package src.clm.views.guest.message
@alldecoratedby{src.clm.utils.decorators.guest_log}
"""
from clm.models.message import Message
from clm.models.user import User
from clm.utils.exception import CLMException
from clm.utils.decorators import guest_log
from clm.utils import mail
@guest_log(log=True)
def add(reque... |
"""
Tests for Layer1 of DynamoDB
"""
import time
import base64
from tests.unit import unittest
from boto.dynamodb.exceptions import DynamoDBKeyNotFoundError
from boto.dynamodb.exceptions import DynamoDBConditionalCheckFailedError
from boto.dynamodb.exceptions import DynamoDBValidationError
from boto.dynamodb.layer1 im... |
# -*- coding: utf-8 -*-
"""
sphinx.directives.code
~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import codecs
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphin... |
"""
WSGI config for analys24tim project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... |
import logging
from typing import Dict, Tuple
from ..calling_conventions import SYSCALL_CC, SimCCSyscall
from ..errors import AngrUnsupportedSyscallError, SimSolverError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger(name=__name__)
class SimUserland(SimOS):
"""
... |
#!/usr/bin/env python
import argparse
import datetime
import time
from wrfpy import utils
from wrfpy.config import config
import os
#from urb import urb
import shutil
import glob
class wps_post(config):
''''
Main function to initialize WPS timestep:
- converts cylc timestring to datetime object
- ... |
"""
For each packet, compute all 1grams of 256 characters and return it
as 256 element dict
AUTHORS::
- Vmon (<EMAIL>)
-2012 Initial version
-2013 adopted for demystegofier
"""
from demystegofier_feature import DemystegofierFeature
class FeatureAverage1Grams(DemystegofierFeature):
def __ini... |
"""Get the recid of a record with a given report-number (from the global 'rn'),
and store it into the global 'sysno'.
"""
__revision__ = "$Id$"
from os import access, rename, F_OK, R_OK
import re
from invenio.search_engine import \
record_exists, \
search_pattern, \
get_field_tags
from invenio.websu... |
# pylint: disable=no-self-use,invalid-name
import numpy
from keras.layers import Input
from keras.models import Model
from deep_qa.layers.time_distributed_embedding import TimeDistributedEmbedding
from deep_qa.layers.vector_matrix_split import VectorMatrixSplit
from deep_qa.layers.wrappers.output_mask import OutputMas... |
#!/usr/bin/env python
import asyncoro, socket, sys, time
def client_send(clients, conn, coro=None):
coro.set_daemon()
asyncoro.logger.debug('%s/%s started with %s', coro.name, id(coro), conn._fileno)
while True:
line = yield conn.recv_msg()
if not line:
asyncoro.logger.debug('... |
from measurements import media
import page_sets
from telemetry import benchmark
from telemetry.page import page_test
from telemetry.value import list_of_scalar_values
from telemetry.value import scalar
class _MSEMeasurement(page_test.PageTest):
def ValidateAndMeasurePage(self, page, tab, results):
media_metric ... |
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.test import TestCase
class TestSessionAuthenticationMiddleware(TestCase):
def setUp(self):
self.user_password = 'test_password'
self.user ... |
import re
from sirano.action import Action
from sirano.exception import UnsupportedFormatException
class SIPIdentityAction(Action):
"""Action plugin for the field Identity of the SIP protocol"""
name = 'sip-identity'
re_sip_identity = re.compile(
r'^"?(?P<display>.+?)??"?\s*<?sips?:(?:(?P<user>... |
import os
import pytest
import capnp
this_dir = os.path.dirname(__file__)
# flake8: noqa: E501
@pytest.fixture
def capability():
capnp.cleanup_global_schema_parser()
return capnp.load(os.path.join(this_dir, 'test_capability.capnp'))
class Server:
def __init__(self, val=1):
self.val = val
d... |
"""Takes a generator of values, and accumulates them for a frontend."""
import collections
import threading
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
from tensorflow.python.summary.impl import directory_watcher
from tensorflow.python.summary.impl import event_file_loa... |
"""
Find intermediate evalutation results in assert statements through builtin AST.
This should replace _assertionold.py eventually.
"""
import sys
import ast
import py
from py._code.assertion import _format_explanation, BuiltinAssertionError
if sys.platform.startswith("java") and sys.version_info < (2, 5, 2):
... |
#!/usr/bin/env python
import argparse
from argparse import RawTextHelpFormatter
import os
import gwide.methods as gtm
from gwide.Classes.gwidePlot_class import GenomeWidePlot
def plot():
""" Script working with concat file generated by pileupsToConcat.py script. Read concat file and according to options.
Can p... |
"""
The point of integration of application and authentication.
"""
from twisted.internet import defer
from twisted.internet.defer import maybeDeferred
from twisted.python import failure, reflect
from twisted.cred import error
from zope.interface import providedBy, Interface
class IRealm(Interface):
"""
The... |
class WpmNS:
def __init__(self, db, langcode, version=None):
self.sep = ':'
self.lc = langcode
self.db = db
self.manual_version = version
def version (self):
if self.manual_version:
return self.manual_version
version = self.db.get(self.db_version... |
# -*- coding: utf-8 -*-
"""
twisted-server.py
~~~~~~~~~~~~~~~~~
A fully-functional HTTP/2 server written for Twisted.
"""
import functools
import mimetypes
import os
import os.path
import sys
from OpenSSL import crypto
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.protocol import ... |
"""
Support for Belkin WeMo lights.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/light.wemo/
"""
import logging
from datetime import timedelta
import homeassistant.util as util
import homeassistant.util.color as color_util
from homeassistant.componen... |
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from lettuce import step, world
from nose.tools import assert_equal, assert_in, assert_not_equal
from selenium.common.exceptions import InvalidElementStateException
from common import *
from contentstore.utils import reverse_course_url
from te... |
import os
import time
from threading import Thread, Lock
from multiprocessing import Process, Queue
from ninja_ide.intellisensei.analyzer import model
from ninja_ide.intellisensei.analyzer import analyzer
try:
unicode
except NameError:
# Python 3
basestring = unicode = str # lint:ok
__completion_daemon... |
"""
Corner with Subpixel Accuracy
may need to find corners with max accuracy
function: cv2.cornerSubPix()
refines corners detected with sub-pixel accuracy
find Harris corners first
then, pass centroids of corners to refine them
"""
# ex
# harris corners marked with red pixels
# refined corners marked in green pixe... |
"""rebase.py: standalone script to batch update bench expectations.
Requires gsutil to access gs://chromium-skia-gm and Rietveld credentials.
Usage:
Copy script to a separate dir outside Skia repo. The script will create a
skia dir on the first run to host the repo, and will create/delete
... |
# -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
sess = tf.Session()
def test1():
hello = tf.constant('Hello, TensorFlow!')
print(sess.run(hello))
def test2():
a = tf.constant(10)
b = tf.constant(32)
print(sess.run(a+b))
def test3():
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.