code stringlengths 1 199k |
|---|
from .application_gateways_operations import ApplicationGatewaysOperations
from .express_route_circuit_authorizations_operations import ExpressRouteCircuitAuthorizationsOperations
from .express_route_circuit_peerings_operations import ExpressRouteCircuitPeeringsOperations
from .express_route_circuits_operations import ... |
from django.utils import timezone
from misago.users.models import Online
from misago.users.online.ranks import clear_ranks_online_cache
def mute_tracker(request):
request._misago_online_tracker = None
def start_tracking(request, user):
online_tracker = Online.objects.create(
user=user,
current_i... |
''' -- imports from python libraries -- '''
import os
import time
import datetime
''' imports from installed packages '''
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from optparse import make_option
try:
from bson import ObjectId
except ImportError: #... |
import os.path
data_dir = os.path.join(os.path.dirname(__file__), 'data')
bin_dir = os.path.join(os.path.dirname(__file__), 'bin') |
import copy
import tempest.common.generator.base_generator as base
import tempest.common.generator.valid_generator as valid
class NegativeTestGenerator(base.BasicGeneratorSet):
@base.generator_type("string")
@base.simple_generator
def gen_int(self, _):
return 4
@base.generator_type("integer")
... |
from metrics import Metric
from telemetry.value import scalar
class CpuMetric(Metric):
"""Calulates CPU load over a span of time."""
def __init__(self, browser):
super(CpuMetric, self).__init__()
self._results = None
self._browser = browser
self._start_cpu = None
def DidStartBrowser(self, browser)... |
from mrjob.job import MRJob
from mrjob.step import MRStep
import csv
cols = 'Name,JobTitle,AgencyID,Agency,HireDate,AnnualSalary,GrossPay'.split(",")
class salaryavg(MRJob):
def avgmapper(self, _, line):
row = dict(zip(cols, [ a.strip() for a in csv.reader([line]).next()]))
self.increment_counter("d... |
"""Deals with the socket communication between the PIMD and driver code.
Copyright (C) 2013, Joshua More and Michele Ceriotti
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 Li... |
"""Common objects shared by all _ps* modules."""
from __future__ import division
import errno
import functools
import os
import socket
import stat
try:
import threading
except ImportError:
import dummy_threading as threading
try:
import enum # py >= 3.4
except ImportError:
enum = None
from collections ... |
import pytest
from utils import conf
@pytest.fixture(scope="session")
def cfme_data(request):
return conf.cfme_data |
from collections import defaultdict, namedtuple
from ycm import vimsupport
import vim
class DiagnosticInterface( object ):
def __init__( self, user_options ):
self._user_options = user_options
# Line and column numbers are 1-based
self._buffer_number_to_line_to_diags = defaultdict(
lambda: defaultdi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'
}
DOCUMENTATION = '''
---
author: Ansible Core Team (@ansible)
module: import_role
short_description: Import a role into... |
import logging
import socket
import time
import threading
import types
from ws4py import WS_KEY, WS_VERSION
from ws4py.exc import HandshakeError, StreamClosed
from ws4py.streaming import Stream
from ws4py.messaging import Message, PongControlMessage
from ws4py.compat import basestring, unicode, dec
DEFAULT_READING_SIZE... |
from django.contrib.auth.models import User
from django.test import TestCase
from djangosaml2.backends import Saml2Backend
from testprofiles.models import TestProfile
class Saml2BackendTests(TestCase):
def test_update_user(self):
# we need a user
user = User.objects.create(username='john')
b... |
import netaddr
from neutron.common import utils
from neutron.openstack.common import log as logging
from neutron.plugins.nec.common import config
from neutron.plugins.nec.common import exceptions as nexc
from neutron.plugins.nec.db import api as ndb
from neutron.plugins.nec import drivers
LOG = logging.getLogger(__name... |
"""Python-based TensorFlow GRPC server.
Takes input arguments cluster_spec, job_name and task_id, and start a blocking
TensorFlow GRPC server.
Usage:
grpc_tensorflow_server.py --cluster_spec=SPEC --job_name=NAME --task_id=ID
Where:
SPEC is <JOB>(,<JOB>)*
JOB is <NAME>|<HOST:PORT>(;<HOST:PORT>)*
NAME is... |
""" In-Memory Disk File Interface for Swift Object Server"""
import time
import hashlib
from contextlib import contextmanager
from eventlet import Timeout
from six import moves
from swift.common.utils import Timestamp
from swift.common.exceptions import DiskFileQuarantined, DiskFileNotExist, \
DiskFileCollision, Di... |
from __future__ import unicode_literals
from six.moves.urllib.parse import parse_qs
from botocore.awsrequest import AWSPreparedRequest
from moto.elb.responses import ELBResponse
from moto.elbv2.responses import ELBV2Response
def api_version_elb_backend(*args, **kwargs):
"""
ELB and ELBV2 (Classic and Applicatio... |
import mock
from nova import db
from nova import exception
from nova.objects import aggregate
from nova.objects import service
from nova.openstack.common import timeutils
from nova.tests.objects import test_compute_node
from nova.tests.objects import test_objects
NOW = timeutils.utcnow().replace(microsecond=0)
fake_ser... |
"""
Regression for #9736.
Checks some pathological column naming to make sure it doesn't break
table creation or queries.
"""
from __future__ import unicode_literals
from django.db import models
class Article(models.Model):
Article_ID = models.AutoField(primary_key=True, db_column='Article ID')
headline = model... |
"""Get and manage Code Intelligence data about source code of many languages.
The Code Intelligence system is one for generating and managing code
structure information on given source code. See the spec for more details:
http://specs.tl.activestate.com/kd/kd-0100.html
General Usage
-------------
from codeintel... |
import numpy as np
import unittest
from . import test_connect_helpers as hf
from .test_connect_parameters import TestParams
class TestOneToOne(TestParams):
# specify connection pattern
rule = 'one_to_one'
conn_dict = {'rule': rule}
# sizes of populations
N = 6
N1 = N
N2 = N
N_array = 100... |
import re
from waflib import Utils
from waflib.Tools import fc,fc_config,fc_scan
from waflib.Configure import conf
from waflib.Tools.compiler_fc import fc_compiler
fc_compiler['linux'].insert(0, 'fc_open64')
@conf
def find_openf95(conf):
"""Find the Open64 Fortran Compiler (will look in the environment variable 'FC')"... |
"""
Tests for L{twisted.manhole.explorer}.
"""
from twisted.trial import unittest
from twisted.manhole.explorer import (
CRUFT_WatchyThingie,
ExplorerImmutable,
Pool,
_WatchMonkey,
)
class Foo:
"""
Test helper.
"""
class PoolTests(unittest.TestCase):
"""
Tests for the Pool class.... |
import six
SizeTieredCompactionStrategy = "SizeTieredCompactionStrategy"
LeveledCompactionStrategy = "LeveledCompactionStrategy"
CACHING_ALL = "ALL"
CACHING_KEYS_ONLY = "KEYS_ONLY"
CACHING_ROWS_ONLY = "ROWS_ONLY"
CACHING_NONE = "NONE"
class CQLEngineException(Exception):
pass
class ValidationError(CQLEngineExceptio... |
from django.contrib import admin
from tardis.apps.equipment.models import Equipment
admin.site.register(Equipment) |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed in t... |
import sys
from gnuradio import filter
try:
from PyQt4 import QtGui, QtCore
import sip
except ImportError:
print "Error: Program requires PyQt4."
sys.exit(1)
try:
from gnuradio.qtgui.plot_from import plot_form
except ImportError:
from plot_form import plot_form
class plot_spectrogram_form(plot_f... |
from os import path
from django.conf import settings
from openstack_dashboard.test import helpers as test
class ErrorPageTests(test.TestCase):
""" Tests for error pages """
urls = 'openstack_dashboard.test.error_pages_urls'
def test_500_error(self):
TEMPLATE_DIRS = (path.join(settings.ROOT_PATH, 'te... |
import numpy as np
import pandas as pd
from pandas.core.dtypes.common import (
is_scalar,
is_numeric_dtype,
is_decimal,
is_datetime_or_timedelta_dtype,
is_number,
_ensure_object)
from pandas.core.dtypes.generic import ABCSeries, ABCIndexClass
from pandas.core.dtypes.cast import maybe_downcast_to... |
"""Tests for session_bundle.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import shutil
import numpy as np
import tensorflow as tf
from tensorflow.contrib.session_bundle import constants
from tensorflow.contrib.session_bundle import ma... |
"""
The Natural Language Toolkit (NLTK) is an open source Python library
for Natural Language Processing. A free online book is available.
(If you use the library for academic research, please cite the book.)
Steven Bird, Ewan Klein, and Edward Loper (2009).
Natural Language Processing with Python. O'Reilly Media Inc... |
import sys
import util
from nltk.corpus.reader.util import *
from nltk.corpus.reader.api import *
class ChasenCorpusReader(CorpusReader):
def __init__(self, root, fileids, encoding=None, sent_splitter=None):
self._sent_splitter = sent_splitter
CorpusReader.__init__(self, root, fileids, encoding)
... |
"""
***************************************************************************
widgetPluginBase.py
---------------------
Date : June 2010
Copyright : (C) 2010 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
************************************... |
import os
import traceback
import mock
import yaml
from rally import api
from rally.common.plugin import discover
from rally.task import engine
from tests.unit import test
class RallyJobsTestCase(test.TestCase):
rally_jobs_path = os.path.join(
os.path.dirname(__file__), "..", "..", "..", "rally-jobs")
@... |
import uwsgi
from mako.template import Template
import time
def application(env, start_response):
start_response( '200 OK', [ ('Content-Type','text/html') ])
mytemplate = Template("<h1>I am Mako at ${thetime}</h1>")
uwsgi.green_schedule()
yield mytemplate.render(thetime = time.time() )
for i in range(1, 100):
my... |
"""Data structures to read recycle bin INFO2 files."""
from lf.dtypes import raw, LERecord
from lf.win.dtypes import DWORD, FILETIME_LE
__docformat__ = "restructuredtext en"
__all__ = [
"INFO2Header", "INFO2Item"
]
class INFO2Header(LERecord):
version = DWORD
unknown1 = DWORD
unknown2 = DWORD # Number ... |
import base64
import copy
from ansible.module_utils.six import iteritems, string_types
from keyword import kwlist
try:
from openshift.helper import PRIMITIVES
from openshift.helper.exceptions import KubernetesException
HAS_K8S_MODULE_HELPER = True
except ImportError as exc:
HAS_K8S_MODULE_HELPER = False... |
"""Support for IPMA weather service."""
from datetime import timedelta
import logging
import async_timeout
from pyipma.api import IPMA_API
from pyipma.location import Location
import voluptuous as vol
from homeassistant.components.weather import (
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_EXCEPTIONAL,
ATTR_COND... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'DataDictionary'
db.delete_table('odk_viewer_datadictionary')
def backwards(self, orm):
# Adding model 'Da... |
import sublime
import sublime_plugin
from os.path import basename
import re
BH_TABSTOPS = re.compile(r"(\$\{BH_(SEL|TAB)(?:\:([^\}]+))?\})")
TAB_REGION = "bh_plugin_wrapping_tabstop"
SEL_REGION = "bh_plugin_wrapping_select"
OUT_REGION = "bh_plugin_wrapping_outlier"
VALID_INSERT_STYLES = (
("inline", "Inline Insert"... |
"""
Automated tests for checking processing/storing large inputs.
"""
import logging
import unittest
import os
import itertools
import tempfile
import numpy as np
import gensim
def testfile():
# temporary data will be stored to this file
return os.path.join(tempfile.gettempdir(), 'gensim_big.tst')
class BigCorp... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import re
from calibre.ebooks.oeb.polish.container import OEB_STYLES, OEB_DOCS
from calibre.ebooks.oeb.normalize_css import no... |
import os, sys, re
verbose = 0
dcount = fcount = 0
maxfileload = 100000
blksize = 1024 * 8
def cpfile(pathFrom, pathTo, maxfileload=maxfileload):
"""
copy file pathFrom to pathTo, byte for byte
"""
if os.path.getsize(pathFrom) <= maxfileload:
bytesFrom = open(pathFrom, 'rb').read() # read smal... |
import sys
import os
from .. import *
from ..constants import *
from ..types import *
from ..util import *
from ctypes import *
def sections(elf, **kwargs):
i = None
ndx = 0 # we skip the first null section
if 'info' in kwargs:
if (isinstance(kwargs['info'], Elf_Scn)):
info = elf_ndxscn(kwargs['info'])
... |
__version__ = "1.1.6" |
from __future__ import unicode_literals
import codecs
import datetime
from decimal import Decimal
import locale
from django.utils.functional import Promise
from django.utils import six
from django.utils.six.moves.urllib.parse import quote
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *... |
"""BibIndexFilenameTokenizer: 'tokenizes' finds file names.
Tokenizer is adapted to work with bibfield and its get_record function.
"""
from invenio.bibindex_tokenizers.BibIndexRecJsonTokenizer import BibIndexRecJsonTokenizer
class BibIndexFilenameTokenizer(BibIndexRecJsonTokenizer):
"""
Tokenizes for fi... |
"""BibFormat element - Prints authors
"""
__revision__ = "$Id$"
import re
from urllib import quote
from cgi import escape
from invenio.config import CFG_BASE_URL, CFG_SITE_RECORD
from invenio.messages import gettext_set_language
from invenio.bibauthority_config import \
CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME, \... |
import array
import struct
import io
import warnings
from struct import unpack_from
from PIL import Image, ImageFile, TiffImagePlugin, _binary
from PIL.JpegPresets import presets
from PIL._util import isStringType
i8 = _binary.i8
o8 = _binary.o8
i16 = _binary.i16be
i32 = _binary.i32be
__version__ = "0.6"
def Skip(self,... |
import unittest
import os
import comm
import shutil
class TestCrosswalkApptoolsFunctions(unittest.TestCase):
def test_build_release(self):
comm.setUp()
comm.create(self)
os.chdir('org.xwalk.test')
buildcmd = comm.HOST_PREFIX + comm.PackTools + "crosswalk-app build release"
co... |
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.cli.demand
import tests.support
class DemandTest(tests.support.TestCase):
def test_bool_default(self):
demands = dnf.cli.demand.DemandSheet()
demands.resolving = True
self.assertTrue(demands.resolving)
... |
"""
Credit Application Configuration
"""
from django.apps import AppConfig
from django.conf import settings
from edx_proctoring.runtime import set_runtime_service
class CreditConfig(AppConfig):
"""
Default configuration for the "openedx.core.djangoapps.credit" Django application.
"""
name = u'openedx.co... |
from __future__ import with_statement
from nose.tools import assert_equal #@UnresolvedImport
from whoosh import fields, formats
from whoosh.compat import u
from whoosh.filedb.filestore import RamStorage
from whoosh.support.testing import TempIndex
def test_single_term():
schema = fields.Schema(text=fields.TEXT(vec... |
from nova import db
from nova import exception
from nova.objects import base
from nova.objects import fields
class EC2InstanceMapping(base.NovaPersistentObject, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'uuid': fields.UUIDField()... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: jenkins_plugin
author: Jiri Tyr (@jtyr)
version_added: '2.2'
sh... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'Post', fields ['post_type']
db.create_index('askbot_post', ['post_type'])
# Adding index on 'Post', fields [... |
"""Creates symlinks to native libraries for an APK.
The native libraries should have previously been pushed to the device (in
options.target_dir). This script then creates links in an apk's lib/ folder to
those native libraries.
"""
import optparse
import os
import sys
from util import build_device
from util import bui... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('jury', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='jury',
options={'verbose_name': 'Juri', 'verbose_nam... |
import re
import logging
from odoo import api, fields, models
from psycopg2 import IntegrityError
from odoo.tools.translate import _
_logger = logging.getLogger(__name__)
@api.model
def location_name_search(self, name='', args=None, operator='ilike', limit=100):
if args is None:
args = []
records = self... |
"""
Code to manage the creation and SQL rendering of 'where' constraints.
"""
import datetime
from django.utils import tree
from django.db.models.fields import Field
from django.db.models.query_utils import QueryWrapper
from datastructures import EmptyResultSet, FullResultSet
AND = 'AND'
OR = 'OR'
class EmptyShortCircu... |
from django.apps import AppConfig
from django.contrib.admin.checks import check_admin_app, check_dependencies
from django.core import checks
from django.utils.translation import gettext_lazy as _
class SimpleAdminConfig(AppConfig):
"""Simple AppConfig which does not do automatic discovery."""
default_auto_field... |
from __future__ import division, absolute_import, print_function
import os
import sys
import types
import re
import warnings
from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype
from numpy.core import ndarray, ufunc, asarray
import numpy as np
from numpy.compat import getargspec, formatargspec
__all... |
from xblock.fields import Scope
from contentstore.utils import get_modulestore
from cms.lib.xblock.mixin import CmsBlockMixin
class CourseMetadata(object):
'''
For CRUD operations on metadata fields which do not have specific editors
on the other pages including any user generated ones.
The objects have... |
"""
WSGI config for trydjango18 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... |
"""Test behavior of headers messages to announce blocks.
Setup:
- Two nodes:
- node0 is the node-under-test. We create two p2p connections to it. The
first p2p connection is a control and should only ever receive inv's. The
second p2p connection tests the headers sending logic.
- node1 is used to cr... |
"""Test cases for XLA devices."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.compiler.tests import xla_test
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.p... |
"""remove bigswitch port tracking table
Revision ID: 86cf4d88bd3
Revises: 569e98a8132b
Create Date: 2013-08-13 21:59:04.373496
"""
revision = '86cf4d88bd3'
down_revision = '569e98a8132b'
migration_for_plugins = [
'neutron.plugins.bigswitch.plugin.NeutronRestProxyV2'
]
from alembic import op
import sqlalchemy as sa
... |
import os
import subprocess
HUNTER_DIR='..'
PACKAGES_DIR=os.path.join(HUNTER_DIR, 'cmake/projects')
DOCS_PKG_DIR=os.path.join(HUNTER_DIR, 'docs', 'packages', 'pkg')
docs_filenames = [x for x in os.listdir(DOCS_PKG_DIR) if x.endswith('.rst')]
docs_entries = [x[:-4] for x in docs_filenames]
pkg_entries = [x for x in os.l... |
import math
import struct
from base64 import decodebytes
from tests.support.asserts import assert_png
def png_dimensions(screenshot):
assert_png(screenshot)
image = decodebytes(screenshot.encode())
width, height = struct.unpack(">LL", image[16:24])
return int(width), int(height) |
import base64
import BaseHTTPServer
import hashlib
import socket
import threading
import unittest
from telemetry.core.backends.chrome_inspector import websocket
class _FakeWebSocketHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
key = self.headers.getheader('Sec-WebSocket-Key')
value = key +... |
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doctype("Shipping Rule")
# default "calculate_based_on"
frappe.db.sql('''update `tabShipping Rule`
set calculate_based_on = "Net Weight"
where ifnull(calculate_based_on, '') = '' ''')
# default "shipping_rule_type"
frappe.db.sql... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: purefa_snap
version_added: '2.4'
short_description: Manage vol... |
"""Tests the initialization logic of django_util."""
import copy
import unittest
import django.conf
from django.conf.urls import include, url
from django.contrib.auth import models as django_models
from django.core import exceptions
import mock
from six.moves import reload_module
from oauth2client.contrib import django... |
"""
iri2uri
Converts an IRI to a URI.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = []
__version__ = "1.0.0"
__license__ = "MIT"
__history__ = """
"""
import urllib.parse
escape_range = [
(0xA0, 0xD7FF),
(0xE000, 0xF8FF),
(0xF900, 0xFD... |
import os
from upgrade_common import install_path, ccnet_dir, seafile_dir, upgrade_db, run_argv
def do_migrate_storage():
'''use seaf-migrate to migrate objects from the 2.1 layout to 3.0 layout'''
args = [
os.path.join(install_path, 'seafile', 'bin', 'seaf-migrate.exe'),
'-c', ccnet_dir,
... |
from django.contrib import messages
from django.test import TestCase, override_settings
from django.urls import reverse
class TestPageExplorer(TestCase):
@override_settings(MESSAGE_TAGS={
messages.DEBUG: 'my-custom-tag',
messages.INFO: 'my-custom-tag',
messages.SUCCESS: 'my-custom-tag',
... |
"""
Test for import machinery
"""
import unittest
import sys
import textwrap
import subprocess
import os
from modulegraph import modulegraph
class TestNativeImport (unittest.TestCase):
# The tests check that Python's import statement
# works as these tests expect.
def importModule(self, name):
if '.... |
"""
Please write tests for all code submitted to the repository. The code will be
used by many people, and will in due course be used in live analyses, so we
need to make sure that we have the best possible defenses against bugs. It also
helps us think about code interfaces, and gives examples of code use that can
be u... |
"""
pygments.filter
~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def apply_filters(stream, filters, lexer=None):
"""
Use this method to apply an iterable of filters to... |
from sympy.strategies.tree import (treeapply, treeapply, greedy, allresults,
brute)
from sympy.core.compatibility import reduce
from functools import partial
def test_treeapply():
tree = ([3, 3], [4, 1], 2)
assert treeapply(tree, {list: min, tuple: max}) == 3
add = lambda *args: sum(args)
mul = ... |
import sys
tests=[
("testExecs/main.exe","",{}),
("python","test_list.py",{'dir':'Wrap'}),
]
longTests=[
]
if __name__=='__main__':
import sys
from rdkit import TestRunner
failed,tests = TestRunner.RunScript('test_list.py',0,1)
sys.exit(len(failed)) |
import os
from telemetry import test as test_module
from telemetry.core import util
from telemetry.page import page_set
from telemetry.page import page_test
data_path = os.path.join(
util.GetChromiumSrcDir(), 'content', 'test', 'data', 'gpu')
wait_timeout = 20 # seconds
harness_script = r"""
var domAutomationCon... |
"""Registration and usage mechanisms for KL-divergences."""
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 array_ops
from tensorflow.python.ops import control_flow_ops
from tensorf... |
from __future__ import unicode_literals
import webnotes
@webnotes.whitelist()
def get_funnel_data(from_date, to_date):
active_leads = webnotes.conn.sql("""select count(*) from `tabLead`
where (date(`modified`) between %s and %s)
and status != "Do Not Contact" """, (from_date, to_date))[0][0]
active_leads += webno... |
import subprocess, os
import SCons.Errors, SCons.Warnings
import SCons.Util
class UnpackWarning(SCons.Warnings.Warning) :
pass
SCons.Warnings.enableWarningClass(UnpackWarning)
def __fileextractor_nix_tar( env, count, no, i ) :
return i.split()[-1]
def __fileextractor_nix_gzip( env, count, no, i ) :
if no ==... |
from ._mod1_0_1_0_1_0 import *
from ._mod1_0_1_0_1_1 import *
from ._mod1_0_1_0_1_2 import *
from ._mod1_0_1_0_1_3 import *
from ._mod1_0_1_0_1_4 import * |
'''The 'grit resize' tool.
'''
import getopt
import os
from grit import grd_reader
from grit import pseudo
from grit import util
from grit.format import rc
from grit.format import rc_header
from grit.node import include
from grit.tool import interface
PROJECT_TEMPLATE = '''\
<?xml version="1.0" encoding="Windows-1252"?... |
from nose.plugins.attrib import attr
from checks import AgentCheck
from tests.checks.common import AgentCheckTest
@attr(requires='apache')
class TestCheckApache(AgentCheckTest):
CHECK_NAME = 'apache'
CONFIG_STUBS = [
{
'apache_status_url': 'http://localhost:8080/server-status',
'... |
from openerp.osv import fields
from openerp.osv import osv
import base64
from openerp.tools.translate import _
class base_report_designer_installer(osv.osv_memory):
_name = 'base_report_designer.installer'
_inherit = 'res.config.installer'
def default_get(self, cr, uid, fields, context=None):
data =... |
import os
import re
import sys
def GetDefaultConcurrentLinks():
# Inherit the legacy environment variable for people that have set it in GYP.
pool_size = int(os.getenv('GYP_LINK_CONCURRENCY', 0))
if pool_size:
return pool_size
if sys.platform in ('win32', 'cygwin'):
import ctypes
class MEMORYSTATUSE... |
nplurals=3 # Ukrainian language has 3 forms:
# 1 singular and 2 plurals
get_plural_id = lambda n: (0 if n % 10 == 1 and n % 100 != 11 else
1 if n % 10 >= 2 and n % 10 <= 4 and
(n % 100 < 10 or n % 100 >= 20) else
2) |
from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from alphanumeric.models import Product
class ProductResource(ModelResource):
class Meta:
resource_name = 'products'
queryset = Product.objects.all()
authorizat... |
"""Provides generic text views
This modules provides several generic views for
serializing models into human-readable text.
"""
import collections as col
import six
class MultiView(object):
"""A Text View Containing Multiple Views
This view simply serializes each
value in the data model, and then
joins ... |
"""
Tests course_creators.views.py.
"""
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.test import TestCase, RequestFactory
from course_creators.views import add_user_with_status_unrequested, add_user_with_status_granted
from course_creators.views import get_... |
from http.client import HTTPConnection
import json
import re
import base64
import sys
import os
import os.path
settings = {}
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[:... |
"""
This module defines functions to implement HTTP Digest Authentication (:rfc:`2617`).
This has full compliance with 'Digest' and 'Basic' authentication methods. In
'Digest' it supports both MD5 and MD5-sess algorithms.
Usage:
First use 'doAuth' to request the client authentication for a
certain resource. You... |
from yowsup.layers import YowLayer
import logging
logger = logging.getLogger(__name__)
class YowLoggerLayer(YowLayer):
def send(self, data):
ldata = list(data) if type(data) is bytearray else data
logger.debug("tx:\n%s" % ldata)
self.toLower(data)
def receive(self, data):
ldata =... |
import json
from social.tests.backends.oauth import OAuth2Test
class WunderlistOAuth2Test(OAuth2Test):
backend_path = 'social.backends.wunderlist.WunderlistOAuth2'
user_data_url = 'https://a.wunderlist.com/api/v1/user'
expected_username = '12345'
access_token_body = json.dumps({
'access_token': ... |
def mediaFeatureSymbol(entry, suffix):
name = entry['name']
if name.startswith('-webkit-'):
name = name[8:]
foundDash = False
newName = ""
for chr in name:
if chr == '-':
foundDash = True
continue
if foundDash:
chr = chr.upper()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.