content stringlengths 4 20k |
|---|
#demonstrates how to use the 3d simulation.
import libaudioverse
import collections
libaudioverse.initialize()
sim = libaudioverse.Simulation()
sim.set_output_device()
world = libaudioverse.EnvironmentNode(sim, "default")
world.panning_strategy = libaudioverse.PanningStrategies.hrtf
source = libaudioverse.SourceNode(s... |
import sys
import os
import getopt
import gzip
import time
from binary import BinaryReader
from rawmesh import RawMesh
from quickhull import QuickHull
shortopts = ''
longopts = [
'dump',
]
options, datafiles = getopt.getopt(sys.argv[1:], shortopts, longopts)
for opt, arg in options:
if opt == "--dump":
... |
try:
import glanceclient.client
Client = glanceclient.client.Client
except ImportError:
import warnings
warnings.warn("Could not import glanceclient.client", ImportWarning)
import pbr.version
version_info = pbr.version.VersionInfo('python-glanceclient')
try:
__version__ = version_info.version_str... |
from .library import *
from .array import *
def approx1(signal, pos0, method=AF_INTERP_LINEAR, off_grid=0.0):
output = array()
safe_call(clib.af_approx1(ct.pointer(output.arr), signal.arr, pos0.arr,\
method, ct.c_double(off_grid)))
return output
def approx2(signal, pos0, pos1... |
"""profiler python module provides APIs to profile TensorFlow models.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.core.profiler.tfprof_log_pb2 import OpLogProto
from tensorflow.core.profiler.tfprof_outp... |
# -*- coding: utf-8 -*-
"""Tests for LinkedIn Add to Profile configuration. """
import ddt
from urllib import urlencode
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from student.models import LinkedInAddToProfileConfiguration
@ddt.ddt
class LinkedInAddToProfileUrlTests(TestCase... |
from unittest import TestCase
from preggy import expect
from thumbor.console import get_server_parameters
class ConsoleTestCase(TestCase):
def test_can_get_default_server_parameters(self):
params = get_server_parameters()
expect(params.port).to_equal(8888)
expect(params.ip).to_equal('0.0... |
"""
Better Figures & Images
------------------------
This plugin:
- Adds a style="width: ???px; height: auto;" to each image in the content
- Also adds the width of the contained image to any parent div.figures.
- If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
- Corrects alt text: if alt == imag... |
#!/usr/bin/env python3
# daemon98.py file post-processor.
# - graphs
# - MySQL queries
# - upload
import configparser
import os
import subprocess
import sys
import syslog
import time
import traceback
from mausy5043libs.libdaemon3 import Daemon
from mausy5043libs.libgraph3 import Graph
from mausy5043libs.libsqldata3 ... |
"""Mocks for tests."""
__author__ = '<EMAIL> (Thomas Stromberg)'
import time
import nameserver
# external dependencies (from third_party)
import dns.message
import dns.rdataclass
import dns.query
GOOD_IP = '127.0.0.1'
SLOW_IP = '9.9.9.9'
PERFECT_IP = '127.127.127.127'
NO_RESPONSE_IP = '10.0.0.1'
BROKEN_IP = '192.16... |
import sys
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from plata.product.models import ProductBase
from plata.shop.models import PriceBase
class Product(ProductBase):
"""(Nearly) the simplest product model ever"""
is_acti... |
from abc import ABCMeta
from marionette_driver import By
from firefox_puppeteer.ui_base_lib import UIBaseLib
class BaseNotification(UIBaseLib):
"""Abstract base class for any kind of notification."""
__metaclass__ = ABCMeta
@property
def close_button(self):
"""Provide access to the close b... |
"""
### Example HTTP operator and sensor
"""
import airflow
from airflow import DAG
from airflow.operators.http_operator import SimpleHttpOperator
from airflow.operators.sensors import HttpSensor
from datetime import timedelta
import json
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'sta... |
import argparse
import boto
import errno
import logging
import os
import socket
import threading
import time
import moto.server
import moto.s3
from girder.utility.s3_assetstore_adapter import makeBotoConnectParams, \
botoConnectS3, S3AssetstoreAdapter
from six.moves import range
_startPort = 31100
_maxTries = 100... |
r"""Removes parts of a graph that are only needed for training.
There are several common transformations that can be applied to GraphDefs
created to train a model, that help reduce the amount of computation needed when
the network is used only for inference. These include:
- Removing training-only operations like ch... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'hyperlink17.xlsx'
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.voss import voss_command
from units.modules.utils import set_module_args
from .voss_module import TestVossModule, load_fixture
class TestVossCo... |
import sys
def main():
if len(sys.argv)<2:
print "usage :",sys.argv[0],"ProtTop.results, ProtTopEval.results"
sys.exit(-1)
ifname = sys.argv[1]
ofname = sys.argv[2]
iPTfile = open(ifname,'r')
toplines = iPTfile.readlines()
iPTfile.close()
num_lines = 0
... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = "\2\1thisismyscretkey\1\2\e\y\y\h"
OPENID_PROVIDERS = [
{"name": "Google", "url": "https://www.google.com/accounts/o8/id"},
{"name": "Yahoo", "url": "https://me.yahoo.com"},
{"name": "AOL", "url": "http://open... |
import ConfigParser
import os
import sys
from collections import OrderedDict
here = os.path.split(__file__)[0]
class ConfigDict(dict):
def __init__(self, base_path, *args, **kwargs):
self.base_path = base_path
dict.__init__(self, *args, **kwargs)
def get_path(self, key, default=None):
... |
import re
from odoo import models, fields, api, _
from odoo.tools import mod10r
from odoo import exceptions
from odoo.addons.base_iban.models.res_partner_bank import normalize_iban
class BankCommon(object):
def is_swiss_postal_num(self, number):
return (self._check_9_pos_postal_num(number) or
... |
"""
Forms and validation code for user registration.
"""
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "require... |
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.comments import signals
from django.contrib.comments.models import Comment
from regressiontests.comment_tests.models import Article, Book
from regressiontests.comment_tests.tests import CommentTestCase
post_redir... |
import sys
sys.path.insert(1, "../../")
import h2o, tests
def plot_test():
kwargs = {}
kwargs['server'] = True
air = h2o.import_file(tests.locate("smalldata/airlines/AirlinesTrain.csv.zip"))
# Constructing test and train sets by sampling (20/80)
s = air[0].runif()
air_train = air[s ... |
FETCH_EVERY_SECONDS = 5 * 60
import datetime, os, subprocess
from sys import executable as python
from time import time, sleep
this_dir = os.path.abspath(os.path.dirname(__file__))
fetch_script = os.path.join(this_dir, "fetch_repositories.py")
while True:
start_time = time()
process = subprocess.Popen([python... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
import re
import cmds as cmds_lib
import validate
class Service(object):
def validateCmds(self, root, path):
cmds = validate.array(root, path, validate.is_any_type({'string', 'object'}), [])
for i, cmd in enumerate(cmds):
cmd_path = path + [i]
if isinstance(cmd, basestring... |
#!/usr/bin/env python
from __future__ import division
__author__ = "Jai Ram Rideout"
__copyright__ = "Copyright 2013, The QIIME Project"
__credits__ = ["Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.7.0-dev"
__maintainer__ = "Jai Ram Rideout"
__email__ = "<EMAIL>"
__status__ = "Development"
from csv import w... |
"""Tests for keras.layers.preprocessing.normalization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import com... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
This tests the SRC 'targz' packager, which does the following:
- create a targz package containing the specified files.
"""
import TestSCons
python = TestSCons.python
test = TestSCons.TestSCons()
tar = test.detect('TAR', 'tar')
if tar:
test.subd... |
from twisted.internet import error
import txsocksx.constants as c
class ParsingError(Exception):
pass
class InvalidServerReply(Exception):
pass
class SOCKSError(Exception):
pass
class MethodsNotAcceptedError(SOCKSError):
pass
class ConnectionError(SOCKSError):
pass
class ConnectionLostEarly(SO... |
'''
GCE external inventory script
=================================
Generates inventory that Ansible can understand by making API requests
Google Compute Engine via the libcloud library. Full install/configuration
instructions for the gce* modules can be found in the comments of
ansible/test/gce_tests.py.
When run a... |
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class InstagramAccount(ProviderAccount):
PROFILE_URL = 'http://instagram.com/'
def get_profile_url(self):
return sel... |
#!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
import string
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PKG_NAME = os.path.basename(SCRIPT_DIR)
PARAMETERS = None
#XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=... |
"""
Module for processing Sitemaps.
Note: The main purpose of this module is to provide support for the
SitemapSpider, its API is subject to change without notice.
"""
import lxml.etree
class Sitemap(object):
"""Class to parse Sitemap (type=urlset) and Sitemap Index
(type=sitemapindex) files"""
def __in... |
#!/usr/bin/python
"""Ansible module that recursively determines if the size of a key in an etcd cluster exceeds a given limit."""
from ansible.module_utils.basic import AnsibleModule
try:
import etcd
IMPORT_EXCEPTION_MSG = None
except ImportError as err:
IMPORT_EXCEPTION_MSG = str(err)
from collect... |
import json
# TODO: See doctring below
class Message:
""""
A message object to be passed between threads via Queue
I{Sample Usage}:
Making a new message that will send terminate from main to display:
C{newMessage = Message("Main", "Display", "Terminate", \{\})}
Making a slide that will update ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from cms.models import ACCESS_CHOICES, Page
from cms.utils.conf import get_cms_setting
from django.conf import settings
from django.db import models, migrations
import django.utils.timezone
from django.utils.translation import ugettext_lazy as _
template... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.six import iteritems
from jinja2.utils import missing
from ansible.module_utils._text import to_native
__all__ = ['AnsibleJ2Vars']
class AnsibleJ2Vars:
'''
Helper class to template all variable conte... |
from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand, CommandError
from django.test.client import RequestFactory
from allaccess.models import Provider
class Command(NoArgsCommand):
"Convert existing providers from django-social-auth to django-all-access."
def handle... |
from nova.console import type as ctype
from nova import test
class TypeTestCase(test.NoDBTestCase):
def test_console(self):
c = ctype.Console(host='127.0.0.1', port=8945)
self.assertTrue(hasattr(c, 'host'))
self.assertTrue(hasattr(c, 'port'))
self.assertTrue(hasattr(c, 'internal_a... |
"""
RESTx: Sane, simple and effective data publishing and integration.
Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
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... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.jvm.zinc.zinc_analysis_element import ZincAnalysisElement
class CompileSetup(ZincAnalysisElement):
headers = ('output mode', 'output directories... |
#!/usr/bin/env python
# coding=utf8
"""
Add tables for extra_src handling
@contact: Debian FTP Master <<EMAIL>>
@copyright: 2011 Mark Hymers <<EMAIL>>
@license: GNU General Public License version 2 or later
"""
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Gen... |
import sys, os
from jsonrpc import ServiceHandler, ServiceException
class ServiceImplementaionNotFound(ServiceException):
pass
class ModPyServiceHandler(ServiceHandler):
def __init__(self, req):
self.req = req
ServiceHandler.__init__(self, None)
def findServiceEndpoint(self, name):
... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from horizon import messages
from openstack_dashboard.dashboards.monitor import monitor
from openstack_dashboard.dashboards.monitor.network_monitor import tables
class AddrBaseTab(tabs.TableTab):
name... |
"""
Script to push the zone configuration to Cisco SAN switches.
"""
import random
import re
from eventlet import greenthread
from oslo_concurrency import processutils
from oslo_log import log as logging
from oslo_utils import excutils
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
f... |
import re
def unwise1(w):
int1 = 0
result = ""
while int1 < len(w):
result = result + chr(int(w[int1:int1 + 2], 36))
int1 += 2
return result
def logblock(s):
if len(s)>12:
return "("+str(len(s))+") "+s[0:5]+"..."+s[-5:]
else:
return "("+str(len(s))+") "+s
def u... |
"""Command for creating target VPN Gateways."""
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import utils
class Create(base_classes.BaseAsyncCreator):
"""Create a VPN Gateway."""
# Placeholder to indicate that a detailed_help field exists and should
# be set outside the ... |
from __future__ import absolute_import
import unittest
from unittest import skipIf
import warnings
import numpy as np
try:
import pandas as pd
is_pandas = True
except ImportError as e:
is_pandas = False
from bokeh.models.sources import DataSource, ColumnDataSource
class TestColumnDataSource(unittest.Tes... |
data = (
'//', # 0x00
'/', # 0x01
',', # 0x02
'!', # 0x03
'!', # 0x04
'-', # 0x05
',', # 0x06
',', # 0x07
';', # 0x08
'?', # 0x09
'~', # 0x0a
'{', # 0x0b
'}', # 0x0c
'*', # 0x0d
'[?]', # 0x0e
'', # 0x0f
'\'', # 0x10
'', # 0x11
'b', # 0x12
'g', # 0x13
'g', #... |
#!/usr/bin/env python
'''
This software was created by United States Government employees at
The Center for the Information Systems Studies and Research (CISR)
at the Naval Postgraduate School NPS. Please note that within the
United States, copyright protection is not available for any works
created by United Sta... |
# class for handling standard operations against a file
import os
import loggenerator
import constants
import re
class FileOps():
def __init__(self, filename):
self.filename = filename
self.f = ''
def open(self):
self.f = open(self.filename, 'w')
def write(se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from actionlib import SimpleActionClient
from pnp_plugin_server.pnp_simple_plugin_server import PNPSimplePluginServer
from pepper_engage_human.msg import FindInteractantAction, FindInteractantResult
from pnp_msgs.msg import ActionResult
from pepper_move_base.... |
"""
Based on Parsedom for XBMC plugins
Copyright (C) 2010-2011 Tobias Ussing And Henrik Mosgaard Jensen
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,... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_array_equal, TestCase, run_module_suite, \
assert_array_almost_equal_nulp, assert_raises, assert_almost_equal
from scipy.special import gammaln, multigammaln
class TestMultiGammaLn(TestCase):
... |
import os
from oslo.config import cfg
from nova.openstack.common.gettextutils import _ # noqa
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
def get_container_rootfs(instance):
return os.path.join(CONF.instances_path, instance['uuid'], 'rootfs')
def get_... |
from django.template.defaultfilters import wordwrap
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class WordwrapTests(SimpleTestCase):
@setup({'wordwrap01':
'{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}'... |
from __future__ import absolute_import
from __future__ import division
from contextlib import contextmanager
from functools import wraps
import inspect
import six
import socket
import time
import threading
from vdsm.config import config
from vdsm.common.function import retry
from vdsm import jsonrpcvdscli
from vdsm.ne... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
"""Functions to compute receptive field of a fully-convolutional network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.receptive_field.python.util import graph_compute_order
from tensorflow.contrib.receptive_... |
from __future__ import absolute_import
from hashlib import sha256
import hmac
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from uuid im... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from pygithub3.services.base import Service
class Labels(Service):
""" Consume `Labels API
<http://developer.github.com/v3/issues/labels>`_ """
def list(self, user=None, repo=None):
""" Get repository's labels
:param str user: Username
... |
class PDBWriter(object):
header = 'REMARK stage {stage}'
footer = 'TER\nEND\n\n'
template = 'ATOM {atom_number:>5d} {atom_name:4s} {residue_name:>3s} {residue_number:5d} {x:8.3f}{y:8.3f}{z:8.3f}'
def __init__(self, atom_numbers, atom_names, residue_numbers, residue_names):
self._atom_number... |
"""This code example gets all activities.
To create activities, run create_activities.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section... |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
from .emitter import *
from .serializer import *
from .representer import *
from .resolver import *
class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
def __init__(self, stream,
default_style=None, default_flow_style=None,
... |
from pymongo import MongoClient
import numpy
mongoclient = MongoClient('127.0.0.1', 27017)
db = mongoclient.tweets
cursor = db.bitly_urls.find()
dataset = dict()
def main():
find_clicks()
find_encoders_count()
find_countries_clicks()
find_domain_clicks()
#dataset['http://bit.ly/2bjLLU3'] = [Fals... |
import json
import os
import pytest
import unittest
import urllib2
import uuid
import wptserve
from .base import TestUsingServer, doc_root
class TestFileHandler(TestUsingServer):
def test_GET(self):
resp = self.request("/document.txt")
self.assertEqual(200, resp.getcode())
self.assertEqual... |
# Authors: Travis Oliphant, Matthew Brett
"""
Base classes for MATLAB file stream reading.
MATLAB is a registered trademark of the Mathworks inc.
"""
from __future__ import division, print_function, absolute_import
import sys
import operator
from scipy._lib.six import reduce
import numpy as np
if sys.version_info... |
"""
Test the PowerOffCommand.
"""
from .. import PowerOffCommand
from .power_fixures import *
class MockStepUpdateResource(PowerOffCommand):
"""Fail resource update mocked object"""
def __init__(self, **args):
super(MockStepUpdateResource, self).__init__(**args)
def _update_resource_state(self, n... |
'''Stream Publisher
@summary: A Publisher in the Publish/Subscriber design pattern. This
publisher is aware of all instances created and calls update_observers
on each StreamPublisher.
@see: http://www.questrade.com/api/documentation/streaming
@copyright: 2016
@author: Peter Cinat
@license: Licens... |
import time
import sys
try:
import boto
import boto.ec2
import boto.vpc
from boto.exception import BotoServerError
HAS_BOTO=True
except ImportError:
HAS_BOTO=False
def boto_exception(err):
'''generic error message handler'''
if hasattr(err, 'error_message'):
error = err.error_m... |
# test set binary operations
sets = [set(), {1}, {1, 2}, {1, 2, 3}, {2, 3}, {2, 3, 5}, {5}, {7}]
for s in sets:
for t in sets:
print(sorted(s), '|', sorted(t), '=', sorted(s | t))
print(sorted(s), '^', sorted(t), '=', sorted(s ^ t))
print(sorted(s), '&', sorted(t), '=', sorted(s & t))
... |
"""
Better Code-Block Line Numbering Plugin
--------------------------
Authored by Jacob Levernier, 2014
Released under the BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
For more information on this plugin, please see the attached Readme.md file.
"""
from pelican import signals # For making this... |
from test import test_support, seq_tests
import gc
class TupleTest(seq_tests.CommonTest):
type2test = tuple
def test_constructors(self):
super(TupleTest, self).test_constructors()
# calling built-in types without argument must return empty
self.assertEqual(tuple(), ())
t0_3 = ... |
from unittest import mock
from oslotest import base
from monasca_api.common.rest import exceptions
from monasca_api.common.rest import utils
class TestRestUtils(base.BaseTestCase):
def setUp(self):
super(TestRestUtils, self).setUp()
self.mock_json_patcher = mock.patch('monasca_api.common.rest.u... |
#!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class patchutils(test.test):
"""
Autotest module for testing basic functionality
of patchutils
@author Gopal Kalita <<EMAIL>> ##
"""
ve... |
"""
Test server config in decorator.
"""
import json
from omero.testlib import ITest
from django.test import RequestFactory
from django.contrib.sessions.middleware import SessionMiddleware
from omeroweb.webclient import webclient_gateway # NOQA
from omero.gateway import BlitzGateway
from omeroweb.decorators import... |
"""Tests for create_cococameratraps_tfexample_main."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import json
import os
import tempfile
import unittest
import numpy as np
from PIL import Image
import tensorflow as tf
from object_detecti... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pytest
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import safe_r... |
import os
import uuid
from googleapiclient import (discovery, errors)
import common.google_error_helper as google_error_helper
# Name of the dataset.
BIGQUERY_DATASET = 'clovis_dataset'
# Name of the table used as a template for new tables.
BIGQUERY_TABLE_TEMPLATE = 'report'
def GetBigQueryService(credentials):
... |
'''Various utility functions
'''
from collections import Counter
from heapq import heappush, heappop, heapify
from struct import pack, unpack
import numpy as np
import re
def count_chars(s):
'''Count number of occurences of each char in str s'''
return Counter(s)
def count_digits(iterable, unsign = True, spl... |
import sys
from com.android.monkeyrunner import MonkeyRunner
# The format of the file we are parsing is very carfeully constructed.
# Each line corresponds to a single command. The line is split into 2
# parts with a | character. Text to the left of the pipe denotes
# which command to run. The text to the right of ... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcredits received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a creditsd or C... |
from test.picardtestcase import PicardTestCase
from picard.similarity import (
similarity,
similarity2,
)
class SimilarityTest(PicardTestCase):
def test_correct(self):
self.assertEqual(similarity("K!", "K!"), 1.0)
self.assertEqual(similarity("BBB", "AAA"), 0.0)
self.assertAlmostE... |
"""This script is wrapper for Chromium that adds some support for how GYP
is invoked by Chromium beyond what can be done in the gclient hooks.
"""
import argparse
import gc
import glob
import gyp_environment
import os
import re
import shlex
import subprocess
import string
import sys
import vs_toolchain
script_dir = o... |
import csv
import logging
import json
from django.core.management.base import BaseCommand, CommandError
logger = logging.getLogger("commands")
item_format = (" \"myuw_category\": \"{}\",\n" +
" \"location_tags\": {},\n" +
" \"critical\": {}")
class Command(BaseComma... |
"""Offer device oriented automation."""
import voluptuous as vol
from homeassistant.components.device_automation import (
TRIGGER_BASE_SCHEMA,
async_get_device_automation_platform,
)
from homeassistant.const import CONF_DOMAIN
# mypy: allow-untyped-defs, no-check-untyped-defs
TRIGGER_SCHEMA = TRIGGER_BASE_SC... |
"""Student's t distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from ten... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Integration test focused on the omero.api.IShare interface
a running server.
Copyright 2008-2014 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import time
import library as lib
import pytest
import... |
"""Constants used by multiple MQTT modules."""
from homeassistant.const import CONF_PAYLOAD
ATTR_DISCOVERY_HASH = "discovery_hash"
ATTR_DISCOVERY_PAYLOAD = "discovery_payload"
ATTR_DISCOVERY_TOPIC = "discovery_topic"
ATTR_PAYLOAD = "payload"
ATTR_QOS = "qos"
ATTR_RETAIN = "retain"
ATTR_TOPIC = "topic"
CONF_BROKER = "... |
data = (
'Yi ', # 0x00
'Ding ', # 0x01
'Kao ', # 0x02
'Qi ', # 0x03
'Shang ', # 0x04
'Xia ', # 0x05
'[?] ', # 0x06
'Mo ', # 0x07
'Zhang ', # 0x08
'San ', # 0x09
'Shang ', # 0x0a
'Xia ', # 0x0b
'Ji ', # 0x0c
'Bu ', # 0x0d
'Yu ', # 0x0e
'Mian ', # 0x0f
'Gai ', # 0x10
'Ch... |
from __future__ import unicode_literals
import webnotes
import json
import copy
@webnotes.whitelist()
def get_data(doctypes, last_modified):
from startup.report_data_map import data_map
import datetime
out = {}
doctypes = json.loads(doctypes)
last_modified = json.loads(last_modified)
start = datetime.dateti... |
from flask import Flask
from flask import request
from flask import render_template
from sqlalchemy import *
from sqlalchemy.orm import *
import geojson
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
#from geoalchemy import *
#from geoalchemy.spatialite import SQLiteComparator
#fr... |
from io import BytesIO
from stat import S_IFDIR, S_IFREG, S_IFLNK
from unittest.case import skipIf
from git.compat import PY3
from git.index import IndexFile
from git.index.fun import (
aggressive_tree_merge
)
from git.objects.fun import (
traverse_tree_recursive,
traverse_trees_recursive,
tree_to_stre... |
import logging
import random
import re
import urllib2
import obelisk
# Create new private key:
#
# $ sx newkey > key1
#
# Show private secret:
#
# $ cat key1 | sx wif-to-secret
#
# Show compressed public key:
#
# $ cat key1 | sx pubkey
#
# You will need 3 keys for buyer, seller and arbitrer
def build_output_inf... |
"""Poll module is ungraded xmodule used by students to
to do set of polls.
On the client side we show:
If student does not yet anwered - Question with set of choices.
If student have answered - Question with statistics for each answers.
"""
import cgi
import json
import logging
from copy import deepcopy
from collecti... |
#!/usr/bin/env python
import json
import boto3
cfn = boto3.client('cloudformation')
paginator = cfn.get_paginator('describe_stacks')
pages = paginator.paginate(StackName="antioch-prod")
details = {}
for page in pages:
for stack in page['Stacks']:
for output in stack['Outputs']:
details[output[... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that a builder without "multi" set can still be called multiple
times if the calls are the same.
"""
import TestSCons
test = TestSCons.TestSCons(match=TestSCons.match_re)
test.write('SConstruct', """
def build(env, target, source):
file = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.