content stringlengths 4 20k |
|---|
import os
import sys
from shutil import copyfile, copytree, rmtree
import fnmatch
from setuptools import setup
long_description = '''
[**Analytics Zoo**](https://github.com/intel-analytics/analytics-zoo/)
is an open source _**Big Data AI**_ platform, and includes the following
features for scaling end-to-end AI to dis... |
#!/usr/bin/env python
from PyQt5.QtWidgets import QTextEdit, QMenu, QFileDialog, QSizePolicy
import mooseutils
class TerminalTextEdit(QTextEdit):
"""
A readonly text edit that replaces terminal codes with appropiate html codes.
Also uses fixed font.
"""
def __init__(self, **kwds):
super(Ter... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from snisi_nutrition import get_domain
logger = logging.getLogger(__name__)
def provider_is_allowed(prole, plocat... |
import pytest
from cfme.utils import error
from cfme.middleware.deployment import MiddlewareDeployment
from cfme.middleware.provider import get_random_list
from cfme.middleware.provider.hawkular import HawkularProvider
from cfme.utils import testgen
from cfme.utils.version import current_version
from deployment_method... |
import json
import logging
import re
logger = logging.getLogger(__name__)
class RtmEventHandler(object):
def __init__(self, slack_clients, msg_writer):
self.clients = slack_clients
self.msg_writer = msg_writer
def handle(self, event):
if 'type' in event:
self._handle_by... |
# coding: utf-8
from __future__ import unicode_literals
from ...matcher import Matcher
def test_issue615(en_tokenizer):
def merge_phrases(matcher, doc, i, matches):
"""Merge a phrase. We have to be careful here because we'll change the
token indices. To avoid problems, merge all the phrases once ... |
from SpecImports import *
import random
from toontown.toonbase import ToontownGlobals
CogParent = 10000
CogParent1 = 11000
BattlePlace1 = 10000
BattlePlace2 = 11000
BattleCellId = 0
Battle2CellId = 1
BattleCells = {BattleCellId: {'parentEntId': BattlePlace1,
'pos': Point3(0, 0, 0)},
Battle2CellId: {'pa... |
import sys
import time
from twitter_ads.client import Client
from twitter_ads.campaign import LineItem
from twitter_ads.enum import METRIC_GROUP
from twitter_ads.utils import split_list
CONSUMER_KEY = 'your consumer key'
CONSUMER_SECRET = 'your consumer secret'
ACCESS_TOKEN = 'access token'
ACCESS_TOKEN_SECRET = 'acc... |
from telemetry.page.actions.all_page_actions import *
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class MseCasesPage(page_module.Page):
def __init__(self, url, page_set):
super(MseCasesPage, self).__init__(url=url, page_set=page_set)
def RunNavigateS... |
"""
Yahoo! Python SDK
* Yahoo! Query Language
* Yahoo! Social API
Find documentation and support on Yahoo! Developer Network: http://developer.yahoo.com
Hosted on GitHub: http://github.com/yahoo/yos-social-python/tree/master
@copyright: Copyrights for code authored by Yahoo! Inc. is licensed under the following t... |
"""
Tests for jpmesh.coordinate.
"""
import unittest
from nose.tools import ok_, eq_
from nose.tools import raises
from jpmesh import FirstMesh, SecondMesh, ThirdMesh
from jpmesh import HalfMesh, QuarterMesh, OneEighthMesh
from jpmesh import parse_mesh_code
from jpmesh import Coordinate
from jpmesh import Angle
de... |
from setuptools import setup, find_packages
from hyde.version import __version__
from distutils.util import convert_path
from fnmatch import fnmatchcase
import os
import sys
PROJECT = 'hyde'
try:
long_description = open('README.rst', 'rt').read()
except IOError:
long_description = ''
#######################... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things GUI.
'''
import logging
LOGGER = logging.getLogger(__name__)
from gi.repository import Gtk
from gi.repository import Gdk
from Xlib.display import Disp... |
"""Test the path_util module."""
from __future__ import print_function
import itertools
import os
import tempfile
import mock
from chromite.lib import constants
from chromite.lib import cros_test_lib
from chromite.lib import git
from chromite.lib import partial_mock
from chromite.lib import path_util
FAKE_SOURCE_... |
from numpy import *
def loadDataSet():
postingList=[['my', 'dog', 'has', 'flea', \
'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', \
'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', '... |
import subprocess, os
class SpSolver:
def __init__(self, basename):
self.simbasename= basename
self.ckiname= self.simbasename + '.cki'
self.ascname= self.simbasename + '.asc'
self.txtname= self.simbasename + '.txt'
self.sampleTime = 0.1
self.debug = True
self.startSpiceNetlist()
def... |
"""\
Examples
For the development.ini you must supply the paster app name:
%(prog)s development.ini --app-name app --init --clear
"""
from pyramid.paster import get_app
import atexit
import logging
import os.path
import select
import shutil
import sys
EPILOG = __doc__
logger = logging.getLogger(__name__)
def... |
import module as mojom
# This module provides a mechanism for determining the packed order and offsets
# of a mojom.Struct.
#
# ps = pack.PackedStruct(struct)
# ps.packed_fields will access a list of PackedField objects, each of which
# will have an offset, a size and a bit (for mojom.BOOLs).
# Size of struct header ... |
"""Bulk uploader for PublicSchool entities, for use with appcfg.py upload_data.
Expected CSV format is http://nces.ed.gov/ccd/psadd.asp, augmented with 3
extra columns for latitude, longitude, and accuracy value (0-9, per
http://code.google.com/apis/maps/documentation/geocoding/#GeocodingAccuracy).
A batch geocoder m... |
"""The low-level ticket-exchanging-links interface of RPC Framework."""
import abc
import collections
import enum
class Ticket(
collections.namedtuple(
'Ticket',
['operation_id', 'sequence_number', 'group', 'method', 'subscription',
'timeout', 'allowance', 'initial_metadata', 'payload',
... |
"""
API operations on Group objects.
"""
import logging
from galaxy.web.base.controller import BaseAPIController, url_for
from galaxy import web
log = logging.getLogger( __name__ )
class GroupRolesAPIController( BaseAPIController ):
@web.expose_api
@web.require_admin
def index( self, trans, group_id, **k... |
# -*- coding: utf-8 -*-
'''
Use a git repository as a Pillar source
---------------------------------------
.. note::
This external pillar has been rewritten for the :doc:`2015.8.0
</topics/releases/2015.8.0>` release. The old method of configuring this
external pillar will be maintained for a couple relea... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import wx
class PhotoCtrl(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
self.frame = wx.Frame(None, title='Photo Control')
self.panel = wx.Panel(self.frame)
self.PhotoMaxSize = 5... |
# Django settings for djangoChustaMind project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('pertxas', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'pe... |
import os.path
import sys # noqa making sure its available for monkey patching
import fixtures
import mock
from nodepool.cmd import nodepoolcmd
from nodepool import tests
class TestNodepoolCMD(tests.DBTestCase):
def patch_argv(self, *args):
argv = ["nodepool", "-s", self.secure_conf]
argv.exten... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
SPDX-License-Identifier: Apache-2.0
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 ... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models import permalink
from django.contrib.auth.models import User
from tagging.fields import TagField
from basic.places.models import Place
import datetime
class Event(models.Model):
""" Event model """
titl... |
from __future__ import absolute_import
import unittest
import time
import json
import logging
import connectordb
import shutil
import os
from jsonschema import SchemaError
# Allows debugging the websocket
#import websocket
# websocket.enableTrace(True)
TEST_URL = connectordb.CONNECTORDB_URL
class subscriber:
... |
from Utils import Logger
LOGGER = Logger(__name__).setup()
try:
import sys
import os
import socket
import cherrypy
from Utils import Command
from Cheetah.Template import Template
from cherrypy.lib.static import serve_file
except ImportError, e:
LOGGER.error(str(e))
sys.exit(1)
... |
#pylint: disable=missing-docstring,invalid-name
from app import models
from app import utils
from app.constants import STUDENT_ROLE, STAFF_ROLE, VALID_ROLES
import json
SEED_OFFERING = "cal/cs61a/sp15"
def is_seeded():
is_seed = models.Course.offering == SEED_OFFERING
return bool(models.Course.query(is_seed... |
""" smashlib.overrides
Things that are not only subclassed from ipython, but intended to
be used instead of their ipython equivalents. Similar to
smashlib.patches, but things in this file are core IPython abstractions.
So far a lot of this is here mostly because smash wants a separate message
bus... |
import argparse, errno, fcntl, hashlib, logging, os, select as _select
import shlex, signal, socket, sqlite3, struct, subprocess
import sys, textwrap, threading, time, traceback
# PY3: It will be even better to use Popen(pass_fds=...),
# and then socket.SOCK_CLOEXEC will be useless.
# (We already follow the ... |
from acos_client.v30 import base
class BladeParameters(base.BaseV30):
def __init__(self, client):
super(BladeParameters, self).__init__(client)
self.base_url = "/vrrp-a/vrid/{0}/blade-parameters"
self.interfaces = {'interface': []}
self.gateways = {
'gateway': {
... |
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sqlite3
import pickle
try:
import Queue
except:
import queue as Queue # lint:ok
from PyQt4.QtGui import QMessageBox
from PyQt4.QtCore import QObject
from PyQt4.QtCore import Q... |
#!/usr/bin/env python3.6
import feedparser as fp
import time
from datetime import datetime, timedelta
import pytz
import sys
from string import Template
with open(sys.argv[1], "r") as f:
subscriptions = f.readlines()
# Date and time setup. I only want posts from 10PM the day before
utc = pytz.utc
homeTZ = pytz.t... |
from ldap3 import Server, Connection, ALL, SUBTREE
import ldap3 as ldap
from lib.Wrappers.Logger import Logger
from lib.Settings import Settings
import hashlib
import base64
class Ldap:
class __Ldap:
ldap = None
def __init__(self, settings=None):
self.settings = settings or Settings(... |
"""
Python Fundamentals 1
@author: Balint Szoke
@date: 2/4/2017
"""
"""---------------------------------------------------
Python is a calculator.
Try these commands one line at a time in the console
---------------------------------------------------"""
2*3
2 * 3 # white space a... |
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, img_as_float
from skimage.color import rgb2gray
###############################################################################
# all functions ###############################################################
####################################... |
"""This file contains subclasses of scipy's LinearOperator to represent sparse linear operators with various structure."""
import scipy
import numpy as np
from scipy.sparse.linalg import LinearOperator
from scipy.sparse.linalg.interface import _ScaledLinearOperator, _SumLinearOperator, _ProductLinearOperator
from scip... |
from __future__ import unicode_literals
import os
import tempfile
import unittest
import mkdocs
from mkdocs import utils
from mkdocs.config import config_options
class OptionallyRequiredTest(unittest.TestCase):
def test_empty(self):
option = config_options.OptionallyRequired()
value = option.v... |
"""
Proxy camera platform that enables image processing of camera data.
For more details about this platform, please refer to the documentation
https://www.home-assistant.io/components/camera.proxy/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA... |
# Time: O(m * n * l)
# Space: O(l)
#
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The same letter cell may not be used more than once.
#
# ... |
"""Provides the code to load PRAW's configuration file `praw.ini`."""
import os
import sys
from six.moves import configparser
from .exceptions import ClientException
class _NotSet(object):
def __bool__(self):
return False
__nonzero__ = __bool__
def __str__(self):
return 'NotSet'
clas... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from ewescrapers import loaders
from ewescrapers.items import ChannelItem, ActionItem, EventItem, RecipeItem
from scrapy.item import Item
import ewescrap... |
from __future__ import print_function, division
from sympy.core import Add, Mul, Pow, S, sympify
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.compatibility import default_sort_key, string_types
from sympy.core.function import Lambda
from sympy.core.mul import _keep_coeff
f... |
import os
from six.moves import http_client
import webtest
from keystone.tests import unit
from keystone.tests.unit.ksfixtures import database
class TestNoAdminTokenAuth(unit.TestCase):
def setUp(self):
super(TestNoAdminTokenAuth, self).setUp()
self.useFixture(database.Database())
self.l... |
__author__ = "João Magalhães <<EMAIL>>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "... |
# coding: utf-8
"""
Custom section with multiple items
Config example::
[projects]
type = items
header = Work on projects
item1 = Project One
item2 = Project Two
item3 = Project Three
"""
from did.utils import item
from did.base import Config
from did.stats import Stats, StatsGroup
# ~~~~~~... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Attachment',
fields=[
('id', models.AutoField(v... |
"""
Script to loop over all theme to create a gallery for Beampy documentation.
"""
from beampy import *
import glob
import os
available_theme = glob.glob('../beampy/themes/*_theme.py')
def create_beampy_slides(theme, output_dir):
doc = document(theme = theme)
with slide():
maketitle('Beampy with ... |
"""Tests for endpoints.api_backend_service."""
import logging
import unittest
import endpoints.api_backend as api_backend
import endpoints.api_backend_service as api_backend_service
import endpoints.api_exceptions as api_exceptions
import mox
import test_util
class ModuleInterfaceTest(test_util.ModuleInterfaceTest,... |
import sys
def num_q(x,p=0.001):
"""Return formatted string for numerical question, that can be included into
cloze type moodle question.
x ... correct answer, p ... precision
"""
return "{1:NUMERICAL:=%f:%f#Pravilno~%f:%f#Premalo pravilnih decimalk}" % (x,p,x,10*p)
def multi_q(answers):
"""R... |
"""Test message creation."""
# pylint: disable=unused-variable
import insteonplm.messages
from insteonplm.messages.allLinkComplete import AllLinkComplete
from insteonplm.messages.allLinkRecordResponse import (
AllLinkRecordResponse)
from insteonplm.messages.buttonEventReport import (
ButtonEventReport)
from ins... |
import sys, glob, os
from os.path import *
def move_sub(basedir, subdir, dry_run = True):
allf = glob.glob('%s/*' % basedir)
#print allf
audiodir = join(basedir, subdir)
cmds = [ 'mkdir %s' % audiodir ]
for f in allf:
cmds += [ 'mv %s %s' % (f, audiodir) ]
if len(cmds) == 1:
# ... |
import os
import unittest
from poker_hands import *
class PokerHandsTest(unittest.TestCase):
def test_higher_card_beats_lower_card(self):
self.assertEqual(who_wins({1: _split('5D 8C 9S JS AC'),
2: _split('2C 5C 7D 8S QH')}), [1])
def test_equal_highest_card(self):... |
""" API utility functions
"""
from pylorax.api.recipes import RecipeError, RecipeFileError, read_recipe_commit
def take_limits(iterable, offset, limit):
""" Apply offset and limit to an iterable object
:param iterable: The object to limit
:type iterable: iter
:param offset: The number of items to skip... |
import time
import math
import GeneralSettings
class PID:
def __init__(self, P=0.51, I=0.0, D=0.00, Ts=0.015):
self.Kp = P
self.Ki = I
self.Kd = D
self.windup_guard = 5.0
self.sample_time = Ts
self.set_point = 0.0
self.last_valid_output = 0.0
se... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Url'
db.create_table(u'app_url', (
(u'id', se... |
from bart.sched.pelt import *
from hypothesis import given
from hypothesis.strategies import integers, tuples, none, one_of
from sys import maxint
from utils_tests import TestBART
# Required to use `int` not `long` henx ma=maxint
nonneg_ints = lambda mi=0, ma=maxint: integers(min_value=mi, max_value=ma)
# Generate a ... |
import os
import mimetypes
import logging
from datetime import datetime, date
from dateutil.tz import tzutc
import dateutil.parser
from sqlalchemy import and_, or_, func, asc as ascending, desc as descending, event
from sqlalchemy.types import *
from sqlalchemy.sql.functions import coalesce
from sqlalchemy.orm import ... |
"""
Test ParlaiParser and other opt/params.py code.
"""
import os
import json
import unittest
from parlai.core.params import ParlaiParser
import parlai.core.agents as agents
import parlai.utils.testing as testing_utils
class _ExampleUpgradeOptAgent(agents.Agent):
def __init__(self, opt, shared=None):
sup... |
import os
import os.path
import shutil
import tempfile
import inspect
from nose.tools import eq_, ok_, assert_raises
from configman import ConfigurationManager
from mock import Mock
from socorro.external.crashstorage_base import CrashIDNotFound
from socorro.external.filesystem.crashstorage import (
FileSystemRawCra... |
from django import template
from django.conf import settings
register = template.Library()
@register.filter
def flatpagehist_diff_previous(self):
return self.diff_previous()
@register.filter
def restructuredparts(value, **overrides):
"""return the restructured text parts"""
try:
from docutil... |
'''
NeuroLearn Utilities
====================
handy utilities.
'''
__all__ = ['get_resource_path',
'get_anatomical',
'set_algorithm',
'attempt_to_import',
'all_same',
'concatenate',
'_bootstrap_apply_func',
'set_decomposition_algorithm'
... |
"""Enables showing modal alerts."""
import json
import typing
import iterm2.connection
class Alert:
"""A modal alert.
:param title: The title, shown in bold at the top.
:param subtitle: The informative text, which may be more than one line
long.
:param window_id: The window to attach the ale... |
import pandas as pd
s = '2018-01-01T12:00+09:00'
print(s)
# 2018-01-01T12:00+09:00
print(type(s))
# <class 'str'>
ts = pd.to_datetime(s)
print(ts)
# 2018-01-01 12:00:00+09:00
print(type(ts))
# <class 'pandas._libs.tslibs.timestamps.Timestamp'>
print(ts.tz)
# pytz.FixedOffset(540)
ts_utc = pd.to_datetime(s, utc=Tr... |
import os
from geonode.settings import *
#
# General Django development settings
#
SITENAME = 'GistdaPortal'
# Defines the directory that contains the settings file as the LOCAL_ROOT
# It is used for relative settings elsewhere.
LOCAL_ROOT = os.path.abspath(os.path.dirname(__file__))
WSGI_APPLICATION = "gistdaportal... |
# -*- coding: utf-8 -*-
### Author: Jose Camacho Collados
import os
import fileinput
from math import sqrt
import operator
import sys
class OutlierDetectionCluster:
#Class modeling a cluster of the dataset, composed of its topic name, its corresponding elements and the outliers to be detected
def __init__(s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import contextlib
import inspect
import os
import random
import subprocess
import sys
import tempfile
import time
import uuid
import unittest
def execute(cmd_string, check_error=True, return_code=0, input=None,
block=True, error_msg='Error executing cmd'):
... |
import sys, random, time, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import memcached_workload_common
from vcoptparse import *
# "I am a string" -> ["I a", "m a s", "trin", "g"]
def rand_split(string, nsub_strings):
cutoffs = random.sample(range(len(strin... |
import random
from django.core.exceptions import ValidationError
from django.db import models
from django import forms
from django.contrib.webdesign import lorem_ipsum
from staging.generators import BaseGenerator
class LoremIpsumForm(forms.Form):
min_words = forms.IntegerField()
max_words = forms.IntegerField... |
from spack import *
class Xssp(AutotoolsPackage):
"""The source code for building the mkdssp, mkhssp, hsspconv, and hsspsoap
programs is bundled in the xssp project"""
homepage = "https://github.com/cmbi/xssp"
url = "https://github.com/cmbi/xssp/archive/3.0.10.tar.gz"
version('3.0.10', s... |
from abc import ABCMeta
from pluginsmanager.model.midi_port import MidiPort
class MidiInput(MidiPort, metaclass=ABCMeta):
"""
MidiInput is the medium in which the midi input port will go into
effect to be processed.
For obtains the inputs::
>>> cctonode
<Lv2Effect object as 'CC2Note... |
import logging, os
logging.basicConfig(filename='simple.log', level=logging.INFO)
path = "/tmp/"
if (os.path.isdir(path)):
print("Path is created")
logging.info('Path is created') |
'''
Basic processing procedures for analog signals (e.g., performing a z-score of a signal, or filtering a signal).
:copyright: Copyright 2014-2015 by the Elephant team, see AUTHORS.txt.
:license: Modified BSD, see LICENSE.txt for details.
'''
from __future__ import division, print_function
import numpy as np
import ... |
from optparse import OptionParser, IndentedHelpFormatter
from os.path import expanduser
from sys import exit
# Import from itools
from itools.log import register_logger, log_info
# Import from usine
from libusine import config, modules, remote_hosts
from libusine.utils import UsineLogger
class HelpFormatter(Indent... |
import json
from django.shortcuts import render
from django.views import defaults
from django.http import HttpResponse
from rest_framework import viewsets, mixins, status
from .models import Arch, SigKey, Label
from . import viewsets as pdc_viewsets
from .serializers import LabelSerializer, ArchSerializer, SigKeySer... |
"""Misc. utilities related to Qt.
Module attributes:
MAXVALS: A dictionary of C/Qt types (as string) mapped to their maximum
value.
MINVALS: A dictionary of C/Qt types (as string) mapped to their minimum
value.
MAX_WORLD_ID: The highest world ID allowed in this version of QtWebEng... |
__author__ = 'justasic'
from django.db import models
from django.contrib.auth.models import User
from NutmegCRM.apps.crm.models import Customer
class Ticket(models.Model):
"""
This is the ticket model used for customer tickets.
The ticket crm is fairly simple. You have customer information linked in the ... |
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- getblockchaininfo
- gettxoutsetinfo
- getdifficulty
- getbestblockhash
- getblockhash
- getblockheader
- getchaintxstats
- getnetworkhashps
- verifychain
Tests correspond to code in rpc/blockchain.cpp.
"""
from de... |
from spack import *
class Htslib(AutotoolsPackage):
"""C library for high-throughput sequencing data formats."""
homepage = "https://github.com/samtools/htslib"
url = "https://github.com/samtools/htslib/releases/download/1.3.1/htslib-1.3.1.tar.bz2"
version('1.4', '2a22ff382654c033c40e4ec3ea8800... |
import collections
import contextlib
import warnings
from distutils import util as distutils
import six
from six.moves import shlex_quote, collections_abc
import fabricio
DEFAULT = object()
@contextlib.contextmanager
def patch(obj, attr, value, default=DEFAULT, force_delete=False):
original = not force_delet... |
# -*- coding: utf-8 -*-
import pprint
from six.moves import reprlib
def _call_and_format_exception(call, x, *args):
try:
# Try the vanilla repr and make sure that the result is a string
return call(x, *args)
except Exception as exc:
exc_name = type(exc).__name__
try:
... |
import json
import os
class VersionInfo:
_version_info = {}
_path = os.path.dirname(os.path.abspath(__file__))
_json_file = os.path.join(_path, 'version_info.json')
def __init__(self):
""" Don't bother instantiating as data is accessed through class methods. """
pass
@classmetho... |
import sys
import traceback
import hashlib
import time
from random import random
from datetime import datetime
from javax.servlet.http import HttpServlet
from java.lang import System
from java.util import LinkedHashMap, ArrayList
from org.python.util import PythonInterpreter
from org.yaml.snakeyaml import Yaml
from j... |
import unittest
from lymph.core.monitoring.metrics import RawMetric
from lymph.core.monitoring.aggregator import Aggregator
def _get_metrics_one():
yield RawMetric('dummy', 'one')
def _get_metrics_two():
yield RawMetric('dummy', 'two')
class AggregatorTestCase(unittest.TestCase):
def test_aggregator... |
# -*- coding: utf-8 -*-
from wakatime.main import execute
from wakatime.packages import requests
import os
import time
from wakatime.compat import u
from wakatime.constants import SUCCESS
from wakatime.stats import guess_lexer
from . import utils
from .utils import ANY, CustomResponse
class LanguagesTestCase(utils... |
import os
from unittest.mock import patch
from pytest import fixture
with patch.dict(os.environ, AWSCOGNITO_DOMAIN='jupyterhub-test.auth.us-west-1.amazoncognito.com'):
from ..awscognito import AWSCognitoAuthenticator, AWSCOGNITO_DOMAIN
from .mocks import setup_oauth_mock
def user_model(username):
"""Return... |
# -*- coding: utf-8 -*-
"""Event testing framework.
Some very important tips:
* You should run with artifactor in order to get per-test HTML event reports.
Usage of ``register_event`` is explained in :py:func:`register_event`.
Uses :py:class:`utils.events.EventTool` through :py:class:`utils.appliance.IPAppliance`.
... |
'''
The MIT License (MIT)
https://github.com/robertchase/spindrift/blob/master/LICENSE.txt
'''
import spindrift.mysql.connection as connection
from spindrift.network import Network
class DB(object):
def __init__(
self,
network=None,
user=None,
pswd... |
"""
Webhook endpoint for Senlin v1 REST API.
"""
from senlin.api.common import util
from senlin.api.common import wsgi
from senlin.objects import base as obj_base
class WebhookController(wsgi.Controller):
"""WSGI controller for webhooks resource in Senlin v1 API."""
REQUEST_SCOPE = 'webhooks'
@wsgi.Con... |
from __future__ import absolute_import
from unittest import skipIf, skipUnless
from django.db import (connection, connections, transaction, DEFAULT_DB_ALIAS, DatabaseError,
IntegrityError)
from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError
from djan... |
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import (ascii, bytes, chr, dict, filter, hex, input,
int, map, next, oct, open, pow, range, round,
str, super, zip)
import itertools
from multiprocessing import Process, Pipe
imp... |
# System imports
import numpy as np
from colorsys import rgb_to_hsv, hsv_to_rgb
from ..reporting import b280
try:
from scipy import signal
from scipy import ndimage
except ModuleNotFoundError if b280() else ImportError:
pass
# print("'scipy' python module not installed")
# Blender imports
# NONE!
# Mo... |
#!/usr/bin/python
import imaplib
import email
import datetime
def process_mailbox(M):
rv, data = M.search(None, "(UNSEEN)")
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(BODY.PEEK[])')
if rv != 'OK':
prin... |
# -*-coding:utf-8-*-
import scrapy
from ZhiSpider.items import PaperItem
PAPER_URL = 'http://kns.cnki.net/KCMS/detail/detail.aspx?'
REF_URL = 'http://kns.cnki.net/kcms/detail/frame/list.aspx?'
# NAME_XPATH = '//*[@class="title"]/text()'
# AUTHORS_XPATH = '//*[@class="author"]/span/a/@onclick'
# INSTITUTIONS_XPATH =... |
# -*- coding: utf-8 -*-
"""
Utility Functions for RokuApp
Created on Fri Jun 19 17:08:47 2015
@author: ddboline
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import time
import requests
from contextl... |
#On the name of ALLAH
import re #Get re class
import math #Get math class
class Converter:
def __init__(self, other,unit=0):
self.unit = unit
self.other = other
def __mul__(self):
return self.unit * self.other
def __div__(self):
return round((self.other/self.unit),2)... |
from __future__ import absolute_import
from __future__ import print_function
from collections import defaultdict
from .pdict import PreservingDict
from .molecule import Molecule
from .physconst import *
def harvest(p4Mol, orca_out, **largs):
"""Harvest variables, gradient, and the molecule from the output and oth... |
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from checkapp.profiles.resources.web_resource import WebResource
class About(WebResource):
def process_GET(self):
return render_to_response('about.html',) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.