content string |
|---|
from weboob.capabilities.cinema import ICapCinema, Person, Movie
from weboob.tools.backend import BaseBackend
from .browser import AllocineBrowser
from urllib import quote_plus
__all__ = ['AllocineBackend']
class AllocineBackend(BaseBackend, ICapCinema):
NAME = 'allocine'
MAINTAINER = u'Julien Veyssier'
... |
from __future__ import unicode_literals
import keyword
import re
from django.utils.datastructures import SortedDict
from django.conf import settings
from django.contrib.gis.utils import LayerMapping
from django.contrib.gis.db import models
from django.contrib.gis import admin
from django.core.exceptions import Valida... |
#!/usr/bin/env python
# Capstone Python bindings, by Nguyen Anh Quynnh <<EMAIL>>
from __future__ import print_function
from capstone import *
from capstone.xcore import *
from xprint import to_x, to_hex, to_x_32
XCORE_CODE = b"\xfe\x0f\xfe\x17\x13\x17\xc6\xfe\xec\x17\x97\xf8\xec\x4f\x1f\xfd\xec\x37\x07\xf2\x45\x5b\... |
from django.conf.urls import patterns, url
urlpatterns = patterns('hbase.views',
url(r'^$', 'app', name='index'),
url(r'api/(?P<url>.+)$', 'api_router'),
url(r'^install_examples$', 'install_examples', name='install_examples'),
) |
# -*- coding: utf-8 -*-
from scrapy import Selector
from libs.misc import get_spider_name_from_domain
from libs.polish import *
from novelsCrawler.spiders.simpleSpider import SimpleSpider
class MyushuwuSpider(SimpleSpider):
"""
classdocs
example: https://m.yushuwu.com/novel/31960.html
"""
dom ... |
# -*- coding: utf-8 -*
#
# Test links:
# http://forum.xda-developers.com/devdb/project/dl/?id=10885
from ..base.simple_downloader import SimpleDownloader
class XdadevelopersCom(SimpleDownloader):
__name__ = "XdadevelopersCom"
__type__ = "downloader"
__version__ = "0.08"
__status__ = "testing"
... |
from .fields import ListField, SetField, DictField, EmbeddedModelField
from django.db import models, connections
from django.db.models import Q
from django.db.models.signals import post_save
from django.db.utils import DatabaseError
from django.dispatch.dispatcher import receiver
from django.test import TestCase
from d... |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
"""
BitBake 'Fetch' implementations
Classes for obtaining upstream sources for the
BitBake build tools.
"""
# Copyright (C) 2003, 2004 Chris Larson
#
# This program is free software; you can redistribute it and/or modify
# it u... |
import math
from unittest import TestCase
from simplejson.compat import long_type, text_type
import simplejson as json
from simplejson.decoder import NaN, PosInf, NegInf
class TestFloat(TestCase):
def test_degenerates_allow(self):
for inf in (PosInf, NegInf):
self.assertEqual(json.loads(json.du... |
from __future__ import absolute_import
import unittest2
from st2tests.base import BaseSensorTestCase
from st2tests.mocks.sensor import MockSensorWrapper
from st2tests.mocks.sensor import MockSensorService
from st2tests.mocks.action import MockActionWrapper
from st2tests.mocks.action import MockActionService
__all__ =... |
"""Checkers for various standard library functions."""
import re
import sys
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers import utils
_VALID_OPEN_MODE_REGEX = re.compile(r'^(r?U|[rwa]\+?b?)$')
if sys.version_info >= (3, 0):
OPEN_MODUL... |
import unittest2 as unittest
from .urls import parse_bug_id, parse_attachment_id
class URLsTest(unittest.TestCase):
def test_parse_bug_id(self):
# FIXME: These would be all better as doctests
self.assertEqual(12345, parse_bug_id("http://webkit.org/b/12345"))
self.assertEqual(12345, parse_... |
from pychart import *
colorline = [color.T(r=((r+3) % 11)/10.0,
g=((g+6) % 11)/10.0,
b=((b+9) % 11)/10.0)
for r in range(11) for g in range(11) for b in range(11)]
def choice_colors(n):
if n:
return colorline[0:-1:len(colorline)/n]
return []
if _... |
"""Dataset class for COIL-100 dataset."""
import os
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
_URL = "http://www.cs.columbia.edu/CAVE/databases/SLAM_coil-20_coil-100/coil-100/coil-100.zip"
_DESCRIPTION = ("""The dataset contains 7200 color images of 100 objects
(72 images per o... |
######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
"""
dyld emulation
"""
import os
from framework import framework_info
from dylib import dylib_info
from it... |
from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import (
run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal, assert_raises
)
from numpy.lib.index_tricks import (
mgrid, ndenumerate,... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.tests import unittest
from ansible.compat.tests import BUILTINS
from ansible.compat.tests.mock import mock_open, patch, MagicMock
from ansible.plugins import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CAC... |
import os
from oslo_config import cfg
from six import moves
from neutron.agent.linux import external_process
from neutron.agent.linux import utils
from neutron.tests import base
from neutron.tests.functional.agent.linux import simple_daemon
UUID_FORMAT = "test-uuid-%d"
SERVICE_NAME = "service"
class BaseTestProce... |
from __future__ import division, absolute_import, print_function
__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'vstack', 'hstack',
'stack']
from . import numeric as _nx
from .numeric import asanyarray, newaxis
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
... |
"""
Pipeline Example.
"""
# $example on$
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import HashingTF, Tokenizer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.app... |
# encoding: 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 'SocialApp.client_id'
db.add_column('socialaccount_socialapp', 'client_id', self.gf('django... |
# -*- coding: utf-8 -*-
r"""Tests special functions
"""
import numpy as np
import pytest
from neutronpy import functions
from scipy.integrate import simps
def test_gauss_norm():
"""Test 1d gaussian
"""
p = np.array([0., 0., 1., -30., 3., 1., 30., 3.])
x = np.linspace(-1e6, 1e6, int(8e6) + 1)
y = ... |
import logging
from rest_framework import decorators, permissions, status
from rest_framework.renderers import JSONPRenderer, JSONRenderer, BrowsableAPIRenderer
from rest_framework.response import Response
import requests
from readthedocs.builds.constants import LATEST
from readthedocs.builds.models import Version
fr... |
import json
import os
import subprocess
from django.utils.translation import ugettext_lazy as _t, ugettext as _
from desktop.lib.conf import Config, coerce_bool, coerce_csv
BASEDIR = os.path.dirname(os.path.abspath(__file__))
USERNAME_SOURCES = ('attributes', 'nameid')
def xmlsec():
"""
xmlsec path
"""
t... |
# coding=utf-8
import unittest
"""890. Find and Replace Pattern
https://leetcode.com/problems/find-and-replace-pattern/description/
You have a list of `words` and a `pattern`, and you want to know which words
in `words` matches the pattern.
A word matches the pattern if there exists a permutation of letters `p` so
t... |
"""
Low-level utilities for preprocessing. Should be functions that apply
to NumPy arrays, not preprocessor classes (though preprocessor classes
should reuse these).
"""
__author__ = "David Warde-Farley"
__copyright__ = "Copyright 2012, Universite de Montreal"
__credits__ = ["David Warde-Farley"]
__license__ = "3-claus... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
"""update lib_raid_errors table
Revision ID: 93ff199763ac
Revises: b1063869f198
Create Date: 2017-07-27 00:13:29.765073+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.schema import Sequence, CreateSequence
# revision identifiers, used by Alembic.
revision = '93ff199763ac'
down_revision = '... |
import BoostBuild
t = BoostBuild.Tester(use_test_config=False)
t.write("jamroot.jam", """
make a.h : : gen-header ;
explicit a.h ;
exe hello : hello.cpp : <implicit-dependency>a.h ;
import os ;
if [ os.name ] = NT
{
actions gen-header
{
echo int i; > $(<)
}
}
else
{
actions gen-header
{
... |
import numpy as np
from numba import cuda
from numba.cuda.testing import unittest, CUDATestCase
class TestCudaEvent(CUDATestCase):
def test_event_elapsed(self):
N = 32
dary = cuda.device_array(N, dtype=np.double)
evtstart = cuda.event()
evtend = cuda.event()
evtstart.recor... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gazeboGui.ui'
#
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon WorkLink"
prefix = "worklink"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "",... |
import shlex
from getpass import getpass
from optparse import Option
from spacecmd.utils import *
def help_user_create(self):
print 'user_create: Create an user'
print '''usage: user_create [options]
options:
-u USERNAME
-f FIRST_NAME
-l LAST_NAME
-e EMAIL
-p PASSWORD
--pam enable PAM authenticati... |
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import datetime
import io
import urllib
from netprofile import PY3
from netprofile.ext.columns import PseudoColumn
from netprofile.export import ExportFormat
from netprofile.pdf import (
DefaultDocTemplate,
PAGE_ORIENTATIONS,... |
import mock
from neutron.extensions import portbindings
from neutron.openstack.common import importutils
from neutron.plugins.brocade import NeutronPlugin as brocade_plugin
from neutron.tests.unit import _test_extension_portbindings as test_bindings
from neutron.tests.unit import test_db_plugin as test_plugin
PLUGIN... |
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
def _needs_update(module, user):
keys = ('email', 'default_project', 'domain', 'enabled')
for key in keys:
if module.params[key] is not None and module.params[key] != user.get(key):
return True
# We do... |
import calendar
import struct
import time
import dns.dnssec
import dns.exception
import dns.rdata
import dns.rdatatype
class BadSigTime(dns.exception.DNSException):
"""Raised when a SIG or RRSIG RR's time cannot be parsed."""
pass
def sigtime_to_posixtime(what):
if len(what) != 14:
raise BadSigTi... |
"""
This module houses the GEOSCoordSeq object, which is used internally
by GEOSGeometry to house the actual coordinates of the Point,
LineString, and LinearRing geometries.
"""
from ctypes import c_double, c_uint, byref
from django.contrib.gis.geos.base import GEOSBase, numpy
from django.contrib.gis.geos.error impo... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import socket
import xmlrpclib
webfaction = xmlrpclib.ServerProxy('https://api.webfaction.com/')
def main():
module = AnsibleModule(
argument_spec = dict(
name = ... |
"""Web pages and functions related to executions."""
import datetime
import json
import math
import time
from zoe_lib.config import get_conf
import zoe_api.exceptions
from zoe_api.web.request_handler import ZoeWebRequestHandler
class ExecutionStartWeb(ZoeWebRequestHandler):
"""Handler class"""
def post(se... |
from collections import OrderedDict
from typing import Dict, Type
from .base import PredictionServiceTransport
from .grpc import PredictionServiceGrpcTransport
from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Ty... |
from __future__ import unicode_literals
from decimal import Decimal
from datetime import datetime
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
class Widget(object):
"""
Widget takes care of converting between impo... |
{
'name': 'MRP Operations start without material',
'version': '1.0',
'author': 'OdooMRP team',
'contributors': ["Daniel Campos <<EMAIL>>",
"Pedro M. Baeza <<EMAIL>>",
"Ana Juaristi <<EMAIL>>"],
'website': 'http://www.odoomrp.com',
"depends": ['mrp_operat... |
import logging
from asyncio import (
start_unix_server, start_server, StreamReader,
StreamWriter)
from ssl import SSLContext
from typing import Union
from urllib.parse import urlparse, unquote
import h11
from multidict import CIMultiDict
from typeguard import check_argument_types
from asphalt.core import Cont... |
import json
from kfp.dsl import ResourceOp
class CreateClusterOp(ResourceOp):
"""Represents an Op which will be translated into a Databricks Cluster creation resource
template.
Examples:
import databricks
databricks.CreateClusterOp(
name="createcluster",
cluster_n... |
# $HeadURL$
__RCSID__ = "$Id$"
"""This Backend sends the Log Messages to a Log Server
It will only report to the server ERROR, EXCEPTION, FATAL
and ALWAYS messages.
"""
import threading
import Queue
from DIRAC.Core.Utilities import Time, Network
from DIRAC.FrameworkSystem.private.logging.backends.BaseBackend import Bas... |
import logging
import optparse
import os
import unittest
from telemetry import benchmark as benchmark_module
from telemetry.core import discover
from telemetry.internal.browser import browser_options
from telemetry.page import legacy_page_test
from telemetry.testing import options_for_unittests
from telemetry.web_perf... |
import time
from datetime import datetime, timedelta
from world import world
from bigml.api import HTTP_NO_CONTENT, HTTP_OK, HTTP_NOT_FOUND
def i_delete_the_project(step):
resource = world.api.delete_project(world.project['resource'])
world.status = resource['code']
assert world.status == HTTP_NO_CONTENT
... |
import collections
import json
import logging
import socket
import time
from telemetry.core.backends.chrome_inspector import websocket
_DomainHandler = collections.namedtuple(
'DomainHandler', ['notification_handler', 'will_close_handler'])
class DispatchNotificationsUntilDoneTimeoutException(Exception):
"""... |
import sys, itertools, os, argparse, urllib2, json, re
class Application_Type(object):
LIST = "list"
WALL = "wall"
class Application(object):
LIST_TYPE = "list"
WALL_TYPE = "wall"
def __init__(self, network, site_id, article_id, instance_type):
self.network = network
self.site_id ... |
from builtins import object
import logging
from libsolr.api import SolrApi
from search.conf import SOLR_URL
LOG = logging.getLogger(__name__)
class SearchController(object):
def __init__(self, user):
self.user = user
def is_collection(self, collection_name):
return collection_name in self.get_solr... |
"""curses
The main package for curses support for Python. Normally used by importing
the package, and perhaps a particular module inside it.
import curses
from curses import textpad
curses.initwin()
...
"""
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
import os as _os... |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_terminal(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def terminal_cfg_line_sessionid(self, **kwargs):
"""Auto Generated Code
"""
... |
data = (
'jjwaels', # 0x00
'jjwaelt', # 0x01
'jjwaelp', # 0x02
'jjwaelh', # 0x03
'jjwaem', # 0x04
'jjwaeb', # 0x05
'jjwaebs', # 0x06
'jjwaes', # 0x07
'jjwaess', # 0x08
'jjwaeng', # 0x09
'jjwaej', # 0x0a
'jjwaec', # 0x0b
'jjwaek', # 0x0c
'jjwaet', # 0x0d
'jjwaep', # 0x0e
'jjw... |
"""This example adds ad group criteria to an ad group. To get ad groups, run
get_ad_groups.py.
Tags: AdGroupCriterionService.mutate
Api: AdWordsOnly
"""
__author__ = '<EMAIL> (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))
# Import appropriate classes from the cli... |
import contextlib
import json
import optparse
import os
import sys
import websocket
from tracinglib import TracingBackend, TracingClient
@contextlib.contextmanager
def Connect(device_ip, devtools_port):
backend = TracingBackend()
try:
backend.Connect(device_ip, devtools_port)
yield backend
finally:
... |
import mock
from nova.scheduler.filters import core_filter
from nova import test
from nova.tests.unit.scheduler import fakes
class TestCoreFilter(test.NoDBTestCase):
def test_core_filter_passes(self):
self.filt_cls = core_filter.CoreFilter()
filter_properties = {'instance_type': {'vcpus': 1}}
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
from collections import defaultdict
from units.compat import unittest
from ansible.template.safe_eval import safe_eval
class TestSafeEval(unittest.TestCase):
def test_safe_eval_usage(self):
# test safe ev... |
"""
AccountsService extends the GDataService to streamline Google Analytics
account information operations.
AnalyticsDataService: Provides methods to query google analytics data feeds.
Extends GDataService.
DataQuery: Queries a Google Analytics Data list feed.
AccountQuery: ... |
from django.db import models
from itertools import chain
BUBBLE_ACTIONS = (
(1, 'link'),
(2, 'pop'),
(3, 'modal'),
(4, 'ajax_crumb'),
)
class Bubble(models.Model):
url=models.CharField... |
'''
This decoder stacks on top of the 'mdio' PD and decodes the CFP 100G
pluggable transceiver protocol.
'''
from .pd import Decoder |
"""engine.SCons.Tool.f77
Tool-specific initialization for the generic Posix f77 Fortran compiler.
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.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2... |
"""Testable usage examples for Stackdriver Logging API wrapper
Each example function takes a ``client`` argument (which must be an instance
of :class:`google.cloud.logging.client.Client`) and uses it to perform a task
with the API.
To facilitate running the examples as system tests, each example is also passed
a ``to... |
#coding=utf-8
from django.db import models
from proftpd.ftpadmin.lib.common import set_hexdigest, fix_path, check_safe_range
from proftpd.ftpadmin.settings import DISABLED_CHOICES, SHELL_CHOICES, FILE_PATH, FTP_GROUP_DEFAULT_GID, FTP_USER_SAFE_HOMEDIR, FTP_ACL_CHOICES
from proftpd.ftpadmin import signals
from proftp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Title : test_TDCT_correlation
# @Project : 3DCTv2
# @Description : pytest test
# @Author : Jan Arnold
# @Email : jan.arnold (at) coraxx.net
# @Copyright : Copyright (C) 2016 Jan Arnold
# @License : GPLv3 (see LICENSE file)
# @Credits :
# @Maintainer ... |
"""Python 3 compatibility shims
"""
import sys
if sys.version_info[0] < 3:
PY3 = False
def b(s):
return s
def u(s):
return unicode(s, 'unicode_escape')
import cStringIO as StringIO
StringIO = BytesIO = StringIO.StringIO
text_type = unicode
binary_type = str
string_types =... |
import perf
class tracepoint(perf.evsel):
def __init__(self, sys, name):
config = perf.tracepoint(sys, name)
perf.evsel.__init__(self,
type = perf.TYPE_TRACEPOINT,
config = config,
freq = 0, sample_period = 1, wak... |
# -*- coding: utf-8 -*-
import logging
from datetime import datetime
from tornado import gen
from tornado.queues import Queue
from concurrent.futures import ThreadPoolExecutor
from db.cache import Cache
from db.persis import Persis
from squirrel.utils import USER_CACHE_MAX, DAY_FMT
q = Queue(maxsize=1000)
LOG = logging... |
"""Tests for tensorflow.ops.tf.scatter."""
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 test_ut... |
import sys
import threading
import time
from zkrest import ZooKeeper
class Agent(threading.Thread):
""" A basic agent that wants to become a master and exit """
root = '/election'
def __init__(self, id):
super(Agent, self).__init__()
self.zk = ZooKeeper()
self.id = id
def ru... |
#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of se... |
import warnings
import numpy as np
from ..externals import six
from ..utils.fixes import in1d
from .fixes import bincount
def compute_class_weight(class_weight, classes, y):
"""Estimate class weights for unbalanced datasets.
Parameters
----------
class_weight : dict, 'balanced' or None
If 'b... |
from distutils.errors import DistutilsArgError
import inspect
import glob
import warnings
import platform
import distutils.command.install as orig
import setuptools
# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
# now. See https://bitbucket.org/pypa/setuptools/issue/199/
_install = orig.... |
"""NeuroM, lightweight and fast.
Examples:
Obtain some morphometrics
>>> import neurom
>>> from neurom import features
>>> nrn = neurom.load_neuron('path/to/neuron')
>>> ap_seg_len = features.get('segment_lengths', nrn, neurite_type=neurom.APICAL_DENDRITE)
>>> ax_sec_len = features.get('section... |
from decimal import Decimal
import unittest
from django_easyfilters.ranges import auto_ranges
class TestRanges(unittest.TestCase):
def test_auto_ranges_simple(self):
"""
Test that auto_ranges produces 'nice' looking automatic ranges.
"""
# An easy case - max_items is just what we... |
# -*- coding: utf-8 -*-
import unittest
import six
from openformats.formats.json import StructuredJsonHandler
from openformats.exceptions import ParseError
from openformats.strings import OpenString
from openformats.tests.formats.common import CommonFormatTestMixin
from openformats.tests.utils.strings import (gener... |
"""Options for BigMLer execute option
"""
def get_execute_options(defaults=None):
"""Execute-related options
"""
if defaults is None:
defaults = {}
options = {
# A BigML script is provided
'--script': {
"action": 'store',
"dest": 'script',
... |
"""
homeassistant.components.switch.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.wink/
"""
import logging
from homeassistant.components.wink import WinkToggleDevice
from homea... |
from fabric.api import lcd, local
from fabric.decorators import runs_once
import os
fabfile_dir = os.path.dirname(__file__)
def update_theme():
theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx')
if not os.path.exists('/tmp/sphinx_rtd_theme'):
local('git clone https://github.... |
import logging
from logging import debug, info, warning, error, critical
import serial
from serial.tools import list_ports
import time
import threading
from collections.abc import Iterable
from motty.config import Config
class HistoryObserver(object):
def __init__(self):
pass
def onNewHistoryEntry(se... |
"""
Maildir-style mailbox support
"""
import os
import stat
import socket
import time
from zope.interface import implements
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.python.compat import set
from twisted.mail import pop3
from twisted.mail import smtp
from twisted.pro... |
import sys
import os
import boto
import optparse
import copy
import boto.exception
import boto.roboto.awsqueryservice
import bdb
import traceback
try:
import epdb as debugger
except ImportError:
import pdb as debugger
def boto_except_hook(debugger_flag, debug_flag):
def excepthook(typ, value, tb):
... |
"""Jobs for recommendations."""
__author__ = 'Xinyu Wu'
import ast
from core import jobs
from core.domain import exp_services
from core.domain import recommendations_services
from core.domain import rights_manager
from core.platform import models
(exp_models, recommendations_models,) = models.Registry.import_models(... |
#!/usr/bin/python3
import os
def main():
test_folder = 'tmp'
for file_name in get_file_structure():
create(os.path.join(test_folder, file_name))
list_files(test_folder)
def get_file_structure():
simple_files = ['123abc.txt', '123xyz.txt', 'fooabc.barmp3', 'abc.abc', '00000000.txt']
level... |
from hashlib import md5
import math
import time
from lxml import etree
from oslo_log import log as logging
import requests
import six
from cinder import exception
from cinder.i18n import _LE
LOG = logging.getLogger(__name__)
class DotHillClient(object):
def __init__(self, host, login, password, protocol):
... |
from __future__ import unicode_literals
import boto
from boto.exception import BotoServerError
from moto import mock_sns
import sure # noqa
@mock_sns
def test_create_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, subprocess, sys
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), "..", "..", "..", "..", "..", "tools"))
import traci, sumolib
sumoBinary = sumolib.checkBinary('sumo')
sumoProcess = subprocess.Popen("%s -c sumo.sumocfg" % (sumoBinary), shell=True, std... |
""" FileDump plugin for Artifactor
Add a stanza to the artifactor config like this,
artifactor:
log_dir: /home/username/outdir
per_run: test #test, run, None
overwrite: True
plugins:
filedump:
enabled: True
plugin: filedump
"""
from artifactor import ArtifactorBasePlugi... |
#!/usr/bin/env python
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import ugettext_lazy
from onadata.apps.logger.models import XForm
from onadata.libs.utils.logger_tools import mongo_sync_st... |
"""
Common utility functions useful throughout the contentstore
"""
import logging
import re
from datetime import datetime
from pytz import UTC
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django_comment_common.models import assi... |
from traits.api import HasTraits, Instance, Button, Enum, Int, Float, Range
from traitsui.api import View, Item, Group
from chaco.api import HPlotContainer, Plot, ArrayPlotData, DataRange1D
from chaco.tools.api import PanTool, ZoomTool
from enable.api import ColorTrait
from enable.component_editor import ComponentEdito... |
from django import http
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site, get_current_site
from django.core.exceptions import ObjectDoesNotExist
def shortcut(request, content_type_id, object_id):
"Redirect to an object's page based on a content-type ID and an ... |
"""
Example SPB Frame Creation
Note the outer Dot1Q Ethertype marking (0x88e7)
backboneEther = Ether(dst='00:bb:00:00:90:00', src='00:bb:00:00:40:00', type=0x8100) # noqa: E501
backboneDot1Q = Dot1Q(vlan=4051,type=0x88e7)
backboneServiceID = SPBM(prio=1,isid=20011)
customerEther = Ether(dst='00:1b:... |
# -*- coding: utf-8 -*-
import json
import logging
import pprint
import urllib2
import werkzeug
from odoo import http
from odoo.http import request
_logger = logging.getLogger(__name__)
class PaypalController(http.Controller):
_notify_url = '/payment/paypal/ipn/'
_return_url = '/payment/paypal/dpn/'
_c... |
import warnings
from django.apps import apps as django_apps
from django.conf import settings
from django.core import urlresolvers, paginator
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.six.m... |
import sublime, sublime_plugin
class MytestCommand(sublime_plugin.TextCommand):
def run(self, edit):
# self.view.insert(edit, 0, "Hello, World! ")
self.view.run_command("show_panel", {"panel": "console"}) # "toggle": 0})
# print self.view.file_name(), "is now the active view"
class SublimeOnSave(sublime_plugin... |
"""HttpClients in this module use httplib to make HTTP requests.
This module make HTTP requests based on httplib, but there are environments
in which an httplib based approach will not work (if running in Google App
Engine for example). In those cases, higher level classes (like AtomService
and GDataService) can swap ... |
{
'name': 'Timesheet on Issues',
'version': '1.0',
'category': 'Project Management',
'description': """
This module adds the Timesheet support for the Issues/Bugs Management in Project.
=================================================================================
Worklogs can be maintained to signi... |
#!/usr/bin/python
import subprocess
import sys
import logging
import dateutil.parser
import pytz
from datetime import datetime, timedelta
logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
def run(args, dry_run=False):
if dry_run:
print "Would have r... |
""" unit tests for the QuantTree implementation """
from __future__ import print_function
import unittest
import io
from rdkit import RDConfig
from rdkit.ML.DecTree import BuildQuantTree
from rdkit.ML.DecTree.QuantTree import QuantTreeNode
from rdkit.ML.Data import MLData
from rdkit.six.moves import cPickle, xrange
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.