content string |
|---|
import os
import unittest
from marionette import MarionetteTestCase
from marionette_driver.addons import Addons, AddonInstallException
here = os.path.abspath(os.path.dirname(__file__))
class TestAddons(MarionetteTestCase):
def setUp(self):
MarionetteTestCase.setUp(self)
self.addons = Addons(self... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ..module_utils.tower_api import TowerAPIModule
KIND_CHOICES = {
'ssh': 'Machine',... |
#
# On Unix we run a server process which keeps track of unlinked
# semaphores. The server ignores SIGINT and SIGTERM and reads from a
# pipe. Every other process of the program has a copy of the writable
# end of the pipe, so we get EOF when all other processes have exited.
# Then the server process unlinks any remai... |
# -*- coding: utf-8 -*-
import os
import re
from module.PyFile import PyFile
from module.plugins.internal.Plugin import Plugin
class ArchiveError(Exception):
pass
class CRCError(Exception):
pass
class PasswordError(Exception):
pass
class Extractor(Plugin):
__name__ = "Extractor"
__type_... |
"""Utilities used in autograph-generated code."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import tensor_util
def is_tensor(*args):
"""Check if any arguments are tensors.
Args:
*args: Python objects that ma... |
#!/usr/bin/env python3
# coding: utf-8
import argparse
import configparser
import logging
import time
import re
import datetime
import serial
import influxdb
SERIAL_RETRY_DELAY = 5.0
logger = logging.getLogger('s2i')
def parse_args_and_config(args):
parser = argparse.ArgumentParser(description='ambient7 - ser... |
import msgpack
import gevent.pool
import gevent.queue
import gevent.event
import gevent.local
import gevent.lock
import gevent_zmq as zmq
from .context import Context
class Sender(object):
def __init__(self, socket):
self._socket = socket
self._send_queue = gevent.queue.Channel()
self._... |
"""Utility functions relating DataFrames to Estimators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.layers import feature_column
from tensorflow.contrib.learn.python.learn.dataframe import series as ss
from tensorflow.python.f... |
from collections import MutableMapping
try:
from threading import RLock
except ImportError: # Platform-specific: No threads available
class RLock:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
pass
try: # Python 2.7+
from collections... |
"""utility classes for the Builder
"""
from __future__ import absolute_import, division, print_function
import os
from builtins import object
from wx.lib.agw.aui.aui_constants import *
from wx.lib.agw.aui.aui_utilities import IndentPressedBitmap, ChopText, TakeScreenShot
import sys
import wx
import wx.lib.agw.aui as... |
from mox import IsA # noqa
from django.core.urlresolvers import reverse # noqa
from django.core.urlresolvers import reverse_lazy # noqa
from django import http
from openstack_dashboard import api
from openstack_dashboard.api import fwaas
from openstack_dashboard.test import helpers as test
class FirewallTests(te... |
from __future__ import absolute_import, division, print_function, unicode_literals
import queue
import sys
import threading
import traceback
from builtins import map, object, str
from collections import defaultdict, deque
from heapq import heappop, heappush
from pants.base.worker_pool import Work
class Job(object):... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pants.backend.jvm.tasks.jvmdoc_gen import Jvmdoc, JvmdocGen
from pants.base.exceptions import TaskError
from pants_test.jvm.jvm_task_test_base import JvmTaskTestBase
dummydoc = Jvmdoc(tool_name='dummydoc', product_type... |
#!/usr/bin/env python
# coding:utf-8
import os
import time
import urllib.parse
import simple_http_server
from .front import front
current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir))
top_path = os.path.abspath(os.path.join(root_path... |
"""
Creates the default Site object.
"""
from django.db.models import signals
from django.db import connections
from django.db import router
from django.contrib.sites.models import Site
from django.contrib.sites import models as site_app
from django.core.management.color import no_style
def create_default_site(app, c... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
)
from ..utils import (
unified_strdate,
)
class UrortIE(InfoExtractor):
IE_DESC = 'NRK P3 Urørt'
_VALID_URL = r'https?://(?:www\.)?urort\.p3\.no/#!/Band/(?P<id>[^/]+)... |
from . import constants
from .charsetprober import CharSetProber
from .codingstatemachine import CodingStateMachine
from .mbcssm import UTF8SMModel
ONE_CHAR_PROB = 0.5
class UTF8Prober(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(UTF8SMMode... |
from mako import compat
from mako.lookup import TemplateLookup
from mako.template import Template
class TGPlugin(object):
"""TurboGears compatible Template Plugin."""
def __init__(self, extra_vars_func=None, options=None, extension='mak'):
self.extra_vars_func = extra_vars_func
self.extensio... |
from cloudbaseinit.openstack.common.gettextutils import _
from cloudbaseinit.openstack.common import log as logging
from cloudbaseinit.openstack.common.notifier import rpc_notifier
LOG = logging.getLogger(__name__)
def notify(context, message):
"""Deprecated in Grizzly. Please use rpc_notifier instead."""
L... |
data = (
'dyil', # 0x00
'dyilg', # 0x01
'dyilm', # 0x02
'dyilb', # 0x03
'dyils', # 0x04
'dyilt', # 0x05
'dyilp', # 0x06
'dyilh', # 0x07
'dyim', # 0x08
'dyib', # 0x09
'dyibs', # 0x0a
'dyis', # 0x0b
'dyiss', # 0x0c
'dying', # 0x0d
'dyij', # 0x0e
'dyic', # 0x0f
'dyik', # ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:... |
"""Connection pooling for psycopg2
This module implements thread-safe (and not) connection pools.
"""
# psycopg/pool.py - pooling code for psycopg
#
# Copyright (C) 2003-2010 Federico Di Gregorio <<EMAIL>>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Gene... |
"""Make sure we're using the fastest backend available"""
from openpyxl import LXML
try:
from xml.etree.cElementTree import Element as cElement
C = True
except ImportError:
C = False
try:
from lxml.etree import Element as lElement
except ImportError:
lElement is None
from xml.etree.ElementTree i... |
from onl.platform.base import OpenNetworkPlatformBase, sysinfo
import struct
import time
class OpenNetworkPlatformQEMU(OpenNetworkPlatformBase):
def manufacturer(self):
return "QEMU"
def _sys_info_dict(self):
return {
sysinfo.MAGIC : 0,
sysinfo.PRODUCT_NAME : "QEMU E... |
from tests.compat import OrderedDict
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase
from boto.vpc import VPCConnection, CustomerGateway
class TestDescribeCustomerGateways(AWSMockServiceTestCase):
connection_class = VPCConnection
def default_body(self):
return b"""
... |
# -*- coding: utf-8 -*-
"""Interpret PEP 345 environment markers.
EXPR [in|==|!=|not in] EXPR [or|and] ...
where EXPR belongs to any of those:
python_version = '%s.%s' % (sys.version_info[0], sys.version_info[1])
python_full_version = sys.version.split()[0]
os.name = os.name
sys.platform = sys.platfo... |
"""Write worksheets to xml representations in an optimized way"""
import datetime
import os
from ..cell import column_index_from_string, get_column_letter, Cell
from ..worksheet import Worksheet
from ..shared.xmltools import XMLGenerator, get_document_content, \
start_tag, end_tag, tag
from ..shared.date_time... |
"""Verifies that a list of libraries is installed on the system.
Takes a a list of arguments with every two subsequent arguments being a logical
tuple of (path, check_soname). The path to the library and either True or False
to indicate whether to check the soname field on the shared library.
Example Usage:
./check_c... |
# strip out a set of nuisance html attributes that can mess up rendering in RSS feeds
import re
from lxml.html.clean import Cleaner
bad_attrs = ['style', '[-a-z]*color', 'background[-a-z]*', 'on*']
single_quoted = "'[^']+'"
double_quoted = '"[^"]+"'
non_space = '[^ "\'>]+'
htmlstrip = re.compile("<" # open
"([^>]+... |
from typing import Dict, Optional, Union
from polyaxon.k8s import k8s_schemas
def sanitize_resources(
resources: Union[k8s_schemas.V1ResourceRequirements, Dict]
) -> Optional[k8s_schemas.V1ResourceRequirements]:
def validate_resources(r_field: Dict) -> Dict:
if not r_field:
return r_field... |
"""
SMTP gateway tests.
"""
import re
from copy import deepcopy
from StringIO import StringIO
from email.parser import Parser
from datetime import datetime
from twisted.internet.defer import fail
from twisted.mail.smtp import User
from twisted.python import log
from mock import Mock
from leap.bitmask.mail.rfc3156 imp... |
import os
from setuptools import setup, find_packages
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
# Use the docstring ... |
"""
Markdown Extension for Liquid-style Tags
----------------------------------------
A markdown extension to allow user-defined tags of the form::
{% tag arg1 arg2 ... argn %}
Where "tag" is associated with some user-defined extension.
These result in a preprocess step within markdown that produces
either markdo... |
"""Composer Extension
Downloads, installs and runs Composer.
"""
import os
import os.path
import sys
import logging
import re
import json
import StringIO
from build_pack_utils import utils
from build_pack_utils import stream_output
from extension_helpers import ExtensionHelper
_log = logging.getLogger('composer')
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.auth.models
from django.core import validators
from django.db import migrations, models
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__first__'),
]
... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import sys;
import os;
sys.path.append("allinpay projects")
from creditscore.creditscore import CreditScore
import numpy as np
import pandas as pd
import time
from sklearn.model_selection import train_test_split
from sklearn.linear_model ... |
#!/usr/bin/env python
import re, sys, operator, os
code_line = re.compile("^\s*\d+:/")
frame_line = re.compile("^\s*\d+\s+/\* frame size = (\d+) \*/")
class frame(object):
def __init__(self, code, frame_size):
self.code = code
self.frame_size = int(frame_size)
frames = []
def process_lst(filena... |
__author__ = 'surchs'
import sys
import numpy as np
from matplotlib import gridspec
from nilearn import plotting as nlp
from matplotlib import pyplot as plt
from matplotlib import colors as mpc
def add_subplot_axes(ax, rect, axisbg='w'):
fig = plt.gcf()
box = ax.get_position()
width = box.width
height... |
from outsourcer import Code
from . import utils
from .base import Expression
from .constants import POS, RESULT, STATUS, TEXT
class Str(Expression):
is_commented = False
def __init__(self, value):
if not isinstance(value, (bytes, str)):
raise TypeError(f'Expected bytes or str. Received: ... |
import numpy as np
from bokeh.models import HoverTool
from bokeh.plotting import ColumnDataSource, figure, output_file, show
from bokeh.sampledata.unemployment1948 import data
# Read in the data with pandas. Convert the year column to string
data['Year'] = [str(x) for x in data['Year']]
years = list(data['Year'])
mon... |
def HelloWorldPython( ):
"""Prints the string 'Hello World(in Python)' into the current document"""
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
#check whether there's already an opened document. Ot... |
import arcpy
import os, json
def makeFeature(geo, wkid):
sr = arcpy.SpatialReference(wkid);
arcpy.CreateFeatureclass_management('in_memory', 'tmpPoly', POLYGON,'#','#','#',sr)
fc = os.path.join('in_memory', 'tmpPoly')
fields = ["SHAPE@"]
insert = arcpy.da.InsertCursor(fc, fields)
insert.insertR... |
"""
Authors: Tim Bedin, Tim Erwin
Copyright 2014 CSIRO
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 applicable law or agreed to in w... |
# -*- coding: utf-8 -*-
from pyknyx.core.dptXlator.dptXlator2ByteFloat import *
import unittest
# Mute logger
from pyknyx.services.logger import logging
logger = logging.getLogger(__name__)
logging.getLogger("pyknyx").setLevel(logging.ERROR)
class DPTXlator2ByteFloatTestCase(unittest.TestCase):
def setUp(self):... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'Y年n月j日' # 2016年9月5日
TIME_FORMAT = 'H:i' # 20:45
DATETIME_FORMAT = 'Y年n月j日 H:i' # 2016年9月5日 2... |
from nova.network.security_group import neutron_driver
from nova.tests.integrated.v3 import test_servers
def fake_get(*args, **kwargs):
nova_group = {}
nova_group['id'] = 'fake'
nova_group['description'] = ''
nova_group['name'] = 'test'
nova_group['project_id'] = 'fake'
nova_group['rules'] = [... |
import traceback
import re
import datetime
import time
from requests.auth import AuthBase
import sickbeard
import generic
import requests
from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import show_name_helpers
from sickbeard import db
from sickbeard impo... |
#!/usr/bin/env python3
import unittest
import django.test
from varapp.data_models.users import *
from varapp.models.users import *
from django.conf import settings
class TestUser(unittest.TestCase):
def test_user_constructor(self):
s = User('A', 'a@a', 'code', '', 1, Person(firstname='A'), Role('guest'))
... |
from __future__ import division, print_function
import sys
import heapq
import timeplot
from optparse import OptionParser
class QItem(object):
def __init__(self, parent, parent_get, parent_push):
self.parent = parent
self.size = 1
self.finish = 0.0
self.parent_get = parent_get
... |
'''SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested wi... |
import gc
import sys
from ryu.services.protocols.bgp.operator.command import Command
from ryu.services.protocols.bgp.operator.command import CommandsResponse
from ryu.services.protocols.bgp.operator.command import STATUS_ERROR
from ryu.services.protocols.bgp.operator.command import STATUS_OK
class Memory(Command):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def create_translation_memory_entries(apps, schema):
Translation = apps.get_model('base', 'Translation')
TranslationMemoryEntry = apps.get_model('base', 'TranslationMemoryEntry')
def get_memory_entry(... |
from odoo import api, fields, models, _
from odoo.tools import html2plaintext
class Stage(models.Model):
_name = "note.stage"
_description = "Note Stage"
_order = 'sequence'
name = fields.Char('Stage Name', translate=True, required=True)
sequence = fields.Integer(help="Used to order the note sta... |
#
# distutils/version.py
#
# Implements multiple version numbering conventions for the
# Python Module Distribution Utilities.
#
# $Id$
#
"""Provides classes to represent module version numbers (one class for
each style of version numbering). There are currently two such classes
implemented: StrictVersion ... |
"""Tests the graph freezing tool."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from tensorflow.core.example import example_pb2
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import saver_pb2
from ten... |
import socket
import struct
import dns.ipv4
import dns.rdata
_proto_tcp = socket.getprotobyname('tcp')
_proto_udp = socket.getprotobyname('udp')
class WKS(dns.rdata.Rdata):
"""WKS record
@ivar address: the address
@type address: string
@ivar protocol: the protocol
@type protocol: int
@ivar b... |
"""
test batched_dot behaviors between NervanaCPU, and NervanaGPU backend
against numpy.
In NervanaGPU, it supports both N as inside dimension or as outer dimension.
In NervanaCPU, it only supports N as inside dimension, since this is what we use.
"""
import numpy as np
from neon.backends.nervanagpu import NervanaGPU
... |
from django.core import checks
from django.db.backends import BaseDatabaseValidation
class DatabaseValidation(BaseDatabaseValidation):
def check_field(self, field, **kwargs):
"""
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255... |
"""Tests for StringToNumber op from parsing_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.pyth... |
# -*- coding: utf-8 -*-
from fabric.api import *
from cabric.cmd import cmd_expanduser,cmd_su
import os
def put_public_key(path=None, user=None):
"""
Upload pub key from remote server.
Limit: Openssh standard key,must comment with user mail.
:param path:local path
:param user:remote username
... |
import os
from os.path import join, normcase, normpath, abspath, isabs, sep
from django.utils.encoding import force_unicode
# Define our own abspath function that can handle joining
# unicode paths to a current working directory that has non-ASCII
# characters in it. This isn't necessary on Windows since the
# Wind... |
"""
Tests common to list and UserList.UserList
"""
import sys
import os
from functools import cmp_to_key
from test import support, seq_tests
class CommonTest(seq_tests.CommonTest):
def test_init(self):
# Iterable arg is optional
self.assertEqual(self.type2test([]), self.type2test())
# ... |
import unittest
from pychess.Savers import pgn
from pychess.Utils.lutils import ldraw
class DrawTestCase(unittest.TestCase):
def setUp(self):
with open('gamefiles/3fold.pgn') as f1:
self.PgnFile1 = pgn.load(f1)
with open('gamefiles/bilbao.pgn') as f2:
self.PgnFil... |
from django.contrib.sites.models import Site
import mock
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
class OpenSearchTestCase(TestCase):
"""Test the SUMO OpenSearch plugin."""
@mock.patch.object(Site.objects, 'get_current')
def test_p... |
"""VLAN network link
"""
from __future__ import absolute_import
from ... import core as netlink
from .. import capi as capi
class VLANLink(object):
def __init__(self, link):
self._link = link
@property
@netlink.nlattr(type=int)
def id(self):
"""vlan identifier"""
return cap... |
import eventlet
import six
from collections import defaultdict
from kombu import Connection
from st2common.query.base import QueryContext
from st2common import log as logging
from st2common.models.db.executionstate import ActionExecutionStateDB
from st2common.persistence.executionstate import ActionExecutionState
fro... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .subtitles import SubtitlesInfoExtractor
from ..utils import (
xpath_text,
int_or_none,
)
class WallaIE(SubtitlesInfoExtractor):
_VALID_URL = r'http://vod\.walla\.co\.il/[^/]+/(?P<id>\d+)/(?P<display_id>.+)'
_TEST = {
'ur... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback.default import CallbackModule as CallbackModule_default
class CallbackModule(CallbackModule_default):
'''
This is the default callback interface, which simply prints messages
to stdout w... |
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
PYLINT_BLACKLIST = [
# TODO: fix me.
# From SCons, not done in google style.
'test/lib/TestCmd.py',
'test/lib/TestCommon.py',... |
#!/usr/bin/python
"""
::
This experiment is used to study........
"""
from __future__ import print_function
from PSL_Apps.utilitiesClass import utilitiesClass
from PSL_Apps.templates import ui_template_graph_nofft as template_graph_nofft
import numpy as np
from PyQt4 import QtGui,QtCore
import pyqtgraph as p... |
__revision__ = "$Id$"
import types, warnings
from Crypto.Util.number import *
# Basic public key class
class pubkey:
"""An abstract class for a public key object.
:undocumented: __getstate__, __setstate__, __eq__, __ne__, validate
"""
def __init__(self):
pass
def __getstate__(self):
... |
# coding=utf-8
"""
Emulate a gmetric client for usage with
[Ganglia Monitoring System](http://ganglia.sourceforge.net/)
"""
from Handler import Handler
import logging
try:
import gmetric
except ImportError:
gmetric = None
class GmetricHandler(Handler):
"""
Implements the abstract Handler class, send... |
"""Representation for the MongoDB internal MinKey type.
"""
class MinKey(object):
"""MongoDB internal MinKey type.
.. versionchanged:: 2.7
``MinKey`` now implements comparison operators.
"""
_type_marker = 255
def __eq__(self, other):
return isinstance(other, MinKey)
def __h... |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""),... |
# pylint: skip-file
# flake8: noqa
class Edit(OpenShiftCLI):
''' Class to wrap the oc command line tools
'''
# pylint: disable=too-many-arguments
def __init__(self,
kind,
namespace,
resource_name=None,
kubeconfig='/etc/origin/master/ad... |
import json
import os
import tarfile
import time
from contextlib import closing
from datetime import datetime
import requests
def get_dict_from_file(file_name):
with open(file_name, 'r', encoding='utf-8') as f:
json_info = json.load(f)
return json_info
class Base(object):
def __init__(self, ser... |
from django import forms
from django.forms.widgets import HiddenInput
from crits.campaigns.campaign import Campaign
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_item_names
class AddCampaignForm(forms.Form):
"""
Django form for adding a new Campaig... |
####
#### Steps for operating on the various forms and their results.
####
from behave import *
###
### radio button click
###
@given('I click the "{id}" radio button')
def step_impl(context, id):
webelt = context.browser.find_element_by_id(id)
webelt.click()
###
### Submission.
###
## Submit analyze pheno... |
import os.path as op
import warnings
import numpy as np
from numpy.testing import assert_raises
from mne import (io, read_events, read_cov, read_source_spaces, read_evokeds,
read_dipole, SourceEstimate)
from mne.datasets import testing
from mne.minimum_norm import read_inverse_operator
from mne.viz i... |
from django.db.models.fields import Field
from django.db.models.sql.expressions import SQLEvaluator
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis import forms
from django.contrib.gis.db.models.proxy import GeometryProxy
from django.contrib.gis.geometry.backend import Geometry, Geometry... |
import time, sys, os, shutil, subprocess, distutils.dir_util
sys.path.append("../../configuration")
if os.path.isfile("log.log"):
os.remove("log.log")
log = open("log.log", "w")
from scripts import *
from buildsite import *
from process import *
from tools import *
from directories import *
printLog(log, "")
printLo... |
"""Util functions and classes for cloudstorage_api."""
__all__ = ['set_default_retry_params',
'RetryParams',
]
import copy
import httplib
import logging
import math
import os
import threading
import time
import urllib
try:
from google.appengine.api import app_identity
from google.appengin... |
"""
Bing (Images)
@website https://www.bing.com/images
@provide-api yes (http://datamarket.azure.com/dataset/bing/search),
max. 5000 query/month
@using-api no (because of query limit)
@results HTML (using search portal)
@stable no (HTML can change)
@parse url, title, img_src
... |
"""
User community signals - useful for hooking into the community
creation process.
"""
from blinker import Namespace
_signals = Namespace()
before_save_collection = _signals.signal('before-save-collection')
"""
This signal is sent right before collection is saved.
Sender is the community. Extra data pass is:
* is... |
import BoostBuild
t = BoostBuild.Tester(use_test_config=False)
t.write("jamroot.jam", "")
t.write("lib/c.cpp", "int bar() { return 0; }\n")
t.write("lib/jamfile.jam", """\
static-lib auxilliary1 : c.cpp ;
lib auxilliary2 : c.cpp ;
""")
def reset():
t.rm("lib/bin")
t.run_build_system(subdir='lib')
t.expect_additi... |
import _layers
import coremltools as _coremltools
import coremltools.models.datatypes as _datatypes
from coremltools.models import neural_network as _neural_network
import json as _json
import mxnet as _mxnet
import numpy as _np
_MXNET_LAYER_REGISTRY = {
'FullyConnected' : _layers.convert_dense,
'Activation'... |
'''Extract Opencl source code into c++ strings, for runtime use.
This file is executed only if .cl files are updated.
It is executed in the ROOT folder of SINGA source repo.
'''
from future.utils import iteritems
distribution = "./src/core/tensor/distribution.cl"
tensormath = "./src/core/tensor/tensor_math_opencl.cl"... |
import BaseHTTPServer
import json
import os.path
import thread
import urlparse
DOC_DIR = os.path.join(os.path.dirname(__file__), 'mmap_app')
class Server(BaseHTTPServer.HTTPServer):
def __init__(self, handler, address='', port=9999, module_state=None):
BaseHTTPServer.HTTPServer.__init__(self, (address, port), ... |
import argparse
from collections import OrderedDict
import sys
from common_includes import *
def IsSvnNumber(rev):
return rev.isdigit() and len(rev) < 8
class Preparation(Step):
MESSAGE = "Preparation."
def RunStep(self):
if os.path.exists(self.Config("ALREADY_MERGING_SENTINEL_FILE")):
if self._opti... |
"""View to accept incoming websocket connection."""
import asyncio
from contextlib import suppress
from functools import partial
import json
import logging
from aiohttp import web, WSMsgType
import async_timeout
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback
from home... |
from openerp import tools
from openerp.osv import fields,osv
class analytic_entries_report(osv.osv):
_name = "analytic.entries.report"
_description = "Analytic Entries Statistics"
_auto = False
_columns = {
'date': fields.date('Date', readonly=True),
'user_id': fields.many2one('res.user... |
"""SCons.Tool.ipkg
Tool-specific initialization for ipkg.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
The ipkg tool calls the ipkg-build. Its only argument should be the
packages fake_root.
"""
#
# Copyrigh... |
'''
Custom exceptions raised by pytz.
'''
__all__ = [
'UnknownTimeZoneError', 'InvalidTimeError', 'AmbiguousTimeError',
'NonExistentTimeError',
]
class UnknownTimeZoneError(KeyError):
'''Exception raised when pytz is passed an unknown timezone.
>>> isinstance(UnknownTimeZoneError(), LookupError)... |
def makeCompatible(expr):
'''Used by convertExpression to convert logical operators to english words.'''
expr = expr.replace('~&', ' NAND ')
expr = expr.replace('~|', ' NOR ')
expr = expr.replace('~^', ' XNOR ')
expr = expr.replace('&', ' AND ')
expr = expr.replace('|', ' OR ')
expr = expr.r... |
"""## Functions for working with arbitrarily nested sequences of elements.
NOTE(mrry): This fork of the `tensorflow.python.util.nest` module
makes two changes:
1. It removes support for lists as a level of nesting in nested structures.
2. It adds support for `SparseTensorValue` as an atomic element.
The motivation f... |
import os
import sys
import pwd
import socket
import json
auth_token = None
def rpc(name, args):
sock = socket.socket(socket.AF_UNIX)
sock.connect('/var/run/pam_ssh.sock')
f = sock.makefile('r+')
f.write(json.dumps([name, args]) + '\n')
f.flush()
resp = int(f.readline())
return resp
def p... |
from __future__ import print_function
from __future__ import unicode_literals
from collections import OrderedDict
from whoosh.analysis.filters import StopFilter
from whoosh.analysis import (KeywordAnalyzer, StandardAnalyzer)
from whoosh.filedb.filestore import FileStorage, RamStorage
from whoosh.fields import Schema, ... |
# -*- coding: utf-8 -*-
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 field 'SubSector.career_guide'
db.add_column(u'admin_subsector', 'career_guide',
... |
# -*- coding: utf-8 -*-
import pytest
import fauxfactory
from cfme import test_requirements
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.common.vm import VM
from cfme.infrastructure.provider import InfraProvider
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme.u... |
#!/usr/bin/python
# ===========================================
# Module execution.
#
import socket
def main():
module = AnsibleModule(
argument_spec=dict(
component=dict(required=True, aliases=['name']),
version=dict(required=True),
token=dict(required=True),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.